|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#20802] The nested-relation form reads the related object AS THE CALLER: |
| 5 | + * the related object's row scope and field permissions apply to the condition |
| 6 | + * exactly as they apply to a direct read of it — with the REAL security layer |
| 7 | + * (`SecurityPlugin` on a real `ObjectQL` over a real `SqlDriver`), through |
| 8 | + * `POST /api/v1/data/:object/query`. |
| 9 | + * |
| 10 | + * The ruling's permission axis, measured: |
| 11 | + * |
| 12 | + * - **A field the caller cannot read.** A direct filter on it is refused today |
| 13 | + * — `403 PERMISSION_DENIED`, the security layer's filter-oracle guard |
| 14 | + * (`assertReadableQueryFields`), naming the field. The nested form reaches |
| 15 | + * that SAME check through the related read, so it answers the same refusal, |
| 16 | + * loudly — ⛔ never a `200` with no rows, and ⛔ never the rows a system read |
| 17 | + * would have matched (which is filtering by a value the caller may not see). |
| 18 | + * There is no second copy of the rule in the engine. |
| 19 | + * - **The related object's row scope.** A related record the caller's RLS |
| 20 | + * hides matches no condition: the rows it would have selected are not |
| 21 | + * selected, and a system caller still gets them. |
| 22 | + * |
| 23 | + * SQLite only: the checks are the security layer's, before any driver |
| 24 | + * dialect is involved; `data-nested-object-door.test.ts` carries the dialect |
| 25 | + * axis of the lowering itself. |
| 26 | + */ |
| 27 | + |
| 28 | +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; |
| 29 | +import type { FilterCondition } from '@objectstack/spec/data'; |
| 30 | +import { PermissionSetSchema } from '@objectstack/spec/security'; |
| 31 | +import { ObjectQL } from '@objectstack/objectql'; |
| 32 | +import { SqlDriver } from '@objectstack/driver-sql'; |
| 33 | +import { SecurityPlugin } from '@objectstack/plugin-security'; |
| 34 | +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; |
| 35 | +import { RestServer } from './rest-server'; |
| 36 | + |
| 37 | +const OBJECT = 'rest_nested_perm_ledger'; |
| 38 | +const OWNER = 'rest_nested_perm_owner'; |
| 39 | + |
| 40 | +const SYS_CTX = { isSystem: true, userId: 'usr_system' }; |
| 41 | + |
| 42 | +const MEMBER_SET = PermissionSetSchema.parse({ |
| 43 | + name: 'member_default', |
| 44 | + label: 'Member', |
| 45 | + objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, |
| 46 | + // The field the caller may not read, on the RELATED object. |
| 47 | + fields: { [`${OWNER}.secret`]: { readable: false, editable: false } }, |
| 48 | + // The related object's row scope: the caller sees owners outside region HIDDEN only. |
| 49 | + rowLevelSecurity: [{ name: 'owner_scope', object: OWNER, operation: 'all', using: "record.region != 'HIDDEN'" }], |
| 50 | +}); |
| 51 | + |
| 52 | +const MEMBER_CTX = { userId: 'usr_member', positions: [], permissions: [MEMBER_SET.name], posture: 'MEMBER' }; |
| 53 | + |
| 54 | +const OWNERS = [ |
| 55 | + { id: 'u1', region: 'NA', secret: 's1' }, |
| 56 | + { id: 'u2', region: 'EU', secret: 's2' }, |
| 57 | + { id: 'u3', region: 'HIDDEN', secret: 's3' }, |
| 58 | +]; |
| 59 | +const ROWS = [ |
| 60 | + { id: 'd1', title: 'a', owner: 'u1' }, |
| 61 | + { id: 'd2', title: 'b', owner: 'u2' }, |
| 62 | + { id: 'd3', title: 'c', owner: 'u1' }, |
| 63 | + { id: 'd4', title: 'd', owner: 'u3' }, |
| 64 | +]; |
| 65 | + |
| 66 | +function createMockServer() { |
| 67 | + const noop = () => {}; |
| 68 | + return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; |
| 69 | +} |
| 70 | + |
| 71 | +function makeRes() { |
| 72 | + const res: any = { |
| 73 | + write: () => true, end: () => {}, |
| 74 | + header: () => res, |
| 75 | + status: (code: number) => { res._status = code; return res; }, |
| 76 | + json: (body: any) => { res._json = body; return res; }, |
| 77 | + }; |
| 78 | + return res; |
| 79 | +} |
| 80 | + |
| 81 | +const idsOf = (rows: any): string[] => (Array.isArray(rows) ? rows : rows?.records ?? []).map((r: any) => r.id).sort(); |
| 82 | +const envelopeOf = (e: any) => ({ code: e?.code, status: e?.statusCode ?? e?.status }); |
| 83 | + |
| 84 | +describe('[#20802] the nested-relation form reads the related object as the caller — the real security layer', () => { |
| 85 | + let engine: ObjectQL; |
| 86 | + let query: (where: FilterCondition, object?: string) => Promise<{ status: number; body: any }>; |
| 87 | + |
| 88 | + beforeAll(async () => { |
| 89 | + engine = new ObjectQL(); |
| 90 | + engine.registerDriver( |
| 91 | + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any), |
| 92 | + true, |
| 93 | + ); |
| 94 | + await engine.init(); |
| 95 | + engine.registerApp({ |
| 96 | + id: 'com.objectstack.qa.nested-relation-permission-20802', |
| 97 | + name: 'Nested relation permission', |
| 98 | + version: '1.0.0', |
| 99 | + type: 'plugin', |
| 100 | + scope: 'system', |
| 101 | + objects: [ |
| 102 | + { |
| 103 | + name: OWNER, |
| 104 | + label: 'Owner', |
| 105 | + sharingModel: 'public_read_write', |
| 106 | + fields: { |
| 107 | + region: { name: 'region', type: 'text' }, |
| 108 | + secret: { name: 'secret', type: 'text' }, |
| 109 | + }, |
| 110 | + }, |
| 111 | + { |
| 112 | + name: OBJECT, |
| 113 | + label: 'Ledger', |
| 114 | + sharingModel: 'public_read_write', |
| 115 | + fields: { |
| 116 | + title: { name: 'title', type: 'text' }, |
| 117 | + owner: { name: 'owner', type: 'lookup', reference: OWNER }, |
| 118 | + }, |
| 119 | + }, |
| 120 | + ], |
| 121 | + } as never); |
| 122 | + await engine.syncSchemas(); |
| 123 | + |
| 124 | + const services: Record<string, unknown> = { |
| 125 | + manifest: { register: vi.fn() }, |
| 126 | + objectql: engine, |
| 127 | + metadata: { |
| 128 | + get: async (_type: string, name: string) => engine.getSchema(name) ?? null, |
| 129 | + list: async () => [MEMBER_SET], |
| 130 | + }, |
| 131 | + }; |
| 132 | + const ctx = { |
| 133 | + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, |
| 134 | + registerService: vi.fn(), |
| 135 | + getService: (name: string) => { |
| 136 | + if (!(name in services)) throw new Error(`service not registered: ${name}`); |
| 137 | + return services[name]; |
| 138 | + }, |
| 139 | + }; |
| 140 | + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' }); |
| 141 | + await plugin.init(ctx as never); |
| 142 | + await plugin.start(ctx as never); |
| 143 | + vi.spyOn((engine as unknown as { logger: { warn: () => void } }).logger, 'warn').mockImplementation(() => undefined); |
| 144 | + |
| 145 | + await engine.insert(OWNER, OWNERS.map((r) => ({ ...r })), { context: SYS_CTX } as never); |
| 146 | + await engine.insert(OBJECT, ROWS.map((r) => ({ ...r })), { context: SYS_CTX } as never); |
| 147 | + |
| 148 | + const protocol = new ObjectStackProtocolImplementation(engine as any); |
| 149 | + const rest = new RestServer(createMockServer() as any, protocol as any, { api: { requireAuth: false } } as any); |
| 150 | + (rest as any).resolveExecCtx = async () => MEMBER_CTX; |
| 151 | + rest.registerRoutes(); |
| 152 | + const route = rest.getRoutes().find((r: any) => r.method === 'POST' && r.path === '/api/v1/data/:object/query'); |
| 153 | + expect(route).toBeDefined(); |
| 154 | + query = async (where, object = OBJECT) => { |
| 155 | + const res = makeRes(); |
| 156 | + await route!.handler({ params: { object }, body: JSON.parse(JSON.stringify({ where })), query: {}, headers: {} } as any, res); |
| 157 | + return { status: res._status ?? 200, body: res._json }; |
| 158 | + }; |
| 159 | + }); |
| 160 | + |
| 161 | + afterAll(async () => { |
| 162 | + try { await engine?.destroy(); } catch { /* noop */ } |
| 163 | + }); |
| 164 | + |
| 165 | + it('CONTROL a condition on a field the caller can read is served under the security layer', async () => { |
| 166 | + const res = await query({ owner: { region: 'NA' } }); |
| 167 | + expect(res.status, JSON.stringify(res.body)).toBe(200); |
| 168 | + expect(idsOf(res.body)).toEqual(['d1', 'd3']); |
| 169 | + }); |
| 170 | + |
| 171 | + it('a field the caller cannot read: the direct filter is refused today, and the nested form answers the SAME refusal — never an empty result', async () => { |
| 172 | + // The one check, measured on a direct read of the related object. |
| 173 | + const direct = await engine.find(OWNER, { where: { secret: 's1' }, context: MEMBER_CTX } as never).then(() => null, (e: any) => e); |
| 174 | + expect(envelopeOf(direct)).toEqual({ code: 'PERMISSION_DENIED', status: 403 }); |
| 175 | + expect(String(direct?.message)).toContain('secret'); |
| 176 | + |
| 177 | + // The nested form, in-process and at the public door. |
| 178 | + const nested = await engine.find(OBJECT, { where: { owner: { secret: 's1' } }, context: MEMBER_CTX } as never) |
| 179 | + .then((rows) => ({ rows }), (e: any) => e); |
| 180 | + expect(envelopeOf(nested)).toEqual({ code: 'PERMISSION_DENIED', status: 403 }); |
| 181 | + expect(String(nested?.message)).toContain('secret'); |
| 182 | + expect(String(nested?.message)).toContain(OWNER); |
| 183 | + |
| 184 | + const res = await query({ owner: { secret: 's1' } }); |
| 185 | + expect(res.status, JSON.stringify(res.body)).toBe(403); |
| 186 | + expect(JSON.stringify(res.body)).toContain('PERMISSION_DENIED'); |
| 187 | + expect(res.body?.records, 'no rows are served beside the refusal').toBeUndefined(); |
| 188 | + |
| 189 | + // What the refusal withholds: a system read CAN filter by the value. |
| 190 | + const system = await engine.find(OBJECT, { where: { owner: { secret: 's1' } }, context: SYS_CTX } as never); |
| 191 | + expect(idsOf(system)).toEqual(['d1', 'd3']); |
| 192 | + }); |
| 193 | + |
| 194 | + it('the related object\'s row scope applies: a related record the caller cannot see matches no condition', async () => { |
| 195 | + const res = await query({ owner: { region: 'HIDDEN' } }); |
| 196 | + expect(res.status, JSON.stringify(res.body)).toBe(200); |
| 197 | + expect(idsOf(res.body)).toEqual([]); |
| 198 | + // The record is there, and a system caller's condition finds it. |
| 199 | + const system = await engine.find(OBJECT, { where: { owner: { region: 'HIDDEN' } }, context: SYS_CTX } as never); |
| 200 | + expect(idsOf(system)).toEqual(['d4']); |
| 201 | + }); |
| 202 | +}); |
0 commit comments