From a17281c5bf2528f026bbb72e77b657efb680d91b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 06:28:42 +0000 Subject: [PATCH 01/11] fix(metadata-protocol, plugin-security): judge a permission set's seal and lock by (package, name) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- .../src/protocol-authoring-channel.ts | 8 +++ .../src/protocol-authoring-gate.ts | 6 +- .../src/protocol-packaged-base-refusal.ts | 57 +++++++++++++++++++ .../metadata-protocol/src/protocol-save.ts | 1 + packages/metadata-protocol/src/protocol.ts | 2 +- .../src/packaged-permission-set-lock-gate.ts | 37 ++++++++++++ 6 files changed, 108 insertions(+), 3 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-authoring-channel.ts b/packages/metadata-protocol/src/protocol-authoring-channel.ts index aa49bcfe063..f893edb2f4d 100644 --- a/packages/metadata-protocol/src/protocol-authoring-channel.ts +++ b/packages/metadata-protocol/src/protocol-authoring-channel.ts @@ -43,6 +43,14 @@ export interface MetadataAuthoringGateContext { * when the door stated none: the gate composes `en`. */ userTextLocales?: readonly string[]; + /** + * [ADR-0150 D2, #34226] The package the write is addressed to: the save's + * `packageId`, or a restore's row binding. Absent or `null` for a write + * naming no package. A gate that judges an item keyed `(package, name)` + * reads it to tell a package's own item from another package's item of + * the same name. + */ + packageId?: string | null; } export type MetadataAuthoringGate = (ctx: MetadataAuthoringGateContext) => void | Promise; diff --git a/packages/metadata-protocol/src/protocol-authoring-gate.ts b/packages/metadata-protocol/src/protocol-authoring-gate.ts index 626d4c88b31..0a688cb1213 100644 --- a/packages/metadata-protocol/src/protocol-authoring-gate.ts +++ b/packages/metadata-protocol/src/protocol-authoring-gate.ts @@ -177,7 +177,7 @@ export async function refuseRestoredBodyTheSaveDoorRefuses( : {}), }); if (this.authoringChannel !== 'package-author') { - await this.runAuthoringGate({ type, name, state: 'active', body }); + await this.runAuthoringGate({ type, name, state: 'active', body, packageId: binding }); } } @@ -186,7 +186,7 @@ export async function runAuthoringGate( this: Pick, evt: { type: string; name: string; state: 'draft' | 'active'; body: unknown; - userTextLocales?: readonly (string | undefined)[]; + userTextLocales?: readonly (string | undefined)[]; packageId?: string | null; }): Promise { const singular = PLURAL_TO_SINGULAR[evt.type] ?? evt.type; const gate = this.authoringGates.get(singular); @@ -208,6 +208,8 @@ export async function runAuthoringGate( ...(evt.userTextLocales !== undefined ? { userTextLocales: evt.userTextLocales.filter((l): l is string => typeof l === 'string' && l.length > 0) } : {}), + // [ADR-0150 D2, #34226] The package the write is addressed to. + ...(typeof evt.packageId === 'string' && evt.packageId !== '' ? { packageId: evt.packageId } : {}), }); } diff --git a/packages/metadata-protocol/src/protocol-packaged-base-refusal.ts b/packages/metadata-protocol/src/protocol-packaged-base-refusal.ts index bd7ba5a94aa..1592f28f9ce 100644 --- a/packages/metadata-protocol/src/protocol-packaged-base-refusal.ts +++ b/packages/metadata-protocol/src/protocol-packaged-base-refusal.ts @@ -61,6 +61,8 @@ import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared'; import { expandViewContainer, isAggregatedViewContainer } from '@objectstack/spec'; import { ITEM_KEY_DISCRIMINATORS, isPairOf, itemDiscriminator, pairOf, type InstalledManifestLookup } from '@objectstack/metadata-core'; import { installedManifestsOfEngine } from './installed-manifests.js'; +import { permissionSetHoldersMeet } from '@objectstack/core'; +import { lookupArtifactItem, shippedArtifactsOf, shippingPackagesOf, type ArtifactLookupHost } from './protocol-artifact-lookup.js'; /** * The `ObjectStackProtocolImplementation` members the functions below read — @@ -151,6 +153,18 @@ export function refusePackagedBaseOverride( request.type, request.packageId as string, ); } + // [ADR-0150 D2, #34226] A permission set is `(package, name)`: a save + // a package addresses to its own set of a name another namespace's + // package ships overrides no shipped set, so the seal does not judge + // it. Every save that does override one stays sealed, as before: one + // naming no package, one addressed to the shipper, one addressed to + // the shipper's customization pair (whatever the pair's namespace), + // and one addressed to a package that shares the shipper's set of the + // name ({@link overridesShippedPermissionSet}). + if (namedBase && (PLURAL_TO_SINGULAR[request.type] ?? request.type) === 'permission' + && !overridesShippedPermissionSet(this.engine, request.packageId as string, request.name)) { + return; + } // [#20819, ADR-0131 D6] The SENTENCE is chosen per ADR-0126 regime, // and names the managed package for every other type; the code and // the status are unchanged. [#23577] Every write reads it, whatever @@ -179,6 +193,49 @@ export function refusePackagedBaseOverride( } } +/** + * [ADR-0150 D2/D9, ADR-0131 D6, #34226] Does a save of the permission set + * `name` addressed to the package `writer` override a set a package ships? + * + * A set is `(package, name)`, and a name is one set per namespace: two + * packages share one set of a name exactly when the ONE predicate the install + * gate and the save door's name rule ask says they meet + * (`permissionSetHoldersMeet`, `@objectstack/core`). So the save overrides the + * set a package Q ships when `writer` is Q, when `writer` is Q's + * customization pair (ADR-0146: the pair customizes Q's own items, whatever + * namespace the pair declares), or when `writer` meets Q under that predicate + * (a co-owner of Q's namespace, a platform namespace, a package with no + * namespace, a name the platform requests by spelling). Every package that + * ships the name is judged, never the first found, so the answer is the same + * in every registration order. + * + * `true` when no shipping package can be read: the seal then judges the name + * as it always did. The plugin-security lock judges the same three + * relations for the same write (`packaged-permission-set-lock-gate.ts`). + */ +function overridesShippedPermissionSet(engine: unknown, writer: string, name: string): boolean { + const lookup: Pick = { + engine: engine as ArtifactLookupHost['engine'], + lookupArtifactItem: (...a) => lookupArtifactItem.call(lookup, ...a), + shippingPackagesOf: (...a) => shippingPackagesOf.call(lookup, ...a), + }; + const shippers = new Set(); + for (const artifact of shippedArtifactsOf.call(lookup, 'permission', name)) { + const packageId = (artifact as { _packageId?: unknown } | null)?._packageId; + if (typeof packageId === 'string' && packageId !== '') shippers.add(packageId); + } + if (shippers.size === 0) return true; + const registry = (engine as { registry?: { getPackage?: (id: string) => { manifest?: { namespace?: unknown } } | undefined } } | null)?.registry; + const namespaceOf = (packageId: string): string | undefined => { + const namespace = registry?.getPackage?.(packageId)?.manifest?.namespace; + return typeof namespace === 'string' && namespace !== '' ? namespace : undefined; + }; + const installed = installedManifestsOfEngine(engine); + return [...shippers].some((shipper) => shipper === writer + || isPairOf(writer, shipper, installed) + || permissionSetHoldersMeet(namespaceOf(writer), namespaceOf(shipper), name)); +} + /** * [ADR-0146 D2] The sealed write's second sentence on a type whose override * channel is open, chosen by who writes: diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 6da4b136ca4..96c5420607a 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -1824,6 +1824,7 @@ export class ProtocolSaveFacet { state: mode === 'draft' ? 'draft' : 'active', body: request.item, ...(request.userTextLocales !== undefined ? { userTextLocales: request.userTextLocales } : {}), + packageId: request.packageId, }); } diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index b55648aea92..67c695f4298 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1755,7 +1755,7 @@ export class ObjectStackProtocolImplementation implements */ private runAuthoringGate(evt: { type: string; name: string; state: 'draft' | 'active'; body: unknown; - userTextLocales?: readonly (string | undefined)[]; + userTextLocales?: readonly (string | undefined)[]; packageId?: string | null; }): Promise { // [#25467 cut 8] The body moved to `protocol-authoring-gate.ts` (see `AuthoringGateHost`). const readAuthoringGates = () => this.authoringGates; diff --git a/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts b/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts index a1147ba8e87..483117aed99 100644 --- a/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts +++ b/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts @@ -57,11 +57,36 @@ * stubs) keeps its existing behavior, and the caller can read the `false`. */ +import { permissionSetHoldersMeet } from '@objectstack/core'; +import { installedManifestsOf, isPairOf, type InstalledPackageSource } from '@objectstack/metadata-core'; import { assertPermissionSetNotPackageDeclared, + classifyPackagedPermissionSet, type LayeredProbe, } from './packaged-permission-set-lock.js'; +/** + * [ADR-0150 D2/D9, ADR-0131 D6, #34226] Does a write of the permission set + * `name` addressed to the package `writer` override the set the package + * `declarer` ships? A set is `(package, name)`, one set per namespace: it does + * when `writer` is the declarer, the declarer's customization pair (ADR-0146, + * whatever namespace the pair declares), or a package the declarer meets + * under the ONE predicate the install gate and the save door's name rule ask + * (`permissionSetHoldersMeet`). The metadata protocol's seal judges the same + * three relations for the same write (`overridesShippedPermissionSet`, + * `protocol-packaged-base-refusal.ts`). + */ +function overridesDeclaredSet(ql: any, writer: string, declarer: string, name: string): boolean { + if (writer === declarer) return true; + const registry = ql?.registry as (InstalledPackageSource & { getPackage?: (id: string) => any }) | undefined; + if (isPairOf(writer, declarer, installedManifestsOf(registry))) return true; + const namespaceOf = (packageId: string): string | undefined => { + const namespace = registry?.getPackage?.(packageId)?.manifest?.namespace; + return typeof namespace === 'string' && namespace !== '' ? namespace : undefined; + }; + return permissionSetHoldersMeet(namespaceOf(writer), namespaceOf(declarer), name); +} + /** The packages a `409` refusal of a read naming no package names (ADR-0150 D5), or `undefined` for any other error. */ function refusedPackageHolders(error: unknown): string[] | undefined { const failure = error as { code?: unknown; refusal?: { candidates?: unknown } } | null; @@ -80,6 +105,8 @@ export interface PermissionSetLockGateContext { body: unknown; /** [#32656] The caller's language ladder, stated by the write door (`MetadataAuthoringGateContext`). */ userTextLocales?: readonly string[]; + /** [ADR-0150 D2, #34226] The package the write is addressed to (`MetadataAuthoringGateContext`); absent for none. */ + packageId?: string | null; } /** @@ -110,6 +137,16 @@ export function registerPackagedPermissionSetLockGate(protocol: any, ql: any): b } } } + // [ADR-0150 D2, #34226] A write a package addresses to its own set of a + // name only other namespaces' packages declare overrides none of their + // sets, so the lock does not judge it. A write naming no package, or one + // that overrides any declarer's set ({@link overridesDeclaredSet}), is + // judged as before; so is a name no source could classify. + const writer = typeof ctx.packageId === 'string' && ctx.packageId !== '' ? ctx.packageId : undefined; + if (writer !== undefined) { + const verdict = classifyPackagedPermissionSet(ctx.name, ql, probe); + if (verdict.status === 'packaged' && !verdict.packageIds.some((declarer) => overridesDeclaredSet(ql, writer, declarer, ctx.name))) return; + } // A metadata-door save that targets a package-declared name is an // override of the shipped base whether or not an overlay row exists yet, // so the remedy the refusal teaches is the clone path. From 7732b8b864673edd3d5eb45bb898175275d7fc77 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:22:12 +0000 Subject: [PATCH 02/11] fix(metadata-protocol, plugin-security): the seal, the lock and the write intents judge a permission set by (package, name), with pins Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- .../34226-permission-set-seal-by-package.md | 21 +++ .../src/protocol-history-and-publish.ts | 6 +- .../src/protocol-packaged-base-refusal.ts | 40 +++-- .../metadata-protocol/src/protocol-save.ts | 4 +- .../packaged-permission-set-lock-gate.test.ts | 166 ++++++++++++++++++ .../src/packaged-permission-set-lock-gate.ts | 9 +- 6 files changed, 224 insertions(+), 22 deletions(-) create mode 100644 .changeset/34226-permission-set-seal-by-package.md diff --git a/.changeset/34226-permission-set-seal-by-package.md b/.changeset/34226-permission-set-seal-by-package.md new file mode 100644 index 00000000000..75d1a109bda --- /dev/null +++ b/.changeset/34226-permission-set-seal-by-package.md @@ -0,0 +1,21 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/plugin-security': patch +--- + +fix(metadata-protocol, plugin-security): a package's save 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 save a package addresses to its 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 lands; the exported `MetadataAuthoringGateContext` gains an optional `packageId`; nothing the save door accepted is refused +Metadata-protocol: none + +A permission set is `(package, name)`, and a name holds one set per namespace (ADR-0150 D2/D9). The metadata door's managed seal (ADR-0126 / ADR-0131 D6) and plugin-security's packaged-permission-set lock both judged a save of a permission set by its name alone. So when package `crm` shipped a set `N`, a package `hr` of another namespace could not save its own set `N`: the save was refused as if it edited `crm`'s shipped set. + +Both now judge the package the save is addressed to. A save of `N` overrides a set a package `Q` ships, and stays sealed and locked exactly as before, when it names no package, is addressed to `Q`, is addressed to `Q`'s customization pair (whatever namespace the pair declares), or is addressed to a package that shares `Q`'s set of the name (a co-owner of `Q`'s namespace, a platform namespace, a package with no namespace, or a name the platform requests by spelling). Every package that ships the name is judged, so the answer is the same in every registration order. Any other package's save of its own `N` lands, is served at that package, and that package's grants confer its own set. + +What moves, for a save of `N` while a package of another namespace ships `N`: + +- FROM 403 `NOT_OVERRIDABLE` (sealed) TO saved, for a save addressed to a package of another namespace than every package that ships `N`, which is not the customization pair of any of them. + +`MetadataAuthoringGateContext` (`@objectstack/metadata-protocol`) gains an optional `packageId`: the package the write is addressed to (a save's `packageId`, a restore's row binding), absent for a write that names none. An authoring gate that judges an item keyed `(package, name)` reads it. Gates that ignore it are unaffected. + +Nothing to migrate. diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 2f82d0b0e1c..328da5ca3aa 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -31,7 +31,7 @@ import type { MetadataItem } from '@objectstack/metadata-core'; import { savedItemNameRefusal } from '@objectstack/metadata/view-container-name'; import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared'; import { serveStoredHashTokens, servedContentHash } from './metadata-redaction.js'; -import { overrideWriteRefusalError } from './protocol-packaged-base-refusal.js'; +import { isOwnPermissionSetWrite, overrideWriteRefusalError } from './protocol-packaged-base-refusal.js'; import type { OverrideWriteVerdict } from './protocol-packaged-base-refusal.js'; import { objectBodyExtensionFieldSuffixRefusal } from './protocol-extension-field-suffix.js'; import { storedFlowVerdictBody } from './protocol-flow-save-replay.js'; @@ -664,7 +664,7 @@ export class ProtocolHistoryAndPublishFacet { * `recordPendingDenialAudit`, rethrow. Skip it and the refusal is silent * again — the pre-#7748 state, not merely a worse one. */ - static async promoteDraftForPublish(host: Pick, request: { + static async promoteDraftForPublish(host: Pick, request: { type: string; name: string; actor?: string; message?: string; /** * [#8907] ADR-0048 — the package binding of the draft being promoted, @@ -1251,7 +1251,7 @@ export class ProtocolHistoryAndPublishFacet { ...(draftForGate ? { judged: { body: draftForGate.body, packageId: promoteInto } } : {}), }; } - const artifactBacked = host.isArtifactBacked(singularType, request.name); + const artifactBacked = host.isArtifactBacked(singularType, request.name) && !isOwnPermissionSetWrite(host.engine, singularType, request.name, promoteInto); const intent: 'override-artifact' | 'runtime-only' = artifactBacked && !declaredOverride ? 'override-artifact' : 'runtime-only'; const ref = { diff --git a/packages/metadata-protocol/src/protocol-packaged-base-refusal.ts b/packages/metadata-protocol/src/protocol-packaged-base-refusal.ts index 1592f28f9ce..c4b487140cc 100644 --- a/packages/metadata-protocol/src/protocol-packaged-base-refusal.ts +++ b/packages/metadata-protocol/src/protocol-packaged-base-refusal.ts @@ -160,11 +160,8 @@ export function refusePackagedBaseOverride( // naming no package, one addressed to the shipper, one addressed to // the shipper's customization pair (whatever the pair's namespace), // and one addressed to a package that shares the shipper's set of the - // name ({@link overridesShippedPermissionSet}). - if (namedBase && (PLURAL_TO_SINGULAR[request.type] ?? request.type) === 'permission' - && !overridesShippedPermissionSet(this.engine, request.packageId as string, request.name)) { - return; - } + // name ({@link isOwnPermissionSetWrite}). + if (isOwnPermissionSetWrite(this.engine, request.type, request.name, request.packageId)) return; // [#20819, ADR-0131 D6] The SENTENCE is chosen per ADR-0126 regime, // and names the managed package for every other type; the code and // the status are unchanged. [#23577] Every write reads it, whatever @@ -193,6 +190,25 @@ export function refusePackagedBaseOverride( } } +/** + * [ADR-0150 D2/D9, ADR-0131 D6, #34226] Is a write of `(type, name)` addressed + * to `packageId` a package's OWN permission set, beside sets other namespaces' + * packages ship — a write that overrides no shipped set + * ({@link overridesShippedPermissionSet}), though the name is artifact-backed? + * + * The one verdict every door that judges such a write as an override of the + * shipped base reads in place of the name-wide artifact check: the save door's + * seal ({@link refusePackagedBaseOverride}), and the write intent the save door + * and the draft promotion hand the repository (`override-artifact` is the + * repository's managed seal). `false` for every other type, and for a write + * naming no package. + */ +export function isOwnPermissionSetWrite(engine: unknown, type: string, name: string, packageId: string | null | undefined): boolean { + if ((PLURAL_TO_SINGULAR[type] ?? type) !== 'permission') return false; + if (typeof packageId !== 'string' || packageId === '') return false; + return !overridesShippedPermissionSet(engine, packageId, name); +} + /** * [ADR-0150 D2/D9, ADR-0131 D6, #34226] Does a save of the permission set * `name` addressed to the package `writer` override a set a package ships? @@ -201,11 +217,11 @@ export function refusePackagedBaseOverride( * packages share one set of a name exactly when the ONE predicate the install * gate and the save door's name rule ask says they meet * (`permissionSetHoldersMeet`, `@objectstack/core`). So the save overrides the - * set a package Q ships when `writer` is Q, when `writer` is Q's - * customization pair (ADR-0146: the pair customizes Q's own items, whatever - * namespace the pair declares), or when `writer` meets Q under that predicate - * (a co-owner of Q's namespace, a platform namespace, a package with no - * namespace, a name the platform requests by spelling). Every package that + * set a package Q ships when `writer` is Q's customization pair (ADR-0146: + * the pair customizes Q's own items, whatever namespace the pair declares), or + * when `writer` meets Q under that predicate: Q itself, a co-owner of Q's + * namespace, a platform namespace, a package with no namespace, a name the + * platform requests by spelling. Every package that * ships the name is judged, never the first found, so the answer is the same * in every registration order. * @@ -231,8 +247,8 @@ function overridesShippedPermissionSet(engine: unknown, writer: string, name: st return typeof namespace === 'string' && namespace !== '' ? namespace : undefined; }; const installed = installedManifestsOfEngine(engine); - return [...shippers].some((shipper) => shipper === writer - || isPairOf(writer, shipper, installed) + // A package meets itself under the predicate, so the shipper's own save is judged by the last clause. + return [...shippers].some((shipper) => isPairOf(writer, shipper, installed) || permissionSetHoldersMeet(namespaceOf(writer), namespaceOf(shipper), name)); } diff --git a/packages/metadata-protocol/src/protocol-save.ts b/packages/metadata-protocol/src/protocol-save.ts index 96c5420607a..d65c9fca77f 100644 --- a/packages/metadata-protocol/src/protocol-save.ts +++ b/packages/metadata-protocol/src/protocol-save.ts @@ -46,7 +46,7 @@ import type { StoredMigrationTodo, } from './stored-migration.js'; import { droppedWithheldKeyNotices } from './protocol-credential-carry-forward.js'; -import { overrideWriteRefusalError } from './protocol-packaged-base-refusal.js'; +import { isOwnPermissionSetWrite, overrideWriteRefusalError } from './protocol-packaged-base-refusal.js'; import { objectBodyExtensionFieldSuffixRefusal } from './protocol-extension-field-suffix.js'; import { flowVerdictBody } from './protocol-flow-save-replay.js'; import { withParsedStoredActions } from './protocol-stored-action-parse.js'; @@ -1909,7 +1909,7 @@ export class ProtocolSaveFacet { } if (lateOverrideVerdict.verdict === 'refuse') throw overrideWriteRefusalError(lateOverrideVerdict); const singularTypeForRepo = PLURAL_TO_SINGULAR[request.type] ?? request.type; - const artifactBacked = host.isArtifactBacked(singularTypeForRepo, request.name); + const artifactBacked = host.isArtifactBacked(singularTypeForRepo, request.name) && !isOwnPermissionSetWrite(host.engine, singularTypeForRepo, request.name, request.packageId); // [ADR-0146 D2] An admitted declared override writes the pair's own // row; it edits no managed item, so the store judges a runtime write. const intent: 'override-artifact' | 'runtime-only' = artifactBacked && !declaredOverride 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 1e037f65a6a..e44c1db5fcc 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 @@ -51,6 +51,8 @@ import { ObjectStackProtocolImplementation, resetEnvWritableMetadataTypes, } from '@objectstack/metadata-protocol'; +import { bindSecurityCatalogReader, createSecurityCatalogReader, resolveUserAuthzGrants } from '@objectstack/core'; +import { SchemaRegistry } from '@objectstack/objectql'; import { registerPackagedPermissionSetLockGate } from './packaged-permission-set-lock-gate.js'; import { PackagedPermissionSetLockedError, @@ -299,3 +301,167 @@ describe('#11843 — the lock answers at the metadata door', () => { expect(registerPackagedPermissionSetLockGate(undefined, {})).toBe(false); }); }); + +// ───────────────────────────────────────────────────────────────────────────── +// [ADR-0150 D2, #34226] The seal and the lock judge a save by (package, name) +// ───────────────────────────────────────────────────────────────────────────── + +/** + * 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 + * saves its OWN set N through the metadata door. + * + * FROM: the save was refused `NOT_OVERRIDABLE` / 403, "provided by a managed + * package and is sealed". The protocol's seal judged the name alone, and so + * did the lock behind it. TO: the save lands, and hr's grant confers hr's set. + * + * Every save that overrides crm's shipped set stays sealed exactly as before + * (ADR-0126 / ADR-0131 D6): one naming no package, one addressed to crm, one + * addressed to crm's customization pair (whose namespace differs from crm's), + * and one addressed to a co-owner of crm's namespace. Those saves are asserted + * to be refused by the SEAL, not by the lock. The lock's own arms are asserted + * at the gate, which the same composition registers on the same registry. + * + * The composition is the real protocol and the real `SchemaRegistry`, both read + * from source (`vitest.config.ts`), over this file's fake engine. Each case + * runs in both registration orders: crm's set registered before the other + * 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 }); + expect(String((err as Error).message)).toContain('provided by a managed package and is sealed'); + }; + + for (const order of ORDERS) { + it(`${order}: hr saves its own set N beside crm's shipped N; it lands, and hr's grant confers hr's set while crm's confers crm's (FROM sealed)`, async () => { + const { engine, protocol, registry } = await composition(order); + const err = await save(protocol, { type: 'permission', name: N, item: setOf('cap_hr'), packageId: HR }); + expect(err).toBeNull(); + expect(metaRowsOf(engine).map((r) => ({ name: r.name, package_id: r.package_id }))).toEqual([{ name: N, package_id: HR }]); + expect({ crm: await confers(registry, CRM), hr: await confers(registry, HR) }).toEqual({ crm: ['cap_crm_shipped'], hr: ['cap_hr'] }); + }, 30_000); + + it(`${order}: with crm AND fin shipping N, hr's own save still lands: every shipper is judged, not the first found`, async () => { + const { engine, protocol } = await composition(order, [CRM, FIN]); + expect(await save(protocol, { type: 'permission', name: N, item: setOf('cap_hr'), packageId: HR })).toBeNull(); + expect(metaRowsOf(engine)).toHaveLength(1); + }, 30_000); + + it.each([ + ['naming no package', undefined], + ['addressed to crm', CRM], + ['addressed to crm\'s customization pair (another namespace)', CRM_PAIR], + ['addressed to a co-owner of crm\'s namespace', CRM_TWO], + ] as const)(`${order}: CONTROL — a save of N %s overrides crm's shipped set and is sealed as before, nothing written`, async (_how, packageId) => { + const { engine, protocol } = await composition(order); + sealed(await save(protocol, { type: 'permission', name: N, item: setOf('cap_x'), ...(packageId ? { packageId } : {}) })); + expect(metaRowsOf(engine)).toEqual([]); + }, 30_000); + + it(`${order}: CONTROL — with fin ALSO shipping N, a save addressed to fin's namespace co-owner is still sealed`, async () => { + const { engine, protocol } = await composition(order, [FIN, CRM]); + sealed(await save(protocol, { type: 'permission', name: N, item: setOf('cap_x'), packageId: CRM_TWO })); + expect(metaRowsOf(engine)).toEqual([]); + }, 30_000); + + it(`${order}: hr's own set saved as a draft then published: the draft lands, the publish promotes it, and hr's grant confers it (FROM the publish sealed)`, async () => { + const { engine, protocol, registry } = await composition(order); + expect(await save(protocol, { type: 'permission', name: N, item: setOf('cap_hr'), packageId: HR, mode: 'draft' })).toBeNull(); + const published = await (protocol as unknown as { publishMetaItem(req: Record): Promise }) + .publishMetaItem({ type: 'permission', name: N, packageId: HR }).then(() => null, (e: unknown) => e); + expect(published).toBeNull(); + expect(metaRowsOf(engine).map((r) => ({ package_id: r.package_id, state: r.state }))).toEqual([{ package_id: HR, state: 'active' }]); + expect({ crm: await confers(registry, CRM), hr: await confers(registry, HR) }).toEqual({ crm: ['cap_crm_shipped'], hr: ['cap_hr'] }); + }, 30_000); + + // The refusal each answers at main: the managed seal at the store for crm and its pair, and the + // one-name-per-namespace rule for the environment and crm's co-owner, which it judges first. + it.each([ + ['naming no package', null, ['NAMESPACE_CONFLICT', 422]], + ['addressed to crm', CRM, ['NOT_OVERRIDABLE', 403]], + ['addressed to crm\'s customization pair (another namespace)', CRM_PAIR, ['NOT_OVERRIDABLE', 403]], + ['addressed to a co-owner of crm\'s namespace', CRM_TWO, ['NAMESPACE_CONFLICT', 422]], + ] as const)(`${order}: CONTROL — the publish door: a stored draft of N %s is not promoted over crm's shipped set`, async (_how, binding, envelope) => { + const { engine, protocol } = await composition(order); + // The draft is hr's, then rebound to the address under test, as a draft stored before this change would be. + expect(await save(protocol, { type: 'permission', name: N, item: setOf('cap_x'), packageId: HR, mode: 'draft' })).toBeNull(); + for (const [key, row] of engine.rows) if (row.__table === 'sys_metadata') engine.rows.set(key, { ...row, package_id: binding }); + const err = await (protocol as unknown as { publishMetaItem(req: Record): Promise }) + .publishMetaItem({ type: 'permission', name: N, ...(binding ? { packageId: binding } : {}) }).then(() => null, (e: unknown) => e); + expect([(err as { code?: unknown } | null)?.code, (err as { status?: unknown } | null)?.status]).toEqual(envelope); + expect(metaRowsOf(engine).map((r) => r.state)).toEqual(['draft']); + }, 30_000); + + it(`${order}: the lock gate judges the same relations: hr's own set passes, every override of crm's set is locked`, async () => { + const { gate } = await composition(order); + expect(await gate(HR)).toBeNull(); + for (const packageId of [undefined, CRM, CRM_PAIR, CRM_TWO]) { + const err = await gate(packageId); + expect(err, `the lock for ${packageId ?? 'no package'}`).toBeInstanceOf(PackagedPermissionSetLockedError); + expect(err).toMatchObject({ code: 'NOT_OVERRIDABLE', status: 403 }); + } + }, 30_000); + } +}); diff --git a/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts b/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts index 483117aed99..85f0dc2e5a9 100644 --- a/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts +++ b/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts @@ -69,15 +69,14 @@ import { * [ADR-0150 D2/D9, ADR-0131 D6, #34226] Does a write of the permission set * `name` addressed to the package `writer` override the set the package * `declarer` ships? A set is `(package, name)`, one set per namespace: it does - * when `writer` is the declarer, the declarer's customization pair (ADR-0146, - * whatever namespace the pair declares), or a package the declarer meets - * under the ONE predicate the install gate and the save door's name rule ask - * (`permissionSetHoldersMeet`). The metadata protocol's seal judges the same + * when `writer` is the declarer's customization pair (ADR-0146, whatever + * namespace the pair declares), or a package the declarer meets under the ONE + * predicate the install gate and the save door's name rule ask + * (`permissionSetHoldersMeet`), the declarer itself included. The metadata protocol's seal judges the same * three relations for the same write (`overridesShippedPermissionSet`, * `protocol-packaged-base-refusal.ts`). */ function overridesDeclaredSet(ql: any, writer: string, declarer: string, name: string): boolean { - if (writer === declarer) return true; const registry = ql?.registry as (InstalledPackageSource & { getPackage?: (id: string) => any }) | undefined; if (isPairOf(writer, declarer, installedManifestsOf(registry))) return true; const namespaceOf = (packageId: string): string | undefined => { From 70b122ae0c4b2e11fd011f7c715be72b11563b37 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:22:21 +0000 Subject: [PATCH 03/11] docs(changeset): name the publish door Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- .changeset/34226-permission-set-seal-by-package.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.changeset/34226-permission-set-seal-by-package.md b/.changeset/34226-permission-set-seal-by-package.md index 75d1a109bda..0bca3d69f1b 100644 --- a/.changeset/34226-permission-set-seal-by-package.md +++ b/.changeset/34226-permission-set-seal-by-package.md @@ -5,16 +5,18 @@ fix(metadata-protocol, plugin-security): a package's save 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 save a package addresses to its 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 lands; the exported `MetadataAuthoringGateContext` gains an optional `packageId`; nothing the save door accepted is refused +Clause-②: yes (widening) — a save (or a draft's publish) a package addresses to its 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 lands; the exported `MetadataAuthoringGateContext` gains an optional `packageId`; nothing the save door accepted is refused Metadata-protocol: none A permission set is `(package, name)`, and a name holds one set per namespace (ADR-0150 D2/D9). The metadata door's managed seal (ADR-0126 / ADR-0131 D6) and plugin-security's packaged-permission-set lock both judged a save of a permission set by its name alone. So when package `crm` shipped a set `N`, a package `hr` of another namespace could not save its own set `N`: the save was refused as if it edited `crm`'s shipped set. -Both now judge the package the save is addressed to. A save of `N` overrides a set a package `Q` ships, and stays sealed and locked exactly as before, when it names no package, is addressed to `Q`, is addressed to `Q`'s customization pair (whatever namespace the pair declares), or is addressed to a package that shares `Q`'s set of the name (a co-owner of `Q`'s namespace, a platform namespace, a package with no namespace, or a name the platform requests by spelling). Every package that ships the name is judged, so the answer is the same in every registration order. Any other package's save of its own `N` lands, is served at that package, and that package's grants confer its own set. +These judges, and the managed seal the store applies to the write a save or a draft's publish hands it, now judge the package the write is addressed to. A save of `N` overrides a set a package `Q` ships, and stays sealed and locked exactly as before, when it names no package, is addressed to `Q`, is addressed to `Q`'s customization pair (whatever namespace the pair declares), or is addressed to a package that shares `Q`'s set of the name (a co-owner of `Q`'s namespace, a platform namespace, a package with no namespace, or a name the platform requests by spelling). Every package that ships the name is judged, so the answer is the same in every registration order. Any other package's save of its own `N` lands, is served at that package, and that package's grants confer its own set. What moves, for a save of `N` while a package of another namespace ships `N`: -- FROM 403 `NOT_OVERRIDABLE` (sealed) TO saved, for a save addressed to a package of another namespace than every package that ships `N`, which is not the customization pair of any of them. +- FROM 403 `NOT_OVERRIDABLE` (sealed) TO saved, for a save addressed to a package of another namespace than every package that ships `N`, which is not the customization pair of any of them. The same holds for a draft save of that set and for its publish. + +Rollback and revert of such a set still judge the name alone, and other sealed package-scoped types keep the name-wide seal. `MetadataAuthoringGateContext` (`@objectstack/metadata-protocol`) gains an optional `packageId`: the package the write is addressed to (a save's `packageId`, a restore's row binding), absent for a write that names none. An authoring gate that judges an item keyed `(package, name)` reads it. Gates that ignore it are unaffected. From ca8808b4e1120777922e91af85c4a83d4376c724 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 07:41:50 +0000 Subject: [PATCH 04/11] test(plugin-security): word the publish controls' comment as measured Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- .../src/packaged-permission-set-lock-gate.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 e44c1db5fcc..8c121bb339b 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 @@ -436,8 +436,8 @@ describe('[#34226] a permission set is (package, name): the seal and the lock ju expect({ crm: await confers(registry, CRM), hr: await confers(registry, HR) }).toEqual({ crm: ['cap_crm_shipped'], hr: ['cap_hr'] }); }, 30_000); - // The refusal each answers at main: the managed seal at the store for crm and its pair, and the - // one-name-per-namespace rule for the environment and crm's co-owner, which it judges first. + // The refusal each answers: the managed seal at the store for crm and its pair, and the + // one-name-per-namespace rule, which the publish judges first, for the environment and crm's co-owner. it.each([ ['naming no package', null, ['NAMESPACE_CONFLICT', 422]], ['addressed to crm', CRM, ['NOT_OVERRIDABLE', 403]], From 1a2f74f5267488556f7f59ab344fd4fc9d899820 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 08:18:40 +0000 Subject: [PATCH 05/11] chore(scripts): ratchet the engine-double ledger for the new pinned findOne double Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 --- scripts/engine-double-contract.pinned.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 7013c2223f8..a613afc3667 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -4419,7 +4419,7 @@ { "file": "packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.test.ts", "verb": "findOne", - "pinned": 1 + "pinned": 2 }, { "file": "packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.test.ts", From da256b7a132d9e3292895fccf175299f4fd2f962 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:19:02 +0000 Subject: [PATCH 06/11] fix(plugin-security): read the declarer's namespace through the typed installed-manifest lookup The intersection with InstalledPackageSource resolved getPackage to the first signature, whose manifest is unknown, so the dts build refused the namespace read (TS2339). Claude-Session: https://claude.ai/code/session_01FEkQ5obaLbqgzRUR9xXfft Co-authored-by: Claude --- .../src/packaged-permission-set-lock-gate.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts b/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts index 85f0dc2e5a9..6055152d9af 100644 --- a/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts +++ b/packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts @@ -77,10 +77,10 @@ import { * `protocol-packaged-base-refusal.ts`). */ function overridesDeclaredSet(ql: any, writer: string, declarer: string, name: string): boolean { - const registry = ql?.registry as (InstalledPackageSource & { getPackage?: (id: string) => any }) | undefined; - if (isPairOf(writer, declarer, installedManifestsOf(registry))) return true; + const installed = installedManifestsOf(ql?.registry as InstalledPackageSource | undefined); + if (isPairOf(writer, declarer, installed)) return true; const namespaceOf = (packageId: string): string | undefined => { - const namespace = registry?.getPackage?.(packageId)?.manifest?.namespace; + const namespace = installed(packageId)?.namespace; return typeof namespace === 'string' && namespace !== '' ? namespace : undefined; }; return permissionSetHoldersMeet(namespaceOf(writer), namespaceOf(declarer), name); From 591e245b71cef0213ba1bd6965c327bd6a770198 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:40:31 +0000 Subject: [PATCH 07/11] fix(metadata-protocol): the undo of a refused package publish judges a permission set by (package, name) undoLandedPromotions still derived its write intent from the name-wide artifact check, so the undo of a package's own permission set beside another namespace's shipped set was refused by the store's seal and the author's draft was not put back. Claude-Session: https://claude.ai/code/session_01FEkQ5obaLbqgzRUR9xXfft Co-authored-by: Claude --- .../src/protocol-history-and-publish.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-history-and-publish.ts b/packages/metadata-protocol/src/protocol-history-and-publish.ts index 328da5ca3aa..b7455732401 100644 --- a/packages/metadata-protocol/src/protocol-history-and-publish.ts +++ b/packages/metadata-protocol/src/protocol-history-and-publish.ts @@ -124,7 +124,7 @@ function unwrittenPromotionError(type: string, name: string): Error { * active row stored, its history append then failed) is not in `landed` — the * promotion threw — and is the store's own non-atomicity on such a runtime. */ -async function undoLandedPromotions(host: Pick, args: { +async function undoLandedPromotions(host: Pick, args: { repo: SysMetadataRepository; landed: ReadonlyArray; /** The pre-publish capture (`existedBefore` / `prevVersion` per item). */ @@ -139,9 +139,15 @@ async function undoLandedPromotions(host: Pick[0]; // Per item, as the revert derives it: a runtime item is not refused by - // the artifact-override gate on its way back out. - const intent: 'override-artifact' | 'runtime-only' = - host.isArtifactBacked(item.singularType, item.d.name) ? 'override-artifact' : 'runtime-only'; + // the artifact-override gate on its way back out. [ADR-0150 D2] Per + // write, as the promotion derived it: a package's own permission set + // beside another namespace's shipped one is a runtime item to the + // package each write addresses (`isOwnPermissionSetWrite`). + const intentFor = (packageId: string | null): 'override-artifact' | 'runtime-only' => + host.isArtifactBacked(item.singularType, item.d.name) + && !isOwnPermissionSetWrite(host.engine, item.singularType, item.d.name, packageId) + ? 'override-artifact' : 'runtime-only'; + const intent = intentFor(item.packageId); try { if (!item.promotedDraft) { throw new Error(`the draft ${item.d.type}/${item.d.name} consumed was not captured, so it cannot be put back`); @@ -177,7 +183,7 @@ async function undoLandedPromotions(host: Pick Date: Mon, 16 Nov 2026 11:50:32 +0000 Subject: [PATCH 08/11] test(plugin-security): pin the undo of a refused package publish for a package's own permission set; name both gate contexts in the changeset Claude-Session: https://claude.ai/code/session_01FEkQ5obaLbqgzRUR9xXfft Co-authored-by: Claude --- .../34226-permission-set-seal-by-package.md | 6 +-- .../packaged-permission-set-lock-gate.test.ts | 40 +++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/.changeset/34226-permission-set-seal-by-package.md b/.changeset/34226-permission-set-seal-by-package.md index 0bca3d69f1b..aad86615565 100644 --- a/.changeset/34226-permission-set-seal-by-package.md +++ b/.changeset/34226-permission-set-seal-by-package.md @@ -5,7 +5,7 @@ fix(metadata-protocol, plugin-security): a package's save 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 save (or a draft's publish) a package addresses to its 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 lands; the exported `MetadataAuthoringGateContext` gains an optional `packageId`; nothing the save door accepted is refused +Clause-②: yes (widening) — a save, a draft save or a draft's publish that a package addresses to its 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 lands; the exported `MetadataAuthoringGateContext` (`@objectstack/metadata-protocol`) and `PermissionSetLockGateContext` (`@objectstack/plugin-security`) each gain an optional `packageId`; nothing the save door accepted is refused Metadata-protocol: none A permission set is `(package, name)`, and a name holds one set per namespace (ADR-0150 D2/D9). The metadata door's managed seal (ADR-0126 / ADR-0131 D6) and plugin-security's packaged-permission-set lock both judged a save of a permission set by its name alone. So when package `crm` shipped a set `N`, a package `hr` of another namespace could not save its own set `N`: the save was refused as if it edited `crm`'s shipped set. @@ -16,8 +16,8 @@ What moves, for a save of `N` while a package of another namespace ships `N`: - FROM 403 `NOT_OVERRIDABLE` (sealed) TO saved, for a save addressed to a package of another namespace than every package that ships `N`, which is not the customization pair of any of them. The same holds for a draft save of that set and for its publish. -Rollback and revert of such a set still judge the name alone, and other sealed package-scoped types keep the name-wide seal. +When a package publish is refused on a runtime that cannot roll back its transaction, the undo of each promotion it made judges the same package the promotion addressed, so a package's own set `N` is taken back out and its draft is put back instead of being reported still live. Rollback and revert of such a set still judge the name alone, and other sealed package-scoped types keep the name-wide seal. -`MetadataAuthoringGateContext` (`@objectstack/metadata-protocol`) gains an optional `packageId`: the package the write is addressed to (a save's `packageId`, a restore's row binding), absent for a write that names none. An authoring gate that judges an item keyed `(package, name)` reads it. Gates that ignore it are unaffected. +`MetadataAuthoringGateContext` (`@objectstack/metadata-protocol`) gains an optional `packageId`: the package the write is addressed to (a save's `packageId`, a restore's row binding), absent for a write that names none. An authoring gate that judges an item keyed `(package, name)` reads it. Gates that ignore it are unaffected. `PermissionSetLockGateContext` (`@objectstack/plugin-security`), the subset of it the lock gate consumes, gains the same optional `packageId`. Nothing to migrate. 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 8c121bb339b..43a446b0b95 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 @@ -454,6 +454,46 @@ describe('[#34226] a permission set is (package, name): the seal and the lock ju expect(metaRowsOf(engine).map((r) => r.state)).toEqual(['draft']); }, 30_000); + // [#32396] On a runtime that cannot roll back, a refused package publish undoes + // each promotion it made by hand. The undo addresses the same package the + // promotion did, so it judges hr's own set N as the promotion did. + it(`${order}: a refused batch publish on a runtime that cannot roll back undoes hr's own set N and puts its draft back (FROM left live)`, async () => { + const { engine, protocol } = await composition(order); + Object.assign(engine, { + getDefaultDriverName: () => 'remote', + getDriverByName: () => ({ supports: { transactionsUnsupported: true } }), + }); + const LATER = 'qa_zz_refused_later'; + expect(await save(protocol, { type: 'permission', name: N, item: setOf('cap_hr'), packageId: HR, mode: 'draft' })).toBeNull(); + expect(await save(protocol, { type: 'permission', name: LATER, item: { ...setOf('cap_later'), name: LATER }, packageId: HR, mode: 'draft' })).toBeNull(); + const draftOf = (name: string) => metaRowsOf(engine).find((r) => r.name === name && r.state === 'draft'); + const draftBefore = { metadata: draftOf(N)?.metadata, checksum: draftOf(N)?.checksum }; + expect(draftBefore.metadata).toBeDefined(); + + // The later promotion's write is refused after hr's N was promoted. + const host = protocol as unknown as { + promoteDraftForPublish(req: { name: string; judgeOnly?: boolean }): Promise; + publishPackageDrafts(req: { packageId: string }): Promise<{ outcome: string; failed: Array<{ name: string; code?: string }> }>; + }; + const real = host.promoteDraftForPublish.bind(host); + const promoted: string[] = []; + host.promoteDraftForPublish = async (req) => { + if (!req.judgeOnly) { + if (req.name === LATER) throw Object.assign(new Error('conflict'), { code: 'METADATA_CONFLICT', status: 409 }); + promoted.push(req.name); + } + return real(req); + }; + + const res = await host.publishPackageDrafts({ packageId: HR }); + + expect(promoted, 'hr\'s N is promoted before the refused write').toEqual([N]); + expect(res.outcome).toBe('refused'); + expect(res.failed.find((f) => f.name === N)?.code, 'undone, not reported live').toBe('BATCH_ABORTED'); + expect(metaRowsOf(engine).map((r) => `${String(r.name)}:${String(r.state)}`).sort()).toEqual([`${LATER}:draft`, `${N}:draft`]); + expect({ metadata: draftOf(N)?.metadata, checksum: draftOf(N)?.checksum }).toEqual(draftBefore); + }, 30_000); + it(`${order}: the lock gate judges the same relations: hr's own set passes, every override of crm's set is locked`, async () => { const { gate } = await composition(order); expect(await gate(HR)).toBeNull(); From 499e0ba74c110ee32ff90243760c36f592cc6b4d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 12:00:48 +0000 Subject: [PATCH 09/11] test(plugin-security): the gate pins' engine double lists a table's own rows by the where's equalities Claude-Session: https://claude.ai/code/session_01FEkQ5obaLbqgzRUR9xXfft Co-authored-by: Claude --- .../src/packaged-permission-set-lock-gate.test.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) 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 43a446b0b95..5b46f4cbc2f 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 @@ -119,9 +119,13 @@ function makeFakeEngine(opts?: { listItemsThrows?: boolean }) { ? { name, _packageId: PKG } : undefined, }, - async find(table: string, _opts: { where: Record }) { + async find(table: string, opts2?: { where?: Record }) { if (table === 'sys_metadata_history') return historyRows; - return Array.from(rows.values()); + // The table's own rows, narrowed by the where's scalar equalities (a batch + // publish lists a package's drafts with one); operator clauses are not read. + const scalar = Object.entries(opts2?.where ?? {}).filter(([, v]) => v === null || typeof v !== 'object'); + return Array.from(rows.values()).filter((r) => (r.__table ?? 'sys_metadata') === table + && scalar.every(([k, v]) => (r[k] ?? null) === v)); }, async findOne(table: string, opts2: { where: Record }) { assertEngineFindOnePredicate(table, opts2); @@ -490,7 +494,7 @@ describe('[#34226] a permission set is (package, name): the seal and the lock ju expect(promoted, 'hr\'s N is promoted before the refused write').toEqual([N]); expect(res.outcome).toBe('refused'); expect(res.failed.find((f) => f.name === N)?.code, 'undone, not reported live').toBe('BATCH_ABORTED'); - expect(metaRowsOf(engine).map((r) => `${String(r.name)}:${String(r.state)}`).sort()).toEqual([`${LATER}:draft`, `${N}:draft`]); + expect(metaRowsOf(engine).map((r) => `${String(r.name)}:${String(r.state)}`).sort()).toEqual([`${N}:draft`, `${LATER}:draft`]); expect({ metadata: draftOf(N)?.metadata, checksum: draftOf(N)?.checksum }).toEqual(draftBefore); }, 30_000); From 343d5a7f1f49cb95be900989d87e5736fb3f71d2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 12:02:39 +0000 Subject: [PATCH 10/11] test(plugin-security): pin the undo of an edited own permission set too; the engine double answers a version's history row Claude-Session: https://claude.ai/code/session_01FEkQ5obaLbqgzRUR9xXfft Co-authored-by: Claude --- .../packaged-permission-set-lock-gate.test.ts | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) 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 5b46f4cbc2f..fe8aa14641f 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 @@ -98,6 +98,8 @@ function makeFakeEngine(opts?: { listItemsThrows?: boolean }) { const r = rows.get(k); return r ? { key: k, row: r } : null; }; + const meetsScalars = (r: Row, where?: Record) => Object.entries(where ?? {}) + .every(([k, v]) => (v !== null && typeof v === 'object') || (r[k] ?? null) === v); const declaredItems = [ { name: PACKAGED_SET, label: 'Support Agent', _packageId: PKG, objects: {} }, { name: SHADOW_SET, label: 'Drafted', _packageId: 'sys_metadata', objects: {} }, @@ -123,13 +125,12 @@ function makeFakeEngine(opts?: { listItemsThrows?: boolean }) { if (table === 'sys_metadata_history') return historyRows; // The table's own rows, narrowed by the where's scalar equalities (a batch // publish lists a package's drafts with one); operator clauses are not read. - const scalar = Object.entries(opts2?.where ?? {}).filter(([, v]) => v === null || typeof v !== 'object'); - return Array.from(rows.values()).filter((r) => (r.__table ?? 'sys_metadata') === table - && scalar.every(([k, v]) => (r[k] ?? null) === v)); + return Array.from(rows.values()).filter((r) => (r.__table ?? 'sys_metadata') === table && meetsScalars(r, opts2?.where)); }, async findOne(table: string, opts2: { where: Record }) { assertEngineFindOnePredicate(table, opts2); - if (table === 'sys_metadata_history') return null; + // A version's history row, as a restore reads it back. + if (table === 'sys_metadata_history') return historyRows.find((h) => meetsScalars(h, opts2.where)) ?? null; return findRow(opts2.where)?.row ?? null; }, async insert(table: string, data: Record) { @@ -461,13 +462,21 @@ describe('[#34226] a permission set is (package, name): the seal and the lock ju // [#32396] On a runtime that cannot roll back, a refused package publish undoes // each promotion it made by hand. The undo addresses the same package the // promotion did, so it judges hr's own set N as the promotion did. - it(`${order}: a refused batch publish on a runtime that cannot roll back undoes hr's own set N and puts its draft back (FROM left live)`, async () => { + // Created: the undo removes the active row. Edited (hr's N live at v1): the undo + // restores v1, a write the store judges by its intent. + it.each(['created', 'edited'] as const)(`${order}: a refused batch publish on a runtime that cannot roll back undoes hr's own set N (%s) and puts its draft back (FROM left live)`, async (shape) => { const { engine, protocol } = await composition(order); Object.assign(engine, { getDefaultDriverName: () => 'remote', getDriverByName: () => ({ supports: { transactionsUnsupported: true } }), }); const LATER = 'qa_zz_refused_later'; + const publishOne = (protocol as unknown as { publishMetaItem(req: Record): Promise }).publishMetaItem; + if (shape === 'edited') { + expect(await save(protocol, { type: 'permission', name: N, item: setOf('cap_hr_v1'), packageId: HR, mode: 'draft' })).toBeNull(); + expect(await publishOne.call(protocol, { type: 'permission', name: N, packageId: HR }).then(() => null, (e: unknown) => e)).toBeNull(); + } + const activeBefore = metaRowsOf(engine).filter((r) => r.state === 'active').map((r) => r.metadata); expect(await save(protocol, { type: 'permission', name: N, item: setOf('cap_hr'), packageId: HR, mode: 'draft' })).toBeNull(); expect(await save(protocol, { type: 'permission', name: LATER, item: { ...setOf('cap_later'), name: LATER }, packageId: HR, mode: 'draft' })).toBeNull(); const draftOf = (name: string) => metaRowsOf(engine).find((r) => r.name === name && r.state === 'draft'); @@ -494,7 +503,8 @@ describe('[#34226] a permission set is (package, name): the seal and the lock ju expect(promoted, 'hr\'s N is promoted before the refused write').toEqual([N]); expect(res.outcome).toBe('refused'); expect(res.failed.find((f) => f.name === N)?.code, 'undone, not reported live').toBe('BATCH_ABORTED'); - expect(metaRowsOf(engine).map((r) => `${String(r.name)}:${String(r.state)}`).sort()).toEqual([`${N}:draft`, `${LATER}:draft`]); + expect(metaRowsOf(engine).filter((r) => r.state === 'active').map((r) => r.metadata), 'the active row is as before the publish').toEqual(activeBefore); + expect(metaRowsOf(engine).filter((r) => r.state === 'draft').map((r) => String(r.name)).sort()).toEqual([N, LATER]); expect({ metadata: draftOf(N)?.metadata, checksum: draftOf(N)?.checksum }).toEqual(draftBefore); }, 30_000); From b054ae27080fe269553af588c293c5ebbb9f93af Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 12:10:29 +0000 Subject: [PATCH 11/11] test(plugin-security): the gate pins' find double applies the caller's bound after its filter Claude-Session: https://claude.ai/code/session_01FEkQ5obaLbqgzRUR9xXfft Co-authored-by: Claude --- .../src/packaged-permission-set-lock-gate.test.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) 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 fe8aa14641f..e2acb13951a 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 @@ -121,11 +121,14 @@ function makeFakeEngine(opts?: { listItemsThrows?: boolean }) { ? { name, _packageId: PKG } : undefined, }, - async find(table: string, opts2?: { where?: Record }) { - if (table === 'sys_metadata_history') return historyRows; + async find(table: string, opts2?: { where?: Record; limit?: number }) { // The table's own rows, narrowed by the where's scalar equalities (a batch // publish lists a package's drafts with one); operator clauses are not read. - return Array.from(rows.values()).filter((r) => (r.__table ?? 'sys_metadata') === table && meetsScalars(r, opts2?.where)); + // The caller's bound applies after the filter, as ObjectQL applies it. + const found = table === 'sys_metadata_history' + ? historyRows + : Array.from(rows.values()).filter((r) => (r.__table ?? 'sys_metadata') === table && meetsScalars(r, opts2?.where)); + return typeof opts2?.limit === 'number' ? found.slice(0, opts2.limit) : found; }, async findOne(table: string, opts2: { where: Record }) { assertEngineFindOnePredicate(table, opts2);