diff --git a/.changeset/34432-install-local-resolver-refusal.md b/.changeset/34432-install-local-resolver-refusal.md new file mode 100644 index 00000000000..06b982726d8 --- /dev/null +++ b/.changeset/34432-install-local-resolver-refusal.md @@ -0,0 +1,14 @@ +--- +'@objectstack/cloud-connection': patch +--- + +fix(cloud-connection): install-local answers a composed artifact the resolver refuses with the resolver's 422 at the declared-rename step, not a 503 telling the author to retry + +Clause-②: no +Metadata-protocol: none + +The declared-rename step of `POST /api/v1/marketplace/install-local` (step 2c″) reads every package body of a composed artifact through the artifact resolver. When the resolver refused the artifact, the step answered `503 SERVICE_UNAVAILABLE`: "the tables its declared rename(s) carry could not be read … Retry once the database answers." Examples are a `packages` that is not a list, or a package entry that carries a retired bare `indexes[].unique: true`. A retry never helps, and the author looked for the fault in the wrong place. + +The step now resolves the bodies before it reads any table. A refusal answers with the resolver's own declared status and code: `422 INVALID_ARTIFACT_PACKAGES` or `INVALID_ARTIFACT_PACKAGE_ENTRY`, with the resolver's sentence. Nothing is written. This is the answer the `isolated`-posture unique-scope gate already gives for the same bytes, through the same reader. An undeclared throw out of the resolver, such as a dependency cycle between two packages of one artifact, is rethrown and is not relabelled. The 503 now means only that a table could not be read. + +The door reaches this step first only on a runtime that predates the install-time code judgements (`collectJobsWithoutBody`, `collectHooksWithoutBody`). A runtime that carries them resolves the packages earlier, so its answer does not change. diff --git a/packages/cloud-connection/src/marketplace-install-local-plugin.ts b/packages/cloud-connection/src/marketplace-install-local-plugin.ts index ad402ab7651..c6ebcab0b33 100644 --- a/packages/cloud-connection/src/marketplace-install-local-plugin.ts +++ b/packages/cloud-connection/src/marketplace-install-local-plugin.ts @@ -474,6 +474,39 @@ function isDeclaredRegisterRefusal(err: unknown): boolean { return declared !== undefined && declared >= 400 && declared < 500; } +/** + * [#34407, #34432] The answer to a package body the artifact resolver refuses + * before any write (`resolveStackCollection` → `resolveArtifactPackageEntries`: + * `INVALID_ARTIFACT_PACKAGES`, `INVALID_ARTIFACT_PACKAGE_ENTRY`, + * `DUPLICATE_ARTIFACT_PACKAGE`, each an ADR-0112 envelope with its declared + * `status: 422`): that refusal's own declared status and code, the resolver's + * sentence, and that nothing was written. The one reader of such a refusal on + * this door's pre-write steps — the D5e gate (2b) and the declared renames + * (2c″) both read the bodies through the resolver, so the same bytes are + * answered the same way whichever step reads them first. + * + * `undefined` for a throw that declares no status below 500 — an undeclared + * throw (the resolver's own dependency-cycle error among them) or a declared + * 5xx: the caller rethrows it, never relabels it. + */ +function declaredRefusalAnswer( + manifestId: string, + err: unknown, +): { status: number; body: { success: false; error: { code: string; message: string } } } | undefined { + const refusal = resolveThrownHttpError(err); + if (refusal.declaredStatus === undefined || refusal.status >= 500) return undefined; + return { + status: refusal.status, + body: { + success: false, + error: { + code: refusal.code, + message: `Package '${manifestId}' cannot be installed: ${String((err as any)?.message ?? err)} Nothing was installed or written.`, + }, + }, + }; +} + /** * [#21490] The one `protocol` verb this plugin calls: the runner of the * uninstall cleanups domain plugins register through @@ -3123,20 +3156,15 @@ export class MarketplaceInstallLocalPlugin implements Plugin { // `packages` the resolver refuses (ADR-0112 `code` + its declared // 4xx status, the refusal the `manifest` service raises on the same // bytes) is answered here, before anything is written — never - // thrown out of the door. An undeclared throw stays a throw. + // thrown out of the door ({@link declaredRefusalAnswer}). An + // undeclared throw stays a throw. let gate: ReturnType; try { gate = this.evaluateGlobalUniqueGate(manifest, previousEntry, body, userId); - } catch (err: any) { - const refusal = resolveThrownHttpError(err); - if (refusal.declaredStatus === undefined || refusal.status >= 500) throw err; - return c.json({ - success: false, - error: { - code: refusal.code, - message: `Package '${manifestId}' cannot be installed: ${String(err?.message ?? err)} Nothing was installed or written.`, - }, - }, refusal.status); + } catch (err: unknown) { + const refused = declaredRefusalAnswer(manifestId, err); + if (!refused) throw err; + return c.json(refused.body, refused.status); } if (gate.blocked) { ctx.logger?.warn?.( @@ -3204,7 +3232,10 @@ export class MarketplaceInstallLocalPlugin implements Plugin { // the physical table by the driver's own rule // ({@link evaluateDeclaredRenames}); a declaration it cannot // honour is refused `422 VALIDATION_ERROR`, naming the field, the - // old key and the reason. Asked before 2c′, so a refusal no token + // old key and the reason; [#34432] a body the artifact resolver + // refuses is answered with that refusal's own status and code, as + // at 2b, and only a table that could not be read answers 503. + // Asked before 2c′, so a refusal no token // answers is never preceded by a 409 asking for one. The carry // itself runs right before step 3, the last moment the running // version still serves the old key. @@ -4566,6 +4597,12 @@ export class MarketplaceInstallLocalPlugin implements Plugin { * - **A refusal**: `422 VALIDATION_ERROR` (this door's body refusal), * each in `details.refusals` with its object, field, old key(s) and * reason. No token answers it: the package must change. + * - **A body the artifact resolver refuses** (a composed artifact whose + * `packages` is not a list, or one of whose entries the entry contract + * refuses): that refusal's own declared status and code + * ({@link declaredRefusalAnswer}, step 2b's reader), before any table is + * read. An undeclared throw out of the resolver is rethrown, never + * relabelled. * - **A reading that failed** (the table could not be read): `503 * SERVICE_UNAVAILABLE`, never taken for "nothing to carry". * - Otherwise the tables to carry, which step 2f carries. @@ -4575,7 +4612,24 @@ export class MarketplaceInstallLocalPlugin implements Plugin { manifestId: string, converted: unknown, installed: unknown, - ): Promise<{ refusal?: { body: Record; status: 422 | 503 }; tables: InstallRenameTable[] }> => { + ): Promise<{ refusal?: { body: Record; status: number }; tables: InstallRenameTable[] }> => { + // [#34432] The bodies the plan reads, resolved FIRST through the fold + // the plan reads them by ({@link packageUpgradeSideOf}: the + // `resolveStackCollection` reads of `objects`, `objectExtensions` and + // `data`), so a body the resolver refuses is told apart from a table + // that could not be read: the resolver is deterministic over the same + // bytes, so the plan below never meets its refusal, and what the plan + // throws is answered as the table read's. Without this, the + // resolver's 422 was answered as the 503 below and its author was told + // to retry once the database answers. + try { + packageUpgradeSideOf(converted); + if (installed !== null && installed !== undefined) packageUpgradeSideOf(installed); + } catch (err: unknown) { + const refused = declaredRefusalAnswer(manifestId, err); + if (!refused) throw err; + return { tables: [], refusal: refused }; + } let plan: { tables: InstallRenameTable[]; refusals: InstallRenameRefusal[] }; try { plan = await planDeclaredRenames(ctx, manifestId, converted, installed); diff --git a/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-34432.test.ts b/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-34432.test.ts new file mode 100644 index 00000000000..f5759aba534 --- /dev/null +++ b/packages/cloud-connection/src/marketplace-install-local-resolver-refusal-34432.test.ts @@ -0,0 +1,232 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34432] Step 2c″ of the install door (the declared renames) reads every + * package body of a composed artifact through the artifact resolver, as the + * `isolated`-posture D5e gate (2b) does. A body the resolver refuses is + * answered with that refusal's own declared status and code — the resolver's + * `422 INVALID_ARTIFACT_PACKAGES` / `INVALID_ARTIFACT_PACKAGE_ENTRY` — and + * nothing is written. Before, every throw out of the rename plan was answered + * `503 SERVICE_UNAVAILABLE` "Retry once the database answers", so an author + * whose bundle is malformed was told the database was down. + * + * Driven through the real `POST /api/v1/marketplace/install-local` handler + * under the `single` posture, where the D5e gate reads no body, over a runtime + * that predates the step-1c code judgements (`@objectstack/runtime` is mocked + * without `collectJobsWithoutBody` / `collectHooksWithoutBody`, as in + * `marketplace-install-local-composed-top-level-reads.test.ts`), so 2c″ is the + * first step to resolve the packages. (A runtime that carries those + * judgements resolves the packages at step 1c first, and the resolver's + * refusal leaves the door as a throw.) The controls pin the rest of the + * contract: a table that really could not be read still answers 503, and an + * undeclared throw out of the resolver (its own dependency-cycle error) is + * rethrown, never relabelled. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; + +vi.mock('@objectstack/runtime', () => ({ + SeedLoaderService: class { + async load() { return { summary: { totalInserted: 0, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; } + async buildDependencyGraph(objects: string[]) { return { objects }; } + }, + resolveSeedLocaleForLoad: async () => undefined, + appDefaultSeedLocale: () => undefined, + describeSeedLocale: () => 'none', +})); + +import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js'; +import { declareInstallerPlatformOwner, installerAuthService, withInstallerGrants } from './install-local-principal.fixtures.js'; +import { LocalManifestSource } from './local-manifest-source.js'; + +type Handler = (c: any) => Promise; +type Row = Record; + +const ROUTE = '/api/v1/marketplace/install-local'; +const SUITE = 'com.example.suite'; + +/** An object whose field declares a rename, so step 2c″ asks the driver to read its table. */ +const LEAD = { name: 'crm_lead', label: 'Lead', fields: { account_name: { type: 'text', label: 'Account', renamedFrom: ['company'] } } }; +const ACCOUNT = { name: 'crm_account', label: 'Account', fields: { name: { type: 'text', label: 'Name' } } }; + +const entry = (id: string, objects: Row[], dependencies?: Record): Row => ({ + manifest: { id, name: id, version: '1.0.0', type: 'module', ...(dependencies ? { dependencies } : {}), objects }, +}); + +/** A composed artifact: `packages[]` and no top-level `objects`, so every reader goes through the resolver. */ +const composed = (packages: unknown): Row => ({ id: SUITE, name: 'Suite', version: '1.0.0', type: 'app', packages }); +const WELL_FORMED = (): Row[] => [entry(`${SUITE}.core`, [ACCOUNT]), entry(`${SUITE}.leads`, [LEAD])]; + +function makeRawApp() { + const routes = new Map(); + return { + routes, + 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), + }; +} + +function makeC(reqBody: any) { + return { + req: { + url: `http://localhost:3000${ROUTE}`, + raw: new Request(`http://localhost:3000${ROUTE}`), + json: async () => reqBody, + param: () => undefined, + header: () => undefined, + query: () => undefined, + }, + json: vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 })), + }; +} + +/** + * A driver with the declared-rename members the door asks. Its plan reads no + * table and carries nothing; `planThrows` makes the table read fail the way a + * database that does not answer fails it (an undeclared throw). + */ +function fakeDriver(opts: { planThrows?: boolean } = {}) { + return { + planDeclaredRenames: vi.fn(async () => { + if (opts.planThrows) throw new Error('connect ECONNREFUSED'); + return { carries: [], refusals: [] }; + }), + carryDeclaredRenames: vi.fn(async () => []), + reverseDeclaredRenames: vi.fn(async () => undefined), + }; +} + +async function boot(dir: string, driver: ReturnType) { + const rawApp = makeRawApp(); + const hooks = new Map(); + const register = vi.fn(); + const services: Record = { + manifest: { register }, + auth: installerAuthService(), + objectql: withInstallerGrants({ + syncSchemas: async () => undefined, + getDriverForObject: () => driver, + registry: { getObject: () => undefined }, + }), + metadata: {}, + }; + const ctx = { + hook: (e: string, h: any) => hooks.set(e, h), + getService: (name: string) => { + if (name === 'http-server') return { getRawApp: () => rawApp }; + const svc = services[name]; + if (svc === undefined) throw new Error(`no ${name}`); + return svc; + }, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + }; + const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir }); + await plugin.start(ctx as any); + await hooks.get('kernel:ready')?.(); + // The door registers its own plugin manifest at boot; only the install's registrations count. + register.mockClear(); + return { + install: (reqBody: Row) => rawApp.routes.get(`POST ${ROUTE}`)!(makeC(reqBody)), + register, + }; +} + +let dir: string; +let posture: string | undefined; +let restoreOwner: () => void; +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'mil-resolver-refusal-')); + posture = process.env.OS_TENANCY_POSTURE; + process.env.OS_TENANCY_POSTURE = 'single'; + restoreOwner = declareInstallerPlatformOwner('admin'); +}); +afterEach(() => { + restoreOwner(); + rmSync(dir, { recursive: true, force: true }); + if (posture === undefined) delete process.env.OS_TENANCY_POSTURE; + else process.env.OS_TENANCY_POSTURE = posture; + vi.restoreAllMocks(); +}); + +/** Nothing registered, no ledger entry, and the table never read. */ +function expectNothingWritten(rt: Awaited>, driver: ReturnType) { + expect(rt.register).not.toHaveBeenCalled(); + expect(new LocalManifestSource(dir).read(SUITE).entry).toBeNull(); + expect(driver.planDeclaredRenames).not.toHaveBeenCalled(); + expect(driver.carryDeclaredRenames).not.toHaveBeenCalled(); +} + +describe('#34432 — step 2c″ answers a body the artifact resolver refuses with that refusal, under the single posture', () => { + it('a `packages` that is not a list answers 422 INVALID_ARTIFACT_PACKAGES, and nothing is written', async () => { + const driver = fakeDriver(); + const rt = await boot(dir, driver); + + const res = await rt.install({ manifest: composed('not-a-list') }); + + expect(res.status, JSON.stringify(res.payload)).toBe(422); + expect(res.payload.success).toBe(false); + expect(res.payload.error.code).toBe('INVALID_ARTIFACT_PACKAGES'); + expectNothingWritten(rt, driver); + }); + + it('a package entry carrying a retired bare `indexes[].unique: true` answers 422 INVALID_ARTIFACT_PACKAGE_ENTRY, and nothing is written', async () => { + const driver = fakeDriver(); + const rt = await boot(dir, driver); + const retired = { ...ACCOUNT, indexes: [{ fields: ['name'], unique: true }] }; + + const res = await rt.install({ manifest: composed([entry(`${SUITE}.core`, [retired]), entry(`${SUITE}.leads`, [LEAD])]) }); + + expect(res.status, JSON.stringify(res.payload)).toBe(422); + expect(res.payload.success).toBe(false); + expect(res.payload.error.code).toBe('INVALID_ARTIFACT_PACKAGE_ENTRY'); + expectNothingWritten(rt, driver); + }); +}); + +describe('#34432 — controls: the 503 stays the unread table\'s, and an undeclared throw stays a throw', () => { + it('CONTROL: a well-formed composed artifact whose renamed field\'s table cannot be read still answers 503 SERVICE_UNAVAILABLE', async () => { + const driver = fakeDriver({ planThrows: true }); + const rt = await boot(dir, driver); + + const res = await rt.install({ manifest: composed(WELL_FORMED()) }); + + expect(res.status, JSON.stringify(res.payload)).toBe(503); + expect(res.payload.error.code).toBe('SERVICE_UNAVAILABLE'); + expect(driver.planDeclaredRenames).toHaveBeenCalledTimes(1); + expect(rt.register).not.toHaveBeenCalled(); + expect(new LocalManifestSource(dir).read(SUITE).entry).toBeNull(); + }); + + it('CONTROL: the same artifact over a table that reads installs', async () => { + const driver = fakeDriver(); + const rt = await boot(dir, driver); + + const res = await rt.install({ manifest: composed(WELL_FORMED()) }); + + expect(res.status, JSON.stringify(res.payload)).toBe(200); + expect(driver.planDeclaredRenames).toHaveBeenCalledTimes(1); + }); + + it('an undeclared throw out of the resolver (a dependency cycle between two packages) is rethrown, never answered 503', async () => { + const driver = fakeDriver(); + const rt = await boot(dir, driver); + const cyclic = [ + entry(`${SUITE}.core`, [ACCOUNT], { [`${SUITE}.leads`]: '*' }), + entry(`${SUITE}.leads`, [LEAD], { [`${SUITE}.core`]: '*' }), + ]; + + const outcome = await rt.install({ manifest: composed(cyclic) }).then( + (res: any) => ({ answered: res }), + (err: unknown) => ({ thrown: err as Error }), + ); + + expect('answered' in outcome ? JSON.stringify(outcome.answered.payload) : 'thrown').toBe('thrown'); + expect((outcome as { thrown: Error }).thrown.message).toContain('Circular dependency'); + expectNothingWritten(rt, driver); + }); +});