Skip to content

Commit ef3daa6

Browse files
committed
fix(cloud-connection,metadata-protocol): install-local's uninstall door asks the verb's guards and writes its audit row
The door cannot delegate to deletePackage, so it skipped the verb's pre-uninstall guards (the dependent-rule refusal) and its package_uninstall ledger row. The protocol now exposes the one runner of its guards (runUninstallGuards) and the one writer of that row (recordPackageUninstall), both of which deletePackage itself calls; the door asks the guards before its first write and records the row after a completed uninstall. Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 405a78e commit ef3daa6

7 files changed

Lines changed: 473 additions & 10 deletions

‎packages/cloud-connection/src/marketplace-install-local-plugin.ts‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,17 @@ type UninstallCleanupRunner = {
427427
runUninstallCleanups?(
428428
request: Pick<DeletePackageRequest, 'packageId' | 'actor'> & { declared?: UninstallDeclared },
429429
): Promise<UninstallCleanupOutcome[]>;
430+
/**
431+
* [#31283] The verb's pre-uninstall guards, asked through the protocol's
432+
* one runner of them — the runner `deletePackage` asks at its first step.
433+
*/
434+
runUninstallGuards?: ObjectStackProtocolImplementation['runUninstallGuards'];
435+
/**
436+
* [#31283] The verb's `package_uninstall` ledger row (#31186), written
437+
* through the protocol's one writer of it — the writer `deletePackage`
438+
* calls at its last step.
439+
*/
440+
recordPackageUninstall?: ObjectStackProtocolImplementation['recordPackageUninstall'];
430441
};
431442

432443
/** The outcome name this door reports when the runner itself could not run. */
@@ -3343,6 +3354,20 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
33433354
const walled = this.refuseWalledCatalogPackage(c, ctx, 'Uninstalling', manifestId, admission);
33443355
if (walled) return walled;
33453356
}
3357+
// [#31283] THE UNINSTALL VERB'S PRE-UNINSTALL GUARDS, ASKED BEFORE
3358+
// ANYTHING MOVES. This door cannot delegate to `deletePackage` (it
3359+
// answers `success: false` for a package with no stored rows, and
3360+
// drops the tables of the objects it removes), so it asks the verb's
3361+
// guards through the protocol's one runner of them
3362+
// (`runUninstallGuards`) — the runtime's dependent-rule refusal (#31232:
3363+
// an active validation rule of another enabled package reads a field
3364+
// this package adds through `objectExtensions`) among them — and holds
3365+
// no copy of any verdict. A refusal is the request's, spelled as the
3366+
// guard spelled it (`code`, `status`, `message`), with nothing moved.
3367+
{
3368+
const refused = await this.askUninstallGuards(c, ctx, manifestId, admission.userId);
3369+
if (refused) return refused;
3370+
}
33463371
// [#28511, ADR-0146 D3] THE REGISTRY'S UNINSTALL REFUSAL, ASKED BEFORE
33473372
// THE LEDGER WRITE. The withdrawal below asks the registry to
33483373
// uninstall the package, and the registry refuses a base whose paired
@@ -3383,6 +3408,8 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
33833408
}
33843409
}
33853410
}
3411+
// [#31283] The version this uninstall removes, for the package's ledger row.
3412+
const removedVersion = this.ledger.read(manifestId).entry?.version;
33863413
try {
33873414
this.ledger.remove(manifestId);
33883415
} catch (err: any) {
@@ -3444,6 +3471,13 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
34443471
// re-sync would only read it back.
34453472
const resync = withdrawal ? undefined : await this.announceUninstall(ctx, manifestId);
34463473
if (resync) cleanups.push(resync);
3474+
// [#31283] The package's own `package_uninstall` ledger row (#31186),
3475+
// written once the uninstall is durable — the ledger entry is gone —
3476+
// through the protocol's one writer of it (`recordPackageUninstall`),
3477+
// never on a refusal above. `itemsRemoved` / `itemsFailed` count the
3478+
// stored `sys_metadata` items an uninstall removes: an install-local
3479+
// package is registered from its ledger entry and has none.
3480+
await this.recordUninstall(ctx, manifestId, removedVersion, admission.userId);
34473481
const withdrawals = (withdrawal ? 1 : 0) + (copies ? 1 : 0) + (resync ? 1 : 0);
34483482
ctx.logger?.info?.(
34493483
`[MarketplaceInstallLocal] uninstalled ${manifestId} (cached manifest removed; `
@@ -3696,6 +3730,65 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
36963730
};
36973731
};
36983732

3733+
/**
3734+
* [#31283] Ask the uninstall verb's pre-uninstall guards about `manifestId`
3735+
* through the protocol's one runner of them (`runUninstallGuards`), and
3736+
* answer the first refusal as this request's: `{ success: false, error:
3737+
* { code, message } }` under the guard's `status`. `undefined` when no
3738+
* guard refuses.
3739+
*
3740+
* No `protocol` service, or a protocol from a build without the runner,
3741+
* holds no guard this door can ask, and the door behaves as before — the
3742+
* capability question {@link runUninstallCleanups} asks of its runner. A
3743+
* throw that is not a coded client refusal is the guard's failure to
3744+
* judge: it propagates, as it does out of `deletePackage`, and the
3745+
* uninstall does not proceed.
3746+
*/
3747+
private askUninstallGuards = async (
3748+
c: any,
3749+
ctx: PluginContext,
3750+
manifestId: string,
3751+
actor: string,
3752+
): Promise<Response | undefined> => {
3753+
let protocol: UninstallCleanupRunner | undefined;
3754+
try { protocol = ctx.getService<UninstallCleanupRunner>('protocol'); } catch { /* no protocol service */ }
3755+
if (typeof protocol?.runUninstallGuards !== 'function') return undefined;
3756+
try {
3757+
await protocol.runUninstallGuards({ packageId: manifestId, ...(actor ? { actor } : {}) });
3758+
return undefined;
3759+
} catch (err: any) {
3760+
const status = err?.status;
3761+
if (typeof err?.code === 'string' && typeof status === 'number' && status >= 400 && status < 500) {
3762+
return c.json({ success: false, error: { code: err.code, message: String(err.message) } }, status);
3763+
}
3764+
throw err;
3765+
}
3766+
};
3767+
3768+
/**
3769+
* [#31283] Write the package's `package_uninstall` ledger row through the
3770+
* protocol's one writer of it (`recordPackageUninstall`). No `protocol`
3771+
* service, or a protocol from a build without the writer, has no row to
3772+
* write; the writer itself never throws.
3773+
*/
3774+
private recordUninstall = async (
3775+
ctx: PluginContext,
3776+
manifestId: string,
3777+
version: string | undefined,
3778+
actor: string,
3779+
): Promise<void> => {
3780+
let protocol: UninstallCleanupRunner | undefined;
3781+
try { protocol = ctx.getService<UninstallCleanupRunner>('protocol'); } catch { /* no protocol service */ }
3782+
if (typeof protocol?.recordPackageUninstall !== 'function') return;
3783+
await protocol.recordPackageUninstall({
3784+
packageId: manifestId,
3785+
...(version ? { version } : {}),
3786+
...(actor ? { actor } : {}),
3787+
itemsRemoved: 0,
3788+
itemsFailed: 0,
3789+
});
3790+
};
3791+
36993792
/**
37003793
* [#21490] Run the protocol's registered uninstall cleanups for a package
37013794
* this door just removed from its ledger — ADR-0086 D3's data-plane
Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #31283 — install-local's own uninstall door
5+
* (`DELETE /api/v1/marketplace/install-local/:manifestId`) asks the uninstall
6+
* verb's pre-uninstall guards before its first write, and writes the verb's
7+
* `package_uninstall` audit row after a completed uninstall — through the
8+
* protocol's public entry points, so there is one verdict and one writer.
9+
*
10+
* ## What was wrong
11+
*
12+
* The door withdraws the package itself and then runs the protocol's uninstall
13+
* cleanups (#21490), but never goes through `deletePackage`: it does not fit
14+
* this door (it answers `success: false` for a package with no stored rows and
15+
* drops the tables of the objects it removes). So it missed what the verb does
16+
* before and after the delete: the pre-uninstall guards (#31232 — the runtime's
17+
* dependent-rule refusal: an active validation rule of another enabled package
18+
* reads a field this package adds through `objectExtensions`), and the
19+
* package's own ledger row (#31186). Measured before the fix on this rig: the
20+
* uninstall answered `200`, the field left the served object, and no audit
21+
* event was written.
22+
*
23+
* ## What is real here
24+
*
25+
* An `ObjectKernel` with `ObjectQLPlugin` — the real `SchemaRegistry` and the
26+
* real `ObjectStackProtocolImplementation` it registers as `protocol` — and the
27+
* runtime's `AppPlugin`, whose `start()` registers the dependent-rule guard on
28+
* that protocol (the guard every caller of the verb meets). The `audit` slot is
29+
* a recorder of the events the protocol hands it (plugin-audit turns them into
30+
* rows, pinned there). The packages are registered the way the runtime's own
31+
* #30999 rig registers them; the ledger entries are written the way an install
32+
* writes them.
33+
*
34+
* ## What these cases pin
35+
*
36+
* - an uninstall of a package whose extension field an active rule of another
37+
* package reads: the verb's `409 PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE`
38+
* and its sentence, and nothing moved — the ledger entry, the registration,
39+
* the served field, no cleanup run, no audit event;
40+
* - CONTROL: a package whose field no rule reads uninstalls, and the protocol
41+
* hands the audit slot exactly one `package_uninstall` event naming it, its
42+
* version and the operator.
43+
*/
44+
45+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
46+
import { mkdtempSync, rmSync } from 'node:fs';
47+
import { tmpdir } from 'node:os';
48+
import { join } from 'node:path';
49+
// The plugin reaches `@objectstack/runtime` through a lazy `import()`; its first
50+
// load is paid here, at module top, never inside a clocked `it`.
51+
import { AppPlugin, formatPackageDisableDependents, readPackageDisableDependents } from '@objectstack/runtime';
52+
import { ObjectKernel } from '@objectstack/core';
53+
import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql';
54+
import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js';
55+
import { LocalManifestSource } from './local-manifest-source.js';
56+
import { INSTALLER_USER_ID, installerAuthService, withInstallerGrants } from './install-local-principal.fixtures.js';
57+
58+
type Handler = (c: any) => Promise<any>;
59+
60+
const ROUTE = '/api/v1/marketplace/install-local';
61+
/** The package owning the object the others extend. */
62+
const JOBS = 'com.acme.jobs';
63+
/** The package under uninstall: it adds `acme_tier` to the jobs object. */
64+
const TIERS = 'com.acme.tiers';
65+
/** CONTROL: it adds `acme_note`, which no rule reads. */
66+
const NOTES = 'com.acme.notes';
67+
/** The package whose active validation rule reads `acme_tier`. */
68+
const READER = 'com.acme.reader';
69+
const JOB = 'acme_job';
70+
const TIER = 'acme_tier';
71+
const NOTE = 'acme_note';
72+
const RULE = 'acme_tier_known';
73+
const CODE = 'PACKAGE_DISABLE_RESTRICTED_BY_VALIDATION_RULE';
74+
75+
let dir: string;
76+
const kernels: ObjectKernel[] = [];
77+
beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'mil-uninstall-guards-')); });
78+
afterEach(async () => {
79+
while (kernels.length) {
80+
const k = kernels.pop()!;
81+
if (k.getState() === 'running') await k.shutdown();
82+
}
83+
rmSync(dir, { recursive: true, force: true });
84+
vi.restoreAllMocks();
85+
});
86+
87+
/** A ledger entry as an install writes it. */
88+
function ledger(manifestId: string) {
89+
new LocalManifestSource(dir).write({
90+
packageId: manifestId,
91+
versionId: 'v1',
92+
manifestId,
93+
version: '1.0.0',
94+
manifest: { id: manifestId, name: manifestId, version: '1.0.0', type: 'module' },
95+
installedAt: '2026-01-01T00:00:00.000Z',
96+
installedBy: INSTALLER_USER_ID,
97+
withSampleData: false,
98+
});
99+
}
100+
const ledgered = (manifestId: string) => new LocalManifestSource(dir).read(manifestId).entry !== null;
101+
102+
/** The jobs object's served field names. */
103+
const servedFields = (ql: ObjectQL) => Object.keys((ql.registry.getObject(JOB) as any)?.fields ?? {});
104+
105+
/** The real engine, protocol and dependent-rule guard; the four packages registered; TIERS and NOTES ledgered. */
106+
async function boot() {
107+
const auditEvents: unknown[] = [];
108+
const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false } as never);
109+
kernels.push(kernel);
110+
await kernel.use(new ObjectQLPlugin());
111+
await kernel.use({
112+
name: 'test.audit-slot',
113+
version: '1.0.0',
114+
init: async (ctx: any) => {
115+
ctx.registerService('audit', {
116+
recordPackageLifecycleEvent: async (event: unknown) => { auditEvents.push(event); },
117+
});
118+
},
119+
start: async () => undefined,
120+
} as never);
121+
// An empty app: its `start()` registers the dependent-rule guard on the protocol.
122+
await kernel.use(new AppPlugin({}));
123+
await kernel.bootstrap();
124+
const ql = kernel.getService<ObjectQL>('objectql');
125+
ql.registry.logLevel = 'silent';
126+
const protocol = kernel.getService<any>('protocol');
127+
128+
for (const id of [JOBS, TIERS, NOTES, READER]) {
129+
ql.registry.installPackage({ id, name: id, version: '1.0.0', type: 'module' } as any, 'authored');
130+
}
131+
ql.registry.registerObject({ name: JOB, label: 'Job', fields: { name: { name: 'name', type: 'text', label: 'Name' } } } as any, JOBS);
132+
ql.registry.registerObject({ name: JOB, fields: { [TIER]: { name: TIER, type: 'text', label: 'Tier' } } } as any, TIERS, undefined, 'extend');
133+
ql.registry.registerObject({ name: JOB, fields: { [NOTE]: { name: NOTE, type: 'text', label: 'Note' } } } as any, NOTES, undefined, 'extend');
134+
ql.registry.registerObject({
135+
name: JOB,
136+
validations: [{ name: RULE, type: 'script', severity: 'error', message: 'Unknown tier', condition: `record.${TIER} == 'unknown'` }],
137+
} as any, READER, undefined, 'extend');
138+
ledger(TIERS);
139+
ledger(NOTES);
140+
141+
const routes = new Map<string, Handler>();
142+
const rawApp = {
143+
get: (p: string, h: Handler) => routes.set(`GET ${p}`, h),
144+
post: (p: string, h: Handler) => routes.set(`POST ${p}`, h),
145+
delete: (p: string, h: Handler) => routes.set(`DELETE ${p}`, h),
146+
};
147+
const hooks = new Map<string, () => Promise<void>>();
148+
const services: Record<string, unknown> = {
149+
manifest: kernel.getService('manifest'),
150+
auth: installerAuthService(),
151+
protocol,
152+
objectql: withInstallerGrants({ registry: ql.registry, syncSchemas: async () => undefined }),
153+
};
154+
const ctx = {
155+
hook: (e: string, h: () => Promise<void>) => hooks.set(e, h),
156+
getService: (name: string) => {
157+
if (name === 'http-server') return { getRawApp: () => rawApp };
158+
if (!(name in services)) throw new Error(`no ${name}`);
159+
return services[name];
160+
},
161+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
162+
trigger: async () => undefined,
163+
};
164+
const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir });
165+
// The `kernel:ready` rehydrate is not what is pinned: the packages are registered above.
166+
(plugin as unknown as Record<string, unknown>).rehydrate = async () => undefined;
167+
await plugin.start(ctx as never);
168+
await hooks.get('kernel:ready')?.();
169+
170+
const uninstall = async (manifestId: string) => {
171+
const json = vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 }));
172+
return routes.get(`DELETE ${ROUTE}/:manifestId`)!({
173+
req: {
174+
url: `http://localhost:3000${ROUTE}/${manifestId}`,
175+
raw: new Request(`http://localhost:3000${ROUTE}/${manifestId}`, { method: 'DELETE' }),
176+
json: async () => ({}),
177+
param: (name: string) => (name === 'manifestId' ? manifestId : undefined),
178+
},
179+
json,
180+
});
181+
};
182+
return { ql, protocol, auditEvents, uninstall };
183+
}
184+
185+
describe('install-local uninstall asks the uninstall verb\'s guards and writes its audit row (#31283)', () => {
186+
it('a package whose extension field an active rule of another package reads is refused with the verb\'s 409; nothing moves', async () => {
187+
const { ql, protocol, auditEvents, uninstall } = await boot();
188+
const runCleanups = vi.spyOn(protocol, 'runUninstallCleanups');
189+
const expected = formatPackageDisableDependents(
190+
`Package '${TIERS}' cannot be uninstalled`,
191+
readPackageDisableDependents(ql.registry, TIERS),
192+
{ operation: 'uninstall' },
193+
);
194+
expect(expected, 'precondition: the rule depends on the field').toContain(RULE);
195+
196+
const res = await uninstall(TIERS);
197+
198+
expect(res.status, JSON.stringify(res.payload)).toBe(409);
199+
expect(res.payload.success).toBe(false);
200+
expect(res.payload.error.code).toBe(CODE);
201+
expect(res.payload.error.message).toBe(expected);
202+
// Nothing moved.
203+
expect(ledgered(TIERS)).toBe(true);
204+
expect(ql.registry.getPackage(TIERS)).toBeDefined();
205+
expect(servedFields(ql)).toEqual(expect.arrayContaining([TIER, NOTE]));
206+
expect(runCleanups).not.toHaveBeenCalled();
207+
expect(auditEvents).toEqual([]);
208+
}, 60_000);
209+
210+
it('CONTROL — a package whose field no rule reads uninstalls and the protocol records one package_uninstall event', async () => {
211+
const { ql, auditEvents, uninstall } = await boot();
212+
213+
const res = await uninstall(NOTES);
214+
215+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
216+
expect(res.payload.success).toBe(true);
217+
expect(ledgered(NOTES)).toBe(false);
218+
expect(ql.registry.getPackage(NOTES)).toBeUndefined();
219+
expect(auditEvents).toEqual([{
220+
action: 'package_uninstall',
221+
packageId: NOTES,
222+
version: '1.0.0',
223+
actor: INSTALLER_USER_ID,
224+
itemsRemoved: 0,
225+
itemsFailed: 0,
226+
}]);
227+
}, 60_000);
228+
});

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ export type {
135135
SeedTenancySplit,
136136
SeedTenancyCollision,
137137
} from './migrations/seed-tenancy-backfill.js';
138-
export type { UninstallCleanup, UninstallCleanupOutcome, UninstallDeclared, UninstallGuard, UninstallGuardRefusal } from './protocol.js';
138+
export type { PackageUninstallRecord, UninstallCleanup, UninstallCleanupOutcome, UninstallDeclared, UninstallGuard, UninstallGuardRefusal } from './protocol.js';
139139
export { captureUninstallDeclared } from './protocol.js';
140140
// [#9960] The ONE declared shape of the `deletePackage` seam, exported so the
141141
// two consumers that speak it (`@objectstack/rest`'s direct-mount package

‎packages/metadata-protocol/src/protocol-package-lifecycle-types.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,23 @@ export type UninstallGuard = (args: {
8585
actor?: string;
8686
}) => UninstallGuardRefusal | undefined | Promise<UninstallGuardRefusal | undefined>;
8787

88+
/**
89+
* [#31186, #31283] What an uninstall door states about the package it
90+
* uninstalled, for the package's own `package_uninstall` ledger row
91+
* ({@link ObjectStackProtocolImplementation.recordPackageUninstall}): the
92+
* package's id, the version it removed, the operator, whether its object
93+
* tables were kept, and how many of its stored `sys_metadata` items were
94+
* removed and failed to be. The environment is the protocol's own.
95+
*/
96+
export interface PackageUninstallRecord {
97+
packageId: string;
98+
version?: string;
99+
actor?: string;
100+
keepData?: boolean;
101+
itemsRemoved: number;
102+
itemsFailed: number;
103+
}
104+
88105
/**
89106
* [ADR-0090 D5, ADR-0131 D4] The security-catalog names an uninstalled package
90107
* held. A grant names its set, and the package's sets are served from the

0 commit comments

Comments
 (0)