diff --git a/.changeset/33536-uninstall-unbinds-action-handlers.md b/.changeset/33536-uninstall-unbinds-action-handlers.md new file mode 100644 index 00000000000..1a2b2810f8f --- /dev/null +++ b/.changeset/33536-uninstall-unbinds-action-handlers.md @@ -0,0 +1,23 @@ +--- +'@objectstack/cloud-connection': patch +'@objectstack/runtime': patch +'@objectstack/objectql': patch +--- + +fix(cloud-connection, runtime, objectql)!: an install-local uninstall withdraws the package's action handlers and body hooks from the running engine, so a call that names no package is served by the one remaining holder at once instead of after a restart + +Clause-②: yes (narrowing) — `ObjectQL#removeActionsByPackage` now hands a key it empties in the slot a call that names no package reads back to the entry another owner still holds under it in its own slot. On `ObjectQL#removePackage`, on the binder's re-bind that drops a package body of a multi-package artifact, and on the authored-action resync's teardown (`removeActionsByPackage('metadata-service')`), the action doors (`POST /api/v1/actions/OBJECT/NAME/ID`, MCP `run_action`) now reach that handed-back entry. Before, they reached the next entry their handler-key rotation held (`OBJECT`, then `global`, then `*`, per handler-key candidate), and answered "not found" only when none was held. The owner gates of the reached entry move with it, so a call that was served can now be refused `403 PERMISSION_DENIED`, `409 ACTION_DISABLED` or `503`. The install-local uninstall the card reports is widening only: a bare call that answered `409 RESOURCE_CONFLICT`, naming the uninstalled package as one of two owners, now answers with the one remaining holder's handler. `@objectstack/runtime` gains the export `unbindAppArtifactHandlers` and the type `AppArtifactHandlerUnbinding`. +Metadata-protocol: none + + +**BREAKING** for a call that names no package, on a key that `removePackage`, a re-bind that drops a body, or the authored-action resync empties while another owner (host code, a plugin, a package or the environment) still holds a handler under it. The emptied key now resolves to that remaining holder's entry, so the call runs that handler, and that entry's owners' gates (403 / 409 `ACTION_DISABLED` / 503) can answer where the door's rotation used to fall through to a later entry and serve it. This is what a restart of the same process already answers. No data migration or heal is needed: nothing persisted changes. The install-local uninstall the card reports is unaffected, because the uninstalled package's handler stayed bound there and the key never emptied. + +**The defect.** `DELETE /api/v1/marketplace/install-local/:manifestId` withdrew the package from the registry and left every handler its install had bound on the engine under `app:`: script-action handlers, body hooks and bundle functions. With two packages each holding an action of one name on one object, a call that names no package kept being refused as ambiguous until the runtime restarted, and the uninstalled package's body hooks kept firing. + +**The fix.** + +- `@objectstack/runtime`: `unbindAppArtifactHandlers(ql, appId, { logger, source })` is the inverse of `bindAppArtifactHandlers`. It removes the actions, hooks and functions of the package's owner and of every owner the package's last bind on that engine recorded (a multi-package artifact's bodies), releases those owners' bare-name function claims, and forgets the bind record, so a later install binds as a first bind. Another package's handlers, host code and the environment's authored-action handlers are untouched. Jobs keep leaving through the `runtime.package-jobs` uninstall cleanup. +- `@objectstack/cloud-connection`: the uninstall door calls it right after the registry withdrawal, and not when the registry refuses the withdrawal (the package stays loaded then). A runtime that has no such export is warned with the remedy, as the install door already warns for a runtime with no binder. +- `@objectstack/objectql`: `removeActionsByPackage` hands a key back to the owner that still holds a handler for it. Each owner keeps its handler in its own package slot, but the slot a call that names no package runs held only the last registration. Removing that registration emptied the key, so the engine's bare `executeAction` answered "not found" while another owner still held a handler. The key now takes back the entry another coordinate's slot holds: the last coordinate holding the key in the order the slots were created, which is not always the last registration of this key. That choice matters where the bare-call rule runs one owner while others hold the key: host code or a plugin beside one package on an object-bound key, and two shared owners with no package (host code beside a plugin, or two plugins). When the earlier-created slot registered this key last, the hand-back runs the other holder's handler where a restart runs the last registration. While two or more packages still hold the key, the bare call is refused naming them as before. + +**Not changed.** `PATCH /api/v1/packages/:id/disable` leaves a disabled package's handlers in place, and the bare-call rule already counts no disabled package as an owner. `DELETE /api/v1/packages/:id` (the protocol's `deletePackage`) does not call this unbind, so it is unchanged. diff --git a/packages/cloud-connection/src/marketplace-install-local-plugin.ts b/packages/cloud-connection/src/marketplace-install-local-plugin.ts index f91ccdc43dd..e56ec1d95f0 100644 --- a/packages/cloud-connection/src/marketplace-install-local-plugin.ts +++ b/packages/cloud-connection/src/marketplace-install-local-plugin.ts @@ -3697,6 +3697,12 @@ export class MarketplaceInstallLocalPlugin implements Plugin { try { registry = ctx.getService('objectql')?.registry; } catch { /* no data engine — nothing registered */ } const declared = captureUninstallDeclared(registry, manifestId); const withdrawal = this.withdrawFromRunningKernel(ctx, manifestId); + // The registry verb reaches no executable handler: the package's + // script-action handlers, body hooks and functions this door's install + // bound on the engine ({@link bindArtifactHandlers}) go right after the + // registry half withdrew, through the binder's own inverse — never on + // a refused withdrawal, which leaves the package loaded and running. + if (!withdrawal) await this.unbindArtifactHandlers(ctx, manifestId); const copies = withdrawal ? undefined : await this.withdrawObjectCopies(ctx, manifestId); // [#24182] …and the copies of OTHER packages' objects that this one's // extensions rewrote: the bridge that wrote them restores the owner's @@ -6646,6 +6652,44 @@ export class MarketplaceInstallLocalPlugin implements Plugin { await schedule(ctx, manifest, { appId: manifestId, ql, source: 'MarketplaceInstallLocal' }); }; + /** + * Withdraw from the running engine the script-action handlers, body hooks + * and functions {@link bindArtifactHandlers} bound for `manifestId`, + * through `unbindAppArtifactHandlers` — the runtime binder's inverse, so + * the door unbinds exactly the owners the binder bound and nothing of + * another package, host code or the environment. The uninstall door runs + * it once the registry has withdrawn the package. + * + * Before this, a withdrawn package's handlers stayed under its owner + * `app:` until a restart: beside another package's action of + * the same object and name, a call that names no package + * (`POST /api/v1/actions/OBJECT/NAME/ID`) went on answering `409 + * RESOURCE_CONFLICT`, naming the uninstalled package as one of two owners. + * + * Resolved lazily through `@objectstack/runtime`, like the binder. Never + * throws: a runtime with no inverse is warned with the remedy, the bind + * door's posture for a runtime with no binder. + */ + private unbindArtifactHandlers = async (ctx: PluginContext, manifestId: string): Promise => { + let ql: IObjectQLEngine | undefined; + try { ql = ctx.getService('objectql'); } catch { /* no data engine — nothing bound */ } + if (!ql) return; + let unbind: typeof import('@objectstack/runtime')['unbindAppArtifactHandlers'] | undefined; + try { + const mod: any = await import('@objectstack/runtime'); + if (typeof mod?.unbindAppArtifactHandlers === 'function') unbind = mod.unbindAppArtifactHandlers; + } catch { /* reported below */ } + if (!unbind) { + ctx.logger?.warn?.( + `[MarketplaceInstallLocal] uninstalled ${manifestId}, but this runtime has no unbindAppArtifactHandlers — ` + + 'its script actions, body hooks and functions stay bound until the runtime restarts. ' + + 'Upgrade @objectstack/runtime alongside @objectstack/cloud-connection.', + ); + return; + } + unbind(ql, manifestId, { logger: ctx.logger, source: 'MarketplaceInstallLocal' }); + }; + /** * [#21489, #21585] The code in `manifest` this door cannot run, which the * install route refuses: diff --git a/packages/cloud-connection/src/marketplace-install-local-uninstall-handlers.test.ts b/packages/cloud-connection/src/marketplace-install-local-uninstall-handlers.test.ts new file mode 100644 index 00000000000..d9a419b1716 --- /dev/null +++ b/packages/cloud-connection/src/marketplace-install-local-uninstall-handlers.test.ts @@ -0,0 +1,325 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `DELETE /api/v1/marketplace/install-local/:manifestId` withdraws the + * package's executable handlers from the running engine, not only its + * registry entry. + * + * ## What was wrong + * + * The door withdrew the package from the registry (`uninstallPackage`) and + * left every handler its install bound on the engine under `app:` + * (`bindAppArtifactHandlers`): the engine's per-package action slots are not + * the registry. Two installed packages each holding a script action `escalate` + * on one object, a call that names no package is refused `409 + * RESOURCE_CONFLICT` naming both — correct. After one of them was uninstalled + * the same call kept answering that `409`, naming the uninstalled package as + * one of the two owners, until a restart; the restart answered `200` with the + * remaining package's result. Its body hooks kept firing the same way. + * + * The withdrawal had a second half in the engine: the unqualified slot a bare + * call runs held the LAST registration under the key — the uninstalled + * package's — and removing a package's handlers emptied that slot rather than + * handing it back to the owner still holding the key, so the bare call would + * have answered "not found" where the restart runs the remaining handler. + * + * ## What is real here + * + * An `ObjectKernel` with `ObjectQLPlugin` — the real engine, whose action + * slots and bare-call ambiguity rule (`executeAction` with no `packageId`) are + * the thing under test, the real `SchemaRegistry` and the real protocol — and + * the runtime's `AppPlugin`, as a booted server composes them. The handlers + * are bound by the REAL runtime binder (`bindAppArtifactHandlers`, the one the + * door's install calls, with the door's own options) through the same engine + * object the door is handed; the packages are registered and ledgered the way + * an install leaves them. The only stand-in is the door's `find`, which + * answers the installer's grants (`withInstallerGrants`). + * + * ## What these cases pin + * + * - the card's shape: two packages, uninstall one, and the bare call is + * served by the remaining one — and the uninstalled package's body hook + * left the engine with its actions; + * - CONTROL: the remaining package's handler and hook are still registered, + * and its package-qualified call still runs; + * - CONTROL: a re-install binds the handler again, and the bare call is + * refused as ambiguous again — two holders, as before the uninstall; + * - a withdrawal the registry refuses leaves the package's handlers bound; + * - a second unbind of the same package is a no-op; + * - host code and the environment's authored-action handler under the same + * key survive the unbind. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +// The plugin reaches `@objectstack/runtime` through a lazy `import()`; its first +// load is paid here, at module top, never inside a clocked `it`. +import { AppPlugin, bindAppArtifactHandlers, unbindAppArtifactHandlers } from '@objectstack/runtime'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js'; +import { LocalManifestSource } from './local-manifest-source.js'; +import { INSTALLER_USER_ID, installerAuthService, withInstallerGrants } from './install-local-principal.fixtures.js'; + +type Handler = (c: any) => Promise; + +const ROUTE = '/api/v1/marketplace/install-local'; +/** The package owning the object; it embeds a script action `escalate` on it. */ +const A = 'com.qa.addr-a'; +/** The package under uninstall: a standalone script action `escalate` on A's object, and a body hook on it. */ +const B = 'com.qa.addr-b'; +const OBJECT = 'qa_a_ticket'; +const ACTION = 'escalate'; +const RECORD = { id: 'rid_1', name: 'First' }; + +/** A script action `escalate` on the ticket object whose body answers which package ran. */ +const escalate = (by: string) => ({ + name: ACTION, + label: 'Escalate', + objectName: OBJECT, + type: 'script', + body: { language: 'js', source: `return { by: '${by}' };` }, +}); +/** A body hook on the ticket object. */ +const stamp = (by: string) => ({ + name: `qa_stamp_${by}`, + object: OBJECT, + events: ['beforeInsert'], + body: { language: 'js', source: `ctx.input.stamped_by = '${by}';` }, +}); + +/** The install route's flattened ledger manifest of each package, as the binder reads it. */ +function bundleOf(id: string) { + const by = id === A ? 'a' : 'b'; + return { + id, + name: id, + version: '1.0.0', + type: 'app', + ...(id === A + ? { objects: [{ name: OBJECT, label: 'Ticket', fields: { name: { type: 'text', label: 'Name' } }, actions: [escalate(by)] }] } + : { actions: [escalate(by)] }), + hooks: [stamp(by)], + }; +} + +let dir: string; +const kernels: ObjectKernel[] = []; +beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'mil-uninstall-handlers-')); }); +afterEach(async () => { + while (kernels.length) { + const k = kernels.pop()!; + if (k.getState() === 'running') await k.shutdown(); + } + rmSync(dir, { recursive: true, force: true }); + vi.restoreAllMocks(); +}); + +/** A ledger entry as an install writes it. */ +function ledger(manifestId: string) { + new LocalManifestSource(dir).write({ + packageId: manifestId, + versionId: 'v1', + manifestId, + version: '1.0.0', + manifest: bundleOf(manifestId), + installedAt: '2026-01-01T00:00:00.000Z', + installedBy: INSTALLER_USER_ID, + withSampleData: false, + }); +} + +/** The real engine, both packages registered, bound and ledgered; the door started over the same engine. */ +async function boot() { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false } as never); + kernels.push(kernel); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new AppPlugin({})); + await kernel.bootstrap(); + const ql = kernel.getService('objectql'); + ql.registry.logLevel = 'silent'; + + // The engine object the door is handed — ONE object for the bind and the + // uninstall, as `ctx.getService('objectql')` is in a server. Every member is + // the real engine's, called on it, but `find`, which answers the installer's + // grants, and the registry view those grants read the organization from. + const granted = withInstallerGrants({ registry: ql.registry, find: ql.find.bind(ql), syncSchemas: async () => undefined }); + const doorQl = new Proxy(ql, { + get: (target, prop) => { + if (prop === 'find' || prop === 'registry' || prop === 'syncSchemas') return (granted as any)[prop]; + const value = Reflect.get(target, prop, target); + return typeof value === 'function' ? value.bind(target) : value; + }, + }); + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + + /** What the install route leaves for one package: registered, its handlers bound, its ledger entry written. */ + const install = (id: string) => { + ql.registry.installPackage({ id, name: id, version: '1.0.0', type: 'app' } as any, 'authored'); + if (id === A) { + ql.registry.registerObject({ name: OBJECT, label: 'Ticket', fields: { name: { name: 'name', type: 'text', label: 'Name' } } } as any, A); + } + const bound = bindAppArtifactHandlers(doorQl as never, bundleOf(id), { + appId: id, + logger: logger as never, + source: 'MarketplaceInstallLocal', + withholdHooksWithoutBody: true, + }); + expect(bound.actions, `precondition: ${id}'s action is bound`).toBe(1); + expect(bound.hooks, `precondition: ${id}'s body hook is bound`).toBe(1); + ledger(id); + }; + install(A); + install(B); + + const routes = new Map(); + const rawApp = { + get: (p: string, h: Handler) => routes.set(`GET ${p}`, h), + post: (p: string, h: Handler) => routes.set(`POST ${p}`, h), + delete: (p: string, h: Handler) => routes.set(`DELETE ${p}`, h), + }; + const hooks = new Map Promise>(); + const services: Record = { + manifest: kernel.getService('manifest'), + auth: installerAuthService(), + protocol: kernel.getService('protocol'), + objectql: doorQl, + }; + const ctx = { + hook: (e: string, h: () => Promise) => hooks.set(e, h), + getService: (name: string) => { + if (name === 'http-server') return { getRawApp: () => rawApp }; + if (!(name in services)) throw new Error(`no ${name}`); + return services[name]; + }, + logger, + trigger: async () => undefined, + }; + const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir }); + // The `kernel:ready` rehydrate is not what is pinned: the packages are installed above. + (plugin as unknown as Record).rehydrate = async () => undefined; + await plugin.start(ctx as never); + await hooks.get('kernel:ready')?.(); + + const uninstall = async (manifestId: string) => { + const json = vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 })); + return routes.get(`DELETE ${ROUTE}/:manifestId`)!({ + req: { + url: `http://localhost:3000${ROUTE}/${manifestId}`, + raw: new Request(`http://localhost:3000${ROUTE}/${manifestId}`, { method: 'DELETE' }), + json: async () => ({}), + param: (name: string) => (name === 'manifestId' ? manifestId : undefined), + }, + json, + }); + }; + /** The engine's dispatch of `POST /actions/OBJECT/escalate/RID` — no package named, unless `packageId` is. */ + const call = (packageId?: string) => { + const actionCtx = { params: { objectName: OBJECT, recordId: RECORD.id }, record: RECORD }; + return packageId === undefined + ? ql.executeAction(OBJECT, ACTION, actionCtx) + : ql.executeAction(OBJECT, ACTION, actionCtx, { packageId }); + }; + /** The packages holding a handler of their own under the action key, from the engine's package-scoped listing. */ + const holders = () => [A, B].filter((id) => ql.listRegisteredActions({ packageId: id }) + .some((row) => row.objectName === OBJECT && row.actionName === ACTION && row.coordinate === id)); + return { ql, doorQl, logger, install, uninstall, call, holders }; +} + +/** The refusal a bare call answers while two packages hold the key: its ADR-0112 envelope and the owners it names. */ +async function refusalOf(pending: Promise) { + const err: any = await pending.then(() => undefined, (e) => e); + return err === undefined ? undefined : { code: err.code, status: err.status, owners: err.owners }; +} + +describe('install-local uninstall withdraws the package\'s action handlers and hooks from the engine', () => { + it('two packages hold `escalate`; after one is uninstalled, the bare call is served by the remaining one', async () => { + const { ql, uninstall, call } = await boot(); + expect(await refusalOf(call()), 'precondition: two holders, the bare call is refused naming both').toEqual({ + code: 'RESOURCE_CONFLICT', status: 409, owners: [`app:${A}`, `app:${B}`], + }); + + const res = await uninstall(B); + expect(res.status, JSON.stringify(res.payload)).toBe(200); + expect(ql.registry.getPackage(B), 'the registry half withdrew it').toBeUndefined(); + + await expect(call()).resolves.toEqual({ by: 'a' }); + // The uninstalled package's body hook left the engine with its actions: + // nothing is left under its owner to unregister. + expect(ql.unregisterHooksByPackage(`app:${B}`)).toBe(0); + }); + + it('CONTROL: the remaining package keeps its handler and its hook, and its package-qualified call runs', async () => { + const { ql, uninstall, call, holders } = await boot(); + expect(holders(), 'precondition: both packages hold the key').toEqual([A, B]); + + expect((await uninstall(B)).status).toBe(200); + + expect(holders()).toEqual([A]); + await expect(call(A)).resolves.toEqual({ by: 'a' }); + expect(ql.unregisterHooksByPackage(`app:${A}`), 'the remaining package\'s hook is still bound').toBe(1); + }); + + it('CONTROL: a re-install binds the handler again, and the bare call is refused as ambiguous again', async () => { + const { install, uninstall, call } = await boot(); + expect((await uninstall(B)).status).toBe(200); + await expect(call()).resolves.toEqual({ by: 'a' }); + + install(B); + + await expect(call(B)).resolves.toEqual({ by: 'b' }); + expect(await refusalOf(call())).toEqual({ + code: 'RESOURCE_CONFLICT', status: 409, owners: [`app:${A}`, `app:${B}`], + }); + }); + + it('a withdrawal the registry refuses leaves the package\'s handlers bound: it stays loaded, so it keeps running', async () => { + const { ql, uninstall, call, holders } = await boot(); + // Refused at the withdrawal itself, after every check asked ahead of it + // let the uninstall through — the door's `registry.uninstallPackage` entry on `cleanups`. + vi.spyOn(ql.registry, 'uninstallPackage').mockImplementation(() => { throw new Error('refused by the test'); }); + + const res = await uninstall(B); + expect(res.status, JSON.stringify(res.payload)).toBe(200); + expect(res.payload.data.cleanups).toContainEqual(expect.objectContaining({ name: 'registry.uninstallPackage', success: false })); + expect(ql.registry.getPackage(B), 'precondition: the registry still holds it').toBeDefined(); + + expect(holders()).toEqual([A, B]); + await expect(call(B)).resolves.toEqual({ by: 'b' }); + expect(await refusalOf(call())).toEqual({ + code: 'RESOURCE_CONFLICT', status: 409, owners: [`app:${A}`, `app:${B}`], + }); + }); + + it('a second unbind of the same package is a no-op', async () => { + const { ql, doorQl, logger, uninstall, call, holders } = await boot(); + expect((await uninstall(B)).status).toBe(200); + + const again = unbindAppArtifactHandlers(doorQl as never, B, { logger: logger as never, source: 'test' }); + + expect(again.owners).toEqual([`app:${B}`]); + expect(holders()).toEqual([A]); + await expect(call()).resolves.toEqual({ by: 'a' }); + expect(ql.unregisterHooksByPackage(`app:${A}`), 'the remaining package\'s hook is still bound').toBe(1); + expect(logger.error).not.toHaveBeenCalled(); + }); + + it('host code and the environment\'s authored-action handler under the same key survive the unbind', async () => { + const { ql, uninstall, call } = await boot(); + // Host code (registered with no owner) and an environment-authored + // handler (the authored-action resync's owner) under the very key. + ql.registerAction(OBJECT, ACTION, () => 'host'); + ql.registerAction(OBJECT, ACTION, () => 'environment', 'metadata-service'); + + expect((await uninstall(B)).status).toBe(200); + + // B holds nothing of its own now, so a call naming it falls back to the + // ONE shared handler under the key: host code's. + await expect(call(B)).resolves.toBe('host'); + // The environment's own slot (coordinate '') keeps its handler. + await expect(call('')).resolves.toBe('environment'); + await expect(call(A)).resolves.toEqual({ by: 'a' }); + }); +}); diff --git a/packages/objectql/src/bound-action-collision-report.test.ts b/packages/objectql/src/bound-action-collision-report.test.ts index f68959e11d1..add561cd63f 100644 --- a/packages/objectql/src/bound-action-collision-report.test.ts +++ b/packages/objectql/src/bound-action-collision-report.test.ts @@ -226,11 +226,18 @@ describe('ObjectQL.registerAction on a key another owner holds', () => { for (const subject of ["'bc_org:rename'", "'app:com.test.owner'", "'app:com.test.twin'"]) expect(message).toContain(subject); }); - it('withdrawing the replacing owner leaves the key with no handler — the consequence the warning names', async () => { + it('withdrawing the replacing owner hands the key back to the owner it replaced — what the engine answers without it', async () => { + // Each owner keeps its handler in its own package slot (#31673), so the + // replaced owner's handler is still held when the replacing one leaves: + // a call that names no package runs it, as an engine the replacing + // owner never registered on does — never "not found". const { engine } = await engineSpied(); engine.registerAction('bc_org', 'rename', () => 'owner', 'app:com.test.owner'); engine.registerAction('bc_org', 'rename', () => 'twin', 'app:com.test.twin'); engine.removeActionsByPackage('app:com.test.twin'); + expect(await engine.executeAction('bc_org', 'rename', {})).toBe('owner'); + // CONTROL: with no other owner left, the key has no handler. + engine.removeActionsByPackage('app:com.test.owner'); await expect(engine.executeAction('bc_org', 'rename', {})).rejects.toThrow(/not found/); }); diff --git a/packages/objectql/src/engine-actions.ts b/packages/objectql/src/engine-actions.ts index 3e3dccc8f26..e29c429a65e 100644 --- a/packages/objectql/src/engine-actions.ts +++ b/packages/objectql/src/engine-actions.ts @@ -459,12 +459,29 @@ export class ActionsFacet { else if (kept !== entry) slot.set(key, kept); } }; + const held = new Set(this.actions.keys()); prune(this.actions); // [ADR-0150 D4, #31673] …and from every package coordinate's slot. for (const [coordinate, slot] of Array.from(this.packageActions.entries())) { prune(slot); if (slot.size === 0) this.packageActions.delete(coordinate); } + // A key the removal emptied in the unqualified slot while another owner's + // handler stays in its own coordinate's slot takes that handler back — + // the very entry that slot holds, so `coordinateOfUnqualified` still + // finds it — the last coordinate holding the key, in the order the + // slots were created (not the last registration of this key). Left + // empty, a call that names no package answered "not found" for an action + // a remaining owner still holds; it now runs one remaining holder's + // handler. While two or more packages still hold the key the bare call + // is refused naming them ({@link unqualifiedHandler}) whichever entry + // this restores. + for (const key of held) { + if (this.actions.has(key)) continue; + let remaining: ActionHandlerEntry | undefined; + for (const slot of this.packageActions.values()) remaining = slot.get(key) ?? remaining; + if (remaining !== undefined) this.actions.set(key, remaining); + } } /** The body of `ObjectQL#setActionActivationStore`; the method's docblock there is its contract. */ diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 448cd2035da..4099d20924a 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -1125,6 +1125,17 @@ export class ObjectQL implements IObjectQLEngine { * package's is replaced by that package's again, rather than leaving the * key empty; a package removed from beneath an override leaves the * override bound, with nothing beneath it to restore. + * + * [ADR-0150 D4/D5] A key whose unqualified handler was the removed + * package's while another owner still holds a handler under it in its own + * slot runs one remaining holder's handler for a call that names no + * package, rather than "not found", and stays in the unqualified + * {@link listRegisteredActions}; the bare-call ambiguity rule still + * refuses it while two or more packages hold the key. The holder is the + * last coordinate holding the key in slot-creation order, not the last + * registration of that key: with host code beside one package on an + * object-bound key it can be the package's where a restart runs host + * code's. */ removeActionsByPackage(packageName: string): void { // [#29986 codemod] The body moved to `engine-actions.ts` (see `ActionsHost`). diff --git a/packages/runtime/src/action-package-addressing.test.ts b/packages/runtime/src/action-package-addressing.test.ts index 25a93b9b3d2..e8093778aa8 100644 --- a/packages/runtime/src/action-package-addressing.test.ts +++ b/packages/runtime/src/action-package-addressing.test.ts @@ -210,6 +210,33 @@ describe('ADR-0150 D4 — the owner gate judges the handler the package call run }); }); +describe('removeActionsByPackage hands an emptied key back — the door reaches that entry and its owner gates (Clause-② narrowing)', () => { + it('reaches host code\'s handed-back entry, where the rotation fell through to `global`, and that entry\'s owner refuses 403', async () => { + install(A); + install(B); + ship(A); + // B's `approve_all` asks a capability the caller lacks; its rotation is OBJECT:approve_all, + // OBJECT:approve (its target), then global:approve_all, the one key held under its own name. + engine.registry.registerItem('action', { + name: 'approve_all', label: 'Approve all', type: 'script', objectName: OBJECT, target: 'approve', requiredPermissions: ['approve_everything'], + body: { language: 'js', source: 'return 1;', capabilities: [] }, + } as never, 'name' as never, B); + engine.registerAction(OBJECT, 'approve', () => 'host'); + bind(A); + engine.registerAction('global', 'approve_all', () => 'all', `app:${B}`); + engine.registerAction('global', 'approve', () => 'global'); + engine.removeActionsByPackage(`app:${A}`); + // Before the hand-back OBJECT:approve was empty: this ran global:approve, and approve_all + // reached global:approve_all, so it owned nothing the call ran. + expect((await executeRegisteredAction(deps, engine, OBJECT, ['approve'], {})).result).toBe('host'); + const declaration = await resolve(); + expect(await actionHandlerOwnerRefusal(deps, { request: {} } as any, { + ql: engine, action: declaration.action, objectName: OBJECT, candidates: ['approve'], + ec: { isSystem: false, permissions: [], positions: [] }, + })).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + }); +}); + describe('[#31697] a caller that names no package', () => { it('is refused naming both packages when two hold the name on the object — at the declaration (D5) and at the dispatch (409), never the last registered', async () => { install(A); diff --git a/packages/runtime/src/app-artifact-handlers.ts b/packages/runtime/src/app-artifact-handlers.ts index 67609a21d71..f68561cd8c8 100644 --- a/packages/runtime/src/app-artifact-handlers.ts +++ b/packages/runtime/src/app-artifact-handlers.ts @@ -542,6 +542,72 @@ function recordBind(ql: object, owner: string, record: BoundRecord): void { byArtifact.set(owner, { owners: [...new Set(record.owners)], functions: record.functions }); } +/** What one {@link unbindAppArtifactHandlers} call tore down. */ +export interface AppArtifactHandlerUnbinding { + /** Every owner whose actions, hooks and functions left the engine: the artifact's owner first. */ + owners: string[]; +} + +/** + * Withdraw from `ql` every executable handler {@link bindAppArtifactHandlers} + * bound for the package `appId` — the binder's inverse, for a package that + * leaves the running kernel (the install-local uninstall door, after its + * registry withdrawal). + * + * The bind registers a package's script-action handlers, body hooks and + * bundle functions on the engine under `app:` (and, for a + * multi-package artifact, under each body's `app:`), and a + * registry withdrawal (`SchemaRegistry.uninstallPackage`) reaches none of + * them: the engine's handler slots are not the registry. Left there, the + * withdrawn package still counted as a holder of each action key, so a call + * that names no package (`POST /actions/OBJECT/NAME/ID`) beside another + * package's action of the same name stayed refused as ambiguous, naming the + * uninstalled package, until a restart; its body hooks kept firing and its + * functions stayed resolvable the same way. + * + * The teardown is the bind's own, applied to every owner and dropping all of + * it: the artifact's owner and every owner its last bind on this engine + * recorded lose their actions (`removeActionsByPackage`), hooks + * (`unregisterHooksByPackage`) and functions (`unregisterFunctionsByPackage`), + * each owner's bare-name function claims go with its functions + * (`releaseFunctionClaims`), and the bind record is forgotten, so a later + * install of the same id binds as a first bind. ⛔ Only those owners: another + * package's handlers, host code and the environment's authored-action + * handlers (`metadata-service`) are untouched. Jobs are not here: the + * uninstall cleanup {@link scheduleAppArtifactJobs} registers cancels them. + * + * Never throws: an engine method that throws is logged at `error` with the + * owner, and the rest of the teardown still runs. + */ +export function unbindAppArtifactHandlers( + ql: IObjectQLEngine, + appId: string, + options: { logger: Logger; source?: string }, +): AppArtifactHandlerUnbinding { + const tag = `[${options.source ?? 'AppPlugin'}]`; + const owner = appArtifactHandlerOwner(appId); + const owners = [...new Set([owner, ...previousBind(ql, owner).owners])]; + const engine = ql as FunctionHoldingEngine; + for (const each of owners) { + try { + if (typeof ql.removeActionsByPackage === 'function') ql.removeActionsByPackage(each); + if (typeof ql.unregisterHooksByPackage === 'function') ql.unregisterHooksByPackage(each); + if (typeof engine.unregisterFunctionsByPackage === 'function') { + engine.unregisterFunctionsByPackage(each); + releaseFunctionClaims(engine, each); + } + } catch (err: any) { + options.logger?.error( + `${tag} Failed to withdraw the handlers of an uninstalled package — what was left stays bound until the runtime restarts`, + err as Error, + { appId, owner: each }, + ); + } + } + boundOwnersByEngine.get(ql)?.delete(owner); + return { owners }; +} + /** The engine's function-holder seam the re-bind reads and writes (`ObjectQL`'s methods of these names). */ interface FunctionHoldingEngine { /** The engine's registry: the bare-name rule records a function's holder as a claim there (`claimBareNameFunctions`). */ diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts index 6f44862e21b..252c5e0e778 100644 --- a/packages/runtime/src/index.ts +++ b/packages/runtime/src/index.ts @@ -164,7 +164,8 @@ export type { DefaultDatasourceDefinition, DefaultDatasourcePluginOptions } from export { AppPlugin, collectBundleHooks, collectBundleFunctions, collectBundleFunctionEntries, collectBundleActions } from './app-plugin.js'; // [#21321] The ONE binder of an app artifact's script-action bodies and body // hooks, under the owner `app:` — called by `AppPlugin.start` and by the -// install-local plugin (`@objectstack/cloud-connection`) on install and rehydrate. +// install-local plugin (`@objectstack/cloud-connection`) on install and rehydrate; +// `unbindAppArtifactHandlers` is its inverse, called by install-local's uninstall. // [#21489] …and its job half: `scheduleAppArtifactJobs` schedules a package's // jobs (a `body` runs sandboxed on every door), and `collectJobsWithoutBody` // names the enabled jobs no JSON door can run (no `body`, or a `body` or `pull` @@ -176,6 +177,7 @@ export { AppPlugin, collectBundleHooks, collectBundleFunctions, collectBundleFun // with the refusal the binder refuses each by at bind: install-local refuses them. export { bindAppArtifactHandlers, + unbindAppArtifactHandlers, appArtifactHandlerOwner, scheduleAppArtifactJobs, collectJobsWithoutBody, @@ -185,6 +187,7 @@ export { export type { AppArtifactHandlerBinding, AppArtifactHandlerBindingOptions, + AppArtifactHandlerUnbinding, AppArtifactJobScheduling, AppArtifactJobSchedulingOptions, JobWithoutBody,