Skip to content

Commit aecae3b

Browse files
committed
fix(cloud-connection): install-local's cloud branch refuses a package declaring a bare name another package holds
The cloud-fetched branch recognised only the security catalog's environment-held refusal and took the lenient path for the registry's bare-name refusal: it ledgered the package and answered hotLoaded false, and the next boot admitted the clash before the seal. It now refuses it 422 PLUGIN_REGISTER_FAILED before any write, as the inline branch does, recognising the error by its own brand (code + name), never by its types. Co-Authored-By: Claude <noreply@anthropic.com>
1 parent d0512c2 commit aecae3b

2 files changed

Lines changed: 338 additions & 5 deletions

File tree

Lines changed: 300 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,300 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #31296 — the cloud-fetched branch of `POST /api/v1/marketplace/install-local`
5+
* refuses a package declaring a bare name another package holds (the #30803
6+
* series: a flow, a webhook, a dataset, …), the way the inline branch does,
7+
* before anything is written.
8+
*
9+
* ## What was wrong
10+
*
11+
* The registry's package door refuses such a package ahead of every one of its
12+
* writes (`BareNameConflictError`, `bare-name-one-holder.ts` in
13+
* `@objectstack/objectql`). The inline branch answered that refusal `422`. The
14+
* cloud-fetched branch recognised only the security catalog's
15+
* environment-held refusal (#25366) and took #22695's lenient path for this
16+
* one: it wrote the ledger entry and answered `200` with `hotLoaded: false`,
17+
* "loads at the next restart". At that restart the entry is rehydrated BEFORE
18+
* the cold boot seals the holders, so the boot admits the clash with one
19+
* warning, and every consumer resolving the name is served one of the two
20+
* packages' items by registration order — the condition the rule refuses.
21+
*
22+
* ## What is real here
23+
*
24+
* The judge is real: an `ObjectKernel` with `ObjectQLPlugin` supplies the
25+
* `manifest` service over the real `SchemaRegistry`, booted to
26+
* `kernel:bootstrapped`, so the holders are sealed and the refusal under test
27+
* is the one production raises. The holding package is installed through the
28+
* same door. The side readers that run after the ledger write (binder,
29+
* translations, seeds) are recorders; they are not what is pinned. The cloud
30+
* leg is a stubbed `fetch`.
31+
*
32+
* ## What these cases pin
33+
*
34+
* - a fresh cloud-fetched install and a cloud-fetched upgrade, each declaring
35+
* a flow name another package holds: `422 PLUGIN_REGISTER_FAILED` in the
36+
* declared envelope, both holders and the rename named, the registry and
37+
* the ledger exactly as before the call, the holder's flow still the
38+
* holder's;
39+
* - CONTROL, an environment-held security catalog name: the same `422` it
40+
* answered before (#25366; its full matrix lives in
41+
* `marketplace-install-local-catalog-name-collision.test.ts`);
42+
* - CONTROL, the same package declaring a flow name nobody holds: `200`,
43+
* `hotLoaded: true`, registered and ledgered.
44+
*
45+
* A register failure that is NOT a registry refusal keeps #22695's lenient
46+
* answer; `marketplace-install-local-hot-loaded.test.ts` pins that.
47+
*/
48+
49+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
50+
import { mkdtempSync, rmSync } from 'node:fs';
51+
import { tmpdir } from 'node:os';
52+
import { join } from 'node:path';
53+
import { BaseResponseSchema, ApiErrorSchema, envelopeViolations } from '@objectstack/spec/api';
54+
// The plugin reaches `@objectstack/runtime` through a lazy `import()`; its first
55+
// load is paid here, at module top, never inside a clocked `it`.
56+
import '@objectstack/runtime';
57+
import { ObjectKernel } from '@objectstack/core';
58+
import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql';
59+
import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js';
60+
import { LocalManifestSource } from './local-manifest-source.js';
61+
import { installerAuthService, withInstallerGrants } from './install-local-principal.fixtures.js';
62+
63+
type Bag = Record<string, any>;
64+
type Handler = (c: any) => Promise<any>;
65+
66+
const ROUTE = '/api/v1/marketplace/install-local';
67+
const CLOUD_URL = 'http://cloud.test';
68+
69+
/** The package already holding the flow name, installed first. */
70+
const HOLDER_ID = 'com.acme.dispatch';
71+
/** The package the cloud-fetched install asks for. */
72+
const INCOMING_ID = 'com.acme.routing';
73+
/** The flow name both declare. */
74+
const HELD_FLOW = 'assign_technician';
75+
/** CONTROL: a flow name nobody holds. */
76+
const FREE_FLOW = 'reassign_technician';
77+
78+
const flow = (name: string, tag: string): Bag => ({
79+
name,
80+
label: `${tag} flow`,
81+
type: 'autolaunched',
82+
status: 'active',
83+
nodes: [{ id: 'start', type: 'start', label: 'Start' }],
84+
edges: [],
85+
});
86+
87+
/** A package version whose namespace is its id's last segment, so the refusal's rename is `NAMESPACE_NAME`. */
88+
const packageVersion = (id: string, version: string, flows: string[], extra: Bag = {}): Bag => {
89+
const ns = id.split('.').pop()!;
90+
return {
91+
id,
92+
name: ns,
93+
namespace: ns,
94+
type: 'app',
95+
version,
96+
flows: flows.map((name) => flow(name, ns)),
97+
...extra,
98+
};
99+
};
100+
101+
let dir: string;
102+
const kernels: ObjectKernel[] = [];
103+
beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'mil-bare-name-conflict-')); });
104+
afterEach(async () => {
105+
while (kernels.length) {
106+
const k = kernels.pop()!;
107+
if (k.getState() === 'running') await k.shutdown();
108+
}
109+
rmSync(dir, { recursive: true, force: true });
110+
vi.unstubAllGlobals();
111+
vi.unstubAllEnvs();
112+
vi.restoreAllMocks();
113+
});
114+
115+
/**
116+
* Serve package versions from the cloud leg, by the `versionId` the install
117+
* asks for; the public fast-path is off and a service key is set, so the
118+
* credential read never reaches the developer's own on-disk binding.
119+
*/
120+
function serveVersions(versions: Record<string, Bag>) {
121+
vi.stubEnv('OS_MARKETPLACE_PUBLIC_BASE_URL', 'off');
122+
vi.stubEnv('OS_CLOUD_API_KEY', 'svc-test-key');
123+
vi.stubGlobal('fetch', vi.fn(async (url: string) => {
124+
const versionId = decodeURIComponent(String(url).split('/versions/')[1]?.split('/')[0] ?? '');
125+
const manifest = versions[versionId];
126+
if (!manifest) return new Response('not found', { status: 404 });
127+
return new Response(
128+
JSON.stringify({ data: { manifest, version: manifest.version, version_id: versionId } }),
129+
{ status: 200, headers: { 'Content-Type': 'application/json' } },
130+
);
131+
}));
132+
}
133+
134+
/** The plugin over a REAL engine's `manifest` service and registry, booted (holders sealed) to `kernel:ready`. */
135+
async function bootPlugin() {
136+
const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false } as never);
137+
kernels.push(kernel);
138+
await kernel.use(new ObjectQLPlugin());
139+
await kernel.bootstrap();
140+
const ql = kernel.getService<ObjectQL>('objectql');
141+
ql.registry.logLevel = 'silent';
142+
143+
const routes = new Map<string, Handler>();
144+
const rawApp = {
145+
get: (p: string, h: Handler) => routes.set(`GET ${p}`, h),
146+
post: (p: string, h: Handler) => routes.set(`POST ${p}`, h),
147+
delete: (p: string, h: Handler) => routes.set(`DELETE ${p}`, h),
148+
};
149+
const hooks = new Map<string, () => Promise<void>>();
150+
const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
151+
const services: Record<string, unknown> = {
152+
manifest: kernel.getService('manifest'),
153+
auth: installerAuthService(),
154+
objectql: withInstallerGrants({
155+
convertPackageBodyForward: (body: unknown) => ql.convertPackageBodyForward(body),
156+
registry: ql.registry,
157+
syncSchemas: async () => undefined,
158+
}),
159+
};
160+
const ctx = {
161+
hook: (e: string, h: () => Promise<void>) => hooks.set(e, h),
162+
getService: (name: string) => {
163+
if (name === 'http-server') return { getRawApp: () => rawApp };
164+
if (!(name in services)) throw new Error(`no ${name}`);
165+
return services[name];
166+
},
167+
logger,
168+
};
169+
170+
const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: CLOUD_URL, storageDir: dir });
171+
const p = plugin as unknown as Record<string, unknown>;
172+
p.bindArtifactHandlers = async () => undefined;
173+
p.applySideEffects = async () => ({ translationsLoaded: 0, seeded: { mode: 'none' } });
174+
175+
await plugin.start(ctx as never);
176+
await hooks.get('kernel:ready')?.();
177+
178+
const install = async (body: Bag) => {
179+
const json = vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 }));
180+
return routes.get(`POST ${ROUTE}`)!({
181+
req: {
182+
url: `http://localhost:3000${ROUTE}`,
183+
raw: new Request(`http://localhost:3000${ROUTE}`),
184+
json: async () => body,
185+
param: () => undefined,
186+
},
187+
json,
188+
});
189+
};
190+
/** The cloud-fetched branch: a `packageId` + `versionId` body, the manifest downloaded from the control plane. */
191+
const installFromCloud = (versionId: string) => install({ packageId: 'pkg_acme_routing', versionId });
192+
/** The holder, through the same door's inline branch. */
193+
const installHolder = async () => {
194+
const res = await install({ manifest: packageVersion(HOLDER_ID, '1.0.0', [HELD_FLOW]) });
195+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
196+
};
197+
return { ql, install, installFromCloud, installHolder };
198+
}
199+
200+
/** Every ledger entry, read off disk. */
201+
const ledger = () => {
202+
const source = new LocalManifestSource(dir);
203+
return { holder: source.read(HOLDER_ID).entry, incoming: source.read(INCOMING_ID).entry };
204+
};
205+
206+
/** The holder's flow is still the holder's: the registry serves its item under the bare name. */
207+
function expectHolderFlowKept(ql: ObjectQL) {
208+
expect(ql.registry.getItem<Bag>('flow', HELD_FLOW)?.label).toBe('dispatch flow');
209+
}
210+
211+
function expectBareNameRefusal(res: any) {
212+
expect(res.status, JSON.stringify(res.payload)).toBe(422);
213+
expect(BaseResponseSchema.safeParse(res.payload).success).toBe(true);
214+
expect(envelopeViolations(res.payload)).toEqual([]);
215+
expect(ApiErrorSchema.safeParse(res.payload.error).success).toBe(true);
216+
expect(res.payload.success).toBe(false);
217+
expect(res.payload.error.code).toBe('PLUGIN_REGISTER_FAILED');
218+
// The registry's own sentence: both holders, the name, and the rename.
219+
expect(res.payload.error.message).toContain(`package "${INCOMING_ID}"`);
220+
expect(res.payload.error.message).toContain(`package "${HOLDER_ID}"`);
221+
expect(res.payload.error.message).toContain(`"${HELD_FLOW}"`);
222+
expect(res.payload.error.message).toContain(`"routing_${HELD_FLOW}"`);
223+
}
224+
225+
describe('install-local cloud branch refuses a package declaring a bare name another package holds, before any write', () => {
226+
const versions = {
227+
'v1-free': packageVersion(INCOMING_ID, '1.0.0', [FREE_FLOW]),
228+
'v1-held': packageVersion(INCOMING_ID, '1.0.0', [HELD_FLOW]),
229+
'v2-held': packageVersion(INCOMING_ID, '2.0.0', [FREE_FLOW, HELD_FLOW]),
230+
};
231+
232+
it('a fresh install is refused: 422 naming both holders and the rename, nothing registered or ledgered', async () => {
233+
serveVersions(versions);
234+
const { ql, installFromCloud, installHolder } = await bootPlugin();
235+
await installHolder();
236+
const before = ledger();
237+
238+
const res = await installFromCloud('v1-held');
239+
240+
expectBareNameRefusal(res);
241+
expect(res.payload.data).toBeUndefined();
242+
expect(ql.registry.getPackage(INCOMING_ID)).toBeUndefined();
243+
expect(ledger()).toEqual(before);
244+
expect(ledger().incoming).toBeNull();
245+
expectHolderFlowKept(ql);
246+
});
247+
248+
it('an upgrade is refused: 422, the installed version still registered and ledgered', async () => {
249+
serveVersions(versions);
250+
const { ql, installFromCloud, installHolder } = await bootPlugin();
251+
await installHolder();
252+
const first = await installFromCloud('v1-free');
253+
expect(first.status, JSON.stringify(first.payload)).toBe(200);
254+
expect(first.payload.data.hotLoaded).toBe(true);
255+
const before = ledger();
256+
257+
const res = await installFromCloud('v2-held');
258+
259+
expectBareNameRefusal(res);
260+
expect(ql.registry.getPackage(INCOMING_ID)?.manifest?.version).toBe('1.0.0');
261+
expect(ledger()).toEqual(before);
262+
expect(ledger().incoming?.version).toBe('1.0.0');
263+
expectHolderFlowKept(ql);
264+
});
265+
266+
it('CONTROL — an environment-held security catalog name keeps its answer: 422 naming the environment catalog', async () => {
267+
serveVersions({
268+
'v1-cloned': packageVersion(INCOMING_ID, '1.0.0', [], {
269+
permissions: [{ name: 'acme_dispatcher_lite', label: 'acme_dispatcher_lite', objects: {} }],
270+
}),
271+
});
272+
const { ql, installFromCloud } = await bootPlugin();
273+
// The environment's item, as `sys_metadata` hydration registers it: the bare slot, no package.
274+
ql.registry.registerItem('permission', { name: 'acme_dispatcher_lite', label: 'customer clone', objects: {} });
275+
276+
const res = await installFromCloud('v1-cloned');
277+
278+
expect(res.status, JSON.stringify(res.payload)).toBe(422);
279+
expect(res.payload.error.code).toBe('PLUGIN_REGISTER_FAILED');
280+
expect(res.payload.error.message).toContain('the environment catalog');
281+
expect(ql.registry.getPackage(INCOMING_ID)).toBeUndefined();
282+
expect(ledger().incoming).toBeNull();
283+
});
284+
285+
it('CONTROL — the same package declaring a flow name nobody holds installs: 200, hot-loaded, ledgered', async () => {
286+
serveVersions(versions);
287+
const { ql, installFromCloud, installHolder } = await bootPlugin();
288+
await installHolder();
289+
290+
const res = await installFromCloud('v1-free');
291+
292+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
293+
expect(res.payload.data.hotLoaded).toBe(true);
294+
expect(res.payload.data.hotLoadError).toBeUndefined();
295+
expect(ql.registry.getPackage(INCOMING_ID)?.manifest?.version).toBe('1.0.0');
296+
expect(ledger().incoming?.version).toBe('1.0.0');
297+
expect(ql.registry.getItem<Bag>('flow', FREE_FLOW)?.label).toBe('routing flow');
298+
expectHolderFlowKept(ql);
299+
});
300+
});

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

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,10 @@
4848
* item already holds a position, permission set or capability name
4949
* the package ships (#25366): no restart clears that, so both
5050
* branches refuse it (`PLUGIN_REGISTER_FAILED`, 422) and nothing is
51-
* registered or written.
51+
* registered or written. So is a register refused because another
52+
* package (or the platform) holds a bare name the package declares
53+
* — a flow, a webhook, a dataset, … (#31296; `bare-name-one-holder.ts`
54+
* in `@objectstack/objectql`): the restart would admit the clash.
5255
*
5356
* `installMode: 'managed' | 'unmanaged'` (ADR-0131 D6; absent means
5457
* `managed`, the key parsed against `InstallModeSchema`) chooses
@@ -338,9 +341,10 @@ import {
338341
} from '@objectstack/metadata-protocol';
339342
import { resolveThrownHttpError } from '@objectstack/types';
340343
import { unknownQueryParamRefusalMessage } from '@objectstack/rest';
341-
// [#25366] The code the registry's security-catalog refusal carries, compared
342-
// rather than `instanceof`-tested: the engine keeps the class unexported so a
343-
// consumer holding the other build realm's copy cannot misread it.
344+
// [#25366] The code the registry's security-catalog refusal carries — and its
345+
// bare-name sibling's (#31296) — compared rather than `instanceof`-tested: the
346+
// engine keeps the classes unexported so a consumer holding the other build
347+
// realm's copy cannot misread them.
344348
import { NAMESPACE_CONFLICT_CODE } from '@objectstack/objectql';
345349

346350
/** What the auth service's in-process session read answers, as `AuthSessionApi` declares it. */
@@ -379,6 +383,29 @@ function refusesEnvironmentHeldCatalogName(err: unknown): boolean {
379383
&& conflicts.some((c) => (c as { existingHolder?: { kind?: unknown } } | null)?.existingHolder?.kind === 'environment');
380384
}
381385

386+
/**
387+
* [#31296] Whether a `manifest.register` failure is the registry's bare-name
388+
* refusal (`BareNameConflictError`, `registry.ts` in `@objectstack/objectql`;
389+
* the rule is `bare-name-one-holder.ts`): the package declares an item of a
390+
* covered type — a flow, a webhook, a dataset, an object-less action, … —
391+
* under a name another package, or the platform, already holds.
392+
*
393+
* Recognised by the error's own brand — the code it shares with its siblings
394+
* plus its `name` — never by its types or holders: which types the rule covers
395+
* and who holds a name are the registry's to decide, so a type the rule gains
396+
* later is refused here without a change.
397+
*
398+
* No restart heals this one either, in the other direction: this ledger entry
399+
* is rehydrated at the next boot BEFORE the cold boot seals the holders, so the
400+
* boot ADMITS the clash with one warning (`BARE_NAME_COLD_BOOT_MODE`), and
401+
* every consumer resolving the name is served one of the two packages' items
402+
* by registration order — the condition the rule exists to refuse.
403+
*/
404+
function refusesBareNameHeldElsewhere(err: unknown): boolean {
405+
const e = err as { code?: unknown; name?: unknown } | null;
406+
return e?.code === NAMESPACE_CONFLICT_CODE && e.name === 'BareNameConflictError';
407+
}
408+
382409
/**
383410
* [#21490] The one `protocol` verb this plugin calls: the runner of the
384411
* uninstall cleanups domain plugins register through
@@ -2893,7 +2920,13 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
28932920
// the inline branch does — `422 PLUGIN_REGISTER_FAILED`, the
28942921
// registry's sentence naming each colliding name and its holder —
28952922
// and the installer renames one of the two items and retries.
2896-
if (refusesEnvironmentHeldCatalogName(err)) {
2923+
// [#31296] The same for the registry's bare-name refusal (another
2924+
// package or the platform holds a flow, webhook, dataset, … name
2925+
// the package declares): a restart would load the entry before the
2926+
// holders are sealed and admit the clash, so the lenient answer
2927+
// would install exactly what the rule refuses
2928+
// ({@link refusesBareNameHeldElsewhere}).
2929+
if (refusesEnvironmentHeldCatalogName(err) || refusesBareNameHeldElsewhere(err)) {
28972930
return c.json({
28982931
success: false,
28992932
error: { code: 'PLUGIN_REGISTER_FAILED', message: `Package '${manifestId}' cannot be installed: ${registerError}` },

0 commit comments

Comments
 (0)