Skip to content

Commit 4b941bb

Browse files
committed
test(organizations): measurement probe for #25062 premise (preview vs walled write)
Measurement-only commit: records what origin/main does today for the import dry run's preview of a walled insert, and what reading the wall's verdict would cost. Not a pin; deleted before any PR. Claude-Session: https://claude.ai/code/session_0157EiYDGYnrsXE9aHv1uMxU Co-authored-by: Claude <noreply@anthropic.com>
1 parent f7d7403 commit 4b941bb

1 file changed

Lines changed: 257 additions & 0 deletions

File tree

Lines changed: 257 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,257 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* MEASUREMENT PROBE for #25062 (premise check, no fix). Not a pin: it records
5+
* what `origin/main` does today, and is deleted before any PR.
6+
*
7+
* Question: can `engine.validate()` (the import dry run) read the Layer 0
8+
* write wall's OWN verdict for a row without (a) an engine-side copy of the
9+
* wall's predicate, (b) running any side-effecting hook or middleware, and
10+
* (c) a new member on a published contract?
11+
*
12+
* Real engine, real SQLite driver, real `OrganizationsPlugin` (Middleware A)
13+
* and real `SecurityPlugin` (step 3.7), booted the way
14+
* `create-explicit-organization-wall.test.ts` boots them.
15+
*/
16+
17+
import { describe, it, expect, afterEach, vi } from 'vitest';
18+
import { ObjectQL } from '@objectstack/objectql';
19+
import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm';
20+
import { SecurityPlugin } from '@objectstack/plugin-security';
21+
import type { PermissionSet } from '@objectstack/spec/security';
22+
import { OrganizationsPlugin } from './organizations-plugin.js';
23+
24+
const OWN_ORG = 'org_alpha';
25+
const FOREIGN_ORG = 'org_north';
26+
const SISTER_ORG = 'org_south';
27+
const INJECTED = 'qa_ledger';
28+
29+
const OBJECTS = [
30+
{
31+
name: INJECTED,
32+
label: 'Ledger',
33+
fields: {
34+
id: { name: 'id', type: 'text', primaryKey: true },
35+
name: { name: 'name', type: 'text' },
36+
},
37+
},
38+
];
39+
40+
const MEMBER: PermissionSet = {
41+
name: 'member_default',
42+
label: 'Member',
43+
objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } },
44+
} as unknown as PermissionSet;
45+
46+
const SYS_CTX = { isSystem: true };
47+
const MEMBER_CTX = { userId: 'usr_member', tenantId: OWN_ORG, positions: [], permissions: [], posture: 'MEMBER' };
48+
const GROUP_CTX = { ...MEMBER_CTX, accessible_org_ids: [OWN_ORG, SISTER_ORG] };
49+
50+
type Posture = 'isolated' | 'group' | 'single';
51+
52+
const engines: ObjectQL[] = [];
53+
afterEach(async () => {
54+
while (engines.length) {
55+
try { await engines.pop()?.destroy(); } catch { /* noop */ }
56+
}
57+
});
58+
59+
interface Booted {
60+
engine: ObjectQL;
61+
security: SecurityPlugin;
62+
table: () => Promise<Array<Record<string, unknown>>>;
63+
services: Record<string, unknown>;
64+
errors: string[];
65+
}
66+
67+
async function boot(posture: Posture): Promise<Booted> {
68+
const engine = new ObjectQL();
69+
engine.registerDriver(new SqliteWasmDriver({ filename: ':memory:' } as never) as never, true);
70+
await engine.init();
71+
engine.registerApp({
72+
id: 'com.objectstack.qa.validate-preview-wall-verdict',
73+
name: 'probe',
74+
version: '1.0.0',
75+
type: 'plugin',
76+
scope: 'system',
77+
objects: OBJECTS,
78+
} as never);
79+
await engine.syncSchemas();
80+
engines.push(engine);
81+
82+
const errors: string[] = [];
83+
const services: Record<string, unknown> = {
84+
manifest: { register: vi.fn() },
85+
objectql: engine,
86+
metadata: {
87+
get: async (_type: string, name: string) => engine.getSchema(name) ?? null,
88+
list: async () => [MEMBER],
89+
},
90+
tenancy: { posture },
91+
};
92+
const ctx = {
93+
logger: { info: vi.fn(), warn: vi.fn(), error: (m: unknown) => errors.push(String(m)), debug: vi.fn() },
94+
registerService: (name: string, service: unknown) => { services[name] = service; },
95+
getService: (name: string) => {
96+
if (!(name in services)) throw new Error(`service not registered: ${name}`);
97+
return services[name];
98+
},
99+
hook: vi.fn(),
100+
};
101+
const organizations = new OrganizationsPlugin({ ensureDefaultOrganization: false });
102+
const security = new SecurityPlugin({ fallbackPermissionSet: 'member_default' });
103+
await organizations.init(ctx as never);
104+
await security.init(ctx as never);
105+
await organizations.start(ctx as never);
106+
await security.start(ctx as never);
107+
vi.spyOn((engine as unknown as { logger: { warn: (m: unknown) => void } }).logger, 'warn').mockImplementation(() => {});
108+
109+
await engine.insert(INJECTED, { id: 'r1', name: 'seeded', organization_id: OWN_ORG }, { context: SYS_CTX } as never);
110+
111+
const table = async () => {
112+
const driver = (engine as unknown as { getDriver(o: string): { knex: unknown } }).getDriver(INJECTED);
113+
const knex = driver.knex as (t: string) => { select: (...c: string[]) => Promise<Array<Record<string, unknown>>> };
114+
const rows = await knex(INJECTED).select('id', 'organization_id');
115+
return [...rows].sort((a, b) => String(a.id).localeCompare(String(b.id)));
116+
};
117+
return { engine, security, table, services, errors };
118+
}
119+
120+
interface Outcome { ok: boolean; code?: string; status?: number }
121+
const attempt = async (run: () => Promise<unknown>): Promise<Outcome> => {
122+
try { await run(); return { ok: true }; } catch (e) {
123+
const err = e as { code?: string; statusCode?: number; status?: number };
124+
return { ok: false, code: err.code, status: err.statusCode ?? err.status };
125+
}
126+
};
127+
128+
const writeAndPreview = async (b: Booted, row: Record<string, unknown>, context: object) => {
129+
const dropped: unknown[] = [];
130+
const preview = await b.engine.validate(INJECTED, { ...row }, { mode: 'insert', context: context as never });
131+
const write = await attempt(() => b.engine.insert(INJECTED, { ...row } as never, {
132+
context, onFieldsDropped: (e: unknown) => dropped.push(e),
133+
} as never));
134+
return { preview, write, dropped, stored: await b.table() };
135+
};
136+
137+
describe('#25062 PROBE: the preview and the walled write, side by side (origin/main)', () => {
138+
it('M1 cell (a), `group`: a sister organization is STORED as sent, and the preview says it is dropped', async () => {
139+
const b = await boot('group');
140+
const r = await writeAndPreview(b, { id: 'r2', name: 'n', organization_id: SISTER_ORG }, GROUP_CTX);
141+
console.log('M1', JSON.stringify({ preview: r.preview.results[0], write: r.write, dropped: r.dropped, stored: r.stored }));
142+
expect(r.write.ok).toBe(true);
143+
expect(r.dropped).toEqual([]);
144+
expect(r.stored).toContainEqual({ id: 'r2', organization_id: SISTER_ORG });
145+
expect(r.preview.results[0]?.droppedFields).toEqual([{ object: INJECTED, fields: ['organization_id'], reason: 'readonly' }]);
146+
});
147+
148+
it('M1 cell (a), `isolated`: the active organization named explicitly, same disagreement', async () => {
149+
const b = await boot('isolated');
150+
const r = await writeAndPreview(b, { id: 'r2', name: 'n', organization_id: OWN_ORG }, MEMBER_CTX);
151+
console.log('M1-iso', JSON.stringify({ preview: r.preview.results[0], write: r.write, dropped: r.dropped }));
152+
expect(r.write.ok).toBe(true);
153+
expect(r.dropped).toEqual([]);
154+
expect(r.preview.results[0]?.droppedFields).toEqual([{ object: INJECTED, fields: ['organization_id'], reason: 'readonly' }]);
155+
});
156+
157+
it('M2 cell (b), `isolated`: a foreign organization is REFUSED 403 by the write, answered valid by the preview', async () => {
158+
const b = await boot('isolated');
159+
const r = await writeAndPreview(b, { id: 'r2', name: 'n', organization_id: FOREIGN_ORG }, MEMBER_CTX);
160+
console.log('M2', JSON.stringify({ preview: r.preview.results[0], valid: r.preview.valid, write: r.write }));
161+
expect(r.write).toEqual({ ok: false, code: 'PERMISSION_DENIED', status: 403 });
162+
expect(r.preview.valid).toBe(true);
163+
expect(r.stored).toEqual([{ id: 'r1', organization_id: OWN_ORG }]);
164+
});
165+
166+
it('M2 control, `single`: the strip takes the value on the write too, so preview and write agree', async () => {
167+
const b = await boot('single');
168+
const r = await writeAndPreview(b, { id: 'r2', name: 'n', organization_id: FOREIGN_ORG }, MEMBER_CTX);
169+
console.log('M2-single', JSON.stringify({ preview: r.preview.results[0], write: r.write, dropped: r.dropped }));
170+
expect(r.write.ok).toBe(true);
171+
expect(r.preview.results[0]?.droppedFields).toEqual(r.dropped);
172+
});
173+
});
174+
175+
describe('#25062 PROBE: the one existing preview seam, `registerWriteGateProbe` (security: `canWriteObject`)', () => {
176+
it('M3: answers one boolean for the whole set, the same `true` for an admitted, a refused and an unwalled organization', async () => {
177+
const answers: Record<string, unknown> = {};
178+
for (const [posture, ctx, org] of [
179+
['isolated', MEMBER_CTX, OWN_ORG],
180+
['isolated', MEMBER_CTX, FOREIGN_ORG],
181+
['group', GROUP_CTX, SISTER_ORG],
182+
['single', MEMBER_CTX, FOREIGN_ORG],
183+
] as const) {
184+
const b = await boot(posture);
185+
const probe = (b.engine as unknown as { _writeGateProbe?: (...a: unknown[]) => Promise<unknown> })._writeGateProbe;
186+
expect(typeof probe, 'plugin-security registered the probe').toBe('function');
187+
answers[`${posture}:${org}`] = await probe!(INJECTED, 'insert', ctx, [{ name: 'n', organization_id: org }]);
188+
}
189+
console.log('M3', JSON.stringify(answers));
190+
expect(answers).toEqual({
191+
'isolated:org_alpha': true,
192+
'isolated:org_north': true,
193+
'group:org_south': true,
194+
'single:org_north': true,
195+
});
196+
});
197+
});
198+
199+
describe('#25062 PROBE: riding the middleware chain as an `insert` with a no-op executor', () => {
200+
const ride = async (b: Booted, data: unknown, context: object, executor: (opCtx: any) => Promise<unknown>) => {
201+
const opCtx: any = { object: INJECTED, operation: 'insert', data, context };
202+
const before = b.engine.writeEpoch.current;
203+
const outcome = await attempt(() => (b.engine as any).executeWithMiddleware(opCtx, () => executor(opCtx)));
204+
return { opCtx, outcome, epochDelta: b.engine.writeEpoch.current - before };
205+
};
206+
207+
it('M4a: the epoch advances, and a no-op executor is refused by the wall\'s own fail-closed "seam never ran" assertion', async () => {
208+
const b = await boot('isolated');
209+
const r = await ride(b, { name: 'n', organization_id: OWN_ORG }, MEMBER_CTX, async () => undefined);
210+
console.log('M4a', JSON.stringify({ outcome: r.outcome, epochDelta: r.epochDelta, errors: b.errors.length, judges: r.opCtx.postHookWriteImageCheck?.judgesOrganization }));
211+
expect(r.epochDelta).toBe(1);
212+
expect(r.outcome).toEqual({ ok: false, code: 'PERMISSION_DENIED', status: 403 });
213+
expect(b.errors.some((m) => m.includes('was executed without the Layer 0'))).toBe(true);
214+
expect(await b.table()).toEqual([{ id: 'r1', organization_id: OWN_ORG }]);
215+
});
216+
217+
it('M4b: an executor that runs the installed seam DOES get the wall\'s verdict (admit + judgesOrganization, or 403)', async () => {
218+
const b = await boot('isolated');
219+
const judge = async (opCtx: any) => {
220+
const seam = opCtx.postHookWriteImageCheck;
221+
seam.honoured = true;
222+
await seam.evaluate(Array.isArray(opCtx.data) ? opCtx.data : [opCtx.data]);
223+
};
224+
const admitted = await ride(b, { name: 'n', organization_id: OWN_ORG }, MEMBER_CTX, judge);
225+
const refused = await ride(b, { name: 'n', organization_id: FOREIGN_ORG }, MEMBER_CTX, judge);
226+
console.log('M4b', JSON.stringify({
227+
admitted: { outcome: admitted.outcome, judges: admitted.opCtx.postHookWriteImageCheck?.judgesOrganization, epochDelta: admitted.epochDelta },
228+
refused: { outcome: refused.outcome, epochDelta: refused.epochDelta },
229+
}));
230+
expect(admitted.outcome.ok).toBe(true);
231+
expect(admitted.opCtx.postHookWriteImageCheck?.judgesOrganization).toBe(true);
232+
expect(refused.outcome).toEqual({ ok: false, code: 'PERMISSION_DENIED', status: 403 });
233+
expect(admitted.epochDelta + refused.epochDelta).toBe(2);
234+
});
235+
236+
it('M4c: Middleware A rewrites the ridden payload (fills an absent organization) — a mutation the preview must copy around', async () => {
237+
const b = await boot('isolated');
238+
const data: Record<string, unknown> = { name: 'n' };
239+
const judge = async (opCtx: any) => {
240+
const seam = opCtx.postHookWriteImageCheck;
241+
if (seam) { seam.honoured = true; await seam.evaluate([opCtx.data]); }
242+
};
243+
await ride(b, data, MEMBER_CTX, judge);
244+
console.log('M4c', JSON.stringify({ data }));
245+
expect(data.organization_id).toBe(OWN_ORG);
246+
});
247+
248+
it('M4d: a chain middleware runs a WRITE-side effect after next() keyed only on the operation (Middleware B, sys_organization)', async () => {
249+
const b = await boot('isolated');
250+
const replayed: unknown[] = [];
251+
b.services['seed-replayer'] = async (orgId: string) => { replayed.push(orgId); return { inserted: 0, updated: 0 }; };
252+
const opCtx: any = { object: 'sys_organization', operation: 'insert', data: { id: 'org_new', name: 'New' }, context: SYS_CTX };
253+
const outcome = await attempt(() => (b.engine as any).executeWithMiddleware(opCtx, async () => undefined));
254+
console.log('M4d', JSON.stringify({ outcome, replayed }));
255+
expect(replayed).toEqual(['org_new']);
256+
});
257+
});

0 commit comments

Comments
 (0)