Skip to content

Commit f56759b

Browse files
committed
fix(cloud-connection): install-local step 2c″ answers a body the artifact resolver refuses with that refusal, not the unread-table 503
Claude-Session: https://claude.ai/code/session_01ADHkmRXuRn93HphKp7kXEz Co-authored-by: Claude <noreply@anthropic.com>
1 parent 1efe7a2 commit f56759b

2 files changed

Lines changed: 291 additions & 13 deletions

File tree

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

Lines changed: 66 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,39 @@ function isDeclaredRegisterRefusal(err: unknown): boolean {
474474
return declared !== undefined && declared >= 400 && declared < 500;
475475
}
476476

477+
/**
478+
* [#34407, #34432] The answer to a package body the artifact resolver refuses
479+
* before any write (`resolveStackCollection` → `resolveArtifactPackageEntries`:
480+
* `INVALID_ARTIFACT_PACKAGES`, `INVALID_ARTIFACT_PACKAGE_ENTRY`,
481+
* `DUPLICATE_ARTIFACT_PACKAGE`, each an ADR-0112 envelope with its declared
482+
* `status: 422`): that refusal's own declared status and code, the resolver's
483+
* sentence, and that nothing was written. The one reader of such a refusal on
484+
* this door's pre-write steps — the D5e gate (2b) and the declared renames
485+
* (2c″) both read the bodies through the resolver, so the same bytes are
486+
* answered the same way whichever step reads them first.
487+
*
488+
* `undefined` for a throw that declares no status below 500 — an undeclared
489+
* throw (the resolver's own dependency-cycle error among them) or a declared
490+
* 5xx: the caller rethrows it, never relabels it.
491+
*/
492+
function declaredRefusalAnswer(
493+
manifestId: string,
494+
err: unknown,
495+
): { status: number; body: { success: false; error: { code: string; message: string } } } | undefined {
496+
const refusal = resolveThrownHttpError(err);
497+
if (refusal.declaredStatus === undefined || refusal.status >= 500) return undefined;
498+
return {
499+
status: refusal.status,
500+
body: {
501+
success: false,
502+
error: {
503+
code: refusal.code,
504+
message: `Package '${manifestId}' cannot be installed: ${String((err as any)?.message ?? err)} Nothing was installed or written.`,
505+
},
506+
},
507+
};
508+
}
509+
477510
/**
478511
* [#21490] The one `protocol` verb this plugin calls: the runner of the
479512
* uninstall cleanups domain plugins register through
@@ -3123,20 +3156,15 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
31233156
// `packages` the resolver refuses (ADR-0112 `code` + its declared
31243157
// 4xx status, the refusal the `manifest` service raises on the same
31253158
// bytes) is answered here, before anything is written — never
3126-
// thrown out of the door. An undeclared throw stays a throw.
3159+
// thrown out of the door ({@link declaredRefusalAnswer}). An
3160+
// undeclared throw stays a throw.
31273161
let gate: ReturnType<MarketplaceInstallLocalPlugin['evaluateGlobalUniqueGate']>;
31283162
try {
31293163
gate = this.evaluateGlobalUniqueGate(manifest, previousEntry, body, userId);
3130-
} catch (err: any) {
3131-
const refusal = resolveThrownHttpError(err);
3132-
if (refusal.declaredStatus === undefined || refusal.status >= 500) throw err;
3133-
return c.json({
3134-
success: false,
3135-
error: {
3136-
code: refusal.code,
3137-
message: `Package '${manifestId}' cannot be installed: ${String(err?.message ?? err)} Nothing was installed or written.`,
3138-
},
3139-
}, refusal.status);
3164+
} catch (err: unknown) {
3165+
const refused = declaredRefusalAnswer(manifestId, err);
3166+
if (!refused) throw err;
3167+
return c.json(refused.body, refused.status);
31403168
}
31413169
if (gate.blocked) {
31423170
ctx.logger?.warn?.(
@@ -3204,7 +3232,10 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
32043232
// the physical table by the driver's own rule
32053233
// ({@link evaluateDeclaredRenames}); a declaration it cannot
32063234
// honour is refused `422 VALIDATION_ERROR`, naming the field, the
3207-
// old key and the reason. Asked before 2c′, so a refusal no token
3235+
// old key and the reason; [#34432] a body the artifact resolver
3236+
// refuses is answered with that refusal's own status and code, as
3237+
// at 2b, and only a table that could not be read answers 503.
3238+
// Asked before 2c′, so a refusal no token
32083239
// answers is never preceded by a 409 asking for one. The carry
32093240
// itself runs right before step 3, the last moment the running
32103241
// version still serves the old key.
@@ -4566,6 +4597,12 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
45664597
* - **A refusal**: `422 VALIDATION_ERROR` (this door's body refusal),
45674598
* each in `details.refusals` with its object, field, old key(s) and
45684599
* reason. No token answers it: the package must change.
4600+
* - **A body the artifact resolver refuses** (a composed artifact whose
4601+
* `packages` is not a list, or one of whose entries the entry contract
4602+
* refuses): that refusal's own declared status and code
4603+
* ({@link declaredRefusalAnswer}, step 2b's reader), before any table is
4604+
* read. An undeclared throw out of the resolver is rethrown, never
4605+
* relabelled.
45694606
* - **A reading that failed** (the table could not be read): `503
45704607
* SERVICE_UNAVAILABLE`, never taken for "nothing to carry".
45714608
* - Otherwise the tables to carry, which step 2f carries.
@@ -4575,7 +4612,23 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
45754612
manifestId: string,
45764613
converted: unknown,
45774614
installed: unknown,
4578-
): Promise<{ refusal?: { body: Record<string, unknown>; status: 422 | 503 }; tables: InstallRenameTable[] }> => {
4615+
): Promise<{ refusal?: { body: Record<string, unknown>; status: number }; tables: InstallRenameTable[] }> => {
4616+
// [#34432] The bodies the plan reads, resolved FIRST through the fold
4617+
// the plan reads them by ({@link packageUpgradeSideOf}: the
4618+
// `resolveStackCollection` reads of `objects`, `objectExtensions` and
4619+
// `data`), so a body the resolver refuses is told apart from a table
4620+
// that could not be read: the plan below then meets the same resolved
4621+
// bodies, and a throw out of it is the table read's. Without this, the
4622+
// resolver's 422 was answered as the 503 below and its author was told
4623+
// to retry once the database answers.
4624+
try {
4625+
packageUpgradeSideOf(converted);
4626+
if (installed !== null && installed !== undefined) packageUpgradeSideOf(installed);
4627+
} catch (err: unknown) {
4628+
const refused = declaredRefusalAnswer(manifestId, err);
4629+
if (!refused) throw err;
4630+
return { tables: [], refusal: refused };
4631+
}
45794632
let plan: { tables: InstallRenameTable[]; refusals: InstallRenameRefusal[] };
45804633
try {
45814634
plan = await planDeclaredRenames(ctx, manifestId, converted, installed);
Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#34432] Step 2c″ of the install door (the declared renames) reads every
5+
* package body of a composed artifact through the artifact resolver, as the
6+
* `isolated`-posture D5e gate (2b) does. A body the resolver refuses is
7+
* answered with that refusal's own declared status and code — the resolver's
8+
* `422 INVALID_ARTIFACT_PACKAGES` / `INVALID_ARTIFACT_PACKAGE_ENTRY` — and
9+
* nothing is written. Before, every throw out of the rename plan was answered
10+
* `503 SERVICE_UNAVAILABLE` "Retry once the database answers", so an author
11+
* whose bundle is malformed was told the database was down.
12+
*
13+
* Driven through the real `POST /api/v1/marketplace/install-local` handler
14+
* under the `single` posture, where the D5e gate reads no body and 2c″ is the
15+
* first step to resolve the packages. The controls pin the rest of the
16+
* contract: a table that really could not be read still answers 503, and an
17+
* undeclared throw out of the resolver (its own dependency-cycle error) is
18+
* rethrown, never relabelled.
19+
*/
20+
21+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
22+
import { mkdtempSync, rmSync } from 'node:fs';
23+
import { join } from 'node:path';
24+
import { tmpdir } from 'node:os';
25+
26+
vi.mock('@objectstack/runtime', () => ({
27+
SeedLoaderService: class {
28+
async load() { return { summary: { totalInserted: 0, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; }
29+
async buildDependencyGraph(objects: string[]) { return { objects }; }
30+
},
31+
resolveSeedLocaleForLoad: async () => undefined,
32+
appDefaultSeedLocale: () => undefined,
33+
describeSeedLocale: () => 'none',
34+
}));
35+
36+
import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js';
37+
import { declareInstallerPlatformOwner, installerAuthService, withInstallerGrants } from './install-local-principal.fixtures.js';
38+
import { LocalManifestSource } from './local-manifest-source.js';
39+
40+
type Handler = (c: any) => Promise<any>;
41+
type Row = Record<string, any>;
42+
43+
const ROUTE = '/api/v1/marketplace/install-local';
44+
const SUITE = 'com.example.suite';
45+
46+
/** An object whose field declares a rename, so step 2c″ asks the driver to read its table. */
47+
const LEAD = { name: 'crm_lead', label: 'Lead', fields: { account_name: { type: 'text', label: 'Account', renamedFrom: ['company'] } } };
48+
const ACCOUNT = { name: 'crm_account', label: 'Account', fields: { name: { type: 'text', label: 'Name' } } };
49+
50+
const entry = (id: string, objects: Row[], dependencies?: Record<string, string>): Row => ({
51+
manifest: { id, name: id, version: '1.0.0', type: 'module', ...(dependencies ? { dependencies } : {}), objects },
52+
});
53+
54+
/** A composed artifact: `packages[]` and no top-level `objects`, so every reader goes through the resolver. */
55+
const composed = (packages: unknown): Row => ({ id: SUITE, name: 'Suite', version: '1.0.0', type: 'app', packages });
56+
const WELL_FORMED = (): Row[] => [entry(`${SUITE}.core`, [ACCOUNT]), entry(`${SUITE}.leads`, [LEAD])];
57+
58+
function makeRawApp() {
59+
const routes = new Map<string, Handler>();
60+
return {
61+
routes,
62+
get: (p: string, h: Handler) => routes.set(`GET ${p}`, h),
63+
post: (p: string, h: Handler) => routes.set(`POST ${p}`, h),
64+
delete: (p: string, h: Handler) => routes.set(`DELETE ${p}`, h),
65+
};
66+
}
67+
68+
function makeC(reqBody: any) {
69+
return {
70+
req: {
71+
url: `http://localhost:3000${ROUTE}`,
72+
raw: new Request(`http://localhost:3000${ROUTE}`),
73+
json: async () => reqBody,
74+
param: () => undefined,
75+
header: () => undefined,
76+
query: () => undefined,
77+
},
78+
json: vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 })),
79+
};
80+
}
81+
82+
/**
83+
* A driver with the declared-rename members the door asks. Its plan reads no
84+
* table and carries nothing; `planThrows` makes the table read fail the way a
85+
* database that does not answer fails it (an undeclared throw).
86+
*/
87+
function fakeDriver(opts: { planThrows?: boolean } = {}) {
88+
return {
89+
planDeclaredRenames: vi.fn(async () => {
90+
if (opts.planThrows) throw new Error('connect ECONNREFUSED');
91+
return { carries: [], refusals: [] };
92+
}),
93+
carryDeclaredRenames: vi.fn(async () => []),
94+
reverseDeclaredRenames: vi.fn(async () => undefined),
95+
};
96+
}
97+
98+
async function boot(dir: string, driver: ReturnType<typeof fakeDriver>) {
99+
const rawApp = makeRawApp();
100+
const hooks = new Map<string, any>();
101+
const register = vi.fn();
102+
const services: Record<string, any> = {
103+
manifest: { register },
104+
auth: installerAuthService(),
105+
objectql: withInstallerGrants({
106+
syncSchemas: async () => undefined,
107+
getDriverForObject: () => driver,
108+
registry: { getObject: () => undefined },
109+
}),
110+
metadata: {},
111+
};
112+
const ctx = {
113+
hook: (e: string, h: any) => hooks.set(e, h),
114+
getService: (name: string) => {
115+
if (name === 'http-server') return { getRawApp: () => rawApp };
116+
const svc = services[name];
117+
if (svc === undefined) throw new Error(`no ${name}`);
118+
return svc;
119+
},
120+
registerService: (name: string, svc: unknown) => { services[name] = svc; },
121+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
122+
};
123+
const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir });
124+
await plugin.start(ctx as any);
125+
await hooks.get('kernel:ready')?.();
126+
return {
127+
install: (reqBody: Row) => rawApp.routes.get(`POST ${ROUTE}`)!(makeC(reqBody)),
128+
register,
129+
};
130+
}
131+
132+
let dir: string;
133+
let posture: string | undefined;
134+
let restoreOwner: () => void;
135+
beforeEach(() => {
136+
dir = mkdtempSync(join(tmpdir(), 'mil-resolver-refusal-'));
137+
posture = process.env.OS_TENANCY_POSTURE;
138+
process.env.OS_TENANCY_POSTURE = 'single';
139+
restoreOwner = declareInstallerPlatformOwner('admin');
140+
});
141+
afterEach(() => {
142+
restoreOwner();
143+
rmSync(dir, { recursive: true, force: true });
144+
if (posture === undefined) delete process.env.OS_TENANCY_POSTURE;
145+
else process.env.OS_TENANCY_POSTURE = posture;
146+
vi.restoreAllMocks();
147+
});
148+
149+
/** Nothing registered, no ledger entry, and the table never read. */
150+
function expectNothingWritten(rt: Awaited<ReturnType<typeof boot>>, driver: ReturnType<typeof fakeDriver>) {
151+
expect(rt.register).not.toHaveBeenCalled();
152+
expect(new LocalManifestSource(dir).read(SUITE).entry).toBeNull();
153+
expect(driver.planDeclaredRenames).not.toHaveBeenCalled();
154+
expect(driver.carryDeclaredRenames).not.toHaveBeenCalled();
155+
}
156+
157+
describe('#34432 — step 2c″ answers a body the artifact resolver refuses with that refusal, under the single posture', () => {
158+
it('a `packages` that is not a list answers 422 INVALID_ARTIFACT_PACKAGES, and nothing is written', async () => {
159+
const driver = fakeDriver();
160+
const rt = await boot(dir, driver);
161+
162+
const res = await rt.install({ manifest: composed('not-a-list') });
163+
164+
expect(res.status, JSON.stringify(res.payload)).toBe(422);
165+
expect(res.payload.success).toBe(false);
166+
expect(res.payload.error.code).toBe('INVALID_ARTIFACT_PACKAGES');
167+
expectNothingWritten(rt, driver);
168+
});
169+
170+
it('a package entry carrying a retired bare `indexes[].unique: true` answers 422 INVALID_ARTIFACT_PACKAGE_ENTRY, and nothing is written', async () => {
171+
const driver = fakeDriver();
172+
const rt = await boot(dir, driver);
173+
const retired = { ...ACCOUNT, indexes: [{ fields: ['name'], unique: true }] };
174+
175+
const res = await rt.install({ manifest: composed([entry(`${SUITE}.core`, [retired]), entry(`${SUITE}.leads`, [LEAD])]) });
176+
177+
expect(res.status, JSON.stringify(res.payload)).toBe(422);
178+
expect(res.payload.success).toBe(false);
179+
expect(res.payload.error.code).toBe('INVALID_ARTIFACT_PACKAGE_ENTRY');
180+
expectNothingWritten(rt, driver);
181+
});
182+
});
183+
184+
describe('#34432 — controls: the 503 stays the unread table\'s, and an undeclared throw stays a throw', () => {
185+
it('CONTROL: a well-formed composed artifact whose renamed field\'s table cannot be read still answers 503 SERVICE_UNAVAILABLE', async () => {
186+
const driver = fakeDriver({ planThrows: true });
187+
const rt = await boot(dir, driver);
188+
189+
const res = await rt.install({ manifest: composed(WELL_FORMED()) });
190+
191+
expect(res.status, JSON.stringify(res.payload)).toBe(503);
192+
expect(res.payload.error.code).toBe('SERVICE_UNAVAILABLE');
193+
expect(driver.planDeclaredRenames).toHaveBeenCalledTimes(1);
194+
expect(rt.register).not.toHaveBeenCalled();
195+
expect(new LocalManifestSource(dir).read(SUITE).entry).toBeNull();
196+
});
197+
198+
it('CONTROL: the same artifact over a table that reads installs', async () => {
199+
const driver = fakeDriver();
200+
const rt = await boot(dir, driver);
201+
202+
const res = await rt.install({ manifest: composed(WELL_FORMED()) });
203+
204+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
205+
expect(driver.planDeclaredRenames).toHaveBeenCalledTimes(1);
206+
});
207+
208+
it('an undeclared throw out of the resolver (a dependency cycle between two packages) is rethrown, never answered 503', async () => {
209+
const driver = fakeDriver();
210+
const rt = await boot(dir, driver);
211+
const cyclic = [
212+
entry(`${SUITE}.core`, [ACCOUNT], { [`${SUITE}.leads`]: '*' }),
213+
entry(`${SUITE}.leads`, [LEAD], { [`${SUITE}.core`]: '*' }),
214+
];
215+
216+
const outcome = await rt.install({ manifest: composed(cyclic) }).then(
217+
(res: any) => ({ answered: res }),
218+
(err: unknown) => ({ thrown: err as Error }),
219+
);
220+
221+
expect('answered' in outcome ? JSON.stringify(outcome.answered.payload) : 'thrown').toBe('thrown');
222+
expect((outcome as { thrown: Error }).thrown.message).toContain('Circular dependency');
223+
expectNothingWritten(rt, driver);
224+
});
225+
});

0 commit comments

Comments
 (0)