Skip to content

Commit df8adcf

Browse files
committed
fix(metadata-protocol): restore and delete a package's own permission set beside another namespace's shipped set
Claude-Session: https://claude.ai/code/session_01ADHkmPhrvD6HH5p4xPZ2jX Co-authored-by: Claude <noreply@anthropic.com>
1 parent bdd5176 commit df8adcf

3 files changed

Lines changed: 172 additions & 7 deletions

File tree

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

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ import type { IObjectQLEngine, IPubSub } from '@objectstack/spec/contracts';
4242
import { isPairOf } from '@objectstack/metadata-core';
4343
import { installedManifestsOfEngine } from './installed-manifests.js';
4444
import { someShipperOf } from './protocol-environment-rows.js';
45-
import { overrideWriteRefusalError } from './protocol-packaged-base-refusal.js';
45+
import { isOwnPermissionSetWrite, overrideWriteRefusalError } from './protocol-packaged-base-refusal.js';
4646
import { OBJECT_EXTENSION_TYPE, registrableObjectExtension } from './protocol-object-extension-item.js';
4747
import type { ObjectExtensionRegistry } from './protocol-object-extension-item.js';
4848
import { canonicalMetaType } from './protocol-meta-type-schema.js';
@@ -201,19 +201,27 @@ export class ProtocolClassHeadFacet {
201201
* `deriveRestoredBody`, so nothing is written. Any other binding: the
202202
* caller's `artifactBacked` decides the intent, and the body writer is
203203
* {@link restoredBodyWriter}'s alone.
204+
*
205+
* [ADR-0150 D2, #34401] A restore into a package's OWN permission set,
206+
* beside sets other namespaces' packages ship, overrides no shipped set,
207+
* so the name-wide `artifactBacked` is narrowed by the verdict the save,
208+
* publish and undo doors read ({@link isOwnPermissionSetWrite}): the
209+
* store is told a runtime-only write, as that package's save is. Every
210+
* restore that does override a shipped set keeps the intent it had.
204211
*/
205212
static restoreWriteFor(host: Pick<ProtocolHost, 'engine' | 'overrideWriteVerdict' | 'packagedArtifactOwner' | 'restoredBodyWriter' | 'shippedArtifactsOf'>, singularType: string,
206213
name: string,
207214
binding: string | null,
208215
artifactBacked: boolean,
209216
source: string,): { intent: 'override-artifact' | 'runtime-only'; deriveRestoredBody: (historyBody: unknown) => Promise<unknown> } {
217+
const overridesShipped = artifactBacked && !isOwnPermissionSetWrite(host.engine, singularType, name, binding);
210218
// [ADR-0150 D4, #32552] The binding is judged against every package
211219
// that ships the name ({@link someShipperOf}): each namespace's holder
212220
// has its own pair, never only the shipper registered first.
213221
const installed = installedManifestsOfEngine(host.engine);
214-
const pairRow = artifactBacked && someShipperOf(host, singularType, name,
222+
const pairRow = overridesShipped && someShipperOf(host, singularType, name,
215223
(owner) => owner !== undefined && isPairOf(binding, owner, installed));
216-
const intent: 'override-artifact' | 'runtime-only' = artifactBacked && !pairRow ? 'override-artifact' : 'runtime-only';
224+
const intent: 'override-artifact' | 'runtime-only' = overridesShipped && !pairRow ? 'override-artifact' : 'runtime-only';
217225
const writeRestored = host.restoredBodyWriter(singularType, name, binding, source);
218226
const deriveRestoredBody = pairRow
219227
? async (historyBody: unknown): Promise<unknown> => {

‎packages/metadata-protocol/src/protocol-diff-delete-load.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ import type { ServedOverrideRow } from './served-override.js';
4747
import { REFERENCE_SITES } from './reference-sites.js';
4848
import { computeMetadataDiagnostics } from './metadata-diagnostics.js';
4949
import { hasMetadataRedactor, redactMetadataItem } from './metadata-redaction.js';
50-
import { isPairRowRemoval } from './protocol-packaged-base-refusal.js';
50+
import { isOwnPermissionSetWrite, isPairRowRemoval } from './protocol-packaged-base-refusal.js';
5151
import { canonicalMetaType, canonicalizeMetaRequestType } from './protocol-meta-type-schema.js';
5252
import { boundPackageOf, servesSealedOverrideRow } from './protocol-package-bindings.js';
5353
import { remainingRowsPhrase } from './protocol-authoring-refusals.js';
@@ -750,6 +750,13 @@ export class ProtocolDiffDeleteLoadFacet {
750750
}
751751
const packageId: string | null = request.packageId
752752
?? (draftAddress !== undefined ? draftAddress.key : rowsAtAddress.packageId);
753+
// [ADR-0150 D2, #34401] Whether a code-shipped item sits under
754+
// THIS address, which the two receipts below claim: a package's
755+
// own permission set beside sets other namespaces' packages ship
756+
// has none ({@link isOwnPermissionSetWrite}, the verdict its save
757+
// reads), so removing it removes the set, never resets one.
758+
const shippedUnderAddress = artifactBacked
759+
&& !isOwnPermissionSetWrite(host.engine, singularTypeForRepo, request.name, packageId);
753760
// Probe first — "no overlay exists" is a success/no-op, not
754761
// a conflict. The repo would otherwise throw ConflictError.
755762
const current = await repo.get(ref, { state: targetState, packageId, ...memberOption(member) });
@@ -817,7 +824,7 @@ export class ProtocolDiffDeleteLoadFacet {
817824
// unchanged, verbatim.
818825
message: targetState === 'draft'
819826
? `No pending draft for ${request.type}/${request.name}.`
820-
: artifactBacked
827+
: shippedUnderAddress
821828
? `No customization overlay found for ${request.type}/${request.name} — already at artifact default.`
822829
: `No ${singularTypeForRepo} '${request.name}' found — nothing to delete.`,
823830
};
@@ -1005,7 +1012,7 @@ export class ProtocolDiffDeleteLoadFacet {
10051012
// discard reads byte for byte as before.
10061013
message: (request.state === 'draft')
10071014
? `Draft discarded${deletedPackage} — ${request.type}/${request.name}. [seq=${result.seq}]`
1008-
: artifactBacked
1015+
: shippedUnderAddress
10091016
? (remains
10101017
? `Customization overlay deleted${deletedPackage} — ${request.type}/${request.name} still carries another overlay: ${remainingRowsPhrase(remainingPackages, unboundRemains, 'row')}. [seq=${result.seq}]`
10111018
: `Customization overlay deleted${deletedPackage} — ${request.type}/${request.name} reset to artifact default. [seq=${result.seq}]`)

‎packages/plugins/plugin-security/src/packaged-permission-set-lock-gate.test.ts‎

Lines changed: 151 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ function makeFakeEngine(opts?: { listItemsThrows?: boolean }) {
106106
];
107107
return {
108108
rows,
109+
historyRows,
109110
manifests: new Map<string, unknown>([[PKG, { id: PKG }]]),
110111
registry: {
111112
getPackage: () => undefined,
@@ -143,7 +144,9 @@ function makeFakeEngine(opts?: { listItemsThrows?: boolean }) {
143144
historyRows.push(h);
144145
return { id: h.id as string };
145146
}
146-
const k = keyOf(data, table);
147+
// A metadata row is keyed by its address; a row of any other table (a
148+
// package commit) by its own id, so a second one never replaces the first.
149+
const k = table === 'sys_metadata' ? keyOf(data, table) : `${table}|${String(data.id ?? rows.size + 1)}`;
147150
const row: Row = { id: `r_${rows.size + 1}`, __table: table, ...data };
148151
rows.set(k, row);
149152
return { id: row.id as string };
@@ -521,4 +524,151 @@ describe('[#34226] a permission set is (package, name): the seal and the lock ju
521524
}
522525
}, 30_000);
523526
}
527+
528+
// [#34401] A rollback, a commit revert and a package rollback of hr's own set N
529+
// write the row bound to hr, so they judge it as hr's save does: a runtime item
530+
// to hr, never an override of crm's shipped N. A delete of it says what it did.
531+
describe('[#34401] restoring or deleting a package\'s own set N beside another namespace\'s shipped N', () => {
532+
type Proto = {
533+
saveMetaItem(req: Record<string, unknown>): Promise<unknown>;
534+
rollbackMetaItem(req: Record<string, unknown>): Promise<unknown>;
535+
publishPackageDrafts(req: Record<string, unknown>): Promise<{ commitId?: string; failed?: unknown[] }>;
536+
revertCommit(req: Record<string, unknown>): Promise<{ success: boolean; failed: Array<{ name: string; code?: string }> }>;
537+
rollbackToPackageCommit(req: Record<string, unknown>): Promise<{ success: boolean; failed: unknown[] }>;
538+
deleteMetaItem(req: Record<string, unknown>): Promise<{ success: boolean; reset?: boolean; message?: string }>;
539+
};
540+
type Engine = Awaited<ReturnType<typeof composition>>['engine'];
541+
const settle = <T>(p: Promise<T>) => p.then((v) => ({ ok: v, err: null as unknown }), (e: unknown) => ({ ok: undefined as T | undefined, err: e }));
542+
const envelope = (err: unknown) => [(err as { code?: unknown } | null)?.code, (err as { status?: unknown } | null)?.status];
543+
const activeCaps = (engine: Engine) => metaRowsOf(engine)
544+
.filter((r) => r.state === 'active')
545+
.map((r) => ({ package_id: r.package_id, caps: (JSON.parse(String(r.metadata)) as { systemPermissions?: string[] }).systemPermissions }));
546+
/** Every stored row and history entry of N moved to `binding`, as a row stored before the seal would be bound. */
547+
const rebind = (engine: Engine, binding: string | null) => {
548+
for (const [key, row] of engine.rows) if (row.__table === 'sys_metadata') engine.rows.set(key, { ...row, package_id: binding });
549+
for (const h of engine.historyRows) h.package_id = binding;
550+
};
551+
552+
/** hr's own N saved at v1, then edited to v2, each a save addressed to hr. */
553+
async function savedTwice(order: Order, shippers?: readonly string[]) {
554+
const c = await composition(order, shippers);
555+
const p = c.protocol as unknown as Proto;
556+
expect(await save(p, { type: 'permission', name: N, item: setOf('cap_hr_v1'), packageId: HR })).toBeNull();
557+
expect(await save(p, { type: 'permission', name: N, item: setOf('cap_hr_v2'), packageId: HR })).toBeNull();
558+
expect(activeCaps(c.engine)).toEqual([{ package_id: HR, caps: ['cap_hr_v2'] }]);
559+
return { ...c, p };
560+
}
561+
562+
/** hr's own N published at v1 (commit one), then edited and published at v2 (commit two). */
563+
async function publishedTwice(order: Order, shippers?: readonly string[]) {
564+
const c = await composition(order, shippers);
565+
const p = c.protocol as unknown as Proto;
566+
const commits: string[] = [];
567+
for (const cap of ['cap_hr_v1', 'cap_hr_v2']) {
568+
expect(await save(p, { type: 'permission', name: N, item: setOf(cap), packageId: HR, mode: 'draft' })).toBeNull();
569+
const res = await p.publishPackageDrafts({ packageId: HR });
570+
expect(res.commitId, JSON.stringify(res)).toEqual(expect.any(String));
571+
commits.push(res.commitId!);
572+
}
573+
expect(activeCaps(c.engine)).toEqual([{ package_id: HR, caps: ['cap_hr_v2'] }]);
574+
return { ...c, p, commits };
575+
}
576+
577+
for (const order of ORDERS) {
578+
it(`${order}: rolling back hr's own N to v1 restores v1, and hr's grant confers it (FROM 403 NOT_OVERRIDABLE)`, async () => {
579+
const { engine, registry, p } = await savedTwice(order);
580+
const { err } = await settle(p.rollbackMetaItem({ type: 'permission', name: N, toVersion: 1, packageId: HR }));
581+
expect(err).toBeNull();
582+
expect(activeCaps(engine)).toEqual([{ package_id: HR, caps: ['cap_hr_v1'] }]);
583+
expect({ crm: await confers(registry, CRM), hr: await confers(registry, HR) }).toEqual({ crm: ['cap_crm_shipped'], hr: ['cap_hr_v1'] });
584+
}, 30_000);
585+
586+
it(`${order}: reverting hr's commit that edited N restores v1 (FROM N in failed[] with NOT_OVERRIDABLE)`, async () => {
587+
const { engine, registry, p, commits } = await publishedTwice(order);
588+
const res = await p.revertCommit({ commitId: commits[1], packageId: HR });
589+
expect(res.failed).toEqual([]);
590+
expect(res.success).toBe(true);
591+
expect(activeCaps(engine)).toEqual([{ package_id: HR, caps: ['cap_hr_v1'] }]);
592+
expect(await confers(registry, HR)).toEqual(['cap_hr_v1']);
593+
}, 30_000);
594+
595+
it(`${order}: rolling hr back to its earlier commit restores v1 (FROM the revert failed)`, async () => {
596+
const { engine, p, commits } = await publishedTwice(order);
597+
const res = await p.rollbackToPackageCommit({ commitId: commits[0], packageId: HR });
598+
expect(res.failed).toEqual([]);
599+
expect(res.success).toBe(true);
600+
expect(activeCaps(engine)).toEqual([{ package_id: HR, caps: ['cap_hr_v1'] }]);
601+
}, 30_000);
602+
603+
it(`${order}: with crm AND fin shipping N, the rollback and the commit revert still restore: every shipper is judged`, async () => {
604+
const saved = await savedTwice(order, [CRM, FIN]);
605+
expect((await settle(saved.p.rollbackMetaItem({ type: 'permission', name: N, toVersion: 1, packageId: HR }))).err).toBeNull();
606+
expect(activeCaps(saved.engine)).toEqual([{ package_id: HR, caps: ['cap_hr_v1'] }]);
607+
const published = await publishedTwice(order, [FIN, CRM]);
608+
expect((await published.p.revertCommit({ commitId: published.commits[1], packageId: HR })).failed).toEqual([]);
609+
expect(activeCaps(published.engine)).toEqual([{ package_id: HR, caps: ['cap_hr_v1'] }]);
610+
}, 30_000);
611+
612+
// Rows of N bound to an address that overrides crm's shipped set cannot be saved
613+
// there; each case stores hr's rows, then rebinds them, as a row stored before
614+
// the seal would be. The restore into each is refused as it was, nothing written.
615+
// Each envelope is the one main answered, measured before this change: the
616+
// restore's seal for crm and its pair, and a refusal judged ahead of it for
617+
// the rest (the one-name-per-namespace rule, and a package-less address).
618+
it.each([
619+
['bound to no package', null, [CRM], ['RESOURCE_CONFLICT', 409]],
620+
['bound to crm', CRM, [CRM], ['NOT_OVERRIDABLE', 403]],
621+
['bound to crm\'s customization pair (another namespace)', CRM_PAIR, [CRM], ['NOT_OVERRIDABLE', 403]],
622+
['bound to a co-owner of crm\'s namespace', CRM_TWO, [CRM], ['NAMESPACE_CONFLICT', 422]],
623+
['bound to a co-owner of fin\'s namespace, fin also shipping', CRM_TWO, [FIN, CRM], ['NAMESPACE_CONFLICT', 422]],
624+
] as const)(`${order}: CONTROL — a rollback of N %s is refused as before`, async (_how, binding, shippers, expected) => {
625+
const { engine, p } = await savedTwice(order, shippers);
626+
rebind(engine, binding);
627+
const { err } = await settle(p.rollbackMetaItem({ type: 'permission', name: N, toVersion: 1, ...(binding ? { packageId: binding } : {}) }));
628+
expect(envelope(err)).toEqual(expected);
629+
expect(activeCaps(engine)).toEqual([{ package_id: binding, caps: ['cap_hr_v2'] }]);
630+
}, 30_000);
631+
632+
it.each([
633+
['bound to no package', null, [CRM], 'NAMESPACE_CONFLICT'],
634+
['bound to crm', CRM, [CRM], 'NOT_OVERRIDABLE'],
635+
['bound to crm\'s customization pair (another namespace)', CRM_PAIR, [CRM], 'NOT_OVERRIDABLE'],
636+
['bound to a co-owner of crm\'s namespace', CRM_TWO, [CRM], 'NAMESPACE_CONFLICT'],
637+
['bound to a co-owner of fin\'s namespace, fin also shipping', CRM_TWO, [FIN, CRM], 'NAMESPACE_CONFLICT'],
638+
] as const)(`${order}: CONTROL — a revert of a commit of N %s fails N as before`, async (_how, binding, shippers, code) => {
639+
const { engine, p, commits } = await publishedTwice(order, shippers);
640+
rebind(engine, binding);
641+
for (const row of engine.rows.values()) if (row.__table === 'sys_metadata_commit') row.package_id = binding;
642+
const res = await p.revertCommit({ commitId: commits[1] });
643+
expect(res.failed.map((f) => [f.name, f.code])).toEqual([[N, code]]);
644+
expect(activeCaps(engine)).toEqual([{ package_id: binding, caps: ['cap_hr_v2'] }]);
645+
}, 30_000);
646+
647+
it(`${order}: deleting hr's own N removes hr's set and says so, never "reset to artifact default" (FROM the reset receipt)`, async () => {
648+
const { engine, registry, p } = await savedTwice(order);
649+
const res = await p.deleteMetaItem({ type: 'permission', name: N, packageId: HR });
650+
expect(res.success).toBe(true);
651+
// `reset` is "a row was deleted" (DeleteMetaItemResponseSchema): one was.
652+
expect(res.reset).toBe(true);
653+
expect(res.message).toMatch(new RegExp(`^Deleted permission '${N}' \\(package=${HR.replace(/\./g, '\\.')}\\) — it no longer exists\\.`));
654+
expect(metaRowsOf(engine)).toEqual([]);
655+
expect(await confers(registry, CRM)).toEqual(['cap_crm_shipped']);
656+
}, 30_000);
657+
658+
it(`${order}: a delete naming hr when hr holds no N answers that nothing was found, never "already at artifact default" (FROM the reset receipt)`, async () => {
659+
const { protocol } = await composition(order);
660+
const res = await (protocol as unknown as Proto).deleteMetaItem({ type: 'permission', name: N, packageId: HR });
661+
expect([res.success, res.reset, res.message]).toEqual([true, false, `No permission '${N}' found — nothing to delete.`]);
662+
}, 30_000);
663+
664+
it(`${order}: CONTROL — deleting the customization of crm's N stored for crm's pair still reads as a reset to the artifact default`, async () => {
665+
const { engine, p } = await savedTwice(order);
666+
rebind(engine, CRM_PAIR);
667+
const res = await p.deleteMetaItem({ type: 'permission', name: N, packageId: CRM_PAIR });
668+
expect(res.success).toBe(true);
669+
expect(res.reset).toBe(true);
670+
expect(res.message).toContain('reset to artifact default');
671+
}, 30_000);
672+
}
673+
});
524674
});

0 commit comments

Comments
 (0)