Skip to content

Commit 3d07159

Browse files
committed
fix(objectql,plugin-security): the write preview answers a row's organization from the tenant wall's own verdict
validate() runs no middleware, so the Layer 0 tenant write wall never judged a preview row. On a walled deployment the import dry run reported a caller's organization_id dropped where the write stores it as sent, and answered valid a row naming an organization the write refuses 403. plugin-security: step 3.7's judgement is composed by one method, composeWriteTenantWall (the scope pre-test with its delegator leg, the parts, the forge guard, the emptied organization, the no-active-organization insert arms, and judgesOrganization). The middleware's payload half and stored-image seam call it, with unchanged refusals and log lines. writeWallVerdict answers each preview row from the same method, and is registered on the engine. objectql: registerWriteWallVerdict, an optional member beside registerWriteGateProbe. validate() asks it before the strips and again for a row the strips changed, as the write asks its wall before and after them. A judged organization is spared from the static readonly strip; a refused row answers valid false with the write's code and message, under organization_id or _record, and drops nothing. Unregistered, the strip runs as before. The registerWriteGateProbe docblock no longer says the probe runs step 3.7's organization wall: it asks only the no-active-organization pre-test. Clause-②: yes (widening) Metadata-protocol: none Claude-Session: https://claude.ai/code/session_0157EiYDGYnrsXE9aHv1uMxU Co-authored-by: Claude <noreply@anthropic.com>
1 parent 941fa4e commit 3d07159

10 files changed

Lines changed: 1836 additions & 326 deletions
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql): the write preview (`validate()`, the import dry run) answers a row's `organization_id` from the Layer 0 tenant wall's own verdict
6+
7+
Clause-②: yes (widening)
8+
9+
Metadata-protocol: none
10+
11+
`validate()` runs no middleware, so the tenant write wall never judged a preview row. On a walled deployment (`group` or `isolated`) the preview reported a caller's `organization_id` as dropped where the write stores it as sent, and answered valid a row naming an organization the write refuses with 403.
12+
13+
- **New, optional: `ObjectQL.registerWriteWallVerdict(fn)`**, beside `registerWriteGateProbe`, with its types `WriteWallVerdict` and `WriteWallRowVerdict`. The layer that owns the wall registers it (`@objectstack/plugin-security` does), and the engine never decides the verdict itself.
14+
- **`validate()` reads each row's verdict.** A row whose organization the wall judges keeps `organization_id` through the static `readonly` strip, so no `droppedFields` entry names it, as on the write. A row the wall refuses answers `valid: false` with the write's own code (`PERMISSION_DENIED`) and message, under `organization_id` for a refused value and `_record` for the caller's state, and it drops nothing. Rows stay independent, and the set's `valid` stays the conjunction. A row the strips changed is asked about again, as the write's stored-image half judges it.
15+
- **Unregistered, nothing changes**: the strip runs as before, which is what the write does in a composition without the security plugin.
16+
- **Named limit:** the preview runs no hooks, so an organization a `beforeInsert` / `beforeUpdate` hook writes is judged by the write alone.
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/plugin-security': patch
3+
---
4+
5+
fix(plugin-security): step 3.7's tenant write wall is composed by one method, and the write preview asks it about each row
6+
7+
Clause-②: yes (widening)
8+
9+
Metadata-protocol: none
10+
11+
The engine's write preview (`validate()`, the import dry run) runs no middleware, so it never heard the Layer 0 tenant wall's verdict on a row's `organization_id`.
12+
13+
- **One spelling of the wall.** Step 3.7's judgement (the no-active-organization pre-test with its delegator leg, the supplied-value forge guard, the emptied organization on update, the #24784 / #24821 no-active-organization insert arms, and whether the wall judges the organization) is composed by one method, `composeWriteTenantWall`. The middleware's payload half and its stored-image seam both call it. Behaviour, refusals and log lines are unchanged.
14+
- **New: `SecurityPlugin.writeWallVerdict(object, operation, context, rows)`**, registered on the engine as `registerWriteWallVerdict`. It answers each row from that same method: admitted (and whether the wall judges its organization), or refused with the write's `PermissionDeniedError` code and message. It answers `null` for a system context, a context with no user, and a caller the context prologue refuses before the wall is reached. On an engine without the seam the plugin logs one warning at start and the preview keeps its old answer.

‎packages/objectql/src/engine-insert-wall-judged-organization.test.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,9 @@
2121
// the strip takes the value exactly as before (reported, withheld from the
2222
// hook, refused under strict). Seam presence is not the signal: a business
2323
// `check` installs a seam with no wall behind it;
24-
// - `validate()` runs no middleware, so it holds no seam, and its preview is
25-
// unchanged.
24+
// - `validate()` runs no middleware, so it holds no seam: with no write-wall
25+
// verdict registered its preview is unchanged. The verdict it reads instead
26+
// ([#25062]) is pinned in `validate-write-wall-verdict.test.ts`.
2627

2728
import { describe, it, expect, beforeEach } from 'vitest';
2829
import { ObjectQL } from './engine.js';
@@ -263,7 +264,7 @@ describe('[#24822] engine.insert spares organization_id only where the seam decl
263264
expect(stored()).toEqual([NAMED, NAMED]);
264265
});
265266

266-
it('validate() runs no middleware, so it holds no seam: its preview still reports the strip it always reported', async () => {
267+
it('validate() runs no middleware, so it holds no seam: with no write-wall verdict registered its preview still reports the strip', async () => {
267268
const preview = await engine.validate(OBJECT, { name: 'one', organization_id: NAMED }, { mode: 'insert', context: SESSION as any });
268269

269270
expect(preview.results[0]?.droppedFields).toEqual([{ object: OBJECT, fields: ['organization_id'], reason: 'readonly' }]);

‎packages/objectql/src/engine.ts‎

Lines changed: 208 additions & 25 deletions
Large diffs are not rendered by default.

‎packages/objectql/src/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ export type { CompanionFieldMeta, CompanionObjectMeta } from './search-companion
156156

157157
// Export Engine
158158
export { ObjectQL, ObjectRepository, ScopedContext } from './engine.js';
159-
export type { HookHandler, HookEntry, OperationContext, EngineMiddleware, HeldFileResolver, FieldOwnedFileReadAuthorizer } from './engine.js';
159+
export type { HookHandler, HookEntry, OperationContext, EngineMiddleware, HeldFileResolver, FieldOwnedFileReadAuthorizer, WriteWallVerdict, WriteWallRowVerdict } from './engine.js';
160160
export type { AdmittedValueShapeViolationTally } from './engine.js';
161161
// The declarative datasource definition the engine indexes, and the element
162162
// type of `ObjectQL.listDatasourceDefs()`. Exported so a consumer sweeping for
Lines changed: 285 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,285 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
//
3+
// [#25062] `validate()` reads the Layer 0 tenant write wall's verdict on each
4+
// row through `registerWriteWallVerdict`, and nothing else, to answer a row's
5+
// `organization_id` as the write does.
6+
//
7+
// ## The defect
8+
//
9+
// The preview runs no middleware, so the wall never judged its rows. It ran
10+
// the static-`readonly` strip unconditionally: a caller's organization the
11+
// wall admits (and the write stores as sent, `judgesOrganization`) was
12+
// reported DROPPED, and an organization the wall refuses (the write answers
13+
// 403) was answered VALID.
14+
//
15+
// ## What this file holds the engine to, with a stand-in verdict
16+
//
17+
// - unregistered, or answering `null`: the strip runs exactly as before;
18+
// - admitted, the wall judging the organization: the column stays on the row
19+
// and is not reported, while every other read-only key is still taken, and
20+
// an AUTHORED read-only `organization_id` keeps its strip;
21+
// - admitted, the wall not judging it: the strip takes it, as before;
22+
// - refused: THAT row answers `valid: false` with the verdict's field, code
23+
// and message, its neighbours are judged as before, the set's `valid` is
24+
// the conjunction, and the refused row reaches no strip (the write refuses
25+
// it before any strip runs), so the batch listener hears nothing from it;
26+
// - the verdict is asked with the rows as the preview holds them (after the
27+
// defaults, before any hook), the mode and the caller's context;
28+
// - an `update`-mode preview spares the column on the update's own view;
29+
// - a verdict that answers the wrong number of rows, or throws, rejects the
30+
// preview.
31+
//
32+
// The producer is `@objectstack/plugin-security` (`writeWallVerdict`, from the
33+
// method its step 3.7 calls). The two packages together, against the real
34+
// write, are pinned in `organizations/src/validate-preview-wall-verdict.test.ts`
35+
// and, at the HTTP import door, `rest/src/import-dryrun-tenant-wall-parity.test.ts`.
36+
37+
import { describe, it, expect, beforeEach } from 'vitest';
38+
import { ObjectQL } from './engine.js';
39+
import type { WriteWallRowVerdict, WriteWallVerdict } from './engine.js';
40+
41+
function makeDriver() {
42+
const stores = new Map<string, Map<string, any>>();
43+
const storeFor = (o: string) => {
44+
let s = stores.get(o);
45+
if (!s) { s = new Map(); stores.set(o, s); }
46+
return s;
47+
};
48+
const matches = (row: any, where: any): boolean => {
49+
if (!where || typeof where !== 'object') return true;
50+
return Object.entries(where).every(([k, v]: [string, any]) => {
51+
if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`);
52+
return row?.[k] === v;
53+
});
54+
};
55+
const driver: any = {
56+
name: 'memory', version: '0.0.0', supports: {},
57+
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
58+
async find(object: string, ast: any) {
59+
const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where));
60+
// The caller's bound, applied AFTER the filter and by PRESENCE
61+
// (`check:objectql-double-limit`).
62+
return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows;
63+
},
64+
async findOne(object: string, ast: any) {
65+
for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return r;
66+
return null;
67+
},
68+
async create(object: string, data: Record<string, unknown>) {
69+
const row = { ...data };
70+
storeFor(object).set(String(data.id), row);
71+
return row;
72+
},
73+
async update() { return null; }, async updateMany() { return 0; },
74+
async delete() { return true; }, async count() { return 0; },
75+
async bulkCreate() { return []; }, async bulkUpdate() { return []; }, async bulkDelete() {},
76+
async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; },
77+
async commit() {}, async rollback() {},
78+
};
79+
return { driver, storeFor };
80+
}
81+
82+
const OBJECT = 'qa_ledger';
83+
const AUTHORED = 'qa_authored';
84+
const NAMED = 'org_c';
85+
const SESSION = { userId: 'usr_member', tenantId: 'org_a' };
86+
const DENIED = 'PERMISSION_DENIED';
87+
const PLACEMENT = "[Security] Access denied: the insert would place 'qa_ledger' in another tenant (organization_id is outside the caller's organization scope)";
88+
const NO_ORGANIZATION = "[Security] Access denied: 'qa_ledger' is scoped to an organization, and this session has no active organization — so this insert has no organization to place the record in. Join or select an active organization and retry.";
89+
90+
const ADMIT_JUDGED: WriteWallRowVerdict = { admitted: true, judgesOrganization: true };
91+
const ADMIT_UNJUDGED: WriteWallRowVerdict = { admitted: true, judgesOrganization: false };
92+
const refused = (field: 'organization_id' | '_record', message: string): WriteWallRowVerdict =>
93+
({ admitted: false, field, code: DENIED, message });
94+
95+
describe('[#25062] validate() answers a row\'s organization from the write wall\'s verdict', () => {
96+
let engine: ObjectQL;
97+
let storeFor: ReturnType<typeof makeDriver>['storeFor'];
98+
/** Every call the stand-in verdict received. */
99+
let asked: Array<{ object: string; operation: string; context: unknown; rows: Record<string, unknown>[] }>;
100+
101+
beforeEach(async () => {
102+
asked = [];
103+
const logger: any = {
104+
warn() {}, debug() {}, info() {}, error() {}, trace() {}, fatal() {},
105+
child() { return logger; },
106+
};
107+
engine = new ObjectQL({ logger });
108+
const d = makeDriver();
109+
storeFor = d.storeFor;
110+
engine.registerDriver(d.driver, true);
111+
await engine.init();
112+
engine.registry.registerObject({
113+
name: OBJECT,
114+
fields: {
115+
name: { type: 'text' },
116+
tier: { type: 'text', defaultValue: 'standard' },
117+
// Another read-only key the caller may send: the spare never covers it.
118+
ref_code: { type: 'text', readonly: true },
119+
},
120+
} as any);
121+
// An app object whose AUTHOR declares its own read-only organization_id:
122+
// the wall's verdict does not spare it, as it does not on the write.
123+
engine.registry.registerObject({
124+
name: AUTHORED,
125+
fields: { name: { type: 'text' }, organization_id: { type: 'text', readonly: true } },
126+
} as any);
127+
});
128+
129+
/** Register a stand-in verdict answering `answer(rows)` and recording the call. */
130+
const register = (answer: (rows: readonly Record<string, unknown>[]) => readonly WriteWallRowVerdict[] | null) => {
131+
const verdict: WriteWallVerdict = async (object, operation, context, rows) => {
132+
asked.push({ object, operation, context, rows: rows.map((r) => ({ ...r })) });
133+
return answer(rows);
134+
};
135+
engine.registerWriteWallVerdict(verdict);
136+
};
137+
138+
const preview = async (data: unknown, mode: 'insert' | 'update' = 'insert', object = OBJECT) => {
139+
const heard: Array<{ fields: string[]; reason: string }> = [];
140+
const result = await engine.validate(object, data as any, {
141+
mode,
142+
context: SESSION as any,
143+
onFieldsDropped: (e: any) => heard.push({ fields: [...e.fields], reason: e.reason }),
144+
});
145+
return { result, heard };
146+
};
147+
const ORG_DROP = { object: OBJECT, fields: ['organization_id'], reason: 'readonly' };
148+
149+
it('PRECONDITION: the platform injects organization_id as a read-only column on this object', () => {
150+
const field = (engine.getSchema(OBJECT) as any)?.fields?.organization_id;
151+
expect(field?.readonly, 'the strip has the column to take').toBe(true);
152+
});
153+
154+
it('UNREGISTERED: the strip takes the organization and reports it, exactly as before', async () => {
155+
const { result, heard } = await preview({ name: 'one', organization_id: NAMED });
156+
157+
expect(result.valid).toBe(true);
158+
expect(result.results[0]?.droppedFields).toEqual([ORG_DROP]);
159+
expect(heard).toEqual([{ fields: ['organization_id'], reason: 'readonly' }]);
160+
});
161+
162+
it('NULL: a verdict that does not ask the wall leaves the strip as before', async () => {
163+
register(() => null);
164+
const { result } = await preview({ name: 'one', organization_id: NAMED });
165+
166+
expect(asked.length).toBeGreaterThan(0);
167+
expect(result.results[0]).toEqual({ valid: true, errors: [], warnings: [], droppedFields: [ORG_DROP] });
168+
});
169+
170+
it('ADMITTED and JUDGED: the organization stays on the row and is not reported; another read-only key still is', async () => {
171+
register((rows) => rows.map(() => ADMIT_JUDGED));
172+
const { result, heard } = await preview({ name: 'one', organization_id: NAMED, ref_code: 'X-1' });
173+
174+
expect(result.valid).toBe(true);
175+
expect(result.results[0]?.droppedFields).toEqual([{ object: OBJECT, fields: ['ref_code'], reason: 'readonly' }]);
176+
expect(heard).toEqual([{ fields: ['ref_code'], reason: 'readonly' }]);
177+
});
178+
179+
it('ADMITTED, NOT JUDGED: the strip takes the organization, as before', async () => {
180+
register((rows) => rows.map(() => ADMIT_UNJUDGED));
181+
const { result } = await preview({ name: 'one', organization_id: NAMED });
182+
183+
expect(result.results[0]?.droppedFields).toEqual([ORG_DROP]);
184+
});
185+
186+
it('ADMITTED and JUDGED on an AUTHORED read-only organization_id: the author\'s declaration keeps the strip', async () => {
187+
register((rows) => rows.map(() => ADMIT_JUDGED));
188+
const { result } = await preview({ name: 'one', organization_id: NAMED }, 'insert', AUTHORED);
189+
190+
expect(result.results[0]?.droppedFields).toEqual([{ object: AUTHORED, fields: ['organization_id'], reason: 'readonly' }]);
191+
});
192+
193+
it('REFUSED: that row answers the write\'s refusal, its neighbours are judged as before, and the set is the conjunction', async () => {
194+
register((rows) => rows.map((row) => (row.name === 'forged' ? refused('organization_id', PLACEMENT) : ADMIT_JUDGED)));
195+
const { result, heard } = await preview([
196+
{ name: 'first', organization_id: 'org_a' },
197+
{ name: 'forged', organization_id: NAMED, ref_code: 'X-2' },
198+
{ name: 'third', ref_code: 'X-3' },
199+
]);
200+
201+
expect(result.valid).toBe(false);
202+
expect(result.results[0]).toEqual({ valid: true, errors: [], warnings: [] });
203+
expect(result.results[1]).toEqual({
204+
valid: false,
205+
errors: [{ field: 'organization_id', code: DENIED, message: PLACEMENT }],
206+
warnings: [],
207+
});
208+
expect(result.results[2]).toEqual({
209+
valid: true, errors: [], warnings: [],
210+
droppedFields: [{ object: OBJECT, fields: ['ref_code'], reason: 'readonly' }],
211+
});
212+
// The refused row reaches no strip: the batch listener hears the third
213+
// row's `ref_code` and nothing of the second's.
214+
expect(heard).toEqual([{ fields: ['ref_code'], reason: 'readonly' }]);
215+
});
216+
217+
it('REFUSED on the caller\'s state: the refusal names `_record`', async () => {
218+
register((rows) => rows.map(() => refused('_record', NO_ORGANIZATION)));
219+
const { result } = await preview({ name: 'one' });
220+
221+
expect(result.valid).toBe(false);
222+
expect(result.results[0]?.errors).toEqual([{ field: '_record', code: DENIED, message: NO_ORGANIZATION }]);
223+
});
224+
225+
it('ASKED with the rows as the preview holds them: after the defaults, before any hook, with the mode and the context', async () => {
226+
let hookRan = false;
227+
engine.registerHook('beforeInsert', async () => { hookRan = true; }, { object: OBJECT });
228+
register((rows) => rows.map(() => ADMIT_JUDGED));
229+
await preview({ name: 'one', organization_id: NAMED });
230+
231+
expect(asked, 'the strips left the row alone, so it is asked once').toHaveLength(1);
232+
expect(asked[0]).toMatchObject({ object: OBJECT, operation: 'insert', context: SESSION });
233+
expect(asked[0]!.rows).toEqual([expect.objectContaining({ name: 'one', organization_id: NAMED, tier: 'standard' })]);
234+
expect(hookRan, 'the preview runs no hook').toBe(false);
235+
});
236+
237+
it('ASKED AGAIN about a row the strips changed, as the write\'s stored-image half judges it, and only about that row', async () => {
238+
// The stand-in answers as a crossing operator's wall does: it does not
239+
// judge the organization, and a stored row naming none has nowhere to land.
240+
register((rows) => rows.map((row) => (row.organization_id == null ? refused('_record', NO_ORGANIZATION) : ADMIT_UNJUDGED)));
241+
const { result, heard } = await preview([
242+
{ name: 'named', organization_id: NAMED },
243+
{ name: 'unnamed' },
244+
]);
245+
246+
expect(asked).toHaveLength(2);
247+
expect(asked[0]!.rows.map((r) => r.name)).toEqual(['named', 'unnamed']);
248+
expect(asked[1]!.rows, 'the stripped row, as the write would store it').toEqual([
249+
expect.not.objectContaining({ organization_id: expect.anything() }),
250+
]);
251+
expect(asked[1]!.rows[0]).toMatchObject({ name: 'named' });
252+
expect(result.results[0]).toEqual({
253+
valid: false,
254+
errors: [{ field: '_record', code: DENIED, message: NO_ORGANIZATION }],
255+
warnings: [],
256+
});
257+
// The second row named no organization to begin with: refused on the
258+
// first answer, never stripped and never asked again.
259+
expect(result.results[1]?.valid).toBe(false);
260+
expect(heard, 'a refused row drops nothing').toEqual([]);
261+
});
262+
263+
it('UPDATE mode: a judged organization stays on the update\'s own view; an unjudged one is taken', async () => {
264+
storeFor(OBJECT).set('r1', { id: 'r1', name: 'stored', organization_id: 'org_a' });
265+
266+
register((rows) => rows.map(() => ADMIT_JUDGED));
267+
const judged = await preview({ id: 'r1', organization_id: NAMED }, 'update');
268+
expect(asked[0]).toMatchObject({ operation: 'update', rows: [{ id: 'r1', organization_id: NAMED }] });
269+
expect(judged.result.results[0]).toEqual({ valid: true, errors: [], warnings: [] });
270+
271+
register((rows) => rows.map(() => ADMIT_UNJUDGED));
272+
const unjudged = await preview({ id: 'r1', organization_id: NAMED }, 'update');
273+
expect(unjudged.result.results[0]?.droppedFields).toEqual([ORG_DROP]);
274+
});
275+
276+
it('a verdict that answers the wrong number of rows rejects the preview', async () => {
277+
register(() => [ADMIT_JUDGED]);
278+
await expect(preview([{ name: 'one' }, { name: 'two' }])).rejects.toThrow(/answered 1 verdict\(s\) for 2 row\(s\)/);
279+
});
280+
281+
it('a verdict that throws rejects the preview, as a refusal to resolve fails the write', async () => {
282+
engine.registerWriteWallVerdict(async () => { throw new Error('wall unavailable'); });
283+
await expect(preview({ name: 'one' })).rejects.toThrow('wall unavailable');
284+
});
285+
});

0 commit comments

Comments
 (0)