|
| 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 | +}); |
0 commit comments