Skip to content

Commit 26ce8d6

Browse files
committed
feat(cloud-connection): install-local refuses a field patch naming a field or option its target lacks (step 2e)
Claude-Session: https://claude.ai/code/session_01FEkQ5nSMgkteiemkoN31vf Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2aa9af9 commit 26ce8d6

2 files changed

Lines changed: 225 additions & 0 deletions

File tree

Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0146 D10, second rule] `POST /api/v1/marketplace/install-local` step
5+
* 2e: a package whose `objectExtensions[].fieldPatches` names a field its
6+
* target does not have, or an option value the field does not have, is refused
7+
* `400 VALIDATION_ERROR` before anything is registered, written or synced.
8+
*
9+
* The target is the registry's resolved object (ADR-0141 D2 admitted the base
10+
* first), or one the same artifact delivers. A patch that matches installs.
11+
*/
12+
13+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
14+
import { mkdtempSync, rmSync, readdirSync } from 'node:fs';
15+
import { join } from 'node:path';
16+
import { tmpdir } from 'node:os';
17+
import { BaseResponseSchema, ApiErrorSchema, envelopeViolations } from '@objectstack/spec/api';
18+
// An install binds the package's handlers through `@objectstack/runtime` (a
19+
// lazy `import()` inside the plugin); its first load is paid here, at module
20+
// top, never inside a clocked `it`.
21+
import '@objectstack/runtime';
22+
import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js';
23+
import { installerAuthService, withInstallerGrants } from './install-local-principal.fixtures.js';
24+
25+
type Handler = (c: any) => Promise<any>;
26+
27+
const ROUTE = '/api/v1/marketplace/install-local';
28+
const BASE = 'com.example.crm';
29+
30+
/** The installed vendor object, as the registry serves it. */
31+
const ACCOUNT = {
32+
name: 'crm_account',
33+
fields: {
34+
industry: {
35+
type: 'select', label: 'Industry',
36+
options: [{ value: 'tech', label: 'Tech' }, { value: 'retail', label: 'Retail' }],
37+
},
38+
},
39+
};
40+
41+
const extensionPackage = (fieldPatches: Record<string, unknown>) => ({
42+
id: 'com.example.crm-wording', name: 'CRM wording', version: '1.0.0', scope: 'project', type: 'module',
43+
dependencies: { [BASE]: '1.x' },
44+
objectExtensions: [{ extend: 'crm_account', fieldPatches }],
45+
});
46+
47+
function makeRawApp() {
48+
const routes = new Map<string, Handler>();
49+
return {
50+
routes,
51+
get: (p: string, h: Handler) => routes.set(`GET ${p}`, h),
52+
post: (p: string, h: Handler) => routes.set(`POST ${p}`, h),
53+
delete: (p: string, h: Handler) => routes.set(`DELETE ${p}`, h),
54+
};
55+
}
56+
57+
function makeC(body: any) {
58+
const json = vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 }));
59+
return {
60+
req: {
61+
url: `http://localhost:3000${ROUTE}`,
62+
raw: new Request(`http://localhost:3000${ROUTE}`),
63+
json: async () => body,
64+
param: () => undefined,
65+
},
66+
json,
67+
};
68+
}
69+
70+
async function mount(dir: string) {
71+
const rawApp = makeRawApp();
72+
const hooks = new Map<string, any>();
73+
const register = vi.fn();
74+
const syncSchemas = vi.fn(async () => undefined);
75+
const registry = {
76+
getAllPackages: () => [],
77+
getPackage: (id: string) => (id === BASE ? { manifest: { id, version: '1.2.0' } } : undefined),
78+
getObject: (name: string) => (name === ACCOUNT.name ? structuredClone(ACCOUNT) : undefined),
79+
};
80+
const services: Record<string, any> = {
81+
manifest: { register },
82+
auth: installerAuthService(),
83+
objectql: withInstallerGrants({ syncSchemas, registry }),
84+
};
85+
const ctx = {
86+
hook: (e: string, h: any) => hooks.set(e, h),
87+
getService: (name: string) => {
88+
if (name === 'http-server') return { getRawApp: () => rawApp };
89+
const svc = services[name];
90+
if (svc === undefined) throw new Error(`no ${name}`);
91+
return svc;
92+
},
93+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
94+
};
95+
const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir });
96+
await plugin.start(ctx as any);
97+
await hooks.get('kernel:ready')?.();
98+
const registeredAtBoot = register.mock.calls.length;
99+
return {
100+
install: (body: unknown) => rawApp.routes.get(`POST ${ROUTE}`)!(makeC(body)),
101+
installRegistrations: () => register.mock.calls.slice(registeredAtBoot),
102+
syncs: () => syncSchemas.mock.calls.length,
103+
};
104+
}
105+
106+
let dir: string;
107+
beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'mil-field-patch-')); });
108+
afterEach(() => { rmSync(dir, { recursive: true, force: true }); vi.restoreAllMocks(); });
109+
110+
function expectRefusal(res: { payload: any; status: number }, paths: string[]) {
111+
expect(res.status, JSON.stringify(res.payload)).toBe(400);
112+
expect(BaseResponseSchema.safeParse(res.payload).success).toBe(true);
113+
expect(envelopeViolations(res.payload)).toEqual([]);
114+
expect(ApiErrorSchema.safeParse(res.payload.error).success).toBe(true);
115+
expect(res.payload.error.code).toBe('VALIDATION_ERROR');
116+
expect(res.payload.error.details.refusals.map((r: any) => r.path)).toEqual(paths);
117+
}
118+
119+
describe('install-local 2e — the field-patch target check (ADR-0146 D10)', () => {
120+
it('refuses a patch naming a field the installed target does not have, and installs nothing', async () => {
121+
const h = await mount(dir);
122+
const res = await h.install({ manifest: extensionPackage({ sector: { label: 'Sector' } }) });
123+
expectRefusal(res, ['objectExtensions[0].fieldPatches.sector']);
124+
expect(h.installRegistrations()).toEqual([]);
125+
expect(h.syncs()).toBe(0);
126+
expect(readdirSync(dir)).toEqual([]);
127+
});
128+
129+
it('refuses a patch naming an option value the field does not have', async () => {
130+
const h = await mount(dir);
131+
const res = await h.install({ manifest: extensionPackage({ industry: { options: { finance: { label: 'Finance' } } } }) });
132+
expectRefusal(res, ['objectExtensions[0].fieldPatches.industry.options.finance']);
133+
expect(res.payload.error.details.refusals[0]).toMatchObject({ object: 'crm_account', field: 'industry', option: 'finance', reason: 'option' });
134+
expect(h.installRegistrations()).toEqual([]);
135+
});
136+
137+
it('judges a compiled artifact as `os package install <file>` sends it (the nested manifest flattened)', async () => {
138+
const h = await mount(dir);
139+
const pkg = extensionPackage({ sector: { label: 'Sector' } });
140+
const { objectExtensions, ...manifest } = pkg;
141+
const res = await h.install({ manifest: { manifest, objectExtensions, id: manifest.id, version: manifest.version } });
142+
expectRefusal(res, ['objectExtensions[0].fieldPatches.sector']);
143+
});
144+
145+
it('judges a target the same artifact delivers, under its packages[] entry', async () => {
146+
const h = await mount(dir);
147+
const res = await h.install({
148+
manifest: {
149+
id: 'com.example.multi', name: 'Multi', version: '1.0.0', scope: 'project', type: 'app',
150+
packages: [
151+
{ manifest: { id: 'com.example.multi.core', name: 'Core', version: '1.0.0', type: 'app',
152+
objects: [{ name: 'multi_ticket', fields: { status: { type: 'text', label: 'Status' } } }] } },
153+
{ manifest: { id: 'com.example.multi.wording', name: 'Wording', version: '1.0.0', type: 'module',
154+
objectExtensions: [{ extend: 'multi_ticket', fieldPatches: { state: { label: 'State' } } }] } },
155+
],
156+
},
157+
});
158+
expectRefusal(res, ['packages[1].manifest.objectExtensions[0].fieldPatches.state']);
159+
});
160+
161+
it('lit control: a patch whose field and option the target has installs', async () => {
162+
const h = await mount(dir);
163+
const res = await h.install({
164+
manifest: extensionPackage({ industry: { label: 'Sector', options: { tech: { label: 'Technology' } } } }),
165+
});
166+
expect(res.status, JSON.stringify(res.payload)).toBe(200);
167+
expect(h.installRegistrations()).toHaveLength(1);
168+
});
169+
});

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

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,11 @@ import {
207207
// [ADR-0131 D3 · D12 items 7–8] The walled refusal's one predicate: the
208208
// same sentence, the same rung, as every environment-metadata write door.
209209
walledCatalogWriteVerdict,
210+
// [ADR-0146 D10, second rule] The field-patch target check — the judge
211+
// `os validate` asks and the registry fold names its misses by.
212+
fieldPatchTargetRefusals,
213+
fieldPatchTargetRefusalMessage,
214+
type FieldPatchTargetRefusal,
210215
} from '@objectstack/metadata-core';
211216
import { resolveCloudUrl } from './cloud-url.js';
212217
import { resolveMarketplacePublicBaseUrl } from './marketplace-public-url.js';
@@ -2064,6 +2069,26 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
20642069
}, 403);
20652070
}
20662071

2072+
// 2e. [ADR-0146 D10, second rule] ⭐ THE FIELD-PATCH TARGET CHECK,
2073+
// beside the override gate and before any write: a patch naming a
2074+
// field its target does not have, or an option value its field does
2075+
// not have, would change nothing and say nothing. Refused `400
2076+
// VALIDATION_ERROR` on both branches, every refusal located in
2077+
// `details.refusals`. The target is the registry's resolved object
2078+
// (ADR-0141 D2 admitted the base first) or one this artifact
2079+
// delivers.
2080+
const patchTargetRefusals = this.fieldPatchTargetRefusalsOf(ctx, converted);
2081+
if (patchTargetRefusals.length > 0) {
2082+
return c.json({
2083+
success: false,
2084+
error: {
2085+
code: 'VALIDATION_ERROR',
2086+
message: fieldPatchTargetRefusalMessage(manifestId, patchTargetRefusals),
2087+
details: { refusals: patchTargetRefusals },
2088+
},
2089+
}, 400);
2090+
}
2091+
20672092
// 3. Hot-register FIRST so a malformed inline manifest fails the
20682093
// install loudly rather than persisting a broken record that
20692094
// would also fail on every subsequent rehydrate.
@@ -3232,6 +3257,37 @@ export class MarketplaceInstallLocalPlugin implements Plugin {
32323257
* Reads nothing it cannot: with no `objectql` registry or no protocol
32333258
* listing, the gate has no closure to judge and answers empty.
32343259
*/
3260+
/**
3261+
* [ADR-0146 D10, second rule] Step 2e of {@link handleInstall}: every
3262+
* `objectExtensions[].fieldPatches` entry the converted body carries —
3263+
* each `packages[]` entry's, or the body's own — judged against its target
3264+
* by `@objectstack/metadata-core`'s `fieldPatchTargetRefusals`. A target
3265+
* this artifact delivers is read off its body; any other is the registry's
3266+
* resolved object. A target neither knows is not judged here: the
3267+
* extension then registers against an owner that is not loaded, which the
3268+
* registry already reports.
3269+
*/
3270+
private fieldPatchTargetRefusalsOf = (ctx: PluginContext, converted: Record<string, any>): FieldPatchTargetRefusal[] => {
3271+
const multi = Array.isArray(converted.packages);
3272+
const bodies: Array<{ body: Record<string, any>; prefix: string }> = multi
3273+
? converted.packages.flatMap((entry: unknown, index: number) =>
3274+
isPlainObject(entry) && isPlainObject(entry.manifest)
3275+
? [{ body: entry.manifest as Record<string, any>, prefix: `packages[${index}].manifest.` }]
3276+
: [])
3277+
: [{ body: flattenPackageBody(converted), prefix: '' }];
3278+
if (!bodies.some(({ body }) => Array.isArray(body.objectExtensions))) return [];
3279+
const delivered = new Map<string, unknown>();
3280+
for (const { body } of bodies) {
3281+
const objects = body.objects;
3282+
const list = Array.isArray(objects) ? objects : isPlainObject(objects) ? Object.entries(objects).map(([name, o]) => (isPlainObject(o) ? { name, ...o } : o)) : [];
3283+
for (const object of list) if (isPlainObject(object) && typeof object.name === 'string') delivered.set(object.name, object);
3284+
}
3285+
let registry: { getObject?(name: string): unknown } | undefined;
3286+
try { registry = ctx.getService<IObjectQLEngine>('objectql')?.registry as typeof registry; } catch { /* no data engine — only delivered targets are known */ }
3287+
const getTarget = (name: string): unknown => delivered.get(name) ?? registry?.getObject?.(name);
3288+
return bodies.flatMap(({ body, prefix }) => fieldPatchTargetRefusals(body.objectExtensions, getTarget, prefix));
3289+
};
3290+
32353291
private evaluateOverrideWriteGate = async (
32363292
ctx: PluginContext,
32373293
manifestId: string,

0 commit comments

Comments
 (0)