Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .changeset/34226-permission-set-seal-by-package.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
'@objectstack/metadata-protocol': patch
'@objectstack/plugin-security': patch
---

fix(metadata-protocol, plugin-security): a package's save of its own permission set is no longer refused because a package of another namespace ships a set of that name

Clause-②: yes (widening) — a save, a draft save or a draft's publish that a package addresses to its own permission set N, refused 403 `NOT_OVERRIDABLE` ("provided by a managed package and is sealed") while a package of another namespace ships N, now lands; the exported `MetadataAuthoringGateContext` (`@objectstack/metadata-protocol`) and `PermissionSetLockGateContext` (`@objectstack/plugin-security`) each gain an optional `packageId`; nothing the save door accepted is refused
Metadata-protocol: none

A permission set is `(package, name)`, and a name holds one set per namespace (ADR-0150 D2/D9). The metadata door's managed seal (ADR-0126 / ADR-0131 D6) and plugin-security's packaged-permission-set lock both judged a save of a permission set by its name alone. So when package `crm` shipped a set `N`, a package `hr` of another namespace could not save its own set `N`: the save was refused as if it edited `crm`'s shipped set.

These judges, and the managed seal the store applies to the write a save or a draft's publish hands it, now judge the package the write is addressed to. A save of `N` overrides a set a package `Q` ships, and stays sealed and locked exactly as before, when it names no package, is addressed to `Q`, is addressed to `Q`'s customization pair (whatever namespace the pair declares), or is addressed to a package that shares `Q`'s set of the name (a co-owner of `Q`'s namespace, a platform namespace, a package with no namespace, or a name the platform requests by spelling). Every package that ships the name is judged, so the answer is the same in every registration order. Any other package's save of its own `N` lands, is served at that package, and that package's grants confer its own set.

What moves, for a save of `N` while a package of another namespace ships `N`:

- FROM 403 `NOT_OVERRIDABLE` (sealed) TO saved, for a save addressed to a package of another namespace than every package that ships `N`, which is not the customization pair of any of them. The same holds for a draft save of that set and for its publish.

When a package publish is refused on a runtime that cannot roll back its transaction, the undo of each promotion it made judges the same package the promotion addressed, so a package's own set `N` is taken back out and its draft is put back instead of being reported still live. Rollback and revert of such a set still judge the name alone, and other sealed package-scoped types keep the name-wide seal.

`MetadataAuthoringGateContext` (`@objectstack/metadata-protocol`) gains an optional `packageId`: the package the write is addressed to (a save's `packageId`, a restore's row binding), absent for a write that names none. An authoring gate that judges an item keyed `(package, name)` reads it. Gates that ignore it are unaffected. `PermissionSetLockGateContext` (`@objectstack/plugin-security`), the subset of it the lock gate consumes, gains the same optional `packageId`.

Nothing to migrate.
8 changes: 8 additions & 0 deletions packages/metadata-protocol/src/protocol-authoring-channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ export interface MetadataAuthoringGateContext {
* when the door stated none: the gate composes `en`.
*/
userTextLocales?: readonly string[];
/**
* [ADR-0150 D2, #34226] The package the write is addressed to: the save's
* `packageId`, or a restore's row binding. Absent or `null` for a write
* naming no package. A gate that judges an item keyed `(package, name)`
* reads it to tell a package's own item from another package's item of
* the same name.
*/
packageId?: string | null;
}

export type MetadataAuthoringGate = (ctx: MetadataAuthoringGateContext) => void | Promise<void>;
Expand Down
6 changes: 4 additions & 2 deletions packages/metadata-protocol/src/protocol-authoring-gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ export async function refuseRestoredBodyTheSaveDoorRefuses(
: {}),
});
if (this.authoringChannel !== 'package-author') {
await this.runAuthoringGate({ type, name, state: 'active', body });
await this.runAuthoringGate({ type, name, state: 'active', body, packageId: binding });
}
}

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

Expand Down
22 changes: 14 additions & 8 deletions packages/metadata-protocol/src/protocol-history-and-publish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import type { MetadataItem } from '@objectstack/metadata-core';
import { savedItemNameRefusal } from '@objectstack/metadata/view-container-name';
import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared';
import { serveStoredHashTokens, servedContentHash } from './metadata-redaction.js';
import { overrideWriteRefusalError } from './protocol-packaged-base-refusal.js';
import { isOwnPermissionSetWrite, overrideWriteRefusalError } from './protocol-packaged-base-refusal.js';
import type { OverrideWriteVerdict } from './protocol-packaged-base-refusal.js';
import { objectBodyExtensionFieldSuffixRefusal } from './protocol-extension-field-suffix.js';
import { storedFlowVerdictBody } from './protocol-flow-save-replay.js';
Expand Down Expand Up @@ -124,7 +124,7 @@ function unwrittenPromotionError(type: string, name: string): Error {
* active row stored, its history append then failed) is not in `landed` — the
* promotion threw — and is the store's own non-atomicity on such a runtime.
*/
async function undoLandedPromotions(host: Pick<ProtocolHost, 'isArtifactBacked' | 'restoreArtifactRegistryView'>, args: {
async function undoLandedPromotions(host: Pick<ProtocolHost, 'engine' | 'isArtifactBacked' | 'restoreArtifactRegistryView'>, args: {
repo: SysMetadataRepository;
landed: ReadonlyArray<LandedPromotion>;
/** The pre-publish capture (`existedBefore` / `prevVersion` per item). */
Expand All @@ -139,9 +139,15 @@ async function undoLandedPromotions(host: Pick<ProtocolHost, 'isArtifactBacked'
for (const item of [...args.landed].reverse()) {
const ref = { type: item.singularType, name: item.d.name, org: 'env' } as unknown as Parameters<SysMetadataRepository['get']>[0];
// Per item, as the revert derives it: a runtime item is not refused by
// the artifact-override gate on its way back out.
const intent: 'override-artifact' | 'runtime-only' =
host.isArtifactBacked(item.singularType, item.d.name) ? 'override-artifact' : 'runtime-only';
// the artifact-override gate on its way back out. [ADR-0150 D2] Per
// write, as the promotion derived it: a package's own permission set
// beside another namespace's shipped one is a runtime item to the
// package each write addresses (`isOwnPermissionSetWrite`).
const intentFor = (packageId: string | null): 'override-artifact' | 'runtime-only' =>
host.isArtifactBacked(item.singularType, item.d.name)
&& !isOwnPermissionSetWrite(host.engine, item.singularType, item.d.name, packageId)
? 'override-artifact' : 'runtime-only';
const intent = intentFor(item.packageId);
try {
if (!item.promotedDraft) {
throw new Error(`the draft ${item.d.type}/${item.d.name} consumed was not captured, so it cannot be put back`);
Expand Down Expand Up @@ -177,7 +183,7 @@ async function undoLandedPromotions(host: Pick<ProtocolHost, 'isArtifactBacked'
const pending = await args.repo.get(ref, { state: 'draft', packageId: draftKey, ...memberOption(item.d.member) });
if (!pending) {
await args.repo.put(ref, item.promotedDraft.body, {
parentVersion: null, actor, source, message, intent, state: 'draft', packageId: draftKey,
parentVersion: null, actor, source, message, intent: intentFor(draftKey), state: 'draft', packageId: draftKey,
});
// No registry entry serves a draft row: the heal re-derives this
// item's entry from the active rows the store now serves, the
Expand Down Expand Up @@ -664,7 +670,7 @@ export class ProtocolHistoryAndPublishFacet {
* `recordPendingDenialAudit`, rethrow. Skip it and the refusal is silent
* again — the pre-#7748 state, not merely a worse one.
*/
static async promoteDraftForPublish(host: Pick<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: {
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: {
type: string; name: string; actor?: string; message?: string;
/**
* [#8907] ADR-0048 — the package binding of the draft being promoted,
Expand Down Expand Up @@ -1251,7 +1257,7 @@ export class ProtocolHistoryAndPublishFacet {
...(draftForGate ? { judged: { body: draftForGate.body, packageId: promoteInto } } : {}),
};
}
const artifactBacked = host.isArtifactBacked(singularType, request.name);
const artifactBacked = host.isArtifactBacked(singularType, request.name) && !isOwnPermissionSetWrite(host.engine, singularType, request.name, promoteInto);
const intent: 'override-artifact' | 'runtime-only' = artifactBacked && !declaredOverride
? 'override-artifact' : 'runtime-only';
const ref = {
Expand Down
73 changes: 73 additions & 0 deletions packages/metadata-protocol/src/protocol-packaged-base-refusal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ import { PLURAL_TO_SINGULAR } from '@objectstack/spec/shared';
import { expandViewContainer, isAggregatedViewContainer } from '@objectstack/spec';
import { ITEM_KEY_DISCRIMINATORS, isPairOf, itemDiscriminator, pairOf, type InstalledManifestLookup } from '@objectstack/metadata-core';
import { installedManifestsOfEngine } from './installed-manifests.js';
import { permissionSetHoldersMeet } from '@objectstack/core';
import { lookupArtifactItem, shippedArtifactsOf, shippingPackagesOf, type ArtifactLookupHost } from './protocol-artifact-lookup.js';

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

/**
* [ADR-0150 D2/D9, ADR-0131 D6, #34226] Is a write of `(type, name)` addressed
* to `packageId` a package's OWN permission set, beside sets other namespaces'
* packages ship — a write that overrides no shipped set
* ({@link overridesShippedPermissionSet}), though the name is artifact-backed?
*
* The one verdict every door that judges such a write as an override of the
* shipped base reads in place of the name-wide artifact check: the save door's
* seal ({@link refusePackagedBaseOverride}), and the write intent the save door
* and the draft promotion hand the repository (`override-artifact` is the
* repository's managed seal). `false` for every other type, and for a write
* naming no package.
*/
export function isOwnPermissionSetWrite(engine: unknown, type: string, name: string, packageId: string | null | undefined): boolean {
if ((PLURAL_TO_SINGULAR[type] ?? type) !== 'permission') return false;
if (typeof packageId !== 'string' || packageId === '') return false;
return !overridesShippedPermissionSet(engine, packageId, name);
}

/**
* [ADR-0150 D2/D9, ADR-0131 D6, #34226] Does a save of the permission set
* `name` addressed to the package `writer` override a set a package ships?
*
* A set is `(package, name)`, and a name is one set per namespace: two
* packages share one set of a name exactly when the ONE predicate the install
* gate and the save door's name rule ask says they meet
* (`permissionSetHoldersMeet`, `@objectstack/core`). So the save overrides the
* set a package Q ships when `writer` is Q's customization pair (ADR-0146:
* the pair customizes Q's own items, whatever namespace the pair declares), or
* when `writer` meets Q under that predicate: Q itself, a co-owner of Q's
* namespace, a platform namespace, a package with no namespace, a name the
* platform requests by spelling. Every package that
* ships the name is judged, never the first found, so the answer is the same
* in every registration order.
*
* `true` when no shipping package can be read: the seal then judges the name
* as it always did. The plugin-security lock judges the same three
* relations for the same write (`packaged-permission-set-lock-gate.ts`).
*/
function overridesShippedPermissionSet(engine: unknown, writer: string, name: string): boolean {
const lookup: Pick<ArtifactLookupHost, 'engine' | 'lookupArtifactItem' | 'shippingPackagesOf'> = {
engine: engine as ArtifactLookupHost['engine'],
lookupArtifactItem: (...a) => lookupArtifactItem.call(lookup, ...a),
shippingPackagesOf: (...a) => shippingPackagesOf.call(lookup, ...a),
};
const shippers = new Set<string>();
for (const artifact of shippedArtifactsOf.call(lookup, 'permission', name)) {
const packageId = (artifact as { _packageId?: unknown } | null)?._packageId;
if (typeof packageId === 'string' && packageId !== '') shippers.add(packageId);
}
if (shippers.size === 0) return true;
const registry = (engine as { registry?: { getPackage?: (id: string) => { manifest?: { namespace?: unknown } } | undefined } } | null)?.registry;
const namespaceOf = (packageId: string): string | undefined => {
const namespace = registry?.getPackage?.(packageId)?.manifest?.namespace;
return typeof namespace === 'string' && namespace !== '' ? namespace : undefined;
};
const installed = installedManifestsOfEngine(engine);
// A package meets itself under the predicate, so the shipper's own save is judged by the last clause.
return [...shippers].some((shipper) => isPairOf(writer, shipper, installed)
|| permissionSetHoldersMeet(namespaceOf(writer), namespaceOf(shipper), name));
}

/**
* [ADR-0146 D2] The sealed write's second sentence on a type whose override
* channel is open, chosen by who writes:
Expand Down
5 changes: 3 additions & 2 deletions packages/metadata-protocol/src/protocol-save.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ import type {
StoredMigrationTodo,
} from './stored-migration.js';
import { droppedWithheldKeyNotices } from './protocol-credential-carry-forward.js';
import { overrideWriteRefusalError } from './protocol-packaged-base-refusal.js';
import { isOwnPermissionSetWrite, overrideWriteRefusalError } from './protocol-packaged-base-refusal.js';
import { objectBodyExtensionFieldSuffixRefusal } from './protocol-extension-field-suffix.js';
import { flowVerdictBody } from './protocol-flow-save-replay.js';
import { withParsedStoredActions } from './protocol-stored-action-parse.js';
Expand Down Expand Up @@ -1824,6 +1824,7 @@ export class ProtocolSaveFacet {
state: mode === 'draft' ? 'draft' : 'active',
body: request.item,
...(request.userTextLocales !== undefined ? { userTextLocales: request.userTextLocales } : {}),
packageId: request.packageId,
});
}

Expand Down Expand Up @@ -1908,7 +1909,7 @@ export class ProtocolSaveFacet {
}
if (lateOverrideVerdict.verdict === 'refuse') throw overrideWriteRefusalError(lateOverrideVerdict);
const singularTypeForRepo = PLURAL_TO_SINGULAR[request.type] ?? request.type;
const artifactBacked = host.isArtifactBacked(singularTypeForRepo, request.name);
const artifactBacked = host.isArtifactBacked(singularTypeForRepo, request.name) && !isOwnPermissionSetWrite(host.engine, singularTypeForRepo, request.name, request.packageId);
// [ADR-0146 D2] An admitted declared override writes the pair's own
// row; it edits no managed item, so the store judges a runtime write.
const intent: 'override-artifact' | 'runtime-only' = artifactBacked && !declaredOverride
Expand Down
2 changes: 1 addition & 1 deletion packages/metadata-protocol/src/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1755,7 +1755,7 @@ export class ObjectStackProtocolImplementation implements
*/
private runAuthoringGate(evt: {
type: string; name: string; state: 'draft' | 'active'; body: unknown;
userTextLocales?: readonly (string | undefined)[];
userTextLocales?: readonly (string | undefined)[]; packageId?: string | null;
}): Promise<void> {
// [#25467 cut 8] The body moved to `protocol-authoring-gate.ts` (see `AuthoringGateHost`).
const readAuthoringGates = () => this.authoringGates;
Expand Down
Loading
Loading