From 79554591d85ebb2dc17edeaa20527536f2192d89 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 1 Oct 2026 01:15:23 +0000 Subject: [PATCH 1/4] fix(metadata-protocol): Regime C rows for action and permission name their sanctioned path (WIP) Claude-Session: https://claude.ai/code/session_01Ujdtvqs7ree7WyQmEDwEnG Co-authored-by: Claude --- packages/metadata-protocol/src/protocol.ts | 141 ++++++++++++++++----- 1 file changed, 107 insertions(+), 34 deletions(-) diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 52434beab0b..083272a9f70 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -4805,6 +4805,24 @@ function isNonCanonicalStoredType(type: string): boolean { */ type PackagedBaseRegime = 'C'; +/** + * [#20910, ADR-0126 §2] The sanctioned routes a Regime C type's row supplies to + * its refusal: how to reach that type's clone-as-sibling, and how to reach its + * enable/disable switch — each spelled as the route a client calls (and its + * body), never as prose about the type. A row declares the primitives its type + * HAS and only those: the union refuses a row naming neither, so a type cannot + * be declared Regime C with nothing to prescribe. + */ +type PackagedBaseRegimeCRoutes = + | { readonly clone: string; readonly switchOff?: string } + | { readonly clone?: string; readonly switchOff: string }; + +/** [#20910] One type's row: its regime, and the routes that regime names for it. */ +interface PackagedBaseRegimeRow { + readonly regime: PackagedBaseRegime; + readonly routes: PackagedBaseRegimeCRoutes; +} + /** * Implements the per-domain contracts this class ACTUALLY provides (ADR-0076 * D10 — the facade never implemented the other domains; those live in their @@ -14804,19 +14822,60 @@ export class ObjectStackProtocolImplementation implements * {@link PACKAGED_BASE_REFUSAL_BY_REGIME} is keyed off it — never a second * list of type names, and never a type branch in the emitters' prose. * - * It carries `flow` only, deliberately, though ADR-0126 §3's Regime C row is - * longer — `flow`, `permission`, `action`, and pre-charted `tool` / `skill` - * / `position`. A type is declared here only once the Regime C sentence's - * paths are ITS served paths: that sentence names the `/automation` clone - * and switch routes, which exist for a flow alone. `action` has a switch at - * its own route and no clone at all (the action-clone half is not - * chartered, §8 item 2), and `permission` has its own clone machinery, so - * declaring either would advertise a route that does not exist for it — - * both keep the sentence they had until their own sanctioned paths are - * written into the table. + * [#20910] ONE regime, PER-TYPE routes. A row is the type's regime plus the + * sanctioned routes that regime gives THAT type: the regime decides the + * sentence's shape (locked; here is the sanctioned path), the row supplies + * the paths, and {@link PACKAGED_BASE_REFUSAL_BY_REGIME} builds the + * sentence from the row alone. ADR-0126 §3's Regime C types declared here, + * each with only the primitives it has, each route the one it is SERVED + * at: + * + * - `flow` — both (§7): the clone under a new name (§7.1, + * `POST /automation/:name/clone`, body `{ name, label }`, both keys + * required) and the enable/disable switch (§7.2, + * `POST /automation/:name/toggle`, body `{ enabled }`); + * - `action` — the switch only (§8 item 2, amendment ruling 3): + * `POST /actions/_activation/:object/:action`, body `{ enabled }`, the + * `:object` segment spelled `global` for an object-less action. ⛔ No + * clone: the action-clone half is not chartered, so a clone route named + * here would advertise one that does not exist; + * - `permission` — the clone only (§8 item 3, the landed lock-and-clone + * machinery): the "Clone" action on the permission set, which posts the + * copy to `POST /data/sys_permission_set` under a new name. Spelled as + * `plugin-security`'s own lock refusal spells that same path + * (`packaged-permission-set-lock.ts`), so one condition reads one way + * at both doors. + * + * Both switch routes are gated by the ONE §5 write-authority gate + * (`packages/runtime/src/domains/activation-gate.ts`), so both carry the + * same operator-only clause. Still absent: ADR-0126 §3's pre-charted + * `tool` / `skill` / `position` — no sanctioned path is built for them, and + * a row with no route does not compile ({@link PackagedBaseRegimeCRoutes}). */ - private static readonly PACKAGED_BASE_REGIME: Readonly> = { - flow: 'C', + private static readonly PACKAGED_BASE_REGIME: Readonly> = { + flow: { + regime: 'C', + routes: { + clone: 'POST /api/v1/automation/:name/clone, body {name, label}', + switchOff: 'POST /api/v1/automation/:name/toggle, body {enabled: false}; ' + + 'operator-only where one install serves several organizations', + }, + }, + action: { + regime: 'C', + routes: { + switchOff: 'POST /api/v1/actions/_activation/:object/:action, body {enabled: false}, ' + + ':object = global for an object-less action; ' + + 'operator-only where one install serves several organizations', + }, + }, + permission: { + regime: 'C', + routes: { + clone: 'the "Clone" action on the permission set, ' + + 'or POST /api/v1/data/sys_permission_set with a new name', + }, + }, }; /** @@ -14824,14 +14883,14 @@ export class ObjectStackProtocolImplementation implements * PER REGIME ({@link PACKAGED_BASE_REGIME}). A type with no declared regime * keeps the sentence the emitters carry inline, byte for byte. * - * Regime C (§2: behavioral — locked base, disable, clone-as-sibling) names - * its two sanctioned paths and cites the ADR that decided them: - * - * - **clone under a new name** (§7.1) — `POST /automation/:name/clone`, - * whose body `{ name, label }` requires both keys; - * - **the enable/disable switch** (§7.2) — `POST /automation/:name/toggle`, - * body `{ enabled }`, operator-gated per §5 where one install serves - * several organizations (the `group` / `isolated` postures). + * Regime C (§2: behavioral — locked base, disable, clone-as-sibling) states + * the lock, then names the sanctioned paths the type's ROW declares, in one + * fixed order — clone first, then the switch — and cites the ADR that + * decided them. [#20910] Nothing in it reads the type: a flow reads "clone + * it …, or switch it off …" because its row has both, an action reads only + * the switch and a permission set only the clone because theirs have one. + * A `flow`'s sentence is byte-identical to the one this builder replaced + * (pinned). * * ⛔ It does not name the `OS_METADATA_WRITABLE` hatch. The hatch still * opens this lock exactly as before ({@link isOverlayAllowed}), so which @@ -14840,25 +14899,38 @@ export class ObjectStackProtocolImplementation implements * administrator of an installed package cannot do that. * * Kept under the REST door's 500-character client-message bound, past - * which the tail is truncated: 411 characters before the item's name on - * save and 404 on removal, so a name of up to 88 characters arrives whole. + * which the tail is truncated. Characters before the item's name, save / + * removal: `flow` 411 / 404, `action` 380 / 373, `permission` 317 / 310 — + * so a name of up to 88 characters arrives whole for every row. */ private static readonly PACKAGED_BASE_REFUSAL_BY_REGIME: Readonly< - Record string> + Record< + PackagedBaseRegime, + (type: string, name: string, operation: 'save' | 'delete', routes: PackagedBaseRegimeCRoutes) => string + > > = { - C: (type, name, operation) => - `Metadata item '${type}/${name}' is provided by a code package, and its packaged base is locked ` - + (operation === 'delete' ? `against removal. ` : `against in-place edits. `) - + `Clone it under a new name to customize it (POST /api/v1/automation/:name/clone, body {name, label}), ` - + `or switch it off (POST /api/v1/automation/:name/toggle, body {enabled: false}; ` - + `operator-only where one install serves several organizations). ` - + `See docs/adr/0126-packaged-metadata-customization-model.md.`, + C: (type, name, operation, routes) => { + // [verb opening the sentence, verb after "or", the rest of the path] + const paths: Array = [ + ...(routes.clone + ? [['Clone', 'clone', ` it under a new name to customize it (${routes.clone})`] as const] + : []), + ...(routes.switchOff ? [['Switch', 'switch', ` it off (${routes.switchOff})`] as const] : []), + ]; + const prescription = paths + .map(([opening, following, rest], i) => (i === 0 ? opening : following) + rest) + .join(', or '); + return `Metadata item '${type}/${name}' is provided by a code package, and its packaged base is locked ` + + (operation === 'delete' ? `against removal. ` : `against in-place edits. `) + + `${prescription}. ` + + `See docs/adr/0126-packaged-metadata-customization-model.md.`; + }, }; /** - * The regime-chosen refusal sentence for `(type, name, operation)`, or - * `undefined` when the type declares no regime and the emitter keeps its - * own sentence. + * The regime-chosen refusal sentence for `(type, name, operation)`, built + * from the type's row, or `undefined` when the type declares no regime and + * the emitter keeps its own sentence. */ private static packagedBaseRegimeSentence( type: string, name: string, operation: 'save' | 'delete', @@ -14866,7 +14938,8 @@ export class ObjectStackProtocolImplementation implements const singular = PLURAL_TO_SINGULAR[type] ?? type; const regimes = ObjectStackProtocolImplementation.PACKAGED_BASE_REGIME; if (!Object.prototype.hasOwnProperty.call(regimes, singular)) return undefined; - return ObjectStackProtocolImplementation.PACKAGED_BASE_REFUSAL_BY_REGIME[regimes[singular]](singular, name, operation); + const row = regimes[singular]; + return ObjectStackProtocolImplementation.PACKAGED_BASE_REFUSAL_BY_REGIME[row.regime](singular, name, operation, row.routes); } /** From 34ee3dd3e94693d64539b4ac80c425c5d0d65480 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 1 Oct 2026 01:16:42 +0000 Subject: [PATCH 2/4] test(metadata-protocol): pin each Regime C row's refusal (WIP) Claude-Session: https://claude.ai/code/session_01Ujdtvqs7ree7WyQmEDwEnG Co-authored-by: Claude --- .../protocol.packaged-base-refusal.test.ts | 148 ++++++++++++++++-- 1 file changed, 136 insertions(+), 12 deletions(-) diff --git a/packages/metadata-protocol/src/protocol.packaged-base-refusal.test.ts b/packages/metadata-protocol/src/protocol.packaged-base-refusal.test.ts index 6c3d2cd0acd..a4ced951e3a 100644 --- a/packages/metadata-protocol/src/protocol.packaged-base-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.packaged-base-refusal.test.ts @@ -32,13 +32,14 @@ const shipped = (name: string, extra: Record = {}) => /** * Packaged artifacts of three regimes: behavioral (`flow`), overlay (`view`), rolled-back overlay (`page`) — - * plus `action`, which ADR-0126 §3 also puts in Regime C but whose sanctioned paths are not the flow's. + * plus `action` and `permission`, which ADR-0126 §3 also puts in Regime C, each with its own sanctioned path. */ const ARTIFACTS = new Map>([ ['flow', new Map([['pkg_flow', shipped('pkg_flow', { type: 'autolaunched', nodes: [], edges: [] })]])], ['view', new Map([['pkg_view', shipped('pkg_view')]])], ['page', new Map([['pkg_page', shipped('pkg_page')]])], ['action', new Map([['pkg_action', shipped('pkg_action')]])], + ['permission', new Map([['pkg_perm', shipped('pkg_perm')]])], ]); function protocolOn(environmentId: string | undefined): ObjectStackProtocolImplementation { @@ -132,10 +133,11 @@ describe('packagedBaseRefusal — the /meta door\'s locked-base verdict, handed * A Regime C type (`flow`) names Regime C's sanctioned paths — the clone under * a new name (§7.1) and the enable/disable switch (§7.2) — cites ADR-0126, and * names neither the `OS_METADATA_WRITABLE` hatch nor a redeploy an installed - * package's administrator cannot make. Every other type's sentence is - * byte-identical to what it was (the controls): `page` has no regime, and - * `action` is Regime C on paper but its sanctioned paths are not the flow's - * routes, so it keeps its sentence until its own paths are declared. + * package's administrator cannot make. [#20910] So do `action` and + * `permission`, from their own rows: an action names its activation switch and + * no clone (the action-clone half is not chartered), a permission set names its + * clone and no switch. Every type with no regime keeps its sentence byte for + * byte (the control: `page`). */ describe('packagedBaseRefusal — the sentence is chosen per ADR-0126 regime', () => { const CLONE = 'POST /api/v1/automation/:name/clone'; @@ -199,13 +201,135 @@ describe('packagedBaseRefusal — the sentence is chosen per ADR-0126 regime', ( expect(refusal.message).toBe(LEGACY_SAVE('page', 'pkg_page')); }); - it('control: `action` — Regime C on paper, with sanctioned paths that are not the flow\'s — keeps both sentences byte for byte', () => { - const p = protocolOn('env_1'); - const save: any = p.packagedBaseRefusal({ type: 'action', name: 'pkg_action', operation: 'save' }); - const del: any = p.packagedBaseRefusal({ type: 'action', name: 'pkg_action', operation: 'delete' }); - expect(shape(save)).toEqual({ code: 'NOT_OVERRIDABLE', status: 403 }); + it('a regime-less type\'s removal sentence is unchanged too (`object`, no overlay merge at read)', () => { + // `page` merges its overlay at read, so its removal is the #6960 + // carve-out and never refused; `object` is refused, and keeps its line. + const registry = { getArtifactItem: (type: string, name: string) => (type === 'object' ? shipped(name) : undefined) }; + const p = new ObjectStackProtocolImplementation({ registry } as never, () => new Map(), 'env_1'); + const del: any = p.packagedBaseRefusal({ type: 'object', name: 'pkg_object', operation: 'delete' }); expect(shape(del)).toEqual({ code: 'NOT_OVERRIDABLE', status: 403 }); - expect(save.message).toBe(LEGACY_SAVE('action', 'pkg_action')); - expect(del.message).toBe(LEGACY_DELETE('action', 'pkg_action')); + expect(del.message).toBe(LEGACY_DELETE('object', 'pkg_object')); + }); +}); + +/** + * [#20910, ADR-0126 §2 / §3] ONE regime, PER-TYPE routes: each Regime C type's + * refusal is built from its own row, and names only the primitives that type + * has — on save AND on removal. + */ +describe('packagedBaseRefusal — each Regime C type names its OWN sanctioned path', () => { + const ADR_0126 = 'docs/adr/0126-packaged-metadata-customization-model.md'; + const OPERATOR_ONLY = 'operator-only where one install serves several organizations'; + + /** The opening sentence every Regime C refusal shares — the regime's shape, not the type's. */ + const LOCKED = (type: string, name: string, operation: 'save' | 'delete') => + `Metadata item '${type}/${name}' is provided by a code package, and its packaged base is locked ` + + (operation === 'delete' ? 'against removal.' : 'against in-place edits.'); + + const refusal = ( + type: string, name: string, operation: 'save' | 'delete', environmentId: string | undefined = 'env_1', + ): any => protocolOn(environmentId).packagedBaseRefusal({ type, name, operation }); + /** The same verdict on a host-config kernel (no environment id) — not the default parameter. */ + const refusalOnHostConfig = (type: string, name: string, operation: 'save' | 'delete'): any => + protocolOn(undefined).packagedBaseRefusal({ type, name, operation }); + const refusalOn = (environmentId: string | undefined, type: string, name: string, operation: 'save' | 'delete') => + (environmentId === undefined ? refusalOnHostConfig(type, name, operation) : refusal(type, name, operation, environmentId)); + + /** What every Regime C refusal owes, whatever the type: the lock, the ADR, no hatch, no redeploy. */ + const expectRegimeC = (r: any, type: string, name: string, operation: 'save' | 'delete') => { + expect(shape(r)).toEqual({ code: 'NOT_OVERRIDABLE', status: 403 }); + const message = String(r.message); + expect(message.startsWith(`${LOCKED(type, name, operation)} `)).toBe(true); + expect(message.endsWith(`See ${ADR_0126}.`)).toBe(true); + expect(message).not.toContain('OS_METADATA_WRITABLE'); + expect(message).not.toContain('redeploy'); + expect(message).not.toContain('0005-metadata-customization-overlay'); + return message; + }; + + it('`flow` — the sentence is byte-identical to the one the row table replaced, on save and on removal', () => { + // Spelled out literally, NOT through the builder: this is the pin that + // the table refactor moved no byte of the flow sentence. + expect(refusal('flow', 'pkg_flow', 'save').message).toBe( + "Metadata item 'flow/pkg_flow' is provided by a code package, and its packaged base is locked " + + 'against in-place edits. Clone it under a new name to customize it (POST /api/v1/automation/:name/clone, ' + + 'body {name, label}), or switch it off (POST /api/v1/automation/:name/toggle, body {enabled: false}; ' + + 'operator-only where one install serves several organizations). ' + + 'See docs/adr/0126-packaged-metadata-customization-model.md.', + ); + expect(refusal('flow', 'pkg_flow', 'delete').message).toBe( + "Metadata item 'flow/pkg_flow' is provided by a code package, and its packaged base is locked " + + 'against removal. Clone it under a new name to customize it (POST /api/v1/automation/:name/clone, ' + + 'body {name, label}), or switch it off (POST /api/v1/automation/:name/toggle, body {enabled: false}; ' + + 'operator-only where one install serves several organizations). ' + + 'See docs/adr/0126-packaged-metadata-customization-model.md.', + ); + }); + + for (const environmentId of [undefined, 'env_1']) { + for (const operation of ['save', 'delete'] as const) { + it(`\`action\` — ${operation} names the activation switch and no clone ` + + `(${environmentId ? 'environment' : 'host-config'} kernel)`, () => { + const message = expectRegimeC(refusalOn(environmentId, 'action', 'pkg_action', operation), 'action', 'pkg_action', operation); + expect(message).toContain( + 'Switch it off (POST /api/v1/actions/_activation/:object/:action, body {enabled: false}, ' + + `:object = global for an object-less action; ${OPERATOR_ONLY}).`, + ); + // No clone is chartered for an action (ADR-0126 §8 item 2): none is advertised. + expect(message.toLowerCase()).not.toContain('clone'); + expect(message).not.toContain('/automation/'); + }); + } + + it(`\`permission\` — save names its clone and no switch (${environmentId ? 'environment' : 'host-config'} kernel)`, () => { + const message = expectRegimeC(refusalOn(environmentId, 'permission', 'pkg_perm', 'save'), 'permission', 'pkg_perm', 'save'); + expect(message).toContain( + 'Clone it under a new name to customize it (the "Clone" action on the permission set, ' + + 'or POST /api/v1/data/sys_permission_set with a new name).', + ); + expect(message.toLowerCase()).not.toContain('switch it off'); + expect(message).not.toContain('_activation'); + expect(message).not.toContain('/automation/'); + }); + } + + it('`permission` removal stays the #6960 carve-out — the row adds no refusal where there was none', () => { + // `permission` merges its overlay at read (`supportsOverlay: true`), so + // removing its overlay row is repair, never refused on this ground. + expect(refusal('permission', 'pkg_perm', 'delete')).toBeNull(); + expect(refusalOnHostConfig('permission', 'pkg_perm', 'delete')).toBeNull(); + }); + + it('the /meta doors throw the row\'s sentence for an action, on save and on removal (one emitter)', async () => { + const p = protocolOn('env_1'); + const thrownBy = (run: Promise) => run.then(() => undefined, (e: any) => e); + const save: any = await thrownBy(p.saveMetaItem({ type: 'action', name: 'pkg_action', item: { name: 'pkg_action', label: 'x' } })); + const del: any = await thrownBy(p.deleteMetaItem({ type: 'action', name: 'pkg_action' })); + expect({ ...shape(save), message: save?.message }).toEqual({ + ...shape(refusal('action', 'pkg_action', 'save')), message: refusal('action', 'pkg_action', 'save').message, + }); + expect({ ...shape(del), message: del?.message }).toEqual({ + ...shape(refusal('action', 'pkg_action', 'delete')), message: refusal('action', 'pkg_action', 'delete').message, + }); + }); + + it('every row arrives whole through the REST door\'s 500-character bound for an 88-character name', () => { + // `truncateClientMessage` (packages/rest/src/error-response.ts) keeps a + // message only while it is SHORTER than 500 characters; past that the + // tail — where the routes and the ADR citation sit — is cut. + const longName = `pkg_${'x'.repeat(84)}`; + expect(longName).toHaveLength(88); + const registry = { + getArtifactItem: (type: string, name: string) => + (['flow', 'action', 'permission'].includes(type) && name === longName ? shipped(name) : undefined), + }; + const p = new ObjectStackProtocolImplementation({ registry } as never, () => new Map(), 'env_1'); + for (const [type, operation] of [ + ['flow', 'save'], ['flow', 'delete'], ['action', 'save'], ['action', 'delete'], ['permission', 'save'], + ] as const) { + const message = String((p.packagedBaseRefusal({ type, name: longName, operation }) as any).message); + expect(message.length, `${type} ${operation}`).toBeLessThan(500); + expect(message.endsWith(`See ${ADR_0126}.`), `${type} ${operation}`).toBe(true); + } }); }); From 70c33661ba15925c2dccebe8ad18761db76f5811 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 1 Oct 2026 01:18:26 +0000 Subject: [PATCH 3/4] test(rest): pin the action and permission refusals at the /meta door; changeset (WIP) Claude-Session: https://claude.ai/code/session_01Ujdtvqs7ree7WyQmEDwEnG Co-authored-by: Claude --- .../20910-regime-c-action-permission-paths.md | 18 ++ packages/metadata-protocol/src/protocol.ts | 5 +- ...packaged-action-permission-refusal.test.ts | 155 ++++++++++++++++++ 3 files changed, 176 insertions(+), 2 deletions(-) create mode 100644 .changeset/20910-regime-c-action-permission-paths.md create mode 100644 packages/rest/src/rest-meta-packaged-action-permission-refusal.test.ts diff --git a/.changeset/20910-regime-c-action-permission-paths.md b/.changeset/20910-regime-c-action-permission-paths.md new file mode 100644 index 00000000000..f95aaf8cf10 --- /dev/null +++ b/.changeset/20910-regime-c-action-permission-paths.md @@ -0,0 +1,18 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): the refusal of an in-place edit of a packaged action or permission set names that type's own sanctioned path, and a packaged action's removal names one too, not a redeploy or `OS_METADATA_WRITABLE` (#20910) + +Clause-②: no + +ADR-0126 puts `action` and `permission` in Regime C beside `flow`: the packaged base is locked, and the refusal names the sanctioned path. Until now only a flow's refusal did. An in-place `PUT /api/v1/meta/action/:name` or `PUT /api/v1/meta/permission/:name` onto an item a code package ships, without `?package=`, was refused with `403 NOT_OVERRIDABLE` and "Edit the source artifact and redeploy, or set OS_METADATA_WRITABLE to grant a runtime escape hatch", citing ADR-0005. A `DELETE /api/v1/meta/action/:name` of a packaged action was refused with a sentence that named no path at all. + +Each refusal is now built from its type's row in the protocol's regime table, names only the primitives that type has, and cites ADR-0126: + +- a packaged action, on save and on removal: switch it off with `POST /api/v1/actions/_activation/:object/:action` and `{ enabled: false }` (`:object` is `global` for an object-less action). Where one install serves several organizations, only the platform operator can use the switch. No clone is named: cloning an action is not a sanctioned path. +- a packaged permission set, on save: clone it under a new name, with the "Clone" action on the permission set or `POST /api/v1/data/sys_permission_set` with a new name. That is the same wording the permission-set lock in `@objectstack/plugin-security` already uses. + +A packaged flow's refusal is byte-for-byte unchanged. The status, the code and which writes are refused are unchanged too: `OS_METADATA_WRITABLE` still opens the lock as before, and removing a permission set's overlay row is still allowed, as repair. Every type with no declared regime reads exactly as before. + +These sentences are answered where the metadata protocol's package door runs, which is an environment-scoped kernel. Two other refusals are left as they were. A write that names the shipping package with `?package=` is refused with `403 ITEM_LOCKED` by a separate limb. On a kernel whose `/meta` protocol is not environment-scoped, a packaged action's write is refused one layer down, by the metadata repository, with its own sentence. diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 083272a9f70..95cac9c9bab 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -14900,8 +14900,9 @@ export class ObjectStackProtocolImplementation implements * * Kept under the REST door's 500-character client-message bound, past * which the tail is truncated. Characters before the item's name, save / - * removal: `flow` 411 / 404, `action` 380 / 373, `permission` 317 / 310 — - * so a name of up to 88 characters arrives whole for every row. + * removal: `flow` 411 / 404, `action` 365 / 358, `permission` 317 (its + * removal is the #6960 carve-out, never refused on this ground) — so a + * name of up to 88 characters arrives whole for every row (pinned). */ private static readonly PACKAGED_BASE_REFUSAL_BY_REGIME: Readonly< Record< diff --git a/packages/rest/src/rest-meta-packaged-action-permission-refusal.test.ts b/packages/rest/src/rest-meta-packaged-action-permission-refusal.test.ts new file mode 100644 index 00000000000..9b1ca12b6e4 --- /dev/null +++ b/packages/rest/src/rest-meta-packaged-action-permission-refusal.test.ts @@ -0,0 +1,155 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#20910, ADR-0126 §2 / §3] `PUT` / `DELETE /api/v1/meta/:type/:name` on a + * PACKAGED action and a PACKAGED permission set — the refusal a client actually + * reads names that type's OWN sanctioned path, not the `OS_METADATA_WRITABLE` + * hatch and not a redeploy. + * + * ADR-0126 §3 puts both in Regime C beside `flow`, and §2 requires the Regime C + * refusal to name the sanctioned path. Each type's row in the metadata + * protocol's regime table supplies its routes, so the two read differently from + * the flow and from each other: + * + * - an ACTION has the activation switch (§8 item 2, + * `POST /api/v1/actions/_activation/:object/:action`) and no clone — the + * action-clone half is not chartered; + * - a PERMISSION SET has its clone (§8 item 3, the "Clone" action, which posts + * to `POST /api/v1/data/sys_permission_set`) and no switch named here. + * + * The protocol-side pins are + * `packages/metadata-protocol/src/protocol.packaged-base-refusal.test.ts`; this + * file answers the half a protocol-level test cannot: the REAL `/meta` routes + * relay the sentence whole — `403`, `NOT_OVERRIDABLE`, the path named, no hatch + * — past the door's 500-character client-message bound, which truncates the + * tail (where the routes and the ADR citation sit). + * + * Same harness as `rest-meta-packaged-flow-refusal.test.ts`: a REAL + * `ObjectStackProtocolImplementation` over a REAL `SchemaRegistry`, the packaged + * items registered under a package id the way an artifact loader registers + * them. Run on an ENVIRONMENT kernel, where `saveMetaItem` / `deleteMetaItem` + * ask the package door; the refusals land before any store is touched. + */ + +import { describe, it, expect } from 'vitest'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { SchemaRegistry } from '@objectstack/objectql'; +import { RestServer } from './rest-server.js'; + +const PACKAGE_ID = 'com.example.pkg'; +const PACKAGED_ACTION = 'pkg_approve'; +const PACKAGED_PERMISSION = 'pkg_perm'; +/** 88 characters — the longest name the flow row (411 before the name) still delivers whole. */ +const LONG_ACTION = `pkg_${'x'.repeat(84)}`; + +function createMockServer() { + const noop = () => {}; + return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; +} + +function makeRes() { + const res: any = { + write: () => true, end: () => {}, + header: () => res, setHeader: () => res, + status: (code: number) => { res._status = code; return res; }, + json: (body: any) => { res._json = body; return res; }, + }; + return res; +} + +function boot() { + const registry = new SchemaRegistry({ multiTenant: false, collisionPolicy: 'error' }); + for (const name of [PACKAGED_ACTION, LONG_ACTION]) { + registry.registerItem('action', { name, label: 'Approve', type: 'script', target: 'approve_fn' }, 'name', PACKAGE_ID); + } + registry.registerItem('permission', { name: PACKAGED_PERMISSION, label: 'Contributor', objects: {} }, 'name', PACKAGE_ID); + const protocol = new ObjectStackProtocolImplementation( + { registry, findOne: async () => null } as never, () => new Map(), 'env_1', + ); + const rest = new RestServer(createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any); + // The write doors demand `manage_metadata`; held here, so every 403 below is the LOCK. + (rest as any).resolveExecCtx = async () => ({ userId: 'u_admin', systemPermissions: ['manage_metadata'] }); + rest.registerRoutes(); + const route = (method: string) => { + const found = rest.getRoutes().find((r: any) => r.method === method && r.path === '/api/v1/meta/:type/:name'); + if (!found) throw new Error(`${method} /api/v1/meta/:type/:name is not registered`); + return found; + }; + const call = async (method: 'PUT' | 'DELETE', type: string, name: string, body?: unknown) => { + const res = makeRes(); + await route(method).handler({ method, params: { type, name }, query: {}, headers: {}, body } as any, res); + // The door's 4xx envelope: `code` beside the client-facing `error` text. + return { status: res._status, code: res._json?.code, message: res._json?.error }; + }; + return { call }; +} + +/** What every Regime C refusal owes at the wire, whatever the type. */ +const expectRegimeC = (message: unknown, type: string, name: string, operation: 'save' | 'delete') => { + const text = String(message); + expect(text.startsWith( + `Metadata item '${type}/${name}' is provided by a code package, and its packaged base is locked ` + + (operation === 'delete' ? 'against removal. ' : 'against in-place edits. '), + )).toBe(true); + expect(text).not.toContain('OS_METADATA_WRITABLE'); + expect(text).not.toContain('redeploy'); + // Arrived whole: the REST door truncates a client message with a trailing ellipsis. + expect(text.endsWith('See docs/adr/0126-packaged-metadata-customization-model.md.')).toBe(true); + return text; +}; + +const ACTION_SWITCH = 'Switch it off (POST /api/v1/actions/_activation/:object/:action, body {enabled: false}'; +const PERMISSION_CLONE = 'Clone it under a new name to customize it (the "Clone" action on the permission set, ' + + 'or POST /api/v1/data/sys_permission_set with a new name).'; + +describe('PUT / DELETE /api/v1/meta/action/:name on a packaged action — the refusal names the activation switch', () => { + it('PUT answers 403 NOT_OVERRIDABLE naming the switch, no clone, no hatch', async () => { + const { call } = boot(); + const r = await call('PUT', 'action', PACKAGED_ACTION, { + name: PACKAGED_ACTION, label: 'Changed in place', type: 'script', target: 'approve_fn', + }); + expect(r.status).toBe(403); + expect(r.code).toBe('NOT_OVERRIDABLE'); + const text = expectRegimeC(r.message, 'action', PACKAGED_ACTION, 'save'); + expect(text).toContain(ACTION_SWITCH); + expect(text.toLowerCase()).not.toContain('clone'); + }); + + it('DELETE answers 403 NOT_OVERRIDABLE naming the switch too — a removal names a path', async () => { + const { call } = boot(); + const r = await call('DELETE', 'action', PACKAGED_ACTION); + expect(r.status).toBe(403); + expect(r.code).toBe('NOT_OVERRIDABLE'); + const text = expectRegimeC(r.message, 'action', PACKAGED_ACTION, 'delete'); + expect(text).toContain(ACTION_SWITCH); + }); + + it('an 88-character action name still arrives whole, ADR citation included', async () => { + const { call } = boot(); + expect(LONG_ACTION).toHaveLength(88); + const r = await call('DELETE', 'action', LONG_ACTION); + expect(r.code).toBe('NOT_OVERRIDABLE'); + expectRegimeC(r.message, 'action', LONG_ACTION, 'delete'); + }); +}); + +describe('PUT /api/v1/meta/permission/:name on a packaged permission set — the refusal names its clone', () => { + it('PUT answers 403 NOT_OVERRIDABLE naming the clone, no switch, no hatch', async () => { + const { call } = boot(); + const r = await call('PUT', 'permission', PACKAGED_PERMISSION, { + name: PACKAGED_PERMISSION, label: 'Changed in place', objects: {}, + }); + expect(r.status).toBe(403); + expect(r.code).toBe('NOT_OVERRIDABLE'); + const text = expectRegimeC(r.message, 'permission', PACKAGED_PERMISSION, 'save'); + expect(text).toContain(PERMISSION_CLONE); + expect(text.toLowerCase()).not.toContain('switch it off'); + }); + + it('DELETE is not refused on this ground — a permission set\'s overlay removal is repair (the #6960 carve-out)', async () => { + const { call } = boot(); + const r = await call('DELETE', 'permission', PACKAGED_PERMISSION); + expect(r.code).not.toBe('NOT_OVERRIDABLE'); + expect(r.status ?? 200).not.toBe(403); + }); +}); From 9c169378a40971eb723e266d26be0482fef5fb27 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 1 Oct 2026 02:42:42 +0000 Subject: [PATCH 4/4] fix(metadata-protocol): one regime table read by the package door, the repository's type door and its named-base limb Claude-Session: https://claude.ai/code/session_01Ujdtvqs7ree7WyQmEDwEnG Co-authored-by: Claude --- .../20910-regime-c-action-permission-paths.md | 19 +- content/docs/concepts/metadata-lifecycle.mdx | 20 +- .../src/packaged-base-regime.ts | 186 ++++++++++++++++++ .../protocol.delete-rewrap-envelope.test.ts | 13 +- .../protocol.packaged-base-refusal.test.ts | 29 +++ packages/metadata-protocol/src/protocol.ts | 177 ++--------------- ...ata-repository.package-writability.test.ts | 167 +++++++++++++++- .../src/sys-metadata-repository.ts | 51 ++++- ...packaged-action-permission-refusal.test.ts | 70 ++++++- 9 files changed, 543 insertions(+), 189 deletions(-) create mode 100644 packages/metadata-protocol/src/packaged-base-regime.ts diff --git a/.changeset/20910-regime-c-action-permission-paths.md b/.changeset/20910-regime-c-action-permission-paths.md index f95aaf8cf10..730eae421d1 100644 --- a/.changeset/20910-regime-c-action-permission-paths.md +++ b/.changeset/20910-regime-c-action-permission-paths.md @@ -2,17 +2,22 @@ '@objectstack/metadata-protocol': patch --- -fix(metadata-protocol): the refusal of an in-place edit of a packaged action or permission set names that type's own sanctioned path, and a packaged action's removal names one too, not a redeploy or `OS_METADATA_WRITABLE` (#20910) +fix(metadata-protocol): every refusal of an in-place edit of a packaged flow, action or permission set names that type's own sanctioned path, at every door, and a packaged action's removal names one too, not a redeploy or `OS_METADATA_WRITABLE` (#20910) Clause-②: no -ADR-0126 puts `action` and `permission` in Regime C beside `flow`: the packaged base is locked, and the refusal names the sanctioned path. Until now only a flow's refusal did. An in-place `PUT /api/v1/meta/action/:name` or `PUT /api/v1/meta/permission/:name` onto an item a code package ships, without `?package=`, was refused with `403 NOT_OVERRIDABLE` and "Edit the source artifact and redeploy, or set OS_METADATA_WRITABLE to grant a runtime escape hatch", citing ADR-0005. A `DELETE /api/v1/meta/action/:name` of a packaged action was refused with a sentence that named no path at all. +ADR-0126 puts `flow`, `action` and `permission` in Regime C. The packaged base is locked, and the refusal names the sanctioned path. Until now only a flow's package-less refusal did, and only at one of the three places that refuse such a write. The other places prescribed "Edit the source artifact and redeploy, or set OS_METADATA_WRITABLE …" or "Set OS_METADATA_WRITABLE to enable additional types at runtime". A packaged action's removal named no path at all. -Each refusal is now built from its type's row in the protocol's regime table, names only the primitives that type has, and cites ADR-0126: +There is now one regime table, and each type's row names only the primitives that type has: -- a packaged action, on save and on removal: switch it off with `POST /api/v1/actions/_activation/:object/:action` and `{ enabled: false }` (`:object` is `global` for an object-less action). Where one install serves several organizations, only the platform operator can use the switch. No clone is named: cloning an action is not a sanctioned path. -- a packaged permission set, on save: clone it under a new name, with the "Clone" action on the permission set or `POST /api/v1/data/sys_permission_set` with a new name. That is the same wording the permission-set lock in `@objectstack/plugin-security` already uses. +- a packaged flow: clone it under a new name with `POST /api/v1/automation/:name/clone` and `{ name, label }`, or switch it off with `POST /api/v1/automation/:name/toggle` and `{ enabled: false }`; +- a packaged action: switch it off with `POST /api/v1/actions/_activation/:object/:action` and `{ enabled: false }` (`:object` is `global` for an object-less action). No clone is named, because cloning an action is not a sanctioned path; +- a packaged permission set: clone it under a new name, with the "Clone" action on the permission set or `POST /api/v1/data/sys_permission_set` with a new name. This is the same wording the permission-set lock in `@objectstack/plugin-security` already uses. -A packaged flow's refusal is byte-for-byte unchanged. The status, the code and which writes are refused are unchanged too: `OS_METADATA_WRITABLE` still opens the lock as before, and removing a permission set's overlay row is still allowed, as repair. Every type with no declared regime reads exactly as before. +The switches are operator-only where one install serves several organizations. Every refusal cites ADR-0126. All three places that refuse such a write read the same table: -These sentences are answered where the metadata protocol's package door runs, which is an environment-scoped kernel. Two other refusals are left as they were. A write that names the shipping package with `?package=` is refused with `403 ITEM_LOCKED` by a separate limb. On a kernel whose `/meta` protocol is not environment-scoped, a packaged action's write is refused one layer down, by the metadata repository, with its own sentence. +- **`403 NOT_OVERRIDABLE` on an environment-scoped kernel.** This covers `PUT /api/v1/meta/:type/:name` without `?package=`, and for a flow or an action `DELETE` too. +- **`403 NOT_OVERRIDABLE` where the `/meta` protocol is not environment-scoped**, for example the default local `pnpm dev` boot. The metadata repository refuses that write one layer down, and now with the same sentence. +- **`403 ITEM_LOCKED` for a write that names the read-only package with `?package=`, while `OS_METADATA_WRITABLE` is not set for the type.** The sentence now opens "Cannot overlay 'TYPE' in package 'ID': that package is read-only, and its packaged base is locked against in-place edits." and then names the path. + +A packaged flow's package-less sentence is byte-for-byte unchanged. Statuses, codes, `lockSource`, `packageId`, `docs` and which writes are refused are unchanged too. `OS_METADATA_WRITABLE` still opens the lock for a write that names no package. The `ITEM_LOCKED` refusal given while the variable IS set reads exactly as before. Removing a permission set's overlay row is still allowed, as repair. Every type with no declared regime reads exactly as before, at every door. diff --git a/content/docs/concepts/metadata-lifecycle.mdx b/content/docs/concepts/metadata-lifecycle.mdx index 404ea75dd97..be6ce4af08c 100644 --- a/content/docs/concepts/metadata-lifecycle.mdx +++ b/content/docs/concepts/metadata-lifecycle.mdx @@ -91,8 +91,10 @@ The `seq` is the single source of truth for ordering on the server. Note that th Every runtime-authored item lives inside a **writable package** — there are no orphans. Code-defined and installed packages are **read-only** at runtime, so the first step of any Studio/API authoring action is to target a *writable* package (a -"base"): a create/update aimed at a read-only package is rejected, and the author -is asked to pick or create a writable base first. New objects, fields, views, and +"base"): a create aimed at a read-only package is rejected, and the author is asked +to pick or create a writable base first. An in-place edit of an item the read-only +package ships is refused too; for a flow, an action or a permission set the refusal +names that type's sanctioned path instead (see [ADR-0126](#packaged-flows-actions-and-permission-sets-adr-0126)). New objects, fields, views, and flows are namespaced into that package — which is exactly what `os package publish` later ships. See [ADR-0070](https://github.com/objectstack-ai/objectstack/blob/main/docs/adr/0070-package-first-authoring.md). @@ -109,7 +111,7 @@ In shared-database multi-tenancy, **most metadata types must not be per-org cust | `view`, `dashboard`, `report`, `email_template`, `translation` | ✅ | Pure rendering / render-time content. Per-org customization is safe. | | `flow` | ❌ | Flows carry execution side-effects (events, jobs, audit), and the `flow` entry declares `supportsOverlay: false` — the loader cannot merge a per-org flow overlay, so the write permission granted a write nothing could read back: an org-scoped flow overlay wrote successfully and **lost its binding on the next cold start**. Rolled back (#6283) so the silent phantom is a loud `403 not_overridable` at the moment of the write. **`allowRuntimeCreate` stays `true`** — a tenant may still author a *brand-new* flow through the runtime API (ADR-0070 package-first authoring); what is closed is overlaying a *packaged* flow per org. | | `agent` | ❌ | Agents are platform-owned and closed to third parties (ADR-0063 §2) — no per-org agent fork. | -| `permission`, `position` | ❌ | Authorization correctness — a per-org overlay of a packaged permission set *is* silent privilege drift (ADR-0005's security row). Rolled back from an unratified `true` by the 2026-08-08 maintainer ruling (#6483); `position` takes the amendment's `false` default for new types. **`allowRuntimeCreate` stays `true`**: runtime-created sets (including package-bound rows materialized through the metadata door) keep working, while an admin-door edit of a *code-declared* set refuses with `403 not_overridable` — edit the package and re-publish (ADR-0086 two-doors). | +| `permission`, `position` | ❌ | Authorization correctness — a per-org overlay of a packaged permission set *is* silent privilege drift (ADR-0005's security row). Rolled back from an unratified `true` by the 2026-08-08 maintainer ruling (#6483); `position` takes the amendment's `false` default for new types. **`allowRuntimeCreate` stays `true`**: runtime-created sets (including package-bound rows materialized through the metadata door) keep working, while an admin-door edit of a *code-declared* set refuses with `403 not_overridable`, naming the sanctioned path: clone the set under a new name and edit the clone ([ADR-0126](#packaged-flows-actions-and-permission-sets-adr-0126)). The package's own author still changes the declaration in the package and re-publishes (ADR-0086 two-doors). | | `object` | ❌ | Defines the table schema. Overriding a packaged object would break existing data — but `allowRuntimeCreate: true`, so tenants *can* author brand-new objects, **and this is also how a new field is added** (write the object with the field in `fields`). | | `field` | ❌ | **Also `allowRuntimeCreate: false` since protocol 17** (#7893). A field is not a standalone artifact — fields are authored inside their object (`ObjectSchema.fields`), so a `field` write minted a *separate* `sys_metadata` row keyed `('field','.')` that nothing ever composed into the parent: `PUT /meta/field/showcase_task.zz_probe` answered 200 `state=active`, the row read back `_diagnostics.valid: true`, and `GET /meta/object/showcase_task` never listed the field. The door is closed rather than bridged: add a field by writing its **object** (`PUT /meta/object/:name`, or `**/*.object.ts` and redeploy), which both persists and composes. Existing rows are untouched — they were inert before the change too — and remain deletable. | | `datasource` | ❌ | Connection strings; multi-tenant isolation is enforced at a higher layer. (`allowRuntimeCreate: true` — the datasource wizard persists `origin: 'runtime'` rows.) | @@ -126,6 +128,18 @@ The gate is **two-tier** — `allowOrgOverride: false` is not the same as "no ru See [ADR-0005](https://github.com/objectstack-ai/objectstack/blob/main/docs/adr/0005-metadata-customization-overlay.md) for the full design and amendments. +### Packaged flows, actions and permission sets (ADR-0126) + +`flow`, `action` and `permission` are behavioral types, in Regime C of [ADR-0126](https://github.com/objectstack-ai/objectstack/blob/main/docs/adr/0126-packaged-metadata-customization-model.md). A packaged item of one of these types is locked against in-place edits (and, for a flow or an action, against removal). The refusal names the type's sanctioned path, not a redeploy or `OS_METADATA_WRITABLE`, and each type names only the routes it has: + +| Type | Sanctioned path the refusal names | +| :--- | :--- | +| `flow` | Clone it under a new name (`POST /api/v1/automation/:name/clone`, body `{name, label}`), or switch it off (`POST /api/v1/automation/:name/toggle`, body `{enabled: false}`). | +| `action` | Switch it off (`POST /api/v1/actions/_activation/:object/:action`, body `{enabled: false}`; `:object` is `global` for an object-less action). No clone is offered. | +| `permission` | Clone it under a new name: the "Clone" action on the permission set, or `POST /api/v1/data/sys_permission_set` with a new name. | + +The switches are operator-only where one install serves several organizations. The refusal names the same path whichever layer answers it: `403 NOT_OVERRIDABLE` for a write that names no base, and `403 ITEM_LOCKED` for one that names the read-only package. Which writes are refused, and with which code, is unchanged. + --- ## Conflict handling diff --git a/packages/metadata-protocol/src/packaged-base-regime.ts b/packages/metadata-protocol/src/packaged-base-regime.ts new file mode 100644 index 00000000000..7f06cc1d9f9 --- /dev/null +++ b/packages/metadata-protocol/src/packaged-base-regime.ts @@ -0,0 +1,186 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#20819, #20910, ADR-0126 §2 / §3] THE packaged-base regime table — the one + * declaration of which metadata types' locked-base refusals speak for their + * ADR-0126 customization regime, and of the sanctioned routes each such type + * HAS. Every door that refuses an in-place write onto a packaged item of one of + * these types builds its prescription from this table, and from nothing else: + * + * - the metadata protocol's package door (`protocol.ts` + * `refusePackagedBaseOverride` / `refusePackagedBaseRemoval`), on an + * environment-scoped kernel — {@link packagedBaseRegimeSentence}; + * - the repository's type door (`SysMetadataRepository.assertAllowed`), the + * same refusal one layer down where the `/meta` protocol is not + * environment-scoped — {@link packagedBaseRegimeSentence} too; + * - the named-base `ITEM_LOCKED` limb (`SysMetadataRepository + * .readOnlyBaseOverrideError`) with the hatch closed — {@link + * packagedBaseRegimePrescription}. + * + * It lives in its own module because the two files that read it import each + * other one way only (`protocol.ts` imports the repository): a table declared + * in either would make the other reach back for it. Internal — not exported + * from the package entry. + * + * ## Why it exists + * + * ADR-0126 §2 requires a Regime C refusal to name the sanctioned path — "in-place + * edit refused loudly at the write door, the refusal naming the sanctioned path" + * — and §10 gives the reason: a locked base that refuses with its sanctioned + * path in the message is what keeps AI-written metadata from guessing. The + * regime is recorded nowhere else in code (the ADR's table is prose, and the + * registry entries carry no regime field), so this map is its one declaration + * for the refusal — never a second list of type names, and never a type branch + * in any door's prose. + * + * ## ONE regime, PER-TYPE routes + * + * A row is the type's regime plus the sanctioned routes that regime gives THAT + * type: the regime decides the sentence's shape (locked; here is the sanctioned + * path), the row supplies the paths, and the builders below compose the sentence + * from the row alone. ADR-0126 §3's Regime C types declared here, each with only + * the primitives it has, each route the one it is SERVED at: + * + * - `flow` — both (§7): the clone under a new name (§7.1, + * `POST /automation/:name/clone`, body `{ name, label }`, both keys required) + * and the enable/disable switch (§7.2, `POST /automation/:name/toggle`, body + * `{ enabled }`); + * - `action` — the switch only (§8 item 2, amendment ruling 3): + * `POST /actions/_activation/:object/:action`, body `{ enabled }`, the + * `:object` segment spelled `global` for an object-less action. ⛔ No clone: + * the action-clone half is not chartered, so a clone route named here would + * advertise one that does not exist; + * - `permission` — the clone only (§8 item 3, the landed lock-and-clone + * machinery): the "Clone" action on the permission set, which posts the copy + * to `POST /data/sys_permission_set` under a new name. Spelled as + * `plugin-security`'s own lock refusal spells that same path + * (`packaged-permission-set-lock.ts`), so one condition reads one way at + * every door. + * + * Both switch routes are gated by the ONE §5 write-authority gate + * (`packages/runtime/src/domains/activation-gate.ts`), so both carry the same + * operator-only clause. Still absent: ADR-0126 §3's pre-charted `tool` / + * `skill` / `position` — no sanctioned path is built for them, and a row with no + * route does not compile ({@link PackagedBaseRegimeCRoutes}). + * + * ⛔ No sentence built here names the `OS_METADATA_WRITABLE` hatch. The hatch + * still opens these locks exactly as before, so which writes are refused does + * not move — only what the refusal prescribes. ⛔ Nor does any prescribe editing + * the source and redeploying: the administrator of an installed package cannot + * do that. + */ + +import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared'; + +/** An ADR-0126 customization regime a packaged-base refusal speaks for — only the ones it needs today. */ +export type PackagedBaseRegime = 'C'; + +/** + * The sanctioned routes a Regime C type's row supplies to its refusal: how to + * reach that type's clone-as-sibling, and how to reach its enable/disable + * switch — each spelled as the route a client calls (and its body), never as + * prose about the type. A row declares the primitives its type HAS and only + * those: the union refuses a row naming neither. + */ +export type PackagedBaseRegimeCRoutes = + | { readonly clone: string; readonly switchOff?: string } + | { readonly clone?: string; readonly switchOff: string }; + +/** One type's row: its regime, and the routes that regime names for it. */ +export interface PackagedBaseRegimeRow { + readonly regime: PackagedBaseRegime; + readonly routes: PackagedBaseRegimeCRoutes; +} + +/** The table. Keyed by the canonical (singular) metadata type. */ +export const PACKAGED_BASE_REGIME: Readonly> = { + flow: { + regime: 'C', + routes: { + clone: 'POST /api/v1/automation/:name/clone, body {name, label}', + switchOff: 'POST /api/v1/automation/:name/toggle, body {enabled: false}; ' + + 'operator-only where one install serves several organizations', + }, + }, + action: { + regime: 'C', + routes: { + switchOff: 'POST /api/v1/actions/_activation/:object/:action, body {enabled: false}, ' + + ':object = global for an object-less action; ' + + 'operator-only where one install serves several organizations', + }, + }, + permission: { + regime: 'C', + routes: { + clone: 'the "Clone" action on the permission set, ' + + 'or POST /api/v1/data/sys_permission_set with a new name', + }, + }, +}; + +/** The type's row, read on the canonical type, or `undefined` when it declares no regime. */ +export function packagedBaseRegimeRow(type: string): PackagedBaseRegimeRow | undefined { + const singular = PLURAL_TO_SINGULAR[type] ?? type; + return Object.prototype.hasOwnProperty.call(PACKAGED_BASE_REGIME, singular) + ? PACKAGED_BASE_REGIME[singular] + : undefined; +} + +/** + * The PRESCRIPTION half of a regime's refusal, built from the row: for Regime C + * the row's sanctioned paths in one fixed order — clone first, then the switch — + * and the citation of the ADR that decided them. Nothing in it reads the type: + * a flow reads "Clone it …, or switch it off …" because its row has both, an + * action reads only the switch and a permission set only the clone because + * theirs have one. + */ +const PRESCRIPTION_BY_REGIME: Readonly string>> = { + C: (routes) => { + // [verb opening the sentence, verb after "or", the rest of the path] + const paths: Array = [ + ...(routes.clone + ? [['Clone', 'clone', ` it under a new name to customize it (${routes.clone})`] as const] + : []), + ...(routes.switchOff ? [['Switch', 'switch', ` it off (${routes.switchOff})`] as const] : []), + ]; + const prescription = paths + .map(([opening, following, rest], i) => (i === 0 ? opening : following) + rest) + .join(', or '); + return `${prescription}. See docs/adr/0126-packaged-metadata-customization-model.md.`; + }, +}; + +/** + * The regime prescription for `type` — the row's sanctioned paths and the + * ADR-0126 citation, one sentence pair, no opener — or `undefined` when the type + * declares no regime and the emitter keeps its own remedy. + */ +export function packagedBaseRegimePrescription(type: string): string | undefined { + const row = packagedBaseRegimeRow(type); + return row ? PRESCRIPTION_BY_REGIME[row.regime](row.routes) : undefined; +} + +/** + * The whole regime sentence for a packaged item `type/name` refused on save or + * on removal — the lock, then {@link packagedBaseRegimePrescription} — or + * `undefined` when the type declares no regime and the emitter keeps its own + * sentence. Read on the canonical type, and spoken with it. + * + * Kept under the REST door's 500-character client-message bound + * (`truncateClientMessage`, `packages/rest/src/error-response.ts`), past which + * the tail is truncated. Characters before the item's name, save / removal: + * `flow` 411 / 404, `action` 365 / 358, `permission` 317 / 310 — so a name of up + * to 88 characters arrives whole for every row (pinned). A `flow`'s sentence is + * byte-identical to the one the row table replaced (pinned literally). + */ +export function packagedBaseRegimeSentence( + type: string, name: string, operation: 'save' | 'delete', +): string | undefined { + const singular = PLURAL_TO_SINGULAR[type] ?? type; + const prescription = packagedBaseRegimePrescription(singular); + if (prescription === undefined) return undefined; + return `Metadata item '${singular}/${name}' is provided by a code package, and its packaged base is locked ` + + (operation === 'delete' ? `against removal. ` : `against in-place edits. `) + + prescription; +} diff --git a/packages/metadata-protocol/src/protocol.delete-rewrap-envelope.test.ts b/packages/metadata-protocol/src/protocol.delete-rewrap-envelope.test.ts index 38dfbcee3d3..bf65edac3a4 100644 --- a/packages/metadata-protocol/src/protocol.delete-rewrap-envelope.test.ts +++ b/packages/metadata-protocol/src/protocol.delete-rewrap-envelope.test.ts @@ -80,6 +80,7 @@ import { ErrorCode } from '@objectstack/spec/api'; import { DEFAULT_METADATA_TYPE_REGISTRY } from '@objectstack/spec/kernel'; import { ObjectStackProtocolImplementation } from './protocol.js'; import { resetEnvWritableMetadataTypes } from './sys-metadata-repository.js'; +import { packagedBaseRegimeRow } from './packaged-base-regime.js'; /** * The tier whose artifact-backed delete is refused BY THE REPOSITORY on a @@ -309,7 +310,17 @@ describe('#7426 — the repository refusal reaches the caller with its code', () // the token to the envelope, and the bracketed `[NOT_OVERRIDABLE]` // opener it had been trapped in was the duplicate left behind — // `error` is human language, `code` is the machine token. - expect(String(err.message), type).toContain('is not allowOrgOverride in the registry'); + // [#20910, ADR-0126 §2] A type with a Regime C row (`flow`, + // `action`) is refused with its row's removal sentence, naming its + // sanctioned path; every other type keeps the type-door sentence. + if (packagedBaseRegimeRow(type)) { + expect(String(err.message), type).toContain( + `Metadata item '${type}/${name}' is provided by a code package, and its packaged base is locked against removal.`, + ); + expect(String(err.message), type).toContain('docs/adr/0126-packaged-metadata-customization-model.md'); + } else { + expect(String(err.message), type).toContain('is not allowOrgOverride in the registry'); + } expect(String(err.message), type).not.toContain('[NOT_OVERRIDABLE]'); // A refusal that already deleted the row is a log line. expect(rows.size, type).toBe(1); diff --git a/packages/metadata-protocol/src/protocol.packaged-base-refusal.test.ts b/packages/metadata-protocol/src/protocol.packaged-base-refusal.test.ts index a4ced951e3a..b3a565ceeb3 100644 --- a/packages/metadata-protocol/src/protocol.packaged-base-refusal.test.ts +++ b/packages/metadata-protocol/src/protocol.packaged-base-refusal.test.ts @@ -313,6 +313,35 @@ describe('packagedBaseRefusal — each Regime C type names its OWN sanctioned pa }); }); + it('a save NAMING the read-only base takes the named-base ITEM_LOCKED limb — same row, no hatch (both kernel shapes)', () => { + // [#20910] The limb's emitter is `SysMetadataRepository.readOnlyBaseOverrideError`, + // reached through the package door; with the hatch closed it speaks + // for the row too. A booted code package is read-only (`manifests`). + for (const environmentId of [undefined, 'env_1']) { + const registry = { getArtifactItem: (type: string, name: string) => ARTIFACTS.get(type)?.get(name) }; + const p = new ObjectStackProtocolImplementation( + { registry, manifests: new Map([[PACKAGE_ID, {}]]) } as never, () => new Map(), environmentId, + ); + for (const [type, name, path] of [ + ['flow', 'pkg_flow', 'POST /api/v1/automation/:name/clone'], + ['action', 'pkg_action', 'POST /api/v1/actions/_activation/:object/:action'], + ['permission', 'pkg_perm', 'POST /api/v1/data/sys_permission_set'], + ] as const) { + const r: any = p.packagedBaseRefusal({ type, name, operation: 'save', packageId: PACKAGE_ID }); + expect({ code: r?.code, status: r?.status, lockSource: r?.lockSource, packageId: r?.packageId }, type) + .toEqual({ code: 'ITEM_LOCKED', status: 403, lockSource: 'package', packageId: PACKAGE_ID }); + const message = String(r.message); + expect(message.startsWith( + `Cannot overlay '${type}' in package '${PACKAGE_ID}': that package is read-only, and its packaged base ` + + 'is locked against in-place edits. ', + ), type).toBe(true); + expect(message, type).toContain(path); + expect(message, type).not.toContain('OS_METADATA_WRITABLE'); + expect(message.endsWith(`See ${ADR_0126}.`), type).toBe(true); + } + } + }); + it('every row arrives whole through the REST door\'s 500-character bound for an 88-character name', () => { // `truncateClientMessage` (packages/rest/src/error-response.ts) keeps a // message only while it is SHORTER than 500 characters; past that the diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index c17250834b7..4de36f33ebd 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -43,6 +43,7 @@ import type { RuntimeAuthoringIssue } from './runtime-authoring-gate.js'; import { ensureMetadataOverlayIndexes } from './migrations/overlay-index.js'; import { driverCanRunSql, resolveDriverExec } from './migrations/driver-exec.js'; import { SysMetadataRepository, type SysMetadataEngine } from './sys-metadata-repository.js'; +import { packagedBaseRegimeSentence } from './packaged-base-regime.js'; import { bumpWriteEpoch, metaOverlayCacheTtlMs, @@ -4798,31 +4799,6 @@ function isNonCanonicalStoredType(type: string): boolean { return canonicalMetaType(type) !== type && (PLURAL_TO_SINGULAR[type] ?? type) === type; } -/** - * [#20819] An ADR-0126 customization regime the packaged-base refusal speaks - * for — only the regimes it needs today (see - * `ObjectStackProtocolImplementation.PACKAGED_BASE_REGIME`). - */ -type PackagedBaseRegime = 'C'; - -/** - * [#20910, ADR-0126 §2] The sanctioned routes a Regime C type's row supplies to - * its refusal: how to reach that type's clone-as-sibling, and how to reach its - * enable/disable switch — each spelled as the route a client calls (and its - * body), never as prose about the type. A row declares the primitives its type - * HAS and only those: the union refuses a row naming neither, so a type cannot - * be declared Regime C with nothing to prescribe. - */ -type PackagedBaseRegimeCRoutes = - | { readonly clone: string; readonly switchOff?: string } - | { readonly clone?: string; readonly switchOff: string }; - -/** [#20910] One type's row: its regime, and the routes that regime names for it. */ -interface PackagedBaseRegimeRow { - readonly regime: PackagedBaseRegime; - readonly routes: PackagedBaseRegimeCRoutes; -} - /** * Implements the per-domain contracts this class ACTUALLY provides (ADR-0076 * D10 — the facade never implemented the other domains; those live in their @@ -14843,140 +14819,14 @@ export class ObjectStackProtocolImplementation implements return status === 403 && (code === 'NOT_OVERRIDABLE' || code === 'ITEM_LOCKED'); } - /** - * [#20819, ADR-0126 §2 / §3] The customization REGIME of a metadata type, - * declared for the types whose packaged-base refusal speaks for its regime. - * - * ADR-0126 §2 requires a Regime C refusal to name the sanctioned path — - * "in-place edit refused loudly at the write door, the refusal naming the - * sanctioned path" — and §10 gives the reason: a locked base that refuses - * with its sanctioned path in the message is what keeps AI-written metadata - * from guessing. The regime is recorded nowhere else in code (the ADR's - * table is prose, and the registry entries carry no regime field), so this - * map is its one declaration for the refusal, and - * {@link PACKAGED_BASE_REFUSAL_BY_REGIME} is keyed off it — never a second - * list of type names, and never a type branch in the emitters' prose. - * - * [#20910] ONE regime, PER-TYPE routes. A row is the type's regime plus the - * sanctioned routes that regime gives THAT type: the regime decides the - * sentence's shape (locked; here is the sanctioned path), the row supplies - * the paths, and {@link PACKAGED_BASE_REFUSAL_BY_REGIME} builds the - * sentence from the row alone. ADR-0126 §3's Regime C types declared here, - * each with only the primitives it has, each route the one it is SERVED - * at: - * - * - `flow` — both (§7): the clone under a new name (§7.1, - * `POST /automation/:name/clone`, body `{ name, label }`, both keys - * required) and the enable/disable switch (§7.2, - * `POST /automation/:name/toggle`, body `{ enabled }`); - * - `action` — the switch only (§8 item 2, amendment ruling 3): - * `POST /actions/_activation/:object/:action`, body `{ enabled }`, the - * `:object` segment spelled `global` for an object-less action. ⛔ No - * clone: the action-clone half is not chartered, so a clone route named - * here would advertise one that does not exist; - * - `permission` — the clone only (§8 item 3, the landed lock-and-clone - * machinery): the "Clone" action on the permission set, which posts the - * copy to `POST /data/sys_permission_set` under a new name. Spelled as - * `plugin-security`'s own lock refusal spells that same path - * (`packaged-permission-set-lock.ts`), so one condition reads one way - * at both doors. - * - * Both switch routes are gated by the ONE §5 write-authority gate - * (`packages/runtime/src/domains/activation-gate.ts`), so both carry the - * same operator-only clause. Still absent: ADR-0126 §3's pre-charted - * `tool` / `skill` / `position` — no sanctioned path is built for them, and - * a row with no route does not compile ({@link PackagedBaseRegimeCRoutes}). - */ - private static readonly PACKAGED_BASE_REGIME: Readonly> = { - flow: { - regime: 'C', - routes: { - clone: 'POST /api/v1/automation/:name/clone, body {name, label}', - switchOff: 'POST /api/v1/automation/:name/toggle, body {enabled: false}; ' - + 'operator-only where one install serves several organizations', - }, - }, - action: { - regime: 'C', - routes: { - switchOff: 'POST /api/v1/actions/_activation/:object/:action, body {enabled: false}, ' - + ':object = global for an object-less action; ' - + 'operator-only where one install serves several organizations', - }, - }, - permission: { - regime: 'C', - routes: { - clone: 'the "Clone" action on the permission set, ' - + 'or POST /api/v1/data/sys_permission_set with a new name', - }, - }, - }; - - /** - * [#20819, ADR-0126 §2 / §7] The packaged-base refusal's sentence, chosen - * PER REGIME ({@link PACKAGED_BASE_REGIME}). A type with no declared regime - * keeps the sentence the emitters carry inline, byte for byte. - * - * Regime C (§2: behavioral — locked base, disable, clone-as-sibling) states - * the lock, then names the sanctioned paths the type's ROW declares, in one - * fixed order — clone first, then the switch — and cites the ADR that - * decided them. [#20910] Nothing in it reads the type: a flow reads "clone - * it …, or switch it off …" because its row has both, an action reads only - * the switch and a permission set only the clone because theirs have one. - * A `flow`'s sentence is byte-identical to the one this builder replaced - * (pinned). - * - * ⛔ It does not name the `OS_METADATA_WRITABLE` hatch. The hatch still - * opens this lock exactly as before ({@link isOverlayAllowed}), so which - * writes are refused does not move — only what the refusal prescribes. - * ⛔ Nor does it prescribe editing the source and redeploying: the - * administrator of an installed package cannot do that. - * - * Kept under the REST door's 500-character client-message bound, past - * which the tail is truncated. Characters before the item's name, save / - * removal: `flow` 411 / 404, `action` 365 / 358, `permission` 317 (its - * removal is the #6960 carve-out, never refused on this ground) — so a - * name of up to 88 characters arrives whole for every row (pinned). - */ - private static readonly PACKAGED_BASE_REFUSAL_BY_REGIME: Readonly< - Record< - PackagedBaseRegime, - (type: string, name: string, operation: 'save' | 'delete', routes: PackagedBaseRegimeCRoutes) => string - > - > = { - C: (type, name, operation, routes) => { - // [verb opening the sentence, verb after "or", the rest of the path] - const paths: Array = [ - ...(routes.clone - ? [['Clone', 'clone', ` it under a new name to customize it (${routes.clone})`] as const] - : []), - ...(routes.switchOff ? [['Switch', 'switch', ` it off (${routes.switchOff})`] as const] : []), - ]; - const prescription = paths - .map(([opening, following, rest], i) => (i === 0 ? opening : following) + rest) - .join(', or '); - return `Metadata item '${type}/${name}' is provided by a code package, and its packaged base is locked ` - + (operation === 'delete' ? `against removal. ` : `against in-place edits. `) - + `${prescription}. ` - + `See docs/adr/0126-packaged-metadata-customization-model.md.`; - }, - }; - - /** - * The regime-chosen refusal sentence for `(type, name, operation)`, built - * from the type's row, or `undefined` when the type declares no regime and - * the emitter keeps its own sentence. - */ - private static packagedBaseRegimeSentence( - type: string, name: string, operation: 'save' | 'delete', - ): string | undefined { - const singular = PLURAL_TO_SINGULAR[type] ?? type; - const regimes = ObjectStackProtocolImplementation.PACKAGED_BASE_REGIME; - if (!Object.prototype.hasOwnProperty.call(regimes, singular)) return undefined; - const row = regimes[singular]; - return ObjectStackProtocolImplementation.PACKAGED_BASE_REFUSAL_BY_REGIME[row.regime](singular, name, operation, row.routes); - } + // [#20819, #20910, ADR-0126 §2 / §3] The packaged-base refusal's sentence is + // chosen PER REGIME, from the ONE regime table in `./packaged-base-regime.ts` + // (`packagedBaseRegimeSentence` there), which the repository's type door and + // its named-base `ITEM_LOCKED` limb read too — so the three doors onto one + // locked base cannot prescribe three different things. Each Regime C type's + // row supplies its own sanctioned routes (`flow` clone and switch, `action` + // its activation switch, `permission` its clone); a type with no declared + // regime keeps the sentence the emitters below carry inline, byte for byte. /** * [#8184] THE PACKAGE DOOR — `saveMetaItem`'s refusal of a write onto an @@ -14994,7 +14844,10 @@ export class ObjectStackProtocolImplementation implements * * [#20819] Since lifted, the package-less `NOT_OVERRIDABLE` SENTENCE is * chosen per ADR-0126 regime ({@link packagedBaseRegimeSentence}); the - * predicate, the code, the status and the named-base limb are unchanged. + * predicate, the code and the status are unchanged. [#20910] The named-base + * limb's emitter, `readOnlyBaseOverrideError`, takes a Regime C type's + * prescription from the same table — in that emitter, so both doors that + * call it keep one sentence. */ private refusePackagedBaseOverride( request: { type: string; name: string; packageId?: string | null }, @@ -15073,7 +14926,7 @@ export class ObjectStackProtocolImplementation implements // [#20819] The SENTENCE is chosen per ADR-0126 regime; the code, // the status and this branch's predicate are unchanged. const err = new Error( - ObjectStackProtocolImplementation.packagedBaseRegimeSentence(request.type, request.name, 'save') + packagedBaseRegimeSentence(request.type, request.name, 'save') ?? (`Metadata item '${request.type}/${request.name}' is provided by a code package ` + `and the type has not opted into per-org overlay writes (allowOrgOverride=false). ` + `Edit the source artifact and redeploy, or set OS_METADATA_WRITABLE to grant a runtime escape hatch. ` @@ -15113,7 +14966,7 @@ export class ObjectStackProtocolImplementation implements if (artifactBacked && !overlayAllowed && !legacyOverlayRemoval) { // [#20819] Sentence per ADR-0126 regime, as in the save door. const err = new Error( - ObjectStackProtocolImplementation.packagedBaseRegimeSentence(request.type, request.name, 'delete') + packagedBaseRegimeSentence(request.type, request.name, 'delete') ?? (`Metadata item '${request.type}/${request.name}' is provided by a code package ` + `and the type has not opted into per-org overlay writes. ` + `See docs/adr/0005-metadata-customization-overlay.md.`) diff --git a/packages/metadata-protocol/src/sys-metadata-repository.package-writability.test.ts b/packages/metadata-protocol/src/sys-metadata-repository.package-writability.test.ts index 742aab3b948..d93db6641a0 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.package-writability.test.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.package-writability.test.ts @@ -512,11 +512,43 @@ describe('#7682 — the refusal discriminates on package writability', () => { // The other side of the false-prescription pin: opening the hatch (on a // package-less write) remains a real answer, so the sentence must // survive when the hatch is not already set. + // + // [#20910] MOVED from `permission` to `page`, a type with no ADR-0126 + // regime row. ADR-0126 §2 is why the two sentences now differ: a Regime C + // type's packaged base is "refused loudly at the write door, the refusal + // naming the sanctioned path", and for `flow` / `action` / `permission` + // that path is the clone or the switch, never the hatch (the pin beside + // this one). For every type with no regime row the hatch is still the + // answer this limb offers. Measured to reach the SAME limb: `ITEM_LOCKED`, + // `lockSource: 'package'`, the named base echoed back. + const err = await putWith(repo, { + type: 'page', name: 'crm_landing', + intent: 'override-artifact', packageId: READ_ONLY_PKG, + }) as { message?: string }; + expect(err).toMatchObject({ code: 'ITEM_LOCKED', status: 403, lockSource: 'package', packageId: READ_ONLY_PKG }); + expect(String(err.message)).toContain('set OS_METADATA_WRITABLE=page'); + }); + + it('[ADR-0126 §2] …while a Regime C type with the hatch CLOSED is told its sanctioned path, not the hatch', async () => { + // The pin above, on a type that HAS a regime row: same limb, same + // envelope, and the remedy is the row's — `permission`'s is its clone. const err = await putWith(repo, { type: 'permission', name: 'showcase_contributor', intent: 'override-artifact', packageId: READ_ONLY_PKG, }) as { message?: string }; - expect(String(err.message)).toContain('set OS_METADATA_WRITABLE=permission'); + expect(err).toMatchObject({ code: 'ITEM_LOCKED', status: 403, lockSource: 'package', packageId: READ_ONLY_PKG }); + const message = String(err.message); + expect(message.startsWith( + `Cannot overlay 'permission' in package '${READ_ONLY_PKG}': that package is read-only, and its packaged base ` + + 'is locked against in-place edits. ', + )).toBe(true); + expect(message).toContain( + 'Clone it under a new name to customize it (the "Clone" action on the permission set, ' + + 'or POST /api/v1/data/sys_permission_set with a new name).', + ); + expect(message).not.toContain('OS_METADATA_WRITABLE'); + expect(message).not.toContain('redeploy'); + expect(message.endsWith('See docs/adr/0126-packaged-metadata-customization-model.md.')).toBe(true); }); }); @@ -1204,3 +1236,136 @@ describe('#8361 — the create-side hatch clause reaches saveMetaItem', () => { expect(String(err.message)).toContain(`Cannot create job in package '${READ_ONLY_PKG}'`); }, 30_000); }); + +// --------------------------------------------------------------------------- +// [#20910, ADR-0126 §2] The repository's two refusals onto a packaged base — +// the TYPE door and the named-base `ITEM_LOCKED` limb — speak for the type's +// regime row, with the hatch closed, exactly as the protocol's package door +// does. Every type with no regime row keeps its sentence byte for byte. +// --------------------------------------------------------------------------- + +describe('[#20910] the repository doors name a Regime C type\'s sanctioned path, from the one regime table', () => { + const ADR_0126 = 'See docs/adr/0126-packaged-metadata-customization-model.md.'; + const ACTION_SWITCH = 'Switch it off (POST /api/v1/actions/_activation/:object/:action, body {enabled: false}, ' + + ':object = global for an object-less action; operator-only where one install serves several organizations).'; + const PERMISSION_CLONE = 'Clone it under a new name to customize it (the "Clone" action on the permission set, ' + + 'or POST /api/v1/data/sys_permission_set with a new name).'; + const FLOW_PATHS = 'Clone it under a new name to customize it (POST /api/v1/automation/:name/clone, body {name, label}), ' + + 'or switch it off (POST /api/v1/automation/:name/toggle, body {enabled: false}; ' + + 'operator-only where one install serves several organizations).'; + /** Each Regime C row's prescription, spelled out — never read back from the table under test. */ + const PATHS: ReadonlyArray = [ + ['flow', FLOW_PATHS], ['action', ACTION_SWITCH], ['permission', PERMISSION_CLONE], + ]; + + let engine: ReturnType; + let repo: SysMetadataRepository; + + beforeEach(() => { + delete process.env.OS_METADATA_WRITABLE; + resetEnvWritableMetadataTypes(); + ObjectStackProtocolImplementation.resetEnvWritableCache(); + engine = makeFakeEngine(); + repo = new SysMetadataRepository({ engine: engine as never, organizationId: null, orgLabel: 'env' }); + }); + + afterEach(() => { + delete process.env.OS_METADATA_WRITABLE; + resetEnvWritableMetadataTypes(); + ObjectStackProtocolImplementation.resetEnvWritableCache(); + }); + + // ── the type door (a package-less write, hatch closed) ──────────────── + + for (const [type, paths] of PATHS) { + it(`type door, save: a packaged ${type} is refused NOT_OVERRIDABLE with its row's path, no hatch`, async () => { + const err = await putWith(repo, { type, name: `pkg_${type}`, intent: 'override-artifact' }) as any; + expect(err).toMatchObject({ code: 'NOT_OVERRIDABLE', status: 403 }); + expect(String(err.message)).toBe( + `Metadata item '${type}/pkg_${type}' is provided by a code package, and its packaged base is locked ` + + `against in-place edits. ${paths} ${ADR_0126}`, + ); + expect(Array.from(engine.rows.values())).toEqual([]); + }); + } + + for (const [type, paths] of PATHS.filter(([t]) => t !== 'permission')) { + // `permission` merges its overlay at read (`supportsOverlay`), so its + // removal is the #6960 carve-out and never reaches this door. + it(`type door, delete: a packaged ${type}'s removal is refused with its row's path too`, async () => { + const err = await repo + .delete({ org: 'env', type, name: `pkg_${type}` }, { parentVersion: 'sha256:whatever', actor: null, intent: 'override-artifact' }) + .then(() => null, (e: unknown) => e) as any; + expect(err).toMatchObject({ code: 'NOT_OVERRIDABLE', status: 403 }); + expect(String(err.message)).toBe( + `Metadata item '${type}/pkg_${type}' is provided by a code package, and its packaged base is locked ` + + `against removal. ${paths} ${ADR_0126}`, + ); + }); + } + + it('type door, control: a type with no regime row keeps the overlay-allowed list and the hatch, byte for byte', async () => { + const err = await putWith(repo, { type: 'object', name: 'showcase_task', intent: 'override-artifact' }) as any; + expect(err).toMatchObject({ code: 'NOT_OVERRIDABLE', status: 403 }); + expect(String(err.message)).toBe( + "'object' is not allowOrgOverride in the registry. " + + 'Overlay-allowed: view, dashboard, report, translation, email_template. ' + + 'Set OS_METADATA_WRITABLE to enable additional types at runtime.', + ); + }); + + it('type door: the hatch still opens a Regime C type exactly as before (NARROW untouched)', async () => { + process.env.OS_METADATA_WRITABLE = 'action'; + resetEnvWritableMetadataTypes(); + const err = await putWith(repo, { type: 'action', name: 'pkg_action', intent: 'override-artifact' }); + expect(err).toBeNull(); + const metaRows = Array.from(engine.rows.values()).filter((r) => r.__table === 'sys_metadata'); + expect(metaRows[0]).toMatchObject({ package_id: null, organization_id: null }); + }); + + // ── the named-base ITEM_LOCKED limb (a read-only base named, hatch closed) ── + + for (const [type, paths] of PATHS) { + it(`named base, hatch CLOSED: a ${type} answers ITEM_LOCKED with its row's path, envelope unchanged`, async () => { + const err = await putWith(repo, { type, name: `pkg_${type}`, intent: 'override-artifact', packageId: READ_ONLY_PKG }) as any; + expect(err).toMatchObject({ + code: 'ITEM_LOCKED', status: 403, lockSource: 'package', packageId: READ_ONLY_PKG, + docs: 'docs/adr/0010-metadata-protection-model.md', + }); + expect(String(err.message)).toBe( + `Cannot overlay '${type}' in package '${READ_ONLY_PKG}': that package is read-only, and its packaged base ` + + `is locked against in-place edits. ${paths} ${ADR_0126}`, + ); + }); + } + + it('named base, hatch OPEN: a Regime C type keeps the hatch-open remedy byte for byte', async () => { + process.env.OS_METADATA_WRITABLE = 'flow'; + resetEnvWritableMetadataTypes(); + const err = await putWith(repo, { type: 'flow', name: 'pkg_flow', intent: 'override-artifact', packageId: READ_ONLY_PKG }) as any; + expect(err).toMatchObject({ code: 'ITEM_LOCKED', status: 403, lockSource: 'package', packageId: READ_ONLY_PKG }); + expect(String(err.message)).toBe( + `Cannot overlay 'flow' in package '${READ_ONLY_PKG}': that package is read-only ` + + '(provided by code or an installed app) and the type has no per-org overlay channel ' + + '(allowOrgOverride=false), so this item is locked against runtime edits. ' + + 'OS_METADATA_WRITABLE=flow is set, and it does not apply here: the hatch unlocks the ' + + "metadata TYPE (treating it as allowOrgOverride), never a package's writability. " + + "Retry without '?package=' to land the env-wide / per-org overlay the hatch does grant, " + + 'or edit the source artifact and redeploy. See docs/adr/0010-metadata-protection-model.md.', + ); + }); + + it('every Regime C row arrives whole through the REST door\'s 500-character bound with a long package id', () => { + // `truncateClientMessage` (packages/rest/src/error-response.ts) keeps a + // message only while it is SHORTER than 500 characters. 64 characters is + // longer than any package id this repository ships (the longest, + // `com.objectstack.platform-objects.activation-ledger`, is 50). + const longPkg = `com.example.${'x'.repeat(52)}`; + expect(longPkg).toHaveLength(64); + for (const [type] of PATHS) { + const message = String(SysMetadataRepository.readOnlyBaseOverrideError(type, longPkg, false).message); + expect(message.length, type).toBeLessThan(500); + expect(message.endsWith(ADR_0126), type).toBe(true); + } + }); +}); diff --git a/packages/metadata-protocol/src/sys-metadata-repository.ts b/packages/metadata-protocol/src/sys-metadata-repository.ts index 143b63ab82d..91391ad6b0d 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.ts @@ -83,6 +83,7 @@ import type { IObjectQLEngine } from '@objectstack/core'; // lifecycle gate read, so a third read-only signal added there reaches this // door too (that shared-rule argument is the module's whole reason to exist). import { isWritablePackage } from './package-writability.js'; +import { packagedBaseRegimePrescription, packagedBaseRegimeSentence } from './packaged-base-regime.js'; /** * Canonicalise a driver-materialised timestamp into the ISO-8601 string the @@ -529,7 +530,7 @@ export class SysMetadataRepository implements MetadataRepository { // resolution below) on purpose — `undefined` means "the caller named no // base", which is the ordinary env-local overlay and must keep the // type-door codes; `?? null` there is a ROW-KEY default, a different fact. - this.assertAllowed(ref.type, opts.intent, opts.packageId); + this.assertAllowed(ref, 'save', opts.intent, opts.packageId); const state: OverlayState = opts.state ?? 'active'; const body = (spec ?? {}) as Record; @@ -766,7 +767,7 @@ export class SysMetadataRepository implements MetadataRepository { // [#6960] The DELETE verb's own gate — see {@link assertDeleteAllowed}. // `put` keeps calling `assertAllowed` directly; the ruling moved removal // only. - this.assertDeleteAllowed(ref.type, opts.intent); + this.assertDeleteAllowed(ref, opts.intent); const state: OverlayState = opts.state ?? 'active'; const result = await this.withTxn(async (ctx) => { @@ -1586,10 +1587,12 @@ export class SysMetadataRepository implements MetadataRepository { * purpose and warns against symmetrising either way. */ private assertAllowed( - type: string, + ref: { type: string; name: string }, + operation: 'save' | 'delete', intent: MetadataWriteIntent = 'override-artifact', packageId?: string | null, ): void { + const { type } = ref; const singular = PLURAL_TO_SINGULAR[type] ?? type; const allowedByRegistry = OVERLAY_ALLOWED_TYPES.has(singular) || OVERLAY_ALLOWED_TYPES.has(type); if (allowedByRegistry) return; @@ -1632,6 +1635,24 @@ export class SysMetadataRepository implements MetadataRepository { // named a writable one. It never reaches the package dimension. if (hatchOpen) return; + // [#20910, ADR-0126 §2] An item a code package ships, of a type with a + // Regime C row, is refused with the row-built sentence — the SAME one the + // protocol's package door answers on an environment-scoped kernel, which + // never reaches here for this write — naming the type's sanctioned path. A + // locked Regime C base is customized by its clone or switched off, never by + // opening this hatch, so the list-and-hatch sentence below would prescribe + // the wrong door. Reached only with the hatch CLOSED (it returned above). + // Every type with no regime row keeps that sentence, byte for byte. + if (intent !== 'runtime-only') { + const regimeSentence = packagedBaseRegimeSentence(singular, ref.name, operation); + if (regimeSentence !== undefined) { + const err: any = new Error(regimeSentence); + err.code = 'NOT_OVERRIDABLE'; + err.status = 403; + throw err; + } + } + const allowed = [ ...OVERLAY_ALLOWED_TYPES, ...envWritableMetadataTypes(), @@ -1744,8 +1765,20 @@ export class SysMetadataRepository implements MetadataRepository { */ static readOnlyBaseOverrideError(type: string, packageId: string, hatchOpen = false): Error { const singular = PLURAL_TO_SINGULAR[type] ?? type; - const err: any = new Error( - `Cannot overlay '${type}' in package '${packageId}': that package is read-only ` + // [#20910, ADR-0126 §2] With the hatch CLOSED, a type with a Regime C row is + // told its row's sanctioned path — not the hatch: a locked Regime C base is + // customized by its clone or switched off, and the hatch is not that type's + // sanctioned path. The opener is shortened to the lock, so the prescription + // and its ADR-0126 citation arrive whole inside the REST door's + // 500-character bound (pinned with a long package id). The hatch-OPEN + // remedy, the code, the status, `lockSource`, `packageId` and `docs` are + // the same for every type; every type with no regime row keeps both + // remedies below, byte for byte. + const regimePrescription = hatchOpen ? undefined : packagedBaseRegimePrescription(singular); + const err: any = new Error(regimePrescription !== undefined + ? `Cannot overlay '${type}' in package '${packageId}': that package is read-only, and its packaged base ` + + `is locked against in-place edits. ${regimePrescription}` + : `Cannot overlay '${type}' in package '${packageId}': that package is read-only ` + `(provided by code or an installed app) and the type has no per-org overlay channel ` + `(allowOrgOverride=false), so this item is locked against runtime edits. ` // [#8146] The prescription is chosen by whether the hatch is ALREADY @@ -1761,8 +1794,7 @@ export class SysMetadataRepository implements MetadataRepository { : `Edit the source artifact and redeploy, or set OS_METADATA_WRITABLE=${singular} ` + `to grant a runtime escape hatch on this TYPE (it does not unlock package writability, ` + `so pair it with a package-less write).`) - + ` See docs/adr/0010-metadata-protection-model.md.`, - ); + + ` See docs/adr/0010-metadata-protection-model.md.`); err.code = 'ITEM_LOCKED'; err.status = 403; err.lockSource = 'package'; @@ -1817,14 +1849,15 @@ export class SysMetadataRepository implements MetadataRepository { * precisely the artifact-backed case the ruling names. */ private assertDeleteAllowed( - type: string, + ref: { type: string; name: string }, intent: MetadataWriteIntent = 'override-artifact', ): void { + const { type } = ref; if (intent !== 'runtime-only') { const singular = PLURAL_TO_SINGULAR[type] ?? type; if (OVERLAY_CAPABLE_TYPES.has(singular) || OVERLAY_CAPABLE_TYPES.has(type)) return; } - this.assertAllowed(type, intent); + this.assertAllowed(ref, 'delete', intent); } private whereFor( diff --git a/packages/rest/src/rest-meta-packaged-action-permission-refusal.test.ts b/packages/rest/src/rest-meta-packaged-action-permission-refusal.test.ts index 9b1ca12b6e4..6c5863f35b9 100644 --- a/packages/rest/src/rest-meta-packaged-action-permission-refusal.test.ts +++ b/packages/rest/src/rest-meta-packaged-action-permission-refusal.test.ts @@ -27,8 +27,18 @@ * Same harness as `rest-meta-packaged-flow-refusal.test.ts`: a REAL * `ObjectStackProtocolImplementation` over a REAL `SchemaRegistry`, the packaged * items registered under a package id the way an artifact loader registers - * them. Run on an ENVIRONMENT kernel, where `saveMetaItem` / `deleteMetaItem` - * ask the package door; the refusals land before any store is touched. + * them, and that package booted as code (`manifests`), so it is read-only. The + * refusals land before any store is touched. Three doors, one table: + * + * - an ENVIRONMENT kernel, where `saveMetaItem` / `deleteMetaItem` ask the + * protocol's package door; + * - [#20910] a HOST-CONFIG kernel (no environment id — the shape the default + * `pnpm dev` boot measured), where that door is not asked and the write is + * refused one layer down by `SysMetadataRepository.assertAllowed`'s type + * door — with the same row-built sentence; + * - [#20910] a write NAMING the read-only base (`?package=`), refused by the + * named-base `ITEM_LOCKED` limb, which speaks for the row with the hatch + * closed. */ import { describe, it, expect } from 'vitest'; @@ -57,14 +67,15 @@ function makeRes() { return res; } -function boot() { +function boot(environmentId: string | undefined = 'env_1') { const registry = new SchemaRegistry({ multiTenant: false, collisionPolicy: 'error' }); for (const name of [PACKAGED_ACTION, LONG_ACTION]) { registry.registerItem('action', { name, label: 'Approve', type: 'script', target: 'approve_fn' }, 'name', PACKAGE_ID); } registry.registerItem('permission', { name: PACKAGED_PERMISSION, label: 'Contributor', objects: {} }, 'name', PACKAGE_ID); const protocol = new ObjectStackProtocolImplementation( - { registry, findOne: async () => null } as never, () => new Map(), 'env_1', + { registry, findOne: async () => null, manifests: new Map([[PACKAGE_ID, {}]]) } as never, + () => new Map(), environmentId, ); const rest = new RestServer(createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any); // The write doors demand `manage_metadata`; held here, so every 403 below is the LOCK. @@ -75,9 +86,9 @@ function boot() { if (!found) throw new Error(`${method} /api/v1/meta/:type/:name is not registered`); return found; }; - const call = async (method: 'PUT' | 'DELETE', type: string, name: string, body?: unknown) => { + const call = async (method: 'PUT' | 'DELETE', type: string, name: string, body?: unknown, query: Record = {}) => { const res = makeRes(); - await route(method).handler({ method, params: { type, name }, query: {}, headers: {}, body } as any, res); + await route(method).handler({ method, params: { type, name }, query, headers: {}, body } as any, res); // The door's 4xx envelope: `code` beside the client-facing `error` text. return { status: res._status, code: res._json?.code, message: res._json?.error }; }; @@ -153,3 +164,50 @@ describe('PUT /api/v1/meta/permission/:name on a packaged permission set — the expect(r.status ?? 200).not.toBe(403); }); }); + +const ACTION_BODY = { name: PACKAGED_ACTION, label: 'Changed in place', type: 'script', target: 'approve_fn' }; +const PERMISSION_BODY = { name: PACKAGED_PERMISSION, label: 'Changed in place', objects: {} }; + +describe('[#20910] a host-config kernel — the repository\'s type door answers with the same row-built sentence', () => { + it('PUT action answers 403 NOT_OVERRIDABLE naming the switch, no hatch', async () => { + const { call } = boot(undefined); + const r = await call('PUT', 'action', PACKAGED_ACTION, ACTION_BODY); + expect(r.status).toBe(403); + expect(r.code).toBe('NOT_OVERRIDABLE'); + expect(expectRegimeC(r.message, 'action', PACKAGED_ACTION, 'save')).toContain(ACTION_SWITCH); + }); + + it('PUT permission answers 403 NOT_OVERRIDABLE naming the clone, no hatch', async () => { + const { call } = boot(undefined); + const r = await call('PUT', 'permission', PACKAGED_PERMISSION, PERMISSION_BODY); + expect(r.status).toBe(403); + expect(r.code).toBe('NOT_OVERRIDABLE'); + expect(expectRegimeC(r.message, 'permission', PACKAGED_PERMISSION, 'save')).toContain(PERMISSION_CLONE); + }); +}); + +describe('[#20910] a write naming the read-only base (?package=) — the named-base ITEM_LOCKED limb names the row\'s path', () => { + for (const environmentId of [undefined, 'env_1']) { + const kernel = environmentId ? 'environment' : 'host-config'; + for (const [type, name, body, path] of [ + ['action', PACKAGED_ACTION, ACTION_BODY, ACTION_SWITCH], + ['permission', PACKAGED_PERMISSION, PERMISSION_BODY, PERMISSION_CLONE], + ] as const) { + it(`PUT ${type}?package= answers 403 ITEM_LOCKED with the path and no hatch (${kernel} kernel)`, async () => { + const { call } = boot(environmentId); + const r = await call('PUT', type, name, body, { package: PACKAGE_ID }); + expect(r.status).toBe(403); + expect(r.code).toBe('ITEM_LOCKED'); + const text = String(r.message); + expect(text.startsWith( + `Cannot overlay '${type}' in package '${PACKAGE_ID}': that package is read-only, and its packaged base ` + + 'is locked against in-place edits. ', + )).toBe(true); + expect(text).toContain(path); + expect(text).not.toContain('OS_METADATA_WRITABLE'); + expect(text).not.toContain('redeploy'); + expect(text.endsWith('See docs/adr/0126-packaged-metadata-customization-model.md.')).toBe(true); + }); + } + } +});