Skip to content

Commit 7289b8a

Browse files
committed
test(metadata-protocol,runtime): pin the pre-uninstall guard seam and the in-process dependent-rule refusal
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017ihL2c1rk1PGZ51s32cxZt
1 parent 3d98273 commit 7289b8a

3 files changed

Lines changed: 287 additions & 3 deletions

File tree

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -528,7 +528,6 @@ import type {
528528
UninstallCleanupOutcome,
529529
UninstallDeclared,
530530
UninstallGuard,
531-
UninstallGuardRefusal,
532531
} from './protocol-package-lifecycle-types.js';
533532
export { captureUninstallDeclared } from './protocol-package-lifecycle-types.js';
534533
export type {
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #31232 — the pre-uninstall guard registry (`registerUninstallGuard`), the
5+
* before-half of the uninstall-cleanup registry: `deletePackage` asks every
6+
* registered guard, in registration order, before it reads or moves anything,
7+
* and throws the first refusal as its own. The runtime registers the package
8+
* doors' dependent-rule verdict here, so every in-process caller of the verb is
9+
* refused on it; that end-to-end half lives in the runtime's shared
10+
* dependent-rule harness (`packages-disable-module-extension-fields.test.ts`).
11+
*
12+
* What this file pins, on a protocol over an engine double:
13+
* - a refusing guard: the verb rejects with the guard's `code`, `status` and
14+
* `message`, and nothing was read or moved — no `sys_metadata` read, no
15+
* store delete, no registry withdrawal, no cleanup;
16+
* - each guard is handed the package id and exactly the actor the request
17+
* carried; the first refusal wins and later guards are not asked;
18+
* - a guard's own throw propagates as is, with nothing moved;
19+
* - CONTROL: guards that answer nothing let the uninstall proceed as before;
20+
* - CONTROL: a bare protocol (no guard registered) uninstalls as before.
21+
*/
22+
23+
import { describe, it, expect, vi } from 'vitest';
24+
import { ObjectStackProtocolImplementation } from './index.js';
25+
26+
const PACKAGE_ID = 'com.example.tasksapp';
27+
const CODE = 'PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE';
28+
29+
function makeProtocol() {
30+
const registry = {
31+
assertPackageUninstallable: vi.fn(() => undefined),
32+
uninstallPackage: vi.fn(() => true),
33+
};
34+
const engine = { registry, find: vi.fn(async () => []) };
35+
const store = { delete: vi.fn(async () => ({ success: true })) };
36+
const services = new Map<string, unknown>([['package', store]]);
37+
const protocol = new ObjectStackProtocolImplementation(engine as never, () => services as never);
38+
const cleanup = vi.fn(async () => ({ success: true, removed: 0 }));
39+
protocol.registerUninstallCleanup('qa.cleanup', cleanup);
40+
return { protocol, engine, registry, store, cleanup };
41+
}
42+
43+
/** Every step of the verb that reads or moves something, as the double saw it. */
44+
function touched(rig: ReturnType<typeof makeProtocol>) {
45+
return {
46+
read: rig.engine.find.mock.calls.length,
47+
asked: rig.registry.assertPackageUninstallable.mock.calls.length,
48+
stored: rig.store.delete.mock.calls.length,
49+
withdrawn: rig.registry.uninstallPackage.mock.calls.length,
50+
cleaned: rig.cleanup.mock.calls.length,
51+
};
52+
}
53+
const NOTHING = { read: 0, asked: 0, stored: 0, withdrawn: 0, cleaned: 0 };
54+
55+
describe('#31232: deletePackage asks every registered pre-uninstall guard before anything moves', () => {
56+
it('a refusing guard\'s code, status and message are the verb\'s refusal, and nothing is read or moved', async () => {
57+
const rig = makeProtocol();
58+
const message = `Package '${PACKAGE_ID}' cannot be uninstalled: a rule reads its field.`;
59+
rig.protocol.registerUninstallGuard('qa.refuses', () => ({ code: CODE, status: 409, message }));
60+
61+
const refused = await rig.protocol.deletePackage({ packageId: PACKAGE_ID }).then(
62+
() => { throw new Error('the uninstall was not refused'); },
63+
(e: any) => e,
64+
);
65+
66+
expect({ code: refused.code, status: refused.status, message: refused.message }).toEqual({ code: CODE, status: 409, message });
67+
expect(touched(rig)).toEqual(NOTHING);
68+
});
69+
70+
it('hands each guard the package id and the request\'s actor; the first refusal wins and later guards are not asked', async () => {
71+
const rig = makeProtocol();
72+
const passes = vi.fn(async () => undefined);
73+
const refuses = vi.fn(async () => ({ code: CODE, status: 409, message: 'first' }));
74+
const later = vi.fn(() => ({ code: 'RESOURCE_CONFLICT', status: 409, message: 'second' }));
75+
rig.protocol.registerUninstallGuard('qa.passes', passes);
76+
rig.protocol.registerUninstallGuard('qa.refuses', refuses);
77+
rig.protocol.registerUninstallGuard('qa.later', later);
78+
79+
await expect(rig.protocol.deletePackage({ packageId: PACKAGE_ID, actor: 'usr_1', keepData: true }))
80+
.rejects.toMatchObject({ code: CODE, status: 409, message: 'first' });
81+
82+
expect(passes.mock.calls).toEqual([[{ packageId: PACKAGE_ID, actor: 'usr_1' }]]);
83+
expect(refuses.mock.calls).toEqual([[{ packageId: PACKAGE_ID, actor: 'usr_1' }]]);
84+
expect(later).not.toHaveBeenCalled();
85+
expect(touched(rig)).toEqual(NOTHING);
86+
});
87+
88+
it('a guard that throws refuses with its throw, and nothing is read or moved', async () => {
89+
const rig = makeProtocol();
90+
const fault = Object.assign(new Error('the registry could not be read'), { code: 'INTERNAL_ERROR' });
91+
rig.protocol.registerUninstallGuard('qa.throws', () => { throw fault; });
92+
93+
await expect(rig.protocol.deletePackage({ packageId: PACKAGE_ID })).rejects.toBe(fault);
94+
expect(touched(rig)).toEqual(NOTHING);
95+
});
96+
97+
it('a second registration under a name replaces the first', async () => {
98+
const rig = makeProtocol();
99+
rig.protocol.registerUninstallGuard('qa.guard', () => ({ code: CODE, status: 409, message: 'replaced' }));
100+
const replacement = vi.fn(() => undefined);
101+
rig.protocol.registerUninstallGuard('qa.guard', replacement);
102+
103+
await rig.protocol.deletePackage({ packageId: PACKAGE_ID });
104+
105+
expect(replacement).toHaveBeenCalledTimes(1);
106+
expect(rig.store.delete).toHaveBeenCalledTimes(1);
107+
});
108+
109+
it('control: guards that answer nothing let the uninstall proceed through every step, once each', async () => {
110+
const rig = makeProtocol();
111+
const guard = vi.fn(() => undefined);
112+
rig.protocol.registerUninstallGuard('qa.passes', guard);
113+
114+
const res = await rig.protocol.deletePackage({ packageId: PACKAGE_ID });
115+
116+
expect(guard.mock.calls).toEqual([[{ packageId: PACKAGE_ID }]]);
117+
expect(touched(rig)).toEqual({ read: 1, asked: 1, stored: 1, withdrawn: 1, cleaned: 1 });
118+
expect(res.cleanups).toEqual([{ name: 'qa.cleanup', success: true, removed: 0 }]);
119+
});
120+
121+
it('control: a bare protocol, no guard registered, uninstalls exactly as before', async () => {
122+
const rig = makeProtocol();
123+
124+
const res = await rig.protocol.deletePackage({ packageId: PACKAGE_ID });
125+
126+
expect(touched(rig)).toEqual({ read: 1, asked: 1, stored: 1, withdrawn: 1, cleaned: 1 });
127+
expect(rig.store.delete.mock.calls).toEqual([[PACKAGE_ID]]);
128+
expect(rig.registry.uninstallPackage.mock.calls).toEqual([[PACKAGE_ID]]);
129+
expect(res).toMatchObject({ success: false, deletedCount: 0, failedCount: 0 });
130+
});
131+
});

‎packages/runtime/src/domains/packages-disable-module-extension-fields.test.ts‎

Lines changed: 156 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
* A formula over the field does not refuse the disable: it answers `null`.
4646
*/
4747

48-
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
48+
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
4949
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
5050
import { tmpdir } from 'node:os';
5151
import { join } from 'node:path';
@@ -58,8 +58,14 @@ import { resolveThrownHttpError } from '@objectstack/types';
5858
import { AppPlugin } from '../app-plugin.js';
5959
import { HttpDispatcher } from '../http-dispatcher.js';
6060
import { loadDisabledPackageIds, setPackageDisabled } from '../package-state-store.js';
61+
import { PACKAGE_STATE_UNINSTALL_CLEANUP } from '../package-state-host-store.js';
6162
import * as runtime from '../index.js';
62-
import { disableDependentRulesMessage, readDisableDependentRules } from './packages.js';
63+
import {
64+
disableDependentRulesMessage,
65+
PACKAGE_DEPENDENT_RULES_UNINSTALL_GUARD,
66+
packageUninstallDependentRulesRefusal,
67+
readDisableDependentRules,
68+
} from './packages.js';
6369

6470
const ENVIRONMENT_ID = 'env_suite_extension_fields';
6571
const ADMIN = {
@@ -1232,3 +1238,151 @@ describe('[#31067] the verdict the disable door asks is the package entry\'s exp
12321238
expect(registry.getPackage(EXTENDER)?.enabled).toBe(false);
12331239
});
12341240
});
1241+
1242+
/**
1243+
* [#31232] The uninstall VERB (`protocol.deletePackage`, in
1244+
* `@objectstack/metadata-protocol`) withdraws the package's `objectExtensions`
1245+
* fields from the served objects for every in-process caller (a host's own
1246+
* uninstall tool, install-local's pair-install undo, the unmanaged-import
1247+
* rollback), not only behind the package door. The runtime registers the
1248+
* package doors' dependent-rule verdict on the verb as a pre-uninstall guard
1249+
* (`ensureDependentRulesUninstallGuard`, from `AppPlugin.start`), so the verb
1250+
* itself refuses, before it reads or moves anything, with `409`
1251+
* `PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE` and the doors' sentence
1252+
* under an uninstall lead. Measured before this change on this rig: the
1253+
* in-process uninstall answered, the field left the served object, and every
1254+
* write to the object then answered `400 VALIDATION_FAILED`, the rule failing
1255+
* closed on the withdrawn field.
1256+
*
1257+
* Two writable packages extend the app's object with one field each; a third
1258+
* package's active rule reads the first one's field. The verb is the kernel's
1259+
* real protocol, called in process.
1260+
*/
1261+
describe('[#31232] the in-process uninstall verb refuses while an enabled package\'s validation rule reads a field the package adds', () => {
1262+
const TIERS = 'com.qa.inproc.tiers';
1263+
const NOTES = 'com.qa.inproc.notes';
1264+
const READER = 'com.qa.inproc.reader';
1265+
const TIER = 'qy_tier';
1266+
const NOTE = 'qy_note';
1267+
const RULE = 'qy_tier_known';
1268+
const CODE = 'PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE';
1269+
const manifestOf = (id: string) => ({ id, name: id, version: '1.0.0', type: 'module' });
1270+
1271+
let root: string;
1272+
let booted: Booted | undefined;
1273+
let accountId: string;
1274+
let protocol: any;
1275+
1276+
beforeAll(async () => {
1277+
root = mkdtempSync(join(tmpdir(), 'os-suite-ext-inproc-'));
1278+
writeFileSync(join(root, '.keep'), '');
1279+
process.env.OS_HOME = mkdtempSync(join(home, 'inproc-uninstall-'));
1280+
booted = await bootKernel(root);
1281+
const { kernel, engine } = booted;
1282+
for (const id of [TIERS, NOTES, READER]) engine.registry.installPackage(manifestOf(id) as any, 'authored');
1283+
engine.registry.registerObject({ name: ACCOUNT, fields: { [TIER]: { name: TIER, type: 'text', label: 'Tier' } } } as any, TIERS, undefined, 'extend');
1284+
engine.registry.registerObject({ name: ACCOUNT, fields: { [NOTE]: { name: NOTE, type: 'text', label: 'Note' } } } as any, NOTES, undefined, 'extend');
1285+
engine.registry.registerObject({
1286+
name: ACCOUNT,
1287+
validations: [{ name: RULE, type: 'script', severity: 'error', message: 'Unknown tier', condition: `record.${TIER} == 'unknown'` }],
1288+
} as any, READER, undefined, 'extend');
1289+
await engine.syncSchemas();
1290+
const created = await dispatchAs(kernel, 'POST', `/data/${ACCOUNT}`, { name: 'Acme', [TIER]: 'gold', [NOTE]: 'n' });
1291+
expect(created.status, `precondition: the account is written (${String(created.message)})`).toBe(201);
1292+
accountId = idOf(created);
1293+
protocol = kernel.getService<any>('protocol');
1294+
}, 120_000);
1295+
afterAll(async () => {
1296+
vi.restoreAllMocks();
1297+
await shutdown(booted);
1298+
rmSync(root, { recursive: true, force: true });
1299+
}, 60_000);
1300+
1301+
/** The verb's refusal sentence: the exported builder over the exported verdict, under the uninstall lead. */
1302+
const expectedMessage = () => runtime.formatPackageDisableDependents(
1303+
`Package '${TIERS}' cannot be uninstalled`,
1304+
runtime.readPackageDisableDependents(booted!.engine.registry, TIERS),
1305+
);
1306+
1307+
it('the verb answers 409 with the doors\' code and sentence under an uninstall lead, having read and moved nothing', async () => {
1308+
const { kernel, engine } = booted!;
1309+
const disabledBefore = [...loadDisabledPackageIds(ENVIRONMENT_ID)].sort();
1310+
const reads = vi.spyOn(protocol, 'findEnvironmentRows');
1311+
const deletes = vi.spyOn(protocol, 'deleteMetaItem');
1312+
const cleanups = vi.spyOn(protocol, 'runUninstallCleanups');
1313+
const withdrawals = vi.spyOn(engine.registry, 'uninstallPackage');
1314+
1315+
const refused = await protocol.deletePackage({ packageId: TIERS, actor: ADMIN.userId }).then(
1316+
() => { throw new Error('the in-process uninstall was not refused'); },
1317+
(e: any) => e,
1318+
);
1319+
1320+
expect({ status: refused.status, code: refused.code }).toEqual({ status: 409, code: CODE });
1321+
expect(refused.message).toBe(expectedMessage());
1322+
expect(refused.message).toBe(packageUninstallDependentRulesRefusal(engine.registry, TIERS)?.message);
1323+
expect(String(refused.message)).toMatch(new RegExp(`^Package '${TIERS.replace(/\./g, '\\.')}' cannot be uninstalled: an active validation rule reads a field it adds through objectExtensions`));
1324+
expect(String(refused.message)).toContain(`${READER} · ${ACCOUNT} · ${RULE} (reads ${TIER})`);
1325+
1326+
// Nothing read, nothing moved: no stored row read or deleted, no
1327+
// registry withdrawal, no cleanup; the package and its field stay
1328+
// served, the state file is as it was, and writes still land.
1329+
expect({
1330+
reads: reads.mock.calls.length,
1331+
deletes: deletes.mock.calls.length,
1332+
cleanups: cleanups.mock.calls.length,
1333+
withdrawals: withdrawals.mock.calls.length,
1334+
}).toEqual({ reads: 0, deletes: 0, cleanups: 0, withdrawals: 0 });
1335+
expect(engine.registry.getPackage(TIERS)).toBeDefined();
1336+
expect(await servedFieldNames(kernel)).toEqual(expect.arrayContaining([TIER, NOTE]));
1337+
expect([...loadDisabledPackageIds(ENVIRONMENT_ID)].sort()).toEqual(disabledBefore);
1338+
const written = await dispatchAs(kernel, 'PATCH', `/data/${ACCOUNT}/${accountId}`, { [TIER]: 'silver' });
1339+
expect(written.status, String(written.message)).toBe(200);
1340+
expect(await readAccount(kernel, accountId)).toMatchObject({ [TIER]: 'silver' });
1341+
vi.restoreAllMocks();
1342+
});
1343+
1344+
it('the package door answers the same refusal, word for word, and the package stays', async () => {
1345+
const { kernel, engine } = booted!;
1346+
const refused = await dispatchAs(kernel, 'DELETE', `/packages/${TIERS}`);
1347+
expect({ status: refused.status, code: refused.code }).toEqual({ status: 409, code: CODE });
1348+
expect(String(refused.message)).toBe(expectedMessage());
1349+
expect(refused.details).toBeUndefined();
1350+
expect(engine.registry.getPackage(TIERS)).toBeDefined();
1351+
expect(await servedFieldNames(kernel)).toContain(TIER);
1352+
});
1353+
1354+
it('control: a package no rule depends on uninstalls in process as before, its disable record cleared by the verb', async () => {
1355+
const { kernel, engine } = booted!;
1356+
// Disabled first, so the verb has a disable record to clear. The
1357+
// reader's rule stays active on the same object: it reads another field.
1358+
expect((await dispatchAs(kernel, 'PATCH', `/packages/${NOTES}/disable`)).status).toBe(200);
1359+
expect(loadDisabledPackageIds(ENVIRONMENT_ID).has(NOTES), 'precondition: the disable is recorded').toBe(true);
1360+
1361+
const uninstalled = await protocol.deletePackage({ packageId: NOTES, actor: ADMIN.userId });
1362+
1363+
expect(uninstalled.cleanups.map((c: { name: string }) => c.name)).toContain(PACKAGE_STATE_UNINSTALL_CLEANUP);
1364+
expect(engine.registry.getPackage(NOTES)).toBeUndefined();
1365+
expect(loadDisabledPackageIds(ENVIRONMENT_ID).has(NOTES)).toBe(false);
1366+
expect(await servedFieldNames(kernel)).not.toContain(NOTE);
1367+
// The guard is still registered: it answered nothing for this package.
1368+
expect([...(protocol as any).uninstallGuards.keys()]).toContain(PACKAGE_DEPENDENT_RULES_UNINSTALL_GUARD);
1369+
});
1370+
1371+
it('control: proceeds in process once the reading rule is switched off through the tenant overlay, and writes still land', async () => {
1372+
const { kernel, engine } = booted!;
1373+
engine.registry.registerObject({
1374+
name: ACCOUNT, label: 'Account', fields: { name: { name: 'name', type: 'text', label: 'Name' } },
1375+
validations: [{ name: RULE, type: 'script', message: 'Switched off by the tenant', condition: 'true', active: false }],
1376+
_provenance: 'org',
1377+
} as any, APP, undefined, 'overlay');
1378+
const served = ((engine.registry.getObject(ACCOUNT) as any)?.validations ?? []) as Array<{ name?: string; active?: unknown }>;
1379+
expect(served.find((r) => r.name === RULE)?.active, 'precondition: the reader\'s rule is served, switched off').toBe(false);
1380+
1381+
await protocol.deletePackage({ packageId: TIERS, actor: ADMIN.userId });
1382+
1383+
expect(engine.registry.getPackage(TIERS)).toBeUndefined();
1384+
expect(await servedFieldNames(kernel)).not.toContain(TIER);
1385+
const written = await dispatchAs(kernel, 'PATCH', `/data/${ACCOUNT}/${accountId}`, { name: 'Acme Ltd' });
1386+
expect(written.status, String(written.message)).toBe(200);
1387+
});
1388+
});

0 commit comments

Comments
 (0)