Skip to content

Commit 80cdbd4

Browse files
fix(metadata-protocol, plugin-security): judge a permission set's seal, lock and write intent by (package, name) (#34359)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbBePzY6g11h3hyWk5ud4vWy)_ Fixes #34226 Clause-②: yes (widening) — a save, a draft save or a draft's publish that a package addresses to its own permission set N, refused 403 `NOT_OVERRIDABLE` ("provided by a managed package and is sealed") while a package of another namespace ships N, now lands; the exported `MetadataAuthoringGateContext` (`@objectstack/metadata-protocol`) and `PermissionSetLockGateContext` (`@objectstack/plugin-security`) each gain an optional `packageId`; nothing the save door accepted is refused Metadata-protocol: none ## 维护者速读 - 改了什么:包 crm 发布了权限集 N 时,另一命名空间的包 hr 现在可以保存、草稿保存并发布它自己的权限集 N,hr 的授权只生效 hr 自己的 N;凡是覆盖 crm 所发布 N 的保存(不指定包、指定 crm、指定 crm 的定制配对包、指定 crm 同命名空间的包)仍按原样封存拒绝。 - 为什么改:ADR-0150 D2 规定权限集按「包 + 名称」区分,但托管封存、plugin-security 的打包权限集锁和存储层写入意图都只看名称,把别的包的同名集当成自己的封存基线,误拒了合法保存。 - 风险与回滚:风险在判断「这次保存是否覆盖某个已发布集」的谓词;它复用安装门与保存门共用的命名空间谓词 `permissionSetHoldersMeet` 与配对判定 `isPairOf`,只在「写入方与每个发布方都不同命名空间、且不是其配对包」时放行。回滚即 revert 本 PR,无数据迁移。 - 先看:`packages/metadata-protocol/src/protocol-packaged-base-refusal.ts`(封存谓词 `isOwnPermissionSetWrite`),`packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts`(锁的同一判定),`packages/metadata-protocol/src/protocol-save.ts` 与 `protocol-history-and-publish.ts` 中各一行写入意图。 - 两分钟验证:`pnpm --filter @objectstack/plugin-security exec vitest run src/packaged-permission-set-lock-gate.test.ts`,预期 37 个全部通过,其中 `[#34226]` 一组覆盖两种注册顺序下的放行、全部封存对照,以及无法回滚的运行时上批量发布被拒后的撤销。 - 需要你做的:评审本次声明的放宽(权限集保存与草稿发布两处门)。 ## What changes A permission set is `(package, name)`, with one set of a name per namespace (ADR-0150 D2/D9). The managed seal (ADR-0126 / ADR-0131 D6) keeps protecting a package's own shipped base. Four judges decided "is this write an override of a shipped set?" by the name alone. All four now judge the package the write is addressed to, through one verdict: - **The verdict** (`metadata-protocol`, `protocol-packaged-base-refusal.ts`): `isOwnPermissionSetWrite(engine, type, name, packageId)`. It is true only for a `permission` write addressed to a package P such that, for every package Q that ships the name, P is not Q's customization pair (`isPairOf`) and P does not meet Q under `permissionSetHoldersMeet`. The second test covers Q itself, a co-owner of Q's namespace, a platform namespace, a package with no namespace, and a name the platform requests by spelling. Every shipper is judged, never the first found. - **The save door's seal** (`refusePackagedBaseOverride`): does not seal such a write. The read-only named-base limb stays ahead of it, unchanged. - **The repository's managed seal**: the write intent the save door (`protocol-save.ts`) and the draft promotion (`protocol-history-and-publish.ts`) hand the store is `runtime-only` for such a write, not `override-artifact`. One line each, plus the import. - **The undo of a refused package publish** (`undoLandedPromotions`, `protocol-history-and-publish.ts`): on a runtime that cannot roll back, each undo write judges the package it addresses with the same verdict: the active-row restore or removal at the package the promotion wrote, the returned draft at the draft's own binding. Before, the undo of a package's own set beside another namespace's shipped one was refused by the store and reported still live, and the draft was not put back. - **plugin-security's packaged-permission-set lock** (`packaged-permission-set-lock-gate.ts`): skips the lock only when the write is addressed to a package that, for every declarer, is not the declarer's pair and does not meet it. A write naming no package, and a name no source can classify (fail-closed `unknown`), are judged as before. Its exported `PermissionSetLockGateContext` gains the same optional `packageId`. - **The plumbing**: `MetadataAuthoringGateContext` gains an optional `packageId`, the package the write is addressed to. The save door passes `request.packageId` (one line in `protocol-save.ts`). The restore path passes the row's binding. The private `runAuthoringGate` event type in `protocol.ts` gains the same optional field (one line). ## FROM → TO Measured in `packaged-permission-set-lock-gate.test.ts` on this head. FROM was measured on the same harness with every non-test file of this diff reverted to `origin/main` (`5a755791a9`). Package `crm` (namespace `crm`) ships `N`. Every row holds in both registration orders (crm's set registered before or after the other packages install). | Write of `N` | FROM (main) | TO (this PR) | |---|---|---| | `hr` (namespace `hr`) saves its own `N` | 403 `NOT_OVERRIDABLE`, "…is provided by a managed package and is sealed…" | saved; `hr`'s grant confers `hr`'s set, `crm`'s confers `crm`'s | | `hr` saves its own `N` while `crm` and `fin` both ship `N` | 403 `NOT_OVERRIDABLE` | saved | | `hr` saves its own `N` as a draft, then publishes it | draft save 403 `NOT_OVERRIDABLE` | draft lands, publish promotes it, `hr`'s grant confers it | | save naming no package | 403 `NOT_OVERRIDABLE` (seal) | unchanged | | save addressed to `crm` | 403 `NOT_OVERRIDABLE` (seal) | unchanged | | save addressed to `crm`'s customization pair (namespace `crmx`) | 403 `NOT_OVERRIDABLE` (seal) | unchanged | | save addressed to a co-owner of `crm`'s namespace | 403 `NOT_OVERRIDABLE` (seal) | unchanged | | `fin` and `crm` ship `N`; save addressed to a co-owner of `crm`'s namespace | 403 `NOT_OVERRIDABLE` (seal) | unchanged | | the lock gate, for no package / `crm` / `crm`'s pair / `crm`'s co-owner | `PackagedPermissionSetLockedError` | unchanged | | the lock gate, for `hr` | `PackagedPermissionSetLockedError` | passes | | publish of a stored draft bound to `crm` or `crm`'s pair | (no such draft could be stored) | 403 `NOT_OVERRIDABLE` (the store's seal) | | publish of a stored draft bound to no package or to `crm`'s co-owner | (no such draft could be stored) | 422 `NAMESPACE_CONFLICT` (the name rule, judged first) | ## Tests New pins, as a top-level describe in `packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.test.ts`: `[#34226] a permission set is (package, name): the seal and the lock judge a save by the package it addresses`. The harness is the real protocol and the real `SchemaRegistry`, both aliased to source. Each case runs in both registration orders: - `hr`'s own save lands, and each package's grant confers its own set; - with two shippers, `hr`'s own save still lands; - draft save then publish lands; - CONTROLs at the save door: no package, `crm`, `crm`'s pair (other namespace), `crm`'s co-owner, and `fin`'s and `crm`'s co-owner. Each is asserted to be refused by the seal, not the lock; - CONTROLs at the publish door: a stored draft bound to each of those addresses, with the code and status asserted; - the lock gate itself: `hr` passes; no package, `crm`, the pair and the co-owner are locked; - the undo of a refused package publish on a runtime that cannot roll back (`[#32396]` shape, created and edited): `hr`'s own N is reported `BATCH_ABORTED`, the active rows are as before the publish, and N's draft is back byte for byte. The file's engine double now lists a table's own rows by the where's scalar equalities, answers a version's history row, and applies the caller's `limit` after its filter (`check:objectql-double-limit`). Result at `b054ae27`: the full `plugin-security` suite, Test Files 271 passed (271), Tests 6753 passed | 45 skipped, which includes this file at 37 passed (37); under the verify lock with VERDICT command-exit 0. <details><summary>FROM reading (H1): the pins on origin/main source</summary> Every non-test file of the diff was restored from `5a755791a9` and the file was run: 16 failed | 17 passed (33). Every TO case and every case that needs `hr`'s draft failed. `hr`'s save was refused 403 `NOT_OVERRIDABLE`: "Metadata item 'permission/qa_shared_reader' is provided by a managed package and is sealed against in-place edits. Clone it under a new name…". The save-door CONTROLs passed on main, so they hold as before. Afterwards each file's blob equalled HEAD and `git diff HEAD` was empty. </details> <details><summary>Ablations: thirteen legs, each red, each restored (scripts/ablation-replace.mjs, anchor x1 to x0)</summary> The seal and lock legs were read from source through the test aliases, so no dist step applies. | Leg | Result | |---|---| | S1: seal narrowing removed | 14 failed | | S2: seal pair arm removed | 4 failed (the pair CONTROLs at the save and publish doors) | | S3: seal meets arm removed | 8 failed | | S4: seal judges the first shipper only | 2 failed (the `fin`/`crm` co-owner CONTROL) | | I1: save write intent name-wide | 14 failed | | I2: publish write intent name-wide | 2 failed (draft then publish) | | P1: the save door hands the gate no package | 14 failed | | L1: lock narrowing removed | 16 failed | | L2: lock pair arm removed | 2 failed (the gate case) | | L3: lock meets arm removed | 2 failed (the gate case) | | U0: the undo's verdict removed (FROM) | 4 failed (created and edited, both orders) | | U1: the undo's active-row intent at no package | 2 failed (edited: the restore is refused) | | U2: the undo's returned-draft intent at no package | 2 failed (created: the draft put is refused) | The U legs read `metadata-protocol` from source through the test alias, so no dist step applies; each restore was proved by blob equal to HEAD and an empty `git diff HEAD`. The final `git diff HEAD` was empty. The first P1 attempt was refused by the tool, because its replacement was a substring of the original text; it was re-run with a marked replacement. </details> <details><summary>H3 probe (not committed)</summary> A scratch test called `refusePackagedBaseOverride` for `hr`'s own item of each package-scoped type while `crm` ships one. The answers are listed under Acceptance notes. </details> ## Acceptance notes - **H1** (both gates key on the name alone): confirmed, and there is a third judge. After the seal and the lock were narrowed, `hr`'s save was still refused 403 `NOT_OVERRIDABLE` by the repository's managed seal, because the save door's write intent was computed from the name-wide artifact check. The draft promotion computes the same intent. Both are narrowed here through the same verdict. - **H2**: confirmed for the four judges above. Every override of `crm`'s `N` stays sealed, including a save addressed to `crm`'s customization pair whose namespace differs from `crm`'s. - **H3** (acceptance item 2), measured: every sealed package-scoped type shares the name-wide shape. With package `crm` shipping item X and package `hr` of another namespace, `refusePackagedBaseOverride` refuses `hr`'s own save of X as sealed for `flow`, `hook`, `job`, `webhook`, `mapping`, `connector`, `sharing_rule`, `queue`, `assignment_rule`, `app`, `page`, `dataset`, `analytics_cube`, `picklist`, `book`, `api`, `tool`, `skill`, `agent`, and so for `permission` before this PR. `action`'s registration contract refused the bare probe body, but its seal is the same predicate. `dashboard`, `report` and `email_template` are not sealed (environment-overlay types). Only `permission` is changed here: the fix is not the same line for the others, because each type's identity and override channel differ. - **Out of scope**, filed: - #34401: rollback and commit revert of a package's own permission set beside another namespace's shipped set still hand `restoreWriteFor` the name-wide intent, so the store refuses the restore (`protocol-package-commits.ts`, the `revertCommit` restore limb and `rollbackMetaItemUnaudited`). The `revertCommit` removal limb states the same intent, but the store admits it (below); - #34402: the other sealed package-scoped types listed under H3 keep the name-wide seal. - **Delete and discard (L1 R1), measured: not refused, no code change.** `deleteMetaItem` still derives its removal intent from the name-wide `artifactBacked` (`protocol-diff-delete-load.ts`, lines 642 and 851). The store admits that removal anyway: `SysMetadataRepository#assertDeleteAllowed` lets an `override-artifact` delete through for a `supportsOverlay` type, and `permission` is one (`supportsOverlay: true`), so `assertAllowed` is never reached. Measured at this head with a scratch case in the gate file's harness (not committed), in both registration orders: `hr` deleting its own active `N` answered `success: true` and removed the row, and `hr` discarding its own `N` draft answered `success: true` and removed the draft, while `crm` ships `N`. - **Overlap**: PR #34238 edits the same `promoteDraftForPublish` host `Pick` line in `protocol-history-and-publish.ts`. Its head `0ed4158ef6` added `readItemActiveRows`, and this PR adds `engine`. At that head the two conflicted textually, and the resolution is the union of both members. At #34238's current head `db96228e6c` the merge-tree is clean. If the conflict returns, whichever PR lands second needs one mechanical merge of `main`. - The seal's verdict and the lock's relation check are spelled once each, in their own packages (plugin-security cannot import `metadata-protocol` at runtime). Both are built only from the shared predicates `permissionSetHoldersMeet` (`@objectstack/core`) and `isPairOf` (`@objectstack/metadata-core`), and the pins hold the two in step at every address. - `scripts/engine-double-contract.pinned.json`: one count goes 1 → 2 for the new pinned `findOne` double in the gate's test file, as `check:engine-double-contract` asks. ## Verification Head `b054ae27` (unchanged by the L1 R1 round: R1 measured not refused, see Acceptance notes; nothing in code moved): - **CI red at `1a2f74f526`, cause**: one compile error in this PR's own file, `packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.ts(83,68): error TS2339: Property 'namespace' does not exist on type '{}'`. The cast intersected `InstalledPackageSource` with a second `getPackage` signature, and the first signature (manifest `unknown`) won. The namespace is now read through the typed `installedManifestsOf` lookup. Build Core, the three Type Check lanes, Test Core and Live E2E UI all failed on that line. It is not on `main`: the file is new in this PR. - **Review S1 / N1 / N2** (contract record 6915371853): S1 is fixed above (`undoLandedPromotions`), with the pins and the U legs. N1 and N2 are folded into the changeset and the `Clause-②:` line, which now read the same in both. - Build closure `pnpm --filter '@objectstack/plugin-security...' build`: exit 0. - `typecheck`: `metadata-protocol` and `plugin-security` exit 0 at `343d5a7f`; `plugin-security` again at `b054ae27`, exit 0 (the last commit only touched its test file). - `metadata-protocol` full suite at `343d5a7f` (its source is unchanged since): Test Files 345 passed | 9 skipped, Tests 22956 passed | 45 skipped. - `plugin-security` full suite at `b054ae27`: Test Files 271 passed, Tests 6753 passed | 45 skipped. - Derived gate sweep at `b054ae27`: `dispatch-gates --ran` printed `85 derived, 83 run, 2 NOT-MEASURED, 0 UNRUN`; every run family exited 0, including `check:objectql-double-limit`, `check:engine-double-contract`, `check:query-options-erasure` and `check:type-check-debt`. `check:dual-build-cjs-loads` and `check:i18n` exit 3 (PREREQUISITE NOT MET: a full build) and are left to CI. - Overlap: `git merge-tree --write-tree` of `b054ae27` against `origin/main` `f84dc192`, #34238 `db96228e6c` and #34324 `e378b62f30` all exit 0. - CI at `b054ae27`, read once after the L1 R1 measurement: 55 check-runs, 37 success and 18 skipped, no failure and none pending (Build Core, TypeScript Type Check, Test Core, Lint & Repo Gates, Live E2E UI, Dogfood Regression Gate and Check Changeset all success). - No full dogfood battery is owed: the title has no `!` and there is no narrowing arm. --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QsR2jUcj2x2Wr4UErwBi12 <!-- signed: repo:objectstack#1 · os-project-manager · session_01FEkQ5obaLbqgzRUR9xXfft --> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 1089e9e commit 80cdbd4

10 files changed

Lines changed: 390 additions & 18 deletions
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
'@objectstack/metadata-protocol': patch
3+
'@objectstack/plugin-security': patch
4+
---
5+
6+
fix(metadata-protocol, plugin-security): a package's save of its own permission set is no longer refused because a package of another namespace ships a set of that name
7+
8+
Clause-②: yes (widening) — a save, a draft save or a draft's publish that a package addresses to its own permission set N, refused 403 `NOT_OVERRIDABLE` ("provided by a managed package and is sealed") while a package of another namespace ships N, now lands; the exported `MetadataAuthoringGateContext` (`@objectstack/metadata-protocol`) and `PermissionSetLockGateContext` (`@objectstack/plugin-security`) each gain an optional `packageId`; nothing the save door accepted is refused
9+
Metadata-protocol: none
10+
11+
A permission set is `(package, name)`, and a name holds one set per namespace (ADR-0150 D2/D9). The metadata door's managed seal (ADR-0126 / ADR-0131 D6) and plugin-security's packaged-permission-set lock both judged a save of a permission set by its name alone. So when package `crm` shipped a set `N`, a package `hr` of another namespace could not save its own set `N`: the save was refused as if it edited `crm`'s shipped set.
12+
13+
These judges, and the managed seal the store applies to the write a save or a draft's publish hands it, now judge the package the write is addressed to. A save of `N` overrides a set a package `Q` ships, and stays sealed and locked exactly as before, when it names no package, is addressed to `Q`, is addressed to `Q`'s customization pair (whatever namespace the pair declares), or is addressed to a package that shares `Q`'s set of the name (a co-owner of `Q`'s namespace, a platform namespace, a package with no namespace, or a name the platform requests by spelling). Every package that ships the name is judged, so the answer is the same in every registration order. Any other package's save of its own `N` lands, is served at that package, and that package's grants confer its own set.
14+
15+
What moves, for a save of `N` while a package of another namespace ships `N`:
16+
17+
- FROM 403 `NOT_OVERRIDABLE` (sealed) TO saved, for a save addressed to a package of another namespace than every package that ships `N`, which is not the customization pair of any of them. The same holds for a draft save of that set and for its publish.
18+
19+
When a package publish is refused on a runtime that cannot roll back its transaction, the undo of each promotion it made judges the same package the promotion addressed, so a package's own set `N` is taken back out and its draft is put back instead of being reported still live. Rollback and revert of such a set still judge the name alone, and other sealed package-scoped types keep the name-wide seal.
20+
21+
`MetadataAuthoringGateContext` (`@objectstack/metadata-protocol`) gains an optional `packageId`: the package the write is addressed to (a save's `packageId`, a restore's row binding), absent for a write that names none. An authoring gate that judges an item keyed `(package, name)` reads it. Gates that ignore it are unaffected. `PermissionSetLockGateContext` (`@objectstack/plugin-security`), the subset of it the lock gate consumes, gains the same optional `packageId`.
22+
23+
Nothing to migrate.

‎packages/metadata-protocol/src/protocol-authoring-channel.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,14 @@ export interface MetadataAuthoringGateContext {
4343
* when the door stated none: the gate composes `en`.
4444
*/
4545
userTextLocales?: readonly string[];
46+
/**
47+
* [ADR-0150 D2, #34226] The package the write is addressed to: the save's
48+
* `packageId`, or a restore's row binding. Absent or `null` for a write
49+
* naming no package. A gate that judges an item keyed `(package, name)`
50+
* reads it to tell a package's own item from another package's item of
51+
* the same name.
52+
*/
53+
packageId?: string | null;
4654
}
4755

4856
export type MetadataAuthoringGate = (ctx: MetadataAuthoringGateContext) => void | Promise<void>;

‎packages/metadata-protocol/src/protocol-authoring-gate.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ export async function refuseRestoredBodyTheSaveDoorRefuses(
177177
: {}),
178178
});
179179
if (this.authoringChannel !== 'package-author') {
180-
await this.runAuthoringGate({ type, name, state: 'active', body });
180+
await this.runAuthoringGate({ type, name, state: 'active', body, packageId: binding });
181181
}
182182
}
183183

@@ -186,7 +186,7 @@ export async function runAuthoringGate(
186186
this: Pick<AuthoringGateHost, 'authoringGates' | 'engine' | 'isArtifactBacked'>,
187187
evt: {
188188
type: string; name: string; state: 'draft' | 'active'; body: unknown;
189-
userTextLocales?: readonly (string | undefined)[];
189+
userTextLocales?: readonly (string | undefined)[]; packageId?: string | null;
190190
}): Promise<void> {
191191
const singular = PLURAL_TO_SINGULAR[evt.type] ?? evt.type;
192192
const gate = this.authoringGates.get(singular);
@@ -208,6 +208,8 @@ export async function runAuthoringGate(
208208
...(evt.userTextLocales !== undefined
209209
? { userTextLocales: evt.userTextLocales.filter((l): l is string => typeof l === 'string' && l.length > 0) }
210210
: {}),
211+
// [ADR-0150 D2, #34226] The package the write is addressed to.
212+
...(typeof evt.packageId === 'string' && evt.packageId !== '' ? { packageId: evt.packageId } : {}),
211213
});
212214
}
213215

‎packages/metadata-protocol/src/protocol-history-and-publish.ts‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ import type { MetadataItem } from '@objectstack/metadata-core';
3131
import { savedItemNameRefusal } from '@objectstack/metadata/view-container-name';
3232
import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared';
3333
import { serveStoredHashTokens, servedContentHash } from './metadata-redaction.js';
34-
import { overrideWriteRefusalError } from './protocol-packaged-base-refusal.js';
34+
import { isOwnPermissionSetWrite, overrideWriteRefusalError } from './protocol-packaged-base-refusal.js';
3535
import type { OverrideWriteVerdict } from './protocol-packaged-base-refusal.js';
3636
import { objectBodyExtensionFieldSuffixRefusal } from './protocol-extension-field-suffix.js';
3737
import { storedFlowVerdictBody } from './protocol-flow-save-replay.js';
@@ -124,7 +124,7 @@ function unwrittenPromotionError(type: string, name: string): Error {
124124
* active row stored, its history append then failed) is not in `landed` — the
125125
* promotion threw — and is the store's own non-atomicity on such a runtime.
126126
*/
127-
async function undoLandedPromotions(host: Pick<ProtocolHost, 'isArtifactBacked' | 'restoreArtifactRegistryView'>, args: {
127+
async function undoLandedPromotions(host: Pick<ProtocolHost, 'engine' | 'isArtifactBacked' | 'restoreArtifactRegistryView'>, args: {
128128
repo: SysMetadataRepository;
129129
landed: ReadonlyArray<LandedPromotion>;
130130
/** The pre-publish capture (`existedBefore` / `prevVersion` per item). */
@@ -139,9 +139,15 @@ async function undoLandedPromotions(host: Pick<ProtocolHost, 'isArtifactBacked'
139139
for (const item of [...args.landed].reverse()) {
140140
const ref = { type: item.singularType, name: item.d.name, org: 'env' } as unknown as Parameters<SysMetadataRepository['get']>[0];
141141
// Per item, as the revert derives it: a runtime item is not refused by
142-
// the artifact-override gate on its way back out.
143-
const intent: 'override-artifact' | 'runtime-only' =
144-
host.isArtifactBacked(item.singularType, item.d.name) ? 'override-artifact' : 'runtime-only';
142+
// the artifact-override gate on its way back out. [ADR-0150 D2] Per
143+
// write, as the promotion derived it: a package's own permission set
144+
// beside another namespace's shipped one is a runtime item to the
145+
// package each write addresses (`isOwnPermissionSetWrite`).
146+
const intentFor = (packageId: string | null): 'override-artifact' | 'runtime-only' =>
147+
host.isArtifactBacked(item.singularType, item.d.name)
148+
&& !isOwnPermissionSetWrite(host.engine, item.singularType, item.d.name, packageId)
149+
? 'override-artifact' : 'runtime-only';
150+
const intent = intentFor(item.packageId);
145151
try {
146152
if (!item.promotedDraft) {
147153
throw new Error(`the draft ${item.d.type}/${item.d.name} consumed was not captured, so it cannot be put back`);
@@ -177,7 +183,7 @@ async function undoLandedPromotions(host: Pick<ProtocolHost, 'isArtifactBacked'
177183
const pending = await args.repo.get(ref, { state: 'draft', packageId: draftKey, ...memberOption(item.d.member) });
178184
if (!pending) {
179185
await args.repo.put(ref, item.promotedDraft.body, {
180-
parentVersion: null, actor, source, message, intent, state: 'draft', packageId: draftKey,
186+
parentVersion: null, actor, source, message, intent: intentFor(draftKey), state: 'draft', packageId: draftKey,
181187
});
182188
// No registry entry serves a draft row: the heal re-derives this
183189
// item's entry from the active rows the store now serves, the
@@ -664,7 +670,7 @@ export class ProtocolHistoryAndPublishFacet {
664670
* `recordPendingDenialAudit`, rethrow. Skip it and the refusal is silent
665671
* again — the pre-#7748 state, not merely a worse one.
666672
*/
667-
static async promoteDraftForPublish(host: Pick<ProtocolHost, 'anonymousElevatedFlowRefusal' | 'assertRuntimeAuthoringRules' | 'classifyObjectContribution' | 'credentialChannelFor' | 'defaultRecordPageSaveRefusal' | 'ensureOverlayIndex' | 'externalBindingSaveRefusal' | 'getOverlayRepo' | 'isArtifactBacked' | 'isOverlayAllowed' | 'isRuntimeCreateAllowed' | 'isSealedManagedItem' | 'lockWriteRefusal' | 'metadataConflictRefusal' | 'namedBaseOverlayWriteRefusal' | 'objectExtensionItemRefusal' | 'objectNamespaceObjectNameClash' | 'objectNamespacePrefixViolation' | 'objectRegistrationRefusal' | 'optimisticConflictAuditEntry' | 'overlayPackageMismatchError' | 'overrideWriteVerdict' | 'packagelessAddress' | 'packagelessDraftAddress' | 'permissionSetNameCollisionRefusal' | 'resolveSduiManifest' | 'seedExternalIdSaveRefusal' | 'uninstalledNamedBaseRefusal' | 'unknownDatasourceSaveRefusal' | 'unknownGrantObjectSaveRefusal' | 'unknownPicklistBindingSaveRefusal'>, request: {
673+
static async promoteDraftForPublish(host: Pick<ProtocolHost, 'anonymousElevatedFlowRefusal' | 'assertRuntimeAuthoringRules' | 'classifyObjectContribution' | 'credentialChannelFor' | 'defaultRecordPageSaveRefusal' | 'engine' | 'ensureOverlayIndex' | 'externalBindingSaveRefusal' | 'getOverlayRepo' | 'isArtifactBacked' | 'isOverlayAllowed' | 'isRuntimeCreateAllowed' | 'isSealedManagedItem' | 'lockWriteRefusal' | 'metadataConflictRefusal' | 'namedBaseOverlayWriteRefusal' | 'objectExtensionItemRefusal' | 'objectNamespaceObjectNameClash' | 'objectNamespacePrefixViolation' | 'objectRegistrationRefusal' | 'optimisticConflictAuditEntry' | 'overlayPackageMismatchError' | 'overrideWriteVerdict' | 'packagelessAddress' | 'packagelessDraftAddress' | 'permissionSetNameCollisionRefusal' | 'resolveSduiManifest' | 'seedExternalIdSaveRefusal' | 'uninstalledNamedBaseRefusal' | 'unknownDatasourceSaveRefusal' | 'unknownGrantObjectSaveRefusal' | 'unknownPicklistBindingSaveRefusal'>, request: {
668674
type: string; name: string; actor?: string; message?: string;
669675
/**
670676
* [#8907] ADR-0048 — the package binding of the draft being promoted,
@@ -1251,7 +1257,7 @@ export class ProtocolHistoryAndPublishFacet {
12511257
...(draftForGate ? { judged: { body: draftForGate.body, packageId: promoteInto } } : {}),
12521258
};
12531259
}
1254-
const artifactBacked = host.isArtifactBacked(singularType, request.name);
1260+
const artifactBacked = host.isArtifactBacked(singularType, request.name) && !isOwnPermissionSetWrite(host.engine, singularType, request.name, promoteInto);
12551261
const intent: 'override-artifact' | 'runtime-only' = artifactBacked && !declaredOverride
12561262
? 'override-artifact' : 'runtime-only';
12571263
const ref = {

‎packages/metadata-protocol/src/protocol-packaged-base-refusal.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared';
6161
import { expandViewContainer, isAggregatedViewContainer } from '@objectstack/spec';
6262
import { ITEM_KEY_DISCRIMINATORS, isPairOf, itemDiscriminator, pairOf, type InstalledManifestLookup } from '@objectstack/metadata-core';
6363
import { installedManifestsOfEngine } from './installed-manifests.js';
64+
import { permissionSetHoldersMeet } from '@objectstack/core';
65+
import { lookupArtifactItem, shippedArtifactsOf, shippingPackagesOf, type ArtifactLookupHost } from './protocol-artifact-lookup.js';
6466

6567
/**
6668
* The `ObjectStackProtocolImplementation` members the functions below read —
@@ -151,6 +153,15 @@ export function refusePackagedBaseOverride(
151153
request.type, request.packageId as string,
152154
);
153155
}
156+
// [ADR-0150 D2, #34226] A permission set is `(package, name)`: a save
157+
// a package addresses to its own set of a name another namespace's
158+
// package ships overrides no shipped set, so the seal does not judge
159+
// it. Every save that does override one stays sealed, as before: one
160+
// naming no package, one addressed to the shipper, one addressed to
161+
// the shipper's customization pair (whatever the pair's namespace),
162+
// and one addressed to a package that shares the shipper's set of the
163+
// name ({@link isOwnPermissionSetWrite}).
164+
if (isOwnPermissionSetWrite(this.engine, request.type, request.name, request.packageId)) return;
154165
// [#20819, ADR-0131 D6] The SENTENCE is chosen per ADR-0126 regime,
155166
// and names the managed package for every other type; the code and
156167
// the status are unchanged. [#23577] Every write reads it, whatever
@@ -179,6 +190,68 @@ export function refusePackagedBaseOverride(
179190
}
180191
}
181192

193+
/**
194+
* [ADR-0150 D2/D9, ADR-0131 D6, #34226] Is a write of `(type, name)` addressed
195+
* to `packageId` a package's OWN permission set, beside sets other namespaces'
196+
* packages ship — a write that overrides no shipped set
197+
* ({@link overridesShippedPermissionSet}), though the name is artifact-backed?
198+
*
199+
* The one verdict every door that judges such a write as an override of the
200+
* shipped base reads in place of the name-wide artifact check: the save door's
201+
* seal ({@link refusePackagedBaseOverride}), and the write intent the save door
202+
* and the draft promotion hand the repository (`override-artifact` is the
203+
* repository's managed seal). `false` for every other type, and for a write
204+
* naming no package.
205+
*/
206+
export function isOwnPermissionSetWrite(engine: unknown, type: string, name: string, packageId: string | null | undefined): boolean {
207+
if ((PLURAL_TO_SINGULAR[type] ?? type) !== 'permission') return false;
208+
if (typeof packageId !== 'string' || packageId === '') return false;
209+
return !overridesShippedPermissionSet(engine, packageId, name);
210+
}
211+
212+
/**
213+
* [ADR-0150 D2/D9, ADR-0131 D6, #34226] Does a save of the permission set
214+
* `name` addressed to the package `writer` override a set a package ships?
215+
*
216+
* A set is `(package, name)`, and a name is one set per namespace: two
217+
* packages share one set of a name exactly when the ONE predicate the install
218+
* gate and the save door's name rule ask says they meet
219+
* (`permissionSetHoldersMeet`, `@objectstack/core`). So the save overrides the
220+
* set a package Q ships when `writer` is Q's customization pair (ADR-0146:
221+
* the pair customizes Q's own items, whatever namespace the pair declares), or
222+
* when `writer` meets Q under that predicate: Q itself, a co-owner of Q's
223+
* namespace, a platform namespace, a package with no namespace, a name the
224+
* platform requests by spelling. Every package that
225+
* ships the name is judged, never the first found, so the answer is the same
226+
* in every registration order.
227+
*
228+
* `true` when no shipping package can be read: the seal then judges the name
229+
* as it always did. The plugin-security lock judges the same three
230+
* relations for the same write (`packaged-permission-set-lock-gate.ts`).
231+
*/
232+
function overridesShippedPermissionSet(engine: unknown, writer: string, name: string): boolean {
233+
const lookup: Pick<ArtifactLookupHost, 'engine' | 'lookupArtifactItem' | 'shippingPackagesOf'> = {
234+
engine: engine as ArtifactLookupHost['engine'],
235+
lookupArtifactItem: (...a) => lookupArtifactItem.call(lookup, ...a),
236+
shippingPackagesOf: (...a) => shippingPackagesOf.call(lookup, ...a),
237+
};
238+
const shippers = new Set<string>();
239+
for (const artifact of shippedArtifactsOf.call(lookup, 'permission', name)) {
240+
const packageId = (artifact as { _packageId?: unknown } | null)?._packageId;
241+
if (typeof packageId === 'string' && packageId !== '') shippers.add(packageId);
242+
}
243+
if (shippers.size === 0) return true;
244+
const registry = (engine as { registry?: { getPackage?: (id: string) => { manifest?: { namespace?: unknown } } | undefined } } | null)?.registry;
245+
const namespaceOf = (packageId: string): string | undefined => {
246+
const namespace = registry?.getPackage?.(packageId)?.manifest?.namespace;
247+
return typeof namespace === 'string' && namespace !== '' ? namespace : undefined;
248+
};
249+
const installed = installedManifestsOfEngine(engine);
250+
// A package meets itself under the predicate, so the shipper's own save is judged by the last clause.
251+
return [...shippers].some((shipper) => isPairOf(writer, shipper, installed)
252+
|| permissionSetHoldersMeet(namespaceOf(writer), namespaceOf(shipper), name));
253+
}
254+
182255
/**
183256
* [ADR-0146 D2] The sealed write's second sentence on a type whose override
184257
* channel is open, chosen by who writes:

‎packages/metadata-protocol/src/protocol-save.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ import type {
4646
StoredMigrationTodo,
4747
} from './stored-migration.js';
4848
import { droppedWithheldKeyNotices } from './protocol-credential-carry-forward.js';
49-
import { overrideWriteRefusalError } from './protocol-packaged-base-refusal.js';
49+
import { isOwnPermissionSetWrite, overrideWriteRefusalError } from './protocol-packaged-base-refusal.js';
5050
import { objectBodyExtensionFieldSuffixRefusal } from './protocol-extension-field-suffix.js';
5151
import { flowVerdictBody } from './protocol-flow-save-replay.js';
5252
import { withParsedStoredActions } from './protocol-stored-action-parse.js';
@@ -1824,6 +1824,7 @@ export class ProtocolSaveFacet {
18241824
state: mode === 'draft' ? 'draft' : 'active',
18251825
body: request.item,
18261826
...(request.userTextLocales !== undefined ? { userTextLocales: request.userTextLocales } : {}),
1827+
packageId: request.packageId,
18271828
});
18281829
}
18291830

@@ -1908,7 +1909,7 @@ export class ProtocolSaveFacet {
19081909
}
19091910
if (lateOverrideVerdict.verdict === 'refuse') throw overrideWriteRefusalError(lateOverrideVerdict);
19101911
const singularTypeForRepo = PLURAL_TO_SINGULAR[request.type] ?? request.type;
1911-
const artifactBacked = host.isArtifactBacked(singularTypeForRepo, request.name);
1912+
const artifactBacked = host.isArtifactBacked(singularTypeForRepo, request.name) && !isOwnPermissionSetWrite(host.engine, singularTypeForRepo, request.name, request.packageId);
19121913
// [ADR-0146 D2] An admitted declared override writes the pair's own
19131914
// row; it edits no managed item, so the store judges a runtime write.
19141915
const intent: 'override-artifact' | 'runtime-only' = artifactBacked && !declaredOverride

‎packages/metadata-protocol/src/protocol.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1755,7 +1755,7 @@ export class ObjectStackProtocolImplementation implements
17551755
*/
17561756
private runAuthoringGate(evt: {
17571757
type: string; name: string; state: 'draft' | 'active'; body: unknown;
1758-
userTextLocales?: readonly (string | undefined)[];
1758+
userTextLocales?: readonly (string | undefined)[]; packageId?: string | null;
17591759
}): Promise<void> {
17601760
// [#25467 cut 8] The body moved to `protocol-authoring-gate.ts` (see `AuthoringGateHost`).
17611761
const readAuthoringGates = () => this.authoringGates;

0 commit comments

Comments
 (0)