|
| 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