From 0fe3c2a7d23774eb38e25cb4c55ff9485505afa5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:16:31 +0000 Subject: [PATCH 01/18] test(organizations): pin an elevation's stored-image and option-bag organization to the caller's wall Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- ...ated-organization-wall.writes.wall.test.ts | 218 +++++++++++++++++- 1 file changed, 216 insertions(+), 2 deletions(-) diff --git a/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts b/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts index 889bcd0038a..7f8ddd6646a 100644 --- a/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts +++ b/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts @@ -11,7 +11,13 @@ * refused `403 PERMISSION_DENIED`; * - the row a by-id write names is judged where the write runs: inside the * body's own transaction, a row the transaction wrote is the caller's to - * write again, as at the plain door. + * write again, as at the plain door; + * - a write is judged as it will be stored: an organization the write's + * before-hooks leave on the row is held to the same wall as one the write + * sent; + * - an organization the operation's option bag names (`tenantId`, + * `tenantIds`) is held to the caller's wall: a write naming one outside it + * is refused `403`, and a read naming one is answered by the read rule. * * ## What is real * @@ -35,6 +41,17 @@ const TASK = 'eoww_task'; const BODY_LAND = "await ctx.api.object('eoww_task').insert({ name: input.name, organization_id: input.org }); return { landed: 1 };"; const BODY_MOVE = "await ctx.api.object('eoww_task').update({ id: input.target, organization_id: input.org }); return { moved: 1 };"; +// Bodies that forward their caller's input into the option bag of each verb. +const BODY_BAG_FIND = + "const rows = await ctx.api.object('eoww_task').find({ where: {}, tenantId: input.org }); return { seen: rows.map((r) => r.name).sort() };"; +const BODY_BAG_FIND_MANY = + "const rows = await ctx.api.object('eoww_task').find({ where: {}, tenantIds: input.orgs }); return { seen: rows.map((r) => r.name).sort() };"; +const BODY_BAG_UPDATE = + "await ctx.api.object('eoww_task').update({ touched: 'bag' }, { where: { name: input.name }, multi: true, tenantId: input.org }); return { wrote: 1 };"; +const BODY_BAG_UPDATE_BY_ID = + "await ctx.api.object('eoww_task').update({ id: input.target, touched: 'bag' }, { tenantId: input.org }); return { wrote: 1 };"; +const BODY_BAG_DELETE = + "await ctx.api.object('eoww_task').delete({ where: { name: input.name }, multi: true, tenantId: input.org }); return { removed: 1 };"; const APP = { manifest: { id: 'com.example.eoww', namespace: 'eoww', version: '0.0.1', type: 'app', name: 'Elevated Org Wall Writes Fixture' }, @@ -44,7 +61,11 @@ const APP = { name: TASK, label: 'Task', sharingModel: 'public_read_write', - fields: { name: { type: 'text', label: 'Name' }, touched: { type: 'text', label: 'Touched' } }, + fields: { + name: { type: 'text', label: 'Name' }, + touched: { type: 'text', label: 'Touched' }, + hint: { type: 'text', label: 'Hint' }, + }, }, ], actions: [ @@ -66,6 +87,26 @@ const APP = { }, { name: 'eoww_tx_touch', label: 'Transaction touch', objectName: TASK, type: 'script', target: 'eowwTxTouch' }, { name: 'eoww_touch', label: 'Touch', objectName: TASK, type: 'script', target: 'eowwTouch' }, + { name: 'eoww_hooked_land', label: 'Hooked land', objectName: TASK, type: 'script', target: 'eowwHookedLand' }, + { name: 'eoww_hooked_touch', label: 'Hooked touch', objectName: TASK, type: 'script', target: 'eowwHookedTouch' }, + { name: 'eoww_hooked_sweep', label: 'Hooked sweep', objectName: TASK, type: 'script', target: 'eowwHookedSweep' }, + { name: 'eoww_late_bag', label: 'Late bag', objectName: TASK, type: 'script', target: 'eowwLateBag' }, + { name: 'eoww_late_read', label: 'Late read', objectName: TASK, type: 'script', target: 'eowwLateRead' }, + ...( + [ + ['eoww_bag_find', BODY_BAG_FIND], + ['eoww_bag_find_many', BODY_BAG_FIND_MANY], + ['eoww_bag_update', BODY_BAG_UPDATE], + ['eoww_bag_update_by_id', BODY_BAG_UPDATE_BY_ID], + ['eoww_bag_delete', BODY_BAG_DELETE], + ] as const + ).map(([name, source]) => ({ + name, + label: name, + objectName: TASK, + type: 'script', + body: { language: 'js', source, capabilities: ['api.read', 'api.write'] }, + })), ], }; @@ -118,6 +159,65 @@ describe('an app-authored elevation’s writes are judged by its caller’s orga }); return { id }; }); + // A before-hook that names an organization on the row it is handed: the + // `hint` the write carries. + for (const event of ['beforeInsert', 'beforeUpdate']) { + ql.registerHook( + event, + async (ctx: any) => { + const data = ctx.input?.data; + if (data && typeof data.hint === 'string' && data.hint !== '') data.organization_id = data.hint; + }, + { object: TASK }, + ); + } + // A before-hook that writes a tenant key into the option bag of a write it + // is handed, and one that writes it into the bag of a read. + ql.registerHook( + 'beforeUpdate', + async (ctx: any) => { + const touched = ctx.input?.data?.touched; + if (typeof touched === 'string' && touched.startsWith('late:') && ctx.input.options) { + ctx.input.options.tenantId = touched.slice('late:'.length); + } + }, + { object: TASK }, + ); + let lateReadOrg: string | undefined; + ql.registerHook( + 'beforeFind', + async (ctx: any) => { + if (lateReadOrg !== undefined && ctx.input?.options) ctx.input.options.tenantId = lateReadOrg; + }, + { object: TASK }, + ); + ql.registerAction(TASK, 'eowwHookedLand', async (ctx: any) => { + await ctx.engine.insert(TASK, { name: ctx.params?.name, hint: ctx.params?.org }); + return { landed: 1 }; + }); + ql.registerAction(TASK, 'eowwHookedTouch', async (ctx: any) => { + await ctx.engine.update(TASK, String(ctx.params?.target), { touched: 'hooked', hint: ctx.params?.org }); + return { wrote: 1 }; + }); + ql.registerAction(TASK, 'eowwHookedSweep', async (ctx: any) => { + await ctx.api.object(TASK).update({ touched: 'swept', hint: ctx.params?.org }, { where: { name: 'A1' }, multi: true }); + return { wrote: 1 }; + }); + ql.registerAction(TASK, 'eowwLateBag', async (ctx: any) => { + await ctx.api + .object(TASK) + .update({ touched: `late:${String(ctx.params?.org)}` }, { where: { name: { $in: ['A1', ctx.params?.name] } }, multi: true }); + return { wrote: 1 }; + }); + ql.registerAction(TASK, 'eowwLateRead', async (ctx: any) => { + lateReadOrg = String(ctx.params?.org); + try { + const rows = await ctx.api.object(TASK).find({ where: {} }); + return { seen: rows.map((r: any) => r.name).sort() }; + } finally { + lateReadOrg = undefined; + } + }); ql.registerAction(TASK, 'eowwTouch', async (ctx: any) => { await ctx.engine.update(TASK, String(ctx.params?.target), { touched: 'touch' }); return { wrote: 1 }; @@ -214,6 +314,120 @@ describe('an app-authored elevation’s writes are judged by its caller’s orga }); }); + describe('a write is judged as it will be stored', () => { + it('an organization a before-hook places on an insert outside the caller’s wall is refused 403', async () => { + await reseed(); + const r = await run(alice, 'eoww_hooked_land', { name: 'HOOKED-B', org: orgB }); + expect(r.status, JSON.stringify(r.body)).toBe(403); + expect(r.body.error.code).toBe('PERMISSION_DENIED'); + expect(await rowNamed('HOOKED-B')).toBeUndefined(); + }); + + it('an organization a before-hook places on a by-id update outside the caller’s wall is refused 403', async () => { + await reseed(); + const a1 = await rowNamed('A1'); + const r = await run(alice, 'eoww_hooked_touch', { target: a1!.id, org: orgB }); + expect(r.status, JSON.stringify(r.body)).toBe(403); + expect(r.body.error.code).toBe('PERMISSION_DENIED'); + expect(await rowNamed('A1')).toMatchObject({ organization_id: orgA }); + expect((await rowNamed('A1'))!.touched ?? null).toBeNull(); + }); + + it('an organization a before-hook places on a predicate update outside the caller’s wall is refused 403', async () => { + await reseed(); + const r = await run(alice, 'eoww_hooked_sweep', { org: orgB }); + expect(r.status, JSON.stringify(r.body)).toBe(403); + expect(r.body.error.code).toBe('PERMISSION_DENIED'); + expect(await rowNamed('A1')).toMatchObject({ organization_id: orgA }); + expect((await rowNamed('A1'))!.touched ?? null).toBeNull(); + }); + + it('control: a before-hook that places the row in the caller’s own organization lands it there', async () => { + await reseed(); + const landed = await run(alice, 'eoww_hooked_land', { name: 'HOOKED-A', org: orgA }); + expect(landed.status, JSON.stringify(landed.body)).toBe(200); + expect((await rowNamed('HOOKED-A'))!.organization_id).toBe(orgA); + const a1 = await rowNamed('A1'); + const kept = await run(alice, 'eoww_hooked_touch', { target: a1!.id, org: orgA }); + expect(kept.status, JSON.stringify(kept.body)).toBe(200); + expect(await rowNamed('A1')).toMatchObject({ organization_id: orgA, touched: 'hooked' }); + }); + }); + + describe('the option bag’s organization is held to the caller’s wall', () => { + it('a read whose bag names another organization is answered by the read rule', async () => { + await reseed(); + const one = await run(alice, 'eoww_bag_find', { org: orgB }); + expect(one.status, JSON.stringify(one.body)).toBe(200); + expect(one.body.data).toEqual({ seen: [] }); + const many = await run(alice, 'eoww_bag_find_many', { orgs: [orgA, orgB] }); + expect(many.status, JSON.stringify(many.body)).toBe(200); + expect(many.body.data).toEqual({ seen: [] }); + }); + + it('a predicate update whose bag names another organization is refused 403', async () => { + await reseed(); + const r = await run(alice, 'eoww_bag_update', { name: 'B1', org: orgB }); + expect(r.status, JSON.stringify(r.body)).toBe(403); + expect(r.body.error.code).toBe('PERMISSION_DENIED'); + expect((await rowNamed('B1'))!.touched ?? null).toBeNull(); + }); + + it('a by-id update whose bag names another organization is refused 403', async () => { + await reseed(); + const b1 = await rowNamed('B1'); + const r = await run(alice, 'eoww_bag_update_by_id', { target: b1!.id, org: orgB }); + expect(r.status, JSON.stringify(r.body)).toBe(403); + expect(r.body.error.code).toBe('PERMISSION_DENIED'); + expect((await rowNamed('B1'))!.touched ?? null).toBeNull(); + }); + + it('a delete whose bag names another organization is refused 403', async () => { + await reseed(); + const r = await run(alice, 'eoww_bag_delete', { name: 'B1', org: orgB }); + expect(r.status, JSON.stringify(r.body)).toBe(403); + expect(r.body.error.code).toBe('PERMISSION_DENIED'); + expect(await rowNamed('B1')).toBeDefined(); + }); + + it('a tenant key a before-hook writes into the bag of a write is held to the wall too', async () => { + await reseed(); + const r = await run(alice, 'eoww_late_bag', { name: 'B1', org: orgB }); + expect(r.status, JSON.stringify(r.body)).toBe(403); + expect(r.body.error.code).toBe('PERMISSION_DENIED'); + expect((await rowNamed('B1'))!.touched ?? null).toBeNull(); + expect((await rowNamed('A1'))!.touched ?? null).toBeNull(); + }); + + it('a tenant key a before-hook writes into the bag of a read is answered by the read rule', async () => { + await reseed(); + const r = await run(alice, 'eoww_late_read', { org: orgB }); + expect(r.status, JSON.stringify(r.body)).toBe(200); + expect(r.body.data).toEqual({ seen: [] }); + const own = await run(alice, 'eoww_late_read', { org: orgA }); + expect(own.status, JSON.stringify(own.body)).toBe(200); + expect(own.body.data).toEqual({ seen: ['A1'] }); + }); + + it('control: a bag naming the caller’s own organization reads and writes there', async () => { + await reseed(); + const read = await run(alice, 'eoww_bag_find', { org: orgA }); + expect(read.status, JSON.stringify(read.body)).toBe(200); + expect(read.body.data).toEqual({ seen: ['A1'] }); + const wrote = await run(alice, 'eoww_bag_update', { name: 'A1', org: orgA }); + expect(wrote.status, JSON.stringify(wrote.body)).toBe(200); + expect((await rowNamed('A1'))!.touched).toBe('bag'); + }); + + it('control: platform system work that runs for no caller keeps the organization its bag names', async () => { + await reseed(); + const seen = await ql.find(TASK, { where: {}, tenantId: orgB, context: { isSystem: true } }); + expect(seen.map((r: any) => r.name).sort()).toEqual(['B1']); + await ql.update(TASK, { touched: 'platform' }, { where: { name: 'B1' }, multi: true, tenantId: orgB, context: { isSystem: true } }); + expect((await rowNamed('B1'))!.touched).toBe('platform'); + }); + }); + describe('a platform operator under a walled posture, inside the body’s own transaction', () => { it('a row the transaction inserted is the operator’s to update by id in the same transaction', async () => { await reseed(); From a4c2358705e7f5fdf14808a7e2571a56503daec0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:22:44 +0000 Subject: [PATCH 02/18] fix(plugin-security): an elevation's write is judged as stored, and its option bag never widens it past the caller's wall Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- ...ated-organization-wall.writes.wall.test.ts | 23 ++- .../app-automation-organization-wall.test.ts | 125 ++++++++++++ .../src/app-automation-organization-wall.ts | 190 +++++++++++++++++- 3 files changed, 327 insertions(+), 11 deletions(-) diff --git a/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts b/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts index 7f8ddd6646a..b71de8978dd 100644 --- a/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts +++ b/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts @@ -50,6 +50,10 @@ const BODY_BAG_UPDATE = "await ctx.api.object('eoww_task').update({ touched: 'bag' }, { where: { name: input.name }, multi: true, tenantId: input.org }); return { wrote: 1 };"; const BODY_BAG_UPDATE_BY_ID = "await ctx.api.object('eoww_task').update({ id: input.target, touched: 'bag' }, { tenantId: input.org }); return { wrote: 1 };"; +const BODY_BAG_CLEAR_FIND = + "const rows = await ctx.api.object('eoww_task').find({ where: {}, tenantId: null }); return { seen: rows.map((r) => r.name).sort() };"; +const BODY_BAG_CLEAR_UPDATE = + "await ctx.api.object('eoww_task').update({ touched: 'bag' }, { where: { name: input.name }, multi: true, tenantId: '' }); return { wrote: 1 };"; const BODY_BAG_DELETE = "await ctx.api.object('eoww_task').delete({ where: { name: input.name }, multi: true, tenantId: input.org }); return { removed: 1 };"; @@ -99,6 +103,8 @@ const APP = { ['eoww_bag_update', BODY_BAG_UPDATE], ['eoww_bag_update_by_id', BODY_BAG_UPDATE_BY_ID], ['eoww_bag_delete', BODY_BAG_DELETE], + ['eoww_bag_clear_find', BODY_BAG_CLEAR_FIND], + ['eoww_bag_clear_update', BODY_BAG_CLEAR_UPDATE], ] as const ).map(([name, source]) => ({ name, @@ -362,7 +368,22 @@ describe('an app-authored elevation’s writes are judged by its caller’s orga expect(one.body.data).toEqual({ seen: [] }); const many = await run(alice, 'eoww_bag_find_many', { orgs: [orgA, orgB] }); expect(many.status, JSON.stringify(many.body)).toBe(200); - expect(many.body.data).toEqual({ seen: [] }); + expect(many.body.data).toEqual({ seen: ['A1'] }); + }); + + it('a read whose bag clears the tenant key is answered by the read rule', async () => { + await reseed(); + const r = await run(alice, 'eoww_bag_clear_find'); + expect(r.status, JSON.stringify(r.body)).toBe(200); + expect(r.body.data).toEqual({ seen: ['A1'] }); + }); + + it('a write whose bag clears the tenant key is refused 403', async () => { + await reseed(); + const r = await run(alice, 'eoww_bag_clear_update', { name: 'B1' }); + expect(r.status, JSON.stringify(r.body)).toBe(403); + expect(r.body.error.code).toBe('PERMISSION_DENIED'); + expect((await rowNamed('B1'))!.touched ?? null).toBeNull(); }); it('a predicate update whose bag names another organization is refused 403', async () => { diff --git a/packages/plugins/plugin-security/src/app-automation-organization-wall.test.ts b/packages/plugins/plugin-security/src/app-automation-organization-wall.test.ts index 8566c2e4d9b..7e7ee607380 100644 --- a/packages/plugins/plugin-security/src/app-automation-organization-wall.test.ts +++ b/packages/plugins/plugin-security/src/app-automation-organization-wall.test.ts @@ -333,6 +333,131 @@ describe('an app-authored elevation is judged by its caller’s organization wal }); }); + describe('a write is judged as it will be stored', () => { + const member = () => actionBody({ tenantId: 'org_a' }); + + it('a judging seam goes on every insert and update, and the caller’s own organization asks no verdict', async () => { + for (const operation of ['insert', 'update']) { + const deps = depsFor(ORG_A); + const opCtx: any = { object: 'task', operation, context: member(), data: { id: 't_1', name: 'x' }, ast: { object: 'task' } }; + await applyAppAutomationOrganizationWall(opCtx, deps); + expect(typeof opCtx.postHookWriteImageCheck?.evaluate).toBe('function'); + await opCtx.postHookWriteImageCheck.evaluate([{ id: 't_1', organization_id: 'org_a' }]); + expect(deps.callerLayer0).not.toHaveBeenCalled(); + } + }); + + it('a stored row in an organization the wall does not admit is refused 403, and an update left in none', async () => { + const insert: any = { object: 'task', operation: 'insert', context: member(), data: { name: 'x' } }; + await applyAppAutomationOrganizationWall(insert, depsFor(ORG_A)); + const placed = await refusalOf(() => insert.postHookWriteImageCheck.evaluate([{ name: 'x', organization_id: 'org_b' }])); + expect([placed.code, placed.status]).toEqual(['PERMISSION_DENIED', 403]); + const update: any = { object: 'task', operation: 'update', context: member(), data: { id: 't_1', touched: 'x' } }; + await applyAppAutomationOrganizationWall(update, depsFor(ORG_A)); + const emptied = await refusalOf(() => update.postHookWriteImageCheck.evaluate([{ id: 't_1', organization_id: null }])); + expect([emptied.code, emptied.status]).toEqual(['PERMISSION_DENIED', 403]); + }); + + it('control: an organization the wall admits is stored, and a wall with no parts admits any', async () => { + const union: any = { object: 'task', operation: 'insert', context: member(), data: { name: 'x' } }; + await applyAppAutomationOrganizationWall(union, depsFor(UNION)); + await expect(union.postHookWriteImageCheck.evaluate([{ organization_id: 'org_b' }])).resolves.toBeUndefined(); + const none: any = { object: 'catalog', operation: 'insert', context: member(), data: { name: 'x' } }; + await applyAppAutomationOrganizationWall(none, depsFor(NONE)); + await expect(none.postHookWriteImageCheck.evaluate([{ organization_id: 'org_b' }])).resolves.toBeUndefined(); + }); + + it('a seam installed before it is kept: it runs first, and is told it ran', async () => { + const prior = { evaluate: vi.fn(), honoured: false }; + const opCtx: any = { object: 'task', operation: 'insert', context: member(), data: { name: 'x' }, postHookWriteImageCheck: prior }; + await applyAppAutomationOrganizationWall(opCtx, depsFor(ORG_A)); + await opCtx.postHookWriteImageCheck.evaluate([{ name: 'x' }]); + expect(prior.evaluate).toHaveBeenCalledOnce(); + expect(prior.honoured).toBe(true); + }); + + it('control: a platform writer’s own system write gets no seam', async () => { + const opCtx: any = { object: 'task', operation: 'insert', context: { isSystem: true, tenantId: 'org_a' }, data: { name: 'x' } }; + await applyAppAutomationOrganizationWall(opCtx, depsFor(ORG_A)); + expect(opCtx.postHookWriteImageCheck).toBeUndefined(); + }); + }); + + describe('the option bag never widens an elevation past its caller’s wall', () => { + const member = () => actionBody({ tenantId: 'org_a' }); + + it('a read whose bag names or clears an organization scope takes the caller’s wall on its predicate', async () => { + for (const options of [{ tenantId: 'org_b' }, { tenantIds: ['org_a', 'org_b'] }, { tenantId: null }, { tenantId: '' }]) { + const read: any = { object: 'task', operation: 'find', context: member(), options, ast: { object: 'task', where: { a: 1 } } }; + await applyAppAutomationOrganizationWall(read, depsFor(ORG_A)); + expect(read.ast.where).toEqual({ $and: [{ a: 1 }, { organization_id: 'org_a' }] }); + expect(read.tenantLayer0Verdict).toEqual(ORG_A); + } + }); + + it('a write whose bag names an organization outside the wall, or clears the key, is refused 403', async () => { + for (const operation of ['update', 'delete', 'purge']) { + for (const options of [{ tenantId: 'org_b' }, { tenantIds: ['org_a', 'org_b'] }, { tenantId: null }]) { + const e = await refusalOf(() => + applyAppAutomationOrganizationWall({ object: 'task', operation, context: member(), options, ast: { object: 'task' } }, depsFor(ORG_A)), + ); + expect([e.code, e.status]).toEqual(['PERMISSION_DENIED', 403]); + } + } + }); + + it('a denied caller’s delete keeps the read rule: it matches nothing', async () => { + const opCtx: any = { object: 'task', operation: 'delete', context: actionBody(), options: { tenantId: 'org_b' }, ast: { object: 'task' } }; + await applyAppAutomationOrganizationWall(opCtx, depsFor(DENY)); + expect(opCtx.ast.where).toBe(RLS_DENY_FILTER); + }); + + it('a key a before-hook sets later is held as it is set', async () => { + const write: any = { object: 'task', operation: 'update', context: member(), options: {}, ast: { object: 'task' } }; + await applyAppAutomationOrganizationWall(write, depsFor(ORG_A)); + expect(() => { + write.options.tenantId = 'org_b'; + }).toThrow(/organization/); + expect(() => { + write.options.tenantId = null; + }).toThrow(/organization/); + write.options.tenantId = 'org_a'; + expect(write.options.tenantId).toBe('org_a'); + const read: any = { object: 'task', operation: 'find', context: member(), options: {}, ast: { object: 'task' } }; + await applyAppAutomationOrganizationWall(read, depsFor(ORG_A)); + read.options.tenantId = 'org_b'; + expect(read.options.tenantId).toBe(RLS_DENY_FILTER.id); + read.options.tenantIds = ['org_a', 'org_b']; + expect(read.options.tenantIds).toEqual(['org_a']); + }); + + it('a held key the bag does not carry stays out of its keys until set', async () => { + const opCtx: any = { object: 'task', operation: 'find', context: member(), options: { where: {} }, ast: { object: 'task' } }; + await applyAppAutomationOrganizationWall(opCtx, depsFor(ORG_A)); + expect(Object.keys(opCtx.options)).toEqual(['where']); + opCtx.options.tenantId = 'org_a'; + expect(Object.keys(opCtx.options)).toEqual(['where', 'tenantId']); + }); + + it('control: a bag naming an organization the wall admits passes, and a wall with no parts admits any', async () => { + const own: any = { object: 'task', operation: 'update', context: member(), options: { tenantId: 'org_a' }, ast: { object: 'task' } }; + await expect(applyAppAutomationOrganizationWall(own, depsFor(ORG_A))).resolves.toBeUndefined(); + const union: any = { object: 'task', operation: 'update', context: member(), options: { tenantIds: ['org_a', 'org_b'] }, ast: { object: 'task' } }; + await expect(applyAppAutomationOrganizationWall(union, depsFor(UNION))).resolves.toBeUndefined(); + const none: any = { object: 'catalog', operation: 'delete', context: member(), options: { tenantId: 'org_b' }, ast: { object: 'catalog' } }; + await expect(applyAppAutomationOrganizationWall(none, depsFor(NONE))).resolves.toBeUndefined(); + }); + + it('control: a platform writer’s own system bag is untouched', async () => { + const options: Record = { tenantId: 'org_b' }; + const opCtx: any = { object: 'task', operation: 'update', context: { isSystem: true }, options, ast: { object: 'task' } }; + const deps = depsFor(ORG_A); + await applyAppAutomationOrganizationWall(opCtx, deps); + expect(Object.getOwnPropertyDescriptor(options, 'tenantId')).toMatchObject({ value: 'org_b', writable: true }); + expect(deps.callerLayer0).not.toHaveBeenCalled(); + }); + }); + describe('the by-id check is read where the write runs', () => { it('the write’s own context, transaction included, is handed to the check', async () => { const deps = depsFor(ORG_A, { inScope: true }); diff --git a/packages/plugins/plugin-security/src/app-automation-organization-wall.ts b/packages/plugins/plugin-security/src/app-automation-organization-wall.ts index 31981fdf33b..e60c4a4fb71 100644 --- a/packages/plugins/plugin-security/src/app-automation-organization-wall.ts +++ b/packages/plugins/plugin-security/src/app-automation-organization-wall.ts @@ -41,6 +41,18 @@ * - a write whose own data names an organization the wall does not admit, and * an update whose own data empties a row's organization, are refused — * judged for every caller; + * - a write is judged again as it will be stored, as the plain door judges + * it: the rows the write's before-hooks leave are held to the same rule + * (the engine's `postHookWriteImageCheck` seam, its judging half only — + * the system strips stay off), so an organization a hook writes onto the + * row is judged as one the write sent; + * - the option bag's tenant keys (`tenantId`, `tenantIds`, which the engine + * hands its driver as given) never widen the elevation past the wall: a + * write whose bag names an organization the wall does not admit, or clears + * the key, is refused, and a read whose bag does is answered by the read + * rule — the wall is composed onto its predicate, as the plain door's is. A + * before-hook that sets either key on the bag it is handed is held to the + * same rule as it sets it; * - a caller the wall DENIES — no active organization under `isolated`, an * empty membership set under `group`, a person outside every organization * under `single` (ADR-0093 D8.1, as amended) — reads nothing (zero rows, no @@ -319,6 +331,91 @@ function admittedOrganizations(verdict: TenantLayer0Verdict): ReadonlySet = new Set(['find', 'findOne', 'update', 'delete', 'purge']); + +/** The option bag's driver pass-through tenant keys. */ +const BAG_TENANT_KEYS = ['tenantId', 'tenantIds'] as const; + +/** + * What an option bag's tenant keys ask of the driver: the organizations they + * name, and whether `tenantId` is present yet names none (`null`, `''`, any + * value that is not an organization id) — the driver then applies no tenant + * scope at all. `undefined` when the bag sets neither key. + */ +interface BagTenantAsk { + organizations: string[]; + clears: boolean; +} + +function bagTenantAsk(options: unknown): BagTenantAsk | undefined { + if (!options || typeof options !== 'object') return undefined; + const bag = options as { tenantId?: unknown; tenantIds?: unknown }; + const tenantId = bag.tenantId; + const tenantIds = bag.tenantIds; + if (tenantId === undefined && tenantIds === undefined) return undefined; + const organizations: string[] = []; + const clears = tenantId !== undefined && !(typeof tenantId === 'string' && tenantId !== ''); + if (typeof tenantId === 'string' && tenantId !== '') organizations.push(tenantId); + if (Array.isArray(tenantIds)) for (const id of tenantIds) if (typeof id === 'string' && id !== '') organizations.push(id); + return { organizations, clears }; +} + +/** Does the bag's ask reach past `admitted` (`undefined`: the verdict has no wall)? */ +function bagReachesPast(ask: BagTenantAsk, admitted: ReadonlySet | undefined): boolean { + if (admitted === undefined) return false; + return ask.clears || ask.organizations.some((id) => !admitted.has(id)); +} + +/** The refusal of a write whose option bag reaches past the caller's wall. */ +function bagRefusal(source: ElevationSource, object: string, operation: string): PermissionDeniedError { + return new PermissionDeniedError( + `[Security] Access denied: this ${operation} on '${object}' names, in its options, an organization scope the user ` + + `${SUBJECT[source]} runs for may not write in, and ${ELEVATION[source]} does not lift the organization wall.`, + { operation, object }, + ); +} + +/** + * Hold a tenant key a before-hook sets on the operation's option bag to the + * caller's wall, as it is set: `admitted()` answers the organizations the + * wall admits (`undefined`: no wall). A write's key that reaches past it is + * refused; a read's is narrowed to what the wall admits — an organization + * outside it scopes to none, and a key cleared keeps the scope it had. + */ +function holdBagTenantKeys( + bag: Record, + isRead: boolean, + admitted: () => ReadonlySet | undefined, + refuse: () => Error, +): void { + for (const key of BAG_TENANT_KEYS) { + let value = bag[key]; + // Enumerable only while it holds a value, as a plain key would be: the + // engine picks the bag's driver keys by enumerability. + const define = () => + Object.defineProperty(bag, key, { + configurable: true, + enumerable: value !== undefined, + get: () => value, + set: (next: unknown) => { + const ask = next === undefined ? undefined : bagTenantAsk({ [key]: next }); + const wall = admitted(); + if (!ask || !bagReachesPast(ask, wall)) { + value = next; + } else if (!isRead) { + throw refuse(); + } else if (!ask.clears) { + const inside = ask.organizations.filter((id) => wall!.has(id)); + value = key === 'tenantId' ? (inside[0] ?? RLS_DENY_FILTER.id) : inside.length > 0 ? inside : [RLS_DENY_FILTER.id]; + } + define(); + }, + }); + define(); + } +} + /** Rows of a write payload, each a plain object. */ function payloadRows(data: unknown): Record[] { const rows = Array.isArray(data) ? data : data === undefined || data === null ? [] : [data]; @@ -344,6 +441,7 @@ export async function applyAppAutomationOrganizationWall( options?: unknown; ast?: { where?: unknown } | null; tenantLayer0Verdict?: unknown; + postHookWriteImageCheck?: { evaluate(rows: readonly Record[]): unknown; honoured?: boolean }; }, deps: AppAutomationWallDeps, ): Promise { @@ -358,25 +456,97 @@ export async function applyAppAutomationOrganizationWall( // [ADR-0095 D1] A write whose own data names an organization, or an update // whose own data empties the column, is judged for EVERY caller. const touchesOrganization = rows.some((row) => namesOrganization(row) || (verb === 'update' && emptiesOrganization(row))); + // [ADR-0095 D1] The option bag's driver pass-through tenant keys: an + // explicit one wins the driver's scope under every verdict, so the scope + // they ask for is held to the caller's wall. + const bagAsk = BAG_VERBS.has(operation) ? bagTenantAsk(opCtx.options) : undefined; + + // The caller's facts and Layer 0, worked out at most once for this + // operation, and only where something asks for them. The door's facts are + // resolved for the caller where the context does not carry them (a flow + // run's envelope carries no permission sets). + let judged: Promise<{ callerContext: Record; answer: CallerLayer0Answer }> | undefined; + const judge = () => + (judged ??= (async () => { + const callerContext = carriesDoorFacts(caller.callerContext) + ? caller.callerContext + : await deps.completeCaller(caller.callerContext); + return { callerContext, answer: await deps.callerLayer0(callerContext, object, operation) }; + })()); + // The organizations the verdict admits, once it is worked out: `null` until + // then, `undefined` for a verdict with no wall. + let judgedAdmitted: ReadonlySet | undefined | null = null; + // The caller's own active organization, which its wall always admits — the + // judgement where no verdict is worked out (narrower, never wider). A + // decided segment's facts are not its caller's, so it has none. + const ownOrganization = + caller.decided !== true && carriesActiveOrganization(caller.callerContext) ? String(caller.callerContext.tenantId) : undefined; + + // [ADR-0095 D1, the plain door's stored-image half] A write is judged again + // on the rows its before-hooks leave, as `composeWriteTenantWall` judges + // them at the plain door: a row stored in an organization the caller's wall + // does not admit, or an update left in none, is refused. The judging half + // only — the system strips stay off. A row in the caller's own active + // organization needs no verdict, so the common write pays nothing. + if (operation === 'insert' || operation === 'update') { + const prior = opCtx.postHookWriteImageCheck; + opCtx.postHookWriteImageCheck = { + async evaluate(images: readonly Record[]) { + if (prior) { + prior.honoured = true; + await prior.evaluate(images); + } + const asks = images.some( + (row) => + (namesOrganization(row) && String(row[ORGANIZATION_FIELD]) !== ownOrganization) || + (operation === 'update' && emptiesOrganization(row)), + ); + if (!asks) return; + const admitted = admittedOrganizations((await judge()).answer.tenantLayer0Verdict); + if (!admitted) return; + for (const row of images) { + if (namesOrganization(row) && !admitted.has(String(row[ORGANIZATION_FIELD]))) { + throw landingRefusal(caller.source, object, operation); + } + if (operation === 'update' && emptiesOrganization(row)) throw removalRefusal(caller.source, object, operation); + } + }, + }; + } + + // A tenant key a before-hook sets on the bag after this point is held to + // the wall as it is set: the organizations the verdict admits, or — where + // none is worked out — the caller's own active organization alone. + if (BAG_VERBS.has(operation) && opCtx.options && typeof opCtx.options === 'object') { + holdBagTenantKeys( + opCtx.options as Record, + !isWrite, + () => (judgedAdmitted !== null ? judgedAdmitted : new Set(ownOrganization !== undefined ? [ownOrganization] : [])), + () => bagRefusal(caller.source, object, operation), + ); + } + // Judged by the wall's own verdict: a federated object, a decided segment - // (judged by its run's caller), and a write whose own data names or empties - // the organization. - const alwaysAsked = deps.isFederated(object) || caller.decided === true || touchesOrganization; + // (judged by its run's caller), a write whose own data names or empties + // the organization, and an option bag that sets a tenant key. + const alwaysAsked = deps.isFederated(object) || caller.decided === true || touchesOrganization || bagAsk !== undefined; if (!alwaysAsked && !callerMayLackOrganization(caller.callerContext)) return; - // The door's facts, resolved for the caller where the context does not - // carry them (a flow run's envelope carries no permission sets), and the - // question asked again: a resolved active membership may answer it. - const callerContext = carriesDoorFacts(caller.callerContext) - ? caller.callerContext - : await deps.completeCaller(caller.callerContext); + // …and the question asked again: a resolved active membership may answer it. + const { callerContext, answer } = await judge(); if (!alwaysAsked && !callerMayLackOrganization(callerContext)) return; - const answer = await deps.callerLayer0(callerContext, object, operation); const { tenantLayer0Verdict, crossedByPlatformAdmin } = answer; // A deny verdict's projection is the deny sentinel, never "no wall". const layer0 = tenantLayer0Verdict.kind === 'deny' ? (answer.layer0 ?? RLS_DENY_FILTER) : answer.layer0; const denied = tenantLayer0Verdict.kind === 'deny'; + judgedAdmitted = admittedOrganizations(tenantLayer0Verdict); + // A write whose bag reaches past the caller's wall is refused. A denied + // caller's delete and purge keep the read rule below (they match nothing); + // a read's bag is bounded by the wall composed onto its predicate below. + if (bagAsk && isWrite && !(denied && verb === REMOVAL) && bagReachesPast(bagAsk, judgedAdmitted)) { + throw bagRefusal(caller.source, object, operation); + } // [ADR-0123 D2] A denied caller's delete and purge are answered by the read // rule, as its plain door answers them: the wall's deny filter goes onto a // predicate delete (it matches nothing), and a by-id delete answers as a From 5b82319bb4b2d34d4dc8a748daf37c84b341d1df Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:31:24 +0000 Subject: [PATCH 03/18] docs(permissions): the register row states the stored-image and option-bag halves of the elevation's organization wall Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- .changeset/sec2-wf9p-f12.md | 25 +++++++++++++++++++++ content/docs/permissions/system-context.mdx | 2 +- 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 .changeset/sec2-wf9p-f12.md diff --git a/.changeset/sec2-wf9p-f12.md b/.changeset/sec2-wf9p-f12.md new file mode 100644 index 00000000000..4ba8de3befb --- /dev/null +++ b/.changeset/sec2-wf9p-f12.md @@ -0,0 +1,25 @@ +--- +'@objectstack/plugin-security': patch +--- + +fix(plugin-security)!: an elevation's write is judged as it will be stored, and its option bag never widens it past its caller's organization wall + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +The rule: an app-authored elevation (an action body, a hook that runs as system, a flow that runs as system) is held to its caller's organization wall on the row as it will be stored and on the tenant scope its option bag asks for, as the caller's plain door is (ADR-0095 D1, ADR-0123 D2). + +**BREAKING** for an action body, a system hook or a system flow run for a signed-in caller. + +- FROM: the organization a write's before-hooks left on the row, and the `tenantId` / `tenantIds` an operation's option bag named, were not judged against the caller's organization wall. +- TO: + - a write is judged again on the rows its before-hooks leave: a row stored in an organization outside the caller's wall, or an update that leaves a row in no organization, is refused with `403 PERMISSION_DENIED`; + - a write (`update`, `delete`, `purge`) whose option bag names an organization outside the caller's wall, or clears `tenantId`, is refused with `403 PERMISSION_DENIED`; + - a read (`find`, `findOne`) whose option bag names or clears an organization scope is answered by the read rule: the caller's wall is composed onto its predicate, so it reads only rows the wall admits; + - a before-hook that sets `tenantId` or `tenantIds` on the option bag it is handed is held to the same rule as it sets it. + +**Not moved.** A caller with an active organization keeps exactly its reach: a before-hook that keeps the row in an organization the caller's wall admits, and an option bag that names one, behave as before. Objects outside tenancy, objects with no organization column, and a platform operator crossing the wall on an object whose posture permits it are answered as the caller's own requests answer them. System work that runs for no caller (a scheduled run, a platform plugin's own system context, the seeders) is unchanged, its option bag included. + +The fix for a body or hook: write only into organizations the caller may write in, and leave `tenantId` / `tenantIds` off the option bag, or name an organization the caller's wall admits. A row that must land in another organization is written by a member of that organization, through its own request. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 47686def9fe..4d71a6efbaa 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -101,7 +101,7 @@ bugs — it is the protection or the side effect that silently does not happen. |:--|:---|:---|:---|:---| | 1 | **The whole security middleware short-circuits** before any gate runs | plugin-security | Get: every CRUD/FLS/tenant/owner gate below skipped in one branch. Lose: every gate under it in this lane at once, down to and including the write-bypass row that widens the effective write scope to `org` (row 7) — this is the single largest behaviour on the page | `registerAuthzMiddleware` | | 1b | **App-authored automation's system context is REFUSED governed writes to the identity-assignment objects** — a flow run's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and an action body's; checked ahead of the middleware's short-circuit, beside the append-only refusal (`assertAppAutomationAppendOnlyWriteAllowed`) | plugin-security | Get: nothing — an insert, update, delete, transfer, restore or purge of `sys_user_position`, `sys_user_permission_set`, `sys_invitation` or `sys_member` from a context carrying `isSystem` and either a `flowRunId` (a `runAs: 'system'` flow's data nodes) or the app-automation elevation mark (`@objectstack/core`; set only by a hook's `runAs: 'system'` derivation, by the action body's execution-context builder and `ObjectRepository.execute`, and on the api of a hook bound through the hook binder, whose inherited system context and `sudo()` it marks), at any depth of their writes, is refused `PERMISSION_DENIED` before the short-circuit skips the ADR-0090 D12 gate and the identity write guard. The platform's own system api (`platformSystemApi`, objectql) takes the mark and `flowRunId` off a platform hook's api, for the audit writer's own ledger rows. On an app-authored hook's api, on the api an action door hands its handler (a host code action handler's included) and on the api `ObjectRepository.execute` hands the action it dispatches (`ctx.api.object(o).execute(name)`), and on every api derived from any of them, it answers what that api's `sudo()` answers, mark kept, so this refusal, and the action body's owner stamp in the next row, hold through it too. Lose: nothing a platform writer held — a system context with neither (the seeders, better-auth and its reconciliation, invitation placement, platform code's `sudo()`, which never sets the mark, and a hook registered in code) passes on to the short-circuit unchanged, reads are not judged, and a `runAs: 'user'` flow or hook carries no `isSystem`, so the D12 gate judges it as the user it acts for | `elevationSource`, `appAuthoredHookApi` | -| 1c | **App-authored automation's system context meets its caller's organization wall** — an action body's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and a flow run's, read by the same predicate as the identity refusal above (`applyAppAutomationOrganizationWall`, plugin-security); checked ahead of the middleware's short-circuit | plugin-security | Get: its reads and writes are judged by the organization wall of the caller it runs for, under every posture and on every object. Such a context that carries a caller (a `userId`, or the guest entry's envelope) is judged by the caller's own Layer 0 (ADR-0095 D1), computed over the caller's own context and permission sets (resolved for the caller where the context does not carry them, as a flow run's does not). An insert with no active organization on a walled tenant object is refused (`403 PERMISSION_DENIED`); for every such caller, one with an active organization included, a write whose own data names an organization outside its scope or empties a row's organization is refused (`403 PERMISSION_DENIED`); on a federated object its reads are those of the caller's organization scope and a by-id write of a row outside it answers `404 RECORD_NOT_FOUND`, the check read inside the transaction the write carries. A caller the wall denies — no active organization under `isolated`, an empty membership set under `group`, no membership under `single` — reads nothing of a tenant-scoped object, and its delete and purge are answered by that read rule as its plain door answers them (ADR-0123 D2): a predicate delete matches nothing and a by-id delete answers `404 RECORD_NOT_FOUND`. Every other write is refused `PERMISSION_DENIED` (403), naming what is missing (ADR-0123 D4). A system flow run whose own user is its caller carries that user's membership set and posture rung from run setup (a decided segment, a run that began for no caller and a child run of either carry neither); the wall asks Layer 0 alone and resolves what a context lacks once per run. Lose: nothing the caller held — a caller with an active organization keeps its organization's reach (the union of its memberships under `group`); objects outside tenancy, objects with no organization column and a platform operator crossing the wall on a posture-permitting object answer as the caller's plain door answers them. An elevation that carries no caller (a scheduled run, a record-change run fired by a write that carried no user), a system flow that began for no caller in every segment (after an approval decision too, `runCallerOf`, core) and a run a write of such a segment starts, and every platform system context are unchanged | `elevationSource` | +| 1c | **App-authored automation's system context meets its caller's organization wall** — an action body's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and a flow run's, read by the same predicate as the identity refusal above (`applyAppAutomationOrganizationWall`, plugin-security); checked ahead of the middleware's short-circuit | plugin-security | Get: its reads and writes are judged by the organization wall of the caller it runs for, under every posture and on every object. Such a context that carries a caller (a `userId`, or the guest entry's envelope) is judged by the caller's own Layer 0 (ADR-0095 D1), computed over the caller's own context and permission sets (resolved for the caller where the context does not carry them, as a flow run's does not). An insert with no active organization on a walled tenant object is refused (`403 PERMISSION_DENIED`); for every such caller, one with an active organization included, a write whose own data names an organization outside its scope or empties a row's organization is refused (`403 PERMISSION_DENIED`); a write is judged again on the rows its before-hooks leave, by the same rule, as the plain door judges it; the option bag's `tenantId` / `tenantIds` never widen it past the caller's wall — a write whose bag names an organization outside it, or clears the key, is refused (`403 PERMISSION_DENIED`), and a read whose bag does is answered by the read rule, the caller's wall composed onto its predicate; on a federated object its reads are those of the caller's organization scope and a by-id write of a row outside it answers `404 RECORD_NOT_FOUND`, the check read inside the transaction the write carries. A caller the wall denies — no active organization under `isolated`, an empty membership set under `group`, no membership under `single` — reads nothing of a tenant-scoped object, and its delete and purge are answered by that read rule as its plain door answers them (ADR-0123 D2): a predicate delete matches nothing and a by-id delete answers `404 RECORD_NOT_FOUND`. Every other write is refused `PERMISSION_DENIED` (403), naming what is missing (ADR-0123 D4). A system flow run whose own user is its caller carries that user's membership set and posture rung from run setup (a decided segment, a run that began for no caller and a child run of either carry neither); the wall asks Layer 0 alone and resolves what a context lacks once per run. Lose: nothing the caller held — a caller with an active organization keeps its organization's reach (the union of its memberships under `group`); objects outside tenancy, objects with no organization column and a platform operator crossing the wall on a posture-permitting object answer as the caller's plain door answers them. An elevation that carries no caller (a scheduled run, a record-change run fired by a write that carried no user), a system flow that began for no caller in every segment (after an approval decision too, `runCallerOf`, core) and a run a write of such a segment starts, and every platform system context are unchanged | `elevationSource` | | 2 | **`owner_id` is not auto-stamped on INSERT** (the step 3.5 anchor guard is inside the block row 1 skips) — except an action body's insert | plugin-security | Lose: the row lands `owner_id = NULL`, so the default `owner_only_writes` policy hides it **from its own creator**. Get: nothing — this is a gap, not a capability. Except an action body's: an insert from a context carrying `isSystem` and the `'action'` app-automation elevation mark, with no `flowRunId`, has every EMPTY `owner_id` stamped with the envelope's own `userId` ahead of the short-circuit, by the same stamp step 3.5 applies (nothing for the guest; an owner the body sets is kept; an `owner_id` supplied empty beside a supplied queue parks the row). Like a direct create, such an insert is the invoker's own record, so assignment rules (ADR-0142 D5), which route only a row whose owner and queue are both still empty, route neither; a body has no spelling today that asks a rule to route its row. The mark is set on every handler an action door dispatches (a host code action handler included) and by `ObjectRepository.execute`. A flow run, a hook's `runAs: 'system'`, the seeders and every other system context still land the owner they write, or none, and an unowned, queue-less one is still routed | the step 3.5 guard block and the short-circuit that skips it are both inside `registerAuthzMiddleware`; the action-body exception is `isActionBodyElevation` | | 3 | Row-level read filter resolves to "no filter" | plugin-security | Get: unscoped reads. Lose: row-level scoping entirely | `getReadFilter` | | 4 | Field-level security returns **all** fields | plugin-security | Get: every column readable (`getReadableFields`) and writable (`getWritableFields`), and every field a disabled package withholds named to it (`getMetadataReadableWithheldFields`, so the served object's `_withheldFields` keeps every entry). Lose: field masking | `resolveProjectionFieldMask`, `computeMetadataReadableWithheldFields` | From 8a33f787e5f506411bc1c6c37d5abd07100f0d4c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 10:40:15 +0000 Subject: [PATCH 04/18] test(plugin-security): the option-bag write pin's fixture carries only its declared keys Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- .../src/app-automation-organization-wall.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/plugins/plugin-security/src/app-automation-organization-wall.test.ts b/packages/plugins/plugin-security/src/app-automation-organization-wall.test.ts index 7e7ee607380..4af88fed72e 100644 --- a/packages/plugins/plugin-security/src/app-automation-organization-wall.test.ts +++ b/packages/plugins/plugin-security/src/app-automation-organization-wall.test.ts @@ -399,7 +399,7 @@ describe('an app-authored elevation is judged by its caller’s organization wal for (const operation of ['update', 'delete', 'purge']) { for (const options of [{ tenantId: 'org_b' }, { tenantIds: ['org_a', 'org_b'] }, { tenantId: null }]) { const e = await refusalOf(() => - applyAppAutomationOrganizationWall({ object: 'task', operation, context: member(), options, ast: { object: 'task' } }, depsFor(ORG_A)), + applyAppAutomationOrganizationWall({ object: 'task', operation, context: member(), options, ast: {} }, depsFor(ORG_A)), ); expect([e.code, e.status]).toEqual(['PERMISSION_DENIED', 403]); } From 32a4592075cd1081e1f6dcd1faee843ae03310cb Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 13:35:40 +0000 Subject: [PATCH 05/18] test(organizations): pin a hook-returned, replaced or redefined option bag on an elevated insert, read and write to the caller's wall Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- ...ated-organization-wall.writes.wall.test.ts | 131 ++++++++++++++++++ 1 file changed, 131 insertions(+) diff --git a/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts b/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts index b71de8978dd..318d0865ab9 100644 --- a/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts +++ b/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts @@ -54,6 +54,18 @@ const BODY_BAG_CLEAR_FIND = "const rows = await ctx.api.object('eoww_task').find({ where: {}, tenantId: null }); return { seen: rows.map((r) => r.name).sort() };"; const BODY_BAG_CLEAR_UPDATE = "await ctx.api.object('eoww_task').update({ touched: 'bag' }, { where: { name: input.name }, multi: true, tenantId: '' }); return { wrote: 1 };"; +// A read whose `where` carries, as its fourth `$in` member, the organization a +// sandboxed before-hook then hands back as the bag's tenant scope. +const BODY_BAG_HOOK_READ = + "const rows = await ctx.api.object('eoww_task').find({ where: { name: { $in: ['A1', 'B1', 'O1', input.org] } } }); return { seen: rows.map((r) => r.name).sort() };"; +// A sandboxed before-hook that hands back an option bag naming a tenant scope: +// on an insert, the one the row's `bagorg` names; on a read, the fourth member +// of the `where`'s `name.$in`. +const HOOK_BAG_SOURCE = + "if (ctx.input && typeof ctx.input.bagorg === 'string' && ctx.input.bagorg !== '') return { options: { tenantId: ctx.input.bagorg } };" + + 'const w = ctx.inputOptions && ctx.inputOptions.where;' + + 'const list = w && w.name && w.name.$in;' + + 'if (Array.isArray(list) && list.length === 4) return { options: { tenantId: list[3] } };'; const BODY_BAG_DELETE = "await ctx.api.object('eoww_task').delete({ where: { name: input.name }, multi: true, tenantId: input.org }); return { removed: 1 };"; @@ -69,6 +81,8 @@ const APP = { name: { type: 'text', label: 'Name' }, touched: { type: 'text', label: 'Touched' }, hint: { type: 'text', label: 'Hint' }, + bagorg: { type: 'text', label: 'Bag organization' }, + reporg: { type: 'text', label: 'Replaced bag organization' }, }, }, ], @@ -96,6 +110,10 @@ const APP = { { name: 'eoww_hooked_sweep', label: 'Hooked sweep', objectName: TASK, type: 'script', target: 'eowwHookedSweep' }, { name: 'eoww_late_bag', label: 'Late bag', objectName: TASK, type: 'script', target: 'eowwLateBag' }, { name: 'eoww_late_read', label: 'Late read', objectName: TASK, type: 'script', target: 'eowwLateRead' }, + { name: 'eoww_bag_land', label: 'Bag land', objectName: TASK, type: 'script', target: 'eowwBagLand' }, + { name: 'eoww_replaced_land', label: 'Replaced land', objectName: TASK, type: 'script', target: 'eowwReplacedLand' }, + { name: 'eoww_replaced_read', label: 'Replaced read', objectName: TASK, type: 'script', target: 'eowwReplacedRead' }, + { name: 'eoww_redefined_bag', label: 'Redefined bag', objectName: TASK, type: 'script', target: 'eowwRedefinedBag' }, ...( [ ['eoww_bag_find', BODY_BAG_FIND], @@ -105,6 +123,7 @@ const APP = { ['eoww_bag_delete', BODY_BAG_DELETE], ['eoww_bag_clear_find', BODY_BAG_CLEAR_FIND], ['eoww_bag_clear_update', BODY_BAG_CLEAR_UPDATE], + ['eoww_bag_hook_read', BODY_BAG_HOOK_READ], ] as const ).map(([name, source]) => ({ name, @@ -116,6 +135,19 @@ const APP = { ], }; +Object.assign(APP, { + hooks: [ + { + name: 'eoww_bag_hook', + label: 'Bag hook', + object: TASK, + events: ['beforeInsert', 'beforeFind'], + body: { language: 'js', source: HOOK_BAG_SOURCE, capabilities: [] }, + onError: 'abort', + }, + ], +}); + const SYS = { context: { isSystem: true } } as const; describe('an app-authored elevation’s writes are judged by its caller’s organization wall', () => { @@ -197,6 +229,64 @@ describe('an app-authored elevation’s writes are judged by its caller’s orga }, { object: TASK }, ); + // In-process before-hooks that REPLACE the option bag they are handed: on + // an insert with the scope the row's `reporg` names, and on a read with the + // scope the next handler names. + ql.registerHook( + 'beforeInsert', + async (ctx: any) => { + const org = ctx.input?.data?.reporg; + if (typeof org === 'string' && org !== '') ctx.input.options = { ...(ctx.input.options ?? {}), tenantId: org }; + }, + { object: TASK }, + ); + let replacedReadOrg: string | undefined; + ql.registerHook( + 'beforeFind', + async (ctx: any) => { + if (replacedReadOrg !== undefined) ctx.input.options = { ...(ctx.input.options ?? {}), tenantId: replacedReadOrg }; + }, + { object: TASK }, + ); + // An in-process before-hook that REDEFINES the bag's tenant key. + ql.registerHook( + 'beforeUpdate', + async (ctx: any) => { + const touched = ctx.input?.data?.touched; + if (typeof touched === 'string' && touched.startsWith('redef:') && ctx.input.options) { + Object.defineProperty(ctx.input.options, 'tenantId', { + value: touched.slice('redef:'.length), + enumerable: true, + configurable: true, + writable: true, + }); + } + }, + { object: TASK }, + ); + ql.registerAction(TASK, 'eowwBagLand', async (ctx: any) => { + await ctx.engine.insert(TASK, { name: ctx.params?.name, bagorg: ctx.params?.org }); + return { landed: 1 }; + }); + ql.registerAction(TASK, 'eowwReplacedLand', async (ctx: any) => { + await ctx.engine.insert(TASK, { name: ctx.params?.name, reporg: ctx.params?.org }); + return { landed: 1 }; + }); + ql.registerAction(TASK, 'eowwReplacedRead', async (ctx: any) => { + replacedReadOrg = String(ctx.params?.org); + try { + const rows = await ctx.api.object(TASK).find({ where: {} }); + return { seen: rows.map((r: any) => r.name).sort() }; + } finally { + replacedReadOrg = undefined; + } + }); + ql.registerAction(TASK, 'eowwRedefinedBag', async (ctx: any) => { + await ctx.api + .object(TASK) + .update({ touched: `redef:${String(ctx.params?.org)}` }, { where: { name: { $in: ['A1', ctx.params?.name] } }, multi: true }); + return { wrote: 1 }; + }); ql.registerAction(TASK, 'eowwHookedLand', async (ctx: any) => { await ctx.engine.insert(TASK, { name: ctx.params?.name, hint: ctx.params?.org }); return { landed: 1 }; @@ -430,6 +520,47 @@ describe('an app-authored elevation’s writes are judged by its caller’s orga expect(own.body.data).toEqual({ seen: ['A1'] }); }); + it('an insert whose before-hook hands back a bag naming another organization is refused 403', async () => { + await reseed(); + const sandboxed = await run(alice, 'eoww_bag_land', { name: 'BAG-LAND-B', org: orgB }); + expect(sandboxed.status, JSON.stringify(sandboxed.body)).toBe(403); + expect(sandboxed.body.error.code).toBe('PERMISSION_DENIED'); + expect(await rowNamed('BAG-LAND-B')).toBeUndefined(); + const replaced = await run(alice, 'eoww_replaced_land', { name: 'REP-LAND-B', org: orgB }); + expect(replaced.status, JSON.stringify(replaced.body)).toBe(403); + expect(replaced.body.error.code).toBe('PERMISSION_DENIED'); + expect(await rowNamed('REP-LAND-B')).toBeUndefined(); + }); + + it('control: an insert whose before-hook hands back the caller’s own organization lands there', async () => { + await reseed(); + const r = await run(alice, 'eoww_bag_land', { name: 'BAG-LAND-A', org: orgA }); + expect(r.status, JSON.stringify(r.body)).toBe(200); + expect((await rowNamed('BAG-LAND-A'))!.organization_id).toBe(orgA); + }); + + it('a read whose before-hook replaces the bag with another organization is answered by the read rule', async () => { + await reseed(); + const sandboxed = await run(alice, 'eoww_bag_hook_read', { org: orgB }); + expect(sandboxed.status, JSON.stringify(sandboxed.body)).toBe(200); + expect(sandboxed.body.data).toEqual({ seen: [] }); + const replaced = await run(alice, 'eoww_replaced_read', { org: orgB }); + expect(replaced.status, JSON.stringify(replaced.body)).toBe(200); + expect(replaced.body.data).toEqual({ seen: [] }); + const own = await run(alice, 'eoww_replaced_read', { org: orgA }); + expect(own.status, JSON.stringify(own.body)).toBe(200); + expect(own.body.data).toEqual({ seen: ['A1'] }); + }); + + it('a write whose before-hook redefines the bag’s tenant key is held to the wall too', async () => { + await reseed(); + const r = await run(alice, 'eoww_redefined_bag', { name: 'B1', org: orgB }); + expect(r.status, JSON.stringify(r.body)).toBe(403); + expect(r.body.error.code).toBe('PERMISSION_DENIED'); + expect((await rowNamed('B1'))!.touched ?? null).toBeNull(); + expect((await rowNamed('A1'))!.touched ?? null).toBeNull(); + }); + it('control: a bag naming the caller’s own organization reads and writes there', async () => { await reseed(); const read = await run(alice, 'eoww_bag_find', { org: orgA }); From e59ce7e0865ed3c617d1487ee13217b19a32c20d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 13:47:54 +0000 Subject: [PATCH 06/18] test(organizations): the hook-bag read pin drives the in-process replacement only Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- ...ated-organization-wall.writes.wall.test.ts | 20 ++++--------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts b/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts index 318d0865ab9..4862f577dff 100644 --- a/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts +++ b/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts @@ -54,18 +54,10 @@ const BODY_BAG_CLEAR_FIND = "const rows = await ctx.api.object('eoww_task').find({ where: {}, tenantId: null }); return { seen: rows.map((r) => r.name).sort() };"; const BODY_BAG_CLEAR_UPDATE = "await ctx.api.object('eoww_task').update({ touched: 'bag' }, { where: { name: input.name }, multi: true, tenantId: '' }); return { wrote: 1 };"; -// A read whose `where` carries, as its fourth `$in` member, the organization a -// sandboxed before-hook then hands back as the bag's tenant scope. -const BODY_BAG_HOOK_READ = - "const rows = await ctx.api.object('eoww_task').find({ where: { name: { $in: ['A1', 'B1', 'O1', input.org] } } }); return { seen: rows.map((r) => r.name).sort() };"; -// A sandboxed before-hook that hands back an option bag naming a tenant scope: -// on an insert, the one the row's `bagorg` names; on a read, the fourth member -// of the `where`'s `name.$in`. +// A sandboxed before-insert hook that hands back an option bag naming the +// tenant scope the row's `bagorg` names. const HOOK_BAG_SOURCE = - "if (ctx.input && typeof ctx.input.bagorg === 'string' && ctx.input.bagorg !== '') return { options: { tenantId: ctx.input.bagorg } };" + - 'const w = ctx.inputOptions && ctx.inputOptions.where;' + - 'const list = w && w.name && w.name.$in;' + - 'if (Array.isArray(list) && list.length === 4) return { options: { tenantId: list[3] } };'; + "if (ctx.input && typeof ctx.input.bagorg === 'string' && ctx.input.bagorg !== '') return { options: { tenantId: ctx.input.bagorg } };"; const BODY_BAG_DELETE = "await ctx.api.object('eoww_task').delete({ where: { name: input.name }, multi: true, tenantId: input.org }); return { removed: 1 };"; @@ -123,7 +115,6 @@ const APP = { ['eoww_bag_delete', BODY_BAG_DELETE], ['eoww_bag_clear_find', BODY_BAG_CLEAR_FIND], ['eoww_bag_clear_update', BODY_BAG_CLEAR_UPDATE], - ['eoww_bag_hook_read', BODY_BAG_HOOK_READ], ] as const ).map(([name, source]) => ({ name, @@ -141,7 +132,7 @@ Object.assign(APP, { name: 'eoww_bag_hook', label: 'Bag hook', object: TASK, - events: ['beforeInsert', 'beforeFind'], + events: ['beforeInsert'], body: { language: 'js', source: HOOK_BAG_SOURCE, capabilities: [] }, onError: 'abort', }, @@ -541,9 +532,6 @@ describe('an app-authored elevation’s writes are judged by its caller’s orga it('a read whose before-hook replaces the bag with another organization is answered by the read rule', async () => { await reseed(); - const sandboxed = await run(alice, 'eoww_bag_hook_read', { org: orgB }); - expect(sandboxed.status, JSON.stringify(sandboxed.body)).toBe(200); - expect(sandboxed.body.data).toEqual({ seen: [] }); const replaced = await run(alice, 'eoww_replaced_read', { org: orgB }); expect(replaced.status, JSON.stringify(replaced.body)).toBe(200); expect(replaced.body.data).toEqual({ seen: [] }); From 99c2476a7f452aee916fa5b3a44661428415610d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 13:52:17 +0000 Subject: [PATCH 07/18] fix(objectql,plugin-security): an elevation's driver tenant scope is judged where the engine builds it, after every before-hook Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- .../src/engine-delete-and-aggregate.ts | 10 +- .../src/engine-driver-options.test.ts | 45 ++++++++ .../objectql/src/engine-driver-options.ts | 14 ++- packages/objectql/src/engine-find.ts | 4 +- packages/objectql/src/engine-insert.ts | 12 +- packages/objectql/src/engine-top-level.ts | 28 +++++ packages/objectql/src/engine-update.ts | 6 +- packages/objectql/src/engine.ts | 9 +- .../app-automation-organization-wall.test.ts | 57 +++++---- .../src/app-automation-organization-wall.ts | 109 +++++++++--------- 10 files changed, 200 insertions(+), 94 deletions(-) diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 76bc9d881b6..73a8727d5da 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -410,7 +410,7 @@ export class DeleteAndAggregateFacet { const declaredDeleteColumns = declaredColumnSet(deleteSchema); const readPreImage = async (targetId: unknown): Promise | null> => { const preAst: QueryAST = { object, where: { id: targetId }, limit: 1 }; - const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); + const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict, tenantScopeCheck: opCtx.driverTenantScopeCheck }); return withDeclaredColumnsOnly( (await driver.findOne(object, preAst, preOpts)) as Record | null, declaredDeleteColumns, @@ -580,7 +580,7 @@ export class DeleteAndAggregateFacet { // rows: they are its scope check and its per-row realtime events. const cascadeBatch = referentialCascadeDelete === true; if (perRowBeforeHooks || perRowAfterHooks || cascadeBatch) { - const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); + const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict, tenantScopeCheck: opCtx.driverTenantScopeCheck }); // [#21613] Each doomed row is its per-row `previous`: declared set. const doomed = rowsWithDeclaredColumnsOnly( (await driver.find(object, ast, preOpts) as Record[]) ?? [], @@ -620,7 +620,7 @@ export class DeleteAndAggregateFacet { // Every driver call below is handed `driverOptions` — the declared driver // options and nothing else; `input.options` is the hooks' additive view. - const driverOptions = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); + const driverOptions = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict, tenantScopeCheck: opCtx.driverTenantScopeCheck }); hookContext.input.options = mergeDriverOptionsIntoHookView(hookContext.input.options, driverOptions); try { @@ -700,7 +700,7 @@ export class DeleteAndAggregateFacet { removed = await driver.delete( object, hookContext.input.id as string, - this.buildDriverOptions(object, writeContext, hookContext.input.options as any), + this.buildDriverOptions(object, writeContext, hookContext.input.options as any, { tenantScopeCheck: opCtx.driverTenantScopeCheck }), ); // Told only for a row the driver says it removed: `false` // (not found) and an off-contract count of 0 (kept) name no @@ -839,7 +839,7 @@ export class DeleteAndAggregateFacet { // (the `'split'` plan, a driver with no transactions), reads // unlocked and keeps that window (`DriverCapabilities.lockRows`). const runPredicateDelete = async (writeContext?: ExecutionContext): Promise => { - const writeOptions = this.buildDriverOptions(object, writeContext, hookContext.input.options as any); + const writeOptions = this.buildDriverOptions(object, writeContext, hookContext.input.options as any, { tenantScopeCheck: opCtx.driverTenantScopeCheck }); const readOptions = writeOptions?.transaction != null && driver.supports?.lockRows === true ? { ...writeOptions, lockRows: true } : writeOptions; diff --git a/packages/objectql/src/engine-driver-options.test.ts b/packages/objectql/src/engine-driver-options.test.ts index ca91341640e..718d3407637 100644 --- a/packages/objectql/src/engine-driver-options.test.ts +++ b/packages/objectql/src/engine-driver-options.test.ts @@ -250,3 +250,48 @@ describe('the after* hook view of input.options stays additive', () => { expect(mergeDriverOptionsIntoHookView(bag, undefined)).toBe(bag); }); }); + +describe('an operation’s driver tenant-scope check judges the bag the driver is built from', () => { + const VERBS = ['find', 'findOne', 'insert', 'update', 'delete'] as const; + + async function driveWithReplacedBags(withCheck: boolean) { + const { engine, received } = await makeEngine(); + const asked: unknown[] = []; + if (withCheck) { + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + opCtx.driverTenantScopeCheck = { + judge: (keys: Record) => { + asked.push(keys.tenantId); + return { tenantId: ORG }; + }, + }; + await next(); + }); + } + // Every before-hook REPLACES the bag it is handed with one naming another organization. + for (const event of ['beforeFind', 'beforeInsert', 'beforeUpdate', 'beforeDelete']) { + engine.registerHook(event as any, async (ctx: any) => { + ctx.input.options = { ...(ctx.input.options ?? {}), tenantId: 'org_other' }; + }, { object: 'dopt_task' }); + } + await driveEveryVerb(engine); + return { received, asked }; + } + + it('a bag a before-hook replaced is judged, and the driver is handed what the check answers', async () => { + const { received, asked } = await driveWithReplacedBags(true); + for (const method of ['find', 'findOne', 'update', 'updateMany', 'deleteMany']) { + for (const call of received.filter((c) => c.method === method)) expect(call.options!.tenantId, method).toBe(ORG); + } + const insert = received.find((c) => c.method === 'bulkCreate' || c.method === 'create'); + expect(insert!.options!.tenantId).toBe(ORG); + expect(asked.length).toBeGreaterThanOrEqual(VERBS.length); + expect(asked).toContain('org_other'); + }); + + it('control: with no check on the operation, the replaced bag’s explicit key reaches the driver', async () => { + const { received } = await driveWithReplacedBags(false); + const find = received.find((c) => c.method === 'find'); + expect(find!.options!.tenantId).toBe('org_other'); + }); +}); diff --git a/packages/objectql/src/engine-driver-options.ts b/packages/objectql/src/engine-driver-options.ts index f33f15093c6..c77e80b63f7 100644 --- a/packages/objectql/src/engine-driver-options.ts +++ b/packages/objectql/src/engine-driver-options.ts @@ -83,6 +83,7 @@ import { import { isFederatedObject } from './federated-object.js'; import { LockRowsRefusedError } from './lock-rows-refusal-error.js'; import type { ObjectQL } from './engine.js'; +import type { DriverTenantScopeCheck } from './engine-top-level.js'; /** * The `ObjectQL` members the functions below read — every one of them, and no @@ -293,7 +294,7 @@ export function buildDriverOptions( object: string, execCtx?: ExecutionContext, base?: any, - scope: { writeTarget?: boolean; recordedVerdict?: unknown } = {}, + scope: { writeTarget?: boolean; recordedVerdict?: unknown; tenantScopeCheck?: DriverTenantScopeCheck } = {}, ): any { // The open transaction may arrive explicitly via the context, or ambiently // via txStore when an internal query runs during a transactional write @@ -358,6 +359,17 @@ export function buildDriverOptions( // `bypassTenantAudit` / `transaction` still win below), never the rest of // the bag it rode in on. See {@link pickDeclaredDriverOptions}. const declared = pickDeclaredDriverOptions(base); + // [ADR-0095 D1] An explicit tenant key is the caller's intent and wins below, + // so where the operation carries a bound on it (an enforcement layer's + // {@link OperationContext.driverTenantScopeCheck}), the bound judges the keys + // the bag carries NOW — after every before-hook, whatever bag it left. + if (scope.tenantScopeCheck && declared && (declared.tenantId !== undefined || declared.tenantIds !== undefined)) { + const judged = scope.tenantScopeCheck.judge({ tenantId: declared.tenantId, tenantIds: declared.tenantIds }); + delete declared.tenantId; + delete declared.tenantIds; + if (judged.tenantId !== undefined) declared.tenantId = judged.tenantId; + if (judged.tenantIds !== undefined) declared.tenantIds = judged.tenantIds; + } // [#34373] A caller's `lockRows` is a promise it will act on, so it reaches a // driver only where it holds: the object's driver declares // `supports.lockRows`, and a transaction reaches that driver for the call diff --git a/packages/objectql/src/engine-find.ts b/packages/objectql/src/engine-find.ts index 9735ceaa8be..65078c96e21 100644 --- a/packages/objectql/src/engine-find.ts +++ b/packages/objectql/src/engine-find.ts @@ -611,7 +611,7 @@ export class FindFacet { await this.triggerHooks('beforeFind', hookContext); // The driver is handed `driverOptions` — the declared driver options and // nothing else; `input.options` stays the hooks' additive view of the bag. - const driverOptions = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); + const driverOptions = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict, tenantScopeCheck: opCtx.driverTenantScopeCheck }); hookContext.input.options = mergeDriverOptionsIntoHookView(hookContext.input.options, driverOptions); // [ADR-0139 D2] The executor boundary: the AST is final here — after the // doors, the middleware chain and `beforeFind` — so every `ReadableIds` @@ -929,7 +929,7 @@ export class FindFacet { }; await this.triggerHooks('beforeFind', hookContext); // The driver is handed `driverOptions` alone, as in `find`. - const driverOptions = this.buildDriverOptions(objectName, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); + const driverOptions = this.buildDriverOptions(objectName, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict, tenantScopeCheck: opCtx.driverTenantScopeCheck }); hookContext.input.options = mergeDriverOptionsIntoHookView(hookContext.input.options, driverOptions); // [ADR-0139 D2] The executor boundary, as in `find`. const driverAst = await this.composeReadableIdsAtBoundary(objectName, 'findOne', hookContext.input.ast as QueryAST, opCtx.context, driverOptions); diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index 2bf18247089..c0abb8e5e91 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -77,7 +77,7 @@ import { callerInputRefusalLogMeta, writeFailureLogMeta, } from './engine-top-level.js'; import type { - AutonumberReaders, IssuedAutonumber, OperationContext, PermissionResolution, StoredExpressionServing, + AutonumberReaders, DriverTenantScopeCheck, IssuedAutonumber, OperationContext, PermissionResolution, StoredExpressionServing, } from './engine-top-level.js'; import { ObjectQLStatics as ObjectQL } from './engine.js'; import type { InsertManyRowOutcome, ObjectQL as ObjectQLClass } from './engine.js'; @@ -318,9 +318,9 @@ export class InsertFacet { } /** The body of `ObjectQL#readUpdatePriorRow`; the method's docblock there is its contract. */ - static async readUpdatePriorRow(this: Pick, object: string, id: unknown, context: ExecutionContext | undefined, base?: unknown): Promise | null> { + static async readUpdatePriorRow(this: Pick, object: string, id: unknown, context: ExecutionContext | undefined, base?: unknown, tenantScopeCheck?: DriverTenantScopeCheck): Promise | null> { const priorAst: QueryAST = { object, where: { id }, limit: 1 } as QueryAST; - const preOpts = this.buildDriverOptions(object, context, base as any); + const preOpts = this.buildDriverOptions(object, context, base as any, { tenantScopeCheck }); return withDeclaredColumnsOnly( await this.getDriver(object).findOne(object, priorAst, preOpts) as Record | null, declaredColumnSet(this._registry.getObject(object)), @@ -1137,8 +1137,10 @@ export class InsertFacet { ? { ...(optionsBase && typeof optionsBase === 'object' ? optionsBase : {}), tenantId: derivedOrganizationId } : optionsBase, // The active organization is where the row LANDS, in every posture — - // not a read scope (ADR-0131 D8 leaves the write target alone). - { writeTarget: true }, + // not a read scope (ADR-0131 D8 leaves the write target alone). The + // bag a before-hook left is judged where it names the landing; the + // organization the engine derives itself is not the bag's. + { writeTarget: true, ...(derivedOrganizationId === undefined ? { tenantScopeCheck: opCtx.driverTenantScopeCheck } : {}) }, ); // Every driver call below is handed `driverOptions` — the declared driver // options and nothing else; the hooks keep their additive view of the bag. diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index 55c758d47e1..3a237382049 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -4173,6 +4173,22 @@ export interface OperationContext { * a value that does not parse reads as absent, never as an organization. */ tenantLayer0Verdict?: TenantLayer0Verdict; + /** + * [ADR-0095 D1] The bound on the driver's tenant scope that an explicit + * `tenantId` / `tenantIds` in this operation's option bag may ask for. An + * explicit key wins the driver's scope under every verdict (see + * `buildDriverOptions`), and a before-hook can set, replace or hand back + * the bag after every middleware has run; so the engine applies this check + * itself, at every driver bag it builds for the operation, to the keys the + * bag carries at that moment. + * + * Set by an enforcement layer's middleware, and only by it: the security + * plugin sets it for an app-authored elevation that runs for a caller, so + * the elevation's driver scope never reaches past that caller's + * organization wall. ABSENT is the ordinary state, and the engine never + * invents one. + */ + driverTenantScopeCheck?: DriverTenantScopeCheck; /** * [commit a016f08b8] The INSERT post-image seam — where an enforcement layer gets to * judge the row that will actually be stored. @@ -4250,6 +4266,18 @@ export interface OperationContext { * way out knows its check did not happen, and says so loudly rather than * reading an unjudged write as an allowed one. */ +/** + * [ADR-0095 D1] The judgement {@link OperationContext.driverTenantScopeCheck} + * carries. `judge` receives the tenant keys the option bag carries when the + * engine builds a driver bag for the operation (called only when the bag + * carries at least one of them), and answers the keys the driver is to be + * handed in their place: the same, narrowed, or `undefined` for a key the + * operation's own scope is to fill. It refuses by throwing. + */ +export interface DriverTenantScopeCheck { + judge(asked: { tenantId?: unknown; tenantIds?: unknown }): { tenantId?: unknown; tenantIds?: unknown }; +} + export interface PostHookWriteImageCheck { evaluate(rows: readonly Record[]): void | Promise; honoured?: boolean; diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 378b4f0d01f..a3e6432fb8a 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -901,7 +901,7 @@ export class UpdateFacet { // [#22445] Through {@link readUpdatePriorRow}, the ONE spelling of // this read, which the `update`-mode preview reads its stored row // with too — so the preview and this write judge one image. - priorRecord = await this.readUpdatePriorRow(object, id, opCtx.context, hookContext.input.options); + priorRecord = await this.readUpdatePriorRow(object, id, opCtx.context, hookContext.input.options, opCtx.driverTenantScopeCheck); // ── [#7867] The not-found gate ────────────────────────────────── // // A by-id update whose id names no row was a SILENT NO-OP that @@ -1040,7 +1040,7 @@ export class UpdateFacet { await dispatchHooksExplainingWithheldReadonly(readonlyHiddenFromHooks, 'beforeUpdate', () => this.dispatchUnscopedMultiWriteHooks('beforeUpdate', object, hookContext)); } - const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); + const preOpts = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict, tenantScopeCheck: opCtx.driverTenantScopeCheck }); readPriorRows = async () => { if (!priorRowsRead) { priorRowsRead = true; @@ -1220,7 +1220,7 @@ export class UpdateFacet { // Every driver call below is handed `driverOptions` — the declared driver // options and nothing else; `input.options` is the hooks' additive view. - const driverOptions = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict }); + const driverOptions = this.buildDriverOptions(object, opCtx.context, hookContext.input.options as any, { recordedVerdict: opCtx.tenantLayer0Verdict, tenantScopeCheck: opCtx.driverTenantScopeCheck }); hookContext.input.options = mergeDriverOptionsIntoHookView(hookContext.input.options, driverOptions); // [#27495] The credential rows this write seals, the ones it has written // to `sys_secret`, and the handles its committed statement moved the diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 8b26cf65a68..b255beec965 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -297,7 +297,7 @@ import { planStoredExpressions, } from './engine-top-level.js'; import type { - AdmittedValueShapeViolationTally, AutonumberReaders, CascadeDeleteSet, CascadeIssuedDelete, DatasourceDef, + AdmittedValueShapeViolationTally, AutonumberReaders, CascadeDeleteSet, CascadeIssuedDelete, DatasourceDef, DriverTenantScopeCheck, EngineMiddleware, EngineMiddlewareEntry, EngineMiddlewareOptions, EngineReadOptions, FieldOwnedFileReadAuthorizer, FormulaFaultSink, FormulaPlanEntry, FormulaRelated, FunctionEntry, FunctionRegistrationOptions, HeldFileResolver, HookEntry, HookHandler, @@ -310,7 +310,7 @@ export { ENGINE_OPTION_KEY_SETS, ENGINE_WHERE_SLOTS, type EngineMiddleware, type EngineReadOptions, type FieldOwnedFileReadAuthorizer, type FormulaPlanEntry, type FunctionEntry, type FunctionRegistrationOptions, HOOK_EVENT_DISPATCH_VOCABULARY, type HeldFileResolver, type HookEntry, type HookHandler, type MigrationFlagRead, - type OperationContext, type PermissionResolution, type PostHookWriteImageCheck, type ReadableIdsChain, + type OperationContext, type PermissionResolution, type PostHookWriteImageCheck, type DriverTenantScopeCheck, type ReadableIdsChain, type ReadableIdsSecurity, SECURITY_SERVICE_SOURCE_SLOT, type UnservableControlledByParentMaster, type WriteWallRowVerdict, type WriteWallVerdict, assembledViewItemRefusal, cascadeMemberKey, cascadeSetAdd, cascadeSetHas, collectionItemOwnerStampRefusal, declaredDatetimeLowering, declaredMultiValued, droppedFieldEvents, @@ -1958,7 +1958,7 @@ export class ObjectQL implements IObjectQLEngine { object: string, execCtx?: ExecutionContext, base?: any, - scope: { writeTarget?: boolean; recordedVerdict?: unknown } = {}, + scope: { writeTarget?: boolean; recordedVerdict?: unknown; tenantScopeCheck?: DriverTenantScopeCheck } = {}, ): any { // [#25522 cut 12] The body moved to `engine-driver-options.ts`, its docblock with it (see `DriverOptionsHost`). const readTxStore = () => this.txStore; @@ -4752,9 +4752,10 @@ export class ObjectQL implements IObjectQLEngine { id: unknown, context: ExecutionContext | undefined, base?: unknown, + tenantScopeCheck?: DriverTenantScopeCheck, ): Promise | null> { // [#29986 codemod] The body moved to `engine-insert.ts` (see `InsertHost`). - return InsertFacet.readUpdatePriorRow.call(insertHost.of(this), object, id, context, base); + return InsertFacet.readUpdatePriorRow.call(insertHost.of(this), object, id, context, base, tenantScopeCheck); } /** diff --git a/packages/plugins/plugin-security/src/app-automation-organization-wall.test.ts b/packages/plugins/plugin-security/src/app-automation-organization-wall.test.ts index 4af88fed72e..5b4d7a3ce7f 100644 --- a/packages/plugins/plugin-security/src/app-automation-organization-wall.test.ts +++ b/packages/plugins/plugin-security/src/app-automation-organization-wall.test.ts @@ -412,31 +412,47 @@ describe('an app-authored elevation is judged by its caller’s organization wal expect(opCtx.ast.where).toBe(RLS_DENY_FILTER); }); - it('a key a before-hook sets later is held as it is set', async () => { - const write: any = { object: 'task', operation: 'update', context: member(), options: {}, ast: { object: 'task' } }; - await applyAppAutomationOrganizationWall(write, depsFor(ORG_A)); - expect(() => { - write.options.tenantId = 'org_b'; - }).toThrow(/organization/); - expect(() => { - write.options.tenantId = null; - }).toThrow(/organization/); - write.options.tenantId = 'org_a'; - expect(write.options.tenantId).toBe('org_a'); + it('the bag the engine builds the driver’s options from is judged there: a write’s past the wall is refused', async () => { + for (const operation of ['insert', 'update', 'delete', 'purge']) { + const write: any = { object: 'task', operation, context: member(), options: {}, data: { name: 'x' }, ast: { object: 'task' } }; + await applyAppAutomationOrganizationWall(write, depsFor(ORG_A)); + const check = write.driverTenantScopeCheck; + for (const asked of [{ tenantId: 'org_b' }, { tenantId: null }, { tenantIds: ['org_a', 'org_b'] }]) { + const e = await refusalOf(async () => check.judge(asked)); + expect([e.code, e.status]).toEqual(['PERMISSION_DENIED', 403]); + } + expect(check.judge({ tenantId: 'org_a' })).toEqual({ tenantId: 'org_a' }); + } + }); + + it('a read’s bag past the wall is narrowed to it there; a cleared key is left to the operation’s own scope', async () => { const read: any = { object: 'task', operation: 'find', context: member(), options: {}, ast: { object: 'task' } }; await applyAppAutomationOrganizationWall(read, depsFor(ORG_A)); - read.options.tenantId = 'org_b'; - expect(read.options.tenantId).toBe(RLS_DENY_FILTER.id); - read.options.tenantIds = ['org_a', 'org_b']; - expect(read.options.tenantIds).toEqual(['org_a']); + const check = read.driverTenantScopeCheck; + expect(check.judge({ tenantId: 'org_b' })).toEqual({ tenantId: RLS_DENY_FILTER.id, tenantIds: undefined }); + expect(check.judge({ tenantIds: ['org_a', 'org_b'] })).toEqual({ tenantId: undefined, tenantIds: ['org_a'] }); + expect(check.judge({ tenantIds: ['org_b'] })).toEqual({ tenantId: undefined, tenantIds: [RLS_DENY_FILTER.id] }); + expect(check.judge({ tenantId: null })).toEqual({ tenantId: undefined, tenantIds: undefined }); + expect(check.judge({ tenantId: 'org_a' })).toEqual({ tenantId: 'org_a' }); + }); + + it('where the verdict is worked out, the check judges by it: a union member’s bag inside the union passes', async () => { + const opCtx: any = { object: 'task', operation: 'update', context: member(), options: { tenantIds: ['org_a'] }, ast: { object: 'task' } }; + await applyAppAutomationOrganizationWall(opCtx, depsFor(UNION)); + expect(opCtx.driverTenantScopeCheck.judge({ tenantIds: ['org_a', 'org_b'] })).toEqual({ tenantIds: ['org_a', 'org_b'] }); + }); + + it('a denied caller’s delete keeps the read rule at the driver too: its bag is narrowed, not refused', async () => { + const opCtx: any = { object: 'task', operation: 'delete', context: actionBody(), options: { tenantId: 'org_b' }, ast: { object: 'task' } }; + await applyAppAutomationOrganizationWall(opCtx, depsFor(DENY)); + expect(opCtx.driverTenantScopeCheck.judge({ tenantId: 'org_b' })).toEqual({ tenantId: RLS_DENY_FILTER.id, tenantIds: undefined }); }); - it('a held key the bag does not carry stays out of its keys until set', async () => { - const opCtx: any = { object: 'task', operation: 'find', context: member(), options: { where: {} }, ast: { object: 'task' } }; + it('the bag itself is left as the body passed it', async () => { + const options = { where: {}, tenantId: 'org_a' }; + const opCtx: any = { object: 'task', operation: 'find', context: member(), options, ast: { object: 'task' } }; await applyAppAutomationOrganizationWall(opCtx, depsFor(ORG_A)); - expect(Object.keys(opCtx.options)).toEqual(['where']); - opCtx.options.tenantId = 'org_a'; - expect(Object.keys(opCtx.options)).toEqual(['where', 'tenantId']); + expect(Object.getOwnPropertyDescriptor(options, 'tenantId')).toMatchObject({ value: 'org_a', writable: true, enumerable: true }); }); it('control: a bag naming an organization the wall admits passes, and a wall with no parts admits any', async () => { @@ -454,6 +470,7 @@ describe('an app-authored elevation is judged by its caller’s organization wal const deps = depsFor(ORG_A); await applyAppAutomationOrganizationWall(opCtx, deps); expect(Object.getOwnPropertyDescriptor(options, 'tenantId')).toMatchObject({ value: 'org_b', writable: true }); + expect(opCtx.driverTenantScopeCheck).toBeUndefined(); expect(deps.callerLayer0).not.toHaveBeenCalled(); }); }); diff --git a/packages/plugins/plugin-security/src/app-automation-organization-wall.ts b/packages/plugins/plugin-security/src/app-automation-organization-wall.ts index e60c4a4fb71..2882925d2f3 100644 --- a/packages/plugins/plugin-security/src/app-automation-organization-wall.ts +++ b/packages/plugins/plugin-security/src/app-automation-organization-wall.ts @@ -48,11 +48,17 @@ * row is judged as one the write sent; * - the option bag's tenant keys (`tenantId`, `tenantIds`, which the engine * hands its driver as given) never widen the elevation past the wall: a - * write whose bag names an organization the wall does not admit, or clears - * the key, is refused, and a read whose bag does is answered by the read - * rule — the wall is composed onto its predicate, as the plain door's is. A - * before-hook that sets either key on the bag it is handed is held to the - * same rule as it sets it; + * write (an insert included) whose bag names an organization the wall does + * not admit, or clears the key, is refused, and a read whose bag does is + * answered by the read rule — the wall is composed onto its predicate, as + * the plain door's is. The bag a before-hook leaves — set, replaced or + * handed back — is judged by the same rule where the engine builds the + * driver's options (`OperationContext.driverTenantScopeCheck`): a write's is + * refused, a read's is narrowed to what the wall admits. Where no verdict + * is worked out for the operation (a caller with an active organization, + * whose wall the engine already projects), that bag is judged against the + * caller's active organization alone — narrower than a `group` member's + * union, never wider; * - a caller the wall DENIES — no active organization under `isolated`, an * empty membership set under `group`, a person outside every organization * under `single` (ADR-0093 D8.1, as amended) — reads nothing (zero rows, no @@ -331,11 +337,12 @@ function admittedOrganizations(verdict: TenantLayer0Verdict): ReadonlySet = new Set(['find', 'findOne', 'update', 'delete', 'purge']); - -/** The option bag's driver pass-through tenant keys. */ -const BAG_TENANT_KEYS = ['tenantId', 'tenantIds'] as const; +/** + * The verbs whose option bag reaches the driver: `find`, `findOne`, `update`, + * `delete` and `purge` hand the bag over as given, and `insert` takes the bag + * its before-hooks leave as the landing's scope. + */ +const BAG_VERBS: ReadonlySet = new Set(['find', 'findOne', 'insert', 'update', 'delete', 'purge']); /** * What an option bag's tenant keys ask of the driver: the organizations they @@ -377,43 +384,29 @@ function bagRefusal(source: ElevationSource, object: string, operation: string): } /** - * Hold a tenant key a before-hook sets on the operation's option bag to the - * caller's wall, as it is set: `admitted()` answers the organizations the - * wall admits (`undefined`: no wall). A write's key that reaches past it is - * refused; a read's is narrowed to what the wall admits — an organization - * outside it scopes to none, and a key cleared keeps the scope it had. + * Judge the tenant keys a driver bag carries against the caller's wall: + * `admitted()` answers the organizations the wall admits (`undefined`: no + * wall). Keys inside it pass as they are. Past it, `refuse()` answers for a + * write, and a read's keys are narrowed to the wall: an organization outside + * it scopes to none, and a cleared key is left to the operation's own scope. */ -function holdBagTenantKeys( - bag: Record, - isRead: boolean, +function judgeDriverTenantKeys( + asked: { tenantId?: unknown; tenantIds?: unknown }, + narrows: () => boolean, admitted: () => ReadonlySet | undefined, refuse: () => Error, -): void { - for (const key of BAG_TENANT_KEYS) { - let value = bag[key]; - // Enumerable only while it holds a value, as a plain key would be: the - // engine picks the bag's driver keys by enumerability. - const define = () => - Object.defineProperty(bag, key, { - configurable: true, - enumerable: value !== undefined, - get: () => value, - set: (next: unknown) => { - const ask = next === undefined ? undefined : bagTenantAsk({ [key]: next }); - const wall = admitted(); - if (!ask || !bagReachesPast(ask, wall)) { - value = next; - } else if (!isRead) { - throw refuse(); - } else if (!ask.clears) { - const inside = ask.organizations.filter((id) => wall!.has(id)); - value = key === 'tenantId' ? (inside[0] ?? RLS_DENY_FILTER.id) : inside.length > 0 ? inside : [RLS_DENY_FILTER.id]; - } - define(); - }, - }); - define(); - } +): { tenantId?: unknown; tenantIds?: unknown } { + const ask = bagTenantAsk(asked); + if (!ask) return asked; + const wall = admitted(); + if (!bagReachesPast(ask, wall)) return asked; + if (!narrows()) throw refuse(); + const inWall = (id: unknown): id is string => typeof id === 'string' && id !== '' && wall!.has(id); + const tenantId = + typeof asked.tenantId === 'string' && asked.tenantId !== '' ? (inWall(asked.tenantId) ? asked.tenantId : RLS_DENY_FILTER.id) : undefined; + const inside = Array.isArray(asked.tenantIds) ? asked.tenantIds.filter(inWall) : undefined; + const tenantIds = inside === undefined ? undefined : inside.length > 0 ? inside : [RLS_DENY_FILTER.id]; + return { tenantId, tenantIds }; } /** Rows of a write payload, each a plain object. */ @@ -442,6 +435,7 @@ export async function applyAppAutomationOrganizationWall( ast?: { where?: unknown } | null; tenantLayer0Verdict?: unknown; postHookWriteImageCheck?: { evaluate(rows: readonly Record[]): unknown; honoured?: boolean }; + driverTenantScopeCheck?: { judge(asked: { tenantId?: unknown; tenantIds?: unknown }): { tenantId?: unknown; tenantIds?: unknown } }; }, deps: AppAutomationWallDeps, ): Promise { @@ -514,16 +508,22 @@ export async function applyAppAutomationOrganizationWall( }; } - // A tenant key a before-hook sets on the bag after this point is held to - // the wall as it is set: the organizations the verdict admits, or — where - // none is worked out — the caller's own active organization alone. - if (BAG_VERBS.has(operation) && opCtx.options && typeof opCtx.options === 'object') { - holdBagTenantKeys( - opCtx.options as Record, - !isWrite, - () => (judgedAdmitted !== null ? judgedAdmitted : new Set(ownOrganization !== undefined ? [ownOrganization] : [])), - () => bagRefusal(caller.source, object, operation), - ); + // The bag the engine builds the driver's options from — whatever bag the + // before-hooks leave, set, replaced or handed back — is judged where the + // engine builds them: against the organizations the verdict admits, or — + // where none is worked out — the caller's own active organization alone. + // A denied caller's delete and purge keep the read rule (they match nothing). + let deniedRemoval = false; + if (BAG_VERBS.has(operation)) { + opCtx.driverTenantScopeCheck = { + judge: (asked) => + judgeDriverTenantKeys( + asked, + () => !isWrite || deniedRemoval, + () => (judgedAdmitted !== null ? judgedAdmitted : new Set(ownOrganization !== undefined ? [ownOrganization] : [])), + () => bagRefusal(caller.source, object, operation), + ), + }; } // Judged by the wall's own verdict: a federated object, a decided segment @@ -541,6 +541,7 @@ export async function applyAppAutomationOrganizationWall( const layer0 = tenantLayer0Verdict.kind === 'deny' ? (answer.layer0 ?? RLS_DENY_FILTER) : answer.layer0; const denied = tenantLayer0Verdict.kind === 'deny'; judgedAdmitted = admittedOrganizations(tenantLayer0Verdict); + deniedRemoval = denied && verb === REMOVAL; // A write whose bag reaches past the caller's wall is refused. A denied // caller's delete and purge keep the read rule below (they match nothing); // a read's bag is bounded by the wall composed onto its predicate below. From 34dacefd65a0460910806fdd3183685767a6c068 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 14:00:32 +0000 Subject: [PATCH 08/18] docs(permissions): the register row and changeset state the insert and hook-left halves of the option-bag rule Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- .changeset/sec2-wf9p-f12.md | 7 +++++-- content/docs/permissions/system-context.mdx | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.changeset/sec2-wf9p-f12.md b/.changeset/sec2-wf9p-f12.md index 4ba8de3befb..6db58b5177b 100644 --- a/.changeset/sec2-wf9p-f12.md +++ b/.changeset/sec2-wf9p-f12.md @@ -1,5 +1,6 @@ --- '@objectstack/plugin-security': patch +'@objectstack/objectql': patch --- fix(plugin-security)!: an elevation's write is judged as it will be stored, and its option bag never widens it past its caller's organization wall @@ -16,10 +17,12 @@ The rule: an app-authored elevation (an action body, a hook that runs as system, - FROM: the organization a write's before-hooks left on the row, and the `tenantId` / `tenantIds` an operation's option bag named, were not judged against the caller's organization wall. - TO: - a write is judged again on the rows its before-hooks leave: a row stored in an organization outside the caller's wall, or an update that leaves a row in no organization, is refused with `403 PERMISSION_DENIED`; - - a write (`update`, `delete`, `purge`) whose option bag names an organization outside the caller's wall, or clears `tenantId`, is refused with `403 PERMISSION_DENIED`; + - a write (`insert`, `update`, `delete`, `purge`) whose option bag names an organization outside the caller's wall, or clears `tenantId`, is refused with `403 PERMISSION_DENIED`; - a read (`find`, `findOne`) whose option bag names or clears an organization scope is answered by the read rule: the caller's wall is composed onto its predicate, so it reads only rows the wall admits; - - a before-hook that sets `tenantId` or `tenantIds` on the option bag it is handed is held to the same rule as it sets it. + - the option bag a before-hook leaves (a key it sets, a bag it replaces or hands back) is judged by the same rule where the engine builds the driver's options: a write's is refused with `403 PERMISSION_DENIED`, a read's is narrowed to the organizations the wall admits. Where no verdict is worked out for the operation, that bag is judged against the caller's active organization alone. **Not moved.** A caller with an active organization keeps exactly its reach: a before-hook that keeps the row in an organization the caller's wall admits, and an option bag that names one, behave as before. Objects outside tenancy, objects with no organization column, and a platform operator crossing the wall on an object whose posture permits it are answered as the caller's own requests answer them. System work that runs for no caller (a scheduled run, a platform plugin's own system context, the seeders) is unchanged, its option bag included. +Also in this change: `@objectstack/objectql`'s `OperationContext` gains `driverTenantScopeCheck` (type `DriverTenantScopeCheck`), an enforcement layer's bound on the explicit `tenantId` / `tenantIds` of an operation's option bag. The engine applies it to every driver bag it builds for that operation, after every before-hook; absent, nothing changes. + The fix for a body or hook: write only into organizations the caller may write in, and leave `tenantId` / `tenantIds` off the option bag, or name an organization the caller's wall admits. A row that must land in another organization is written by a member of that organization, through its own request. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 40bc618a85a..23bf0461709 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -101,7 +101,7 @@ bugs — it is the protection or the side effect that silently does not happen. |:--|:---|:---|:---|:---| | 1 | **The whole security middleware short-circuits** before any gate runs | plugin-security | Get: every CRUD/FLS/tenant/owner gate below skipped in one branch. Lose: every gate under it in this lane at once, down to and including the write-bypass row that widens the effective write scope to `org` (row 7) — this is the single largest behaviour on the page | `registerAuthzMiddleware` | | 1b | **App-authored automation's system context is REFUSED governed writes to the identity-assignment objects** — a flow run's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and an action body's; checked ahead of the middleware's short-circuit, beside the append-only refusal (`assertAppAutomationAppendOnlyWriteAllowed`) | plugin-security | Get: nothing — an insert, update, delete, transfer, restore or purge of `sys_user_position`, `sys_user_permission_set`, `sys_invitation` or `sys_member` from a context carrying `isSystem` and either a `flowRunId` (a `runAs: 'system'` flow's data nodes) or the app-automation elevation mark (`@objectstack/core`; set only by a hook's `runAs: 'system'` derivation, by the action body's execution-context builder and `ObjectRepository.execute`, and on the api of a hook bound through the hook binder, whose inherited system context and `sudo()` it marks), at any depth of their writes, is refused `PERMISSION_DENIED` before the short-circuit skips the ADR-0090 D12 gate and the identity write guard. The platform's own system api (`platformSystemApi`, objectql) takes the mark and `flowRunId` off a platform hook's api, for the audit writer's own ledger rows. On an app-authored hook's api, on the api an action door hands its handler (a host code action handler's included) and on the api `ObjectRepository.execute` hands the action it dispatches (`ctx.api.object(o).execute(name)`), and on every api derived from any of them, it answers what that api's `sudo()` answers, mark kept, so this refusal, and the action body's owner stamp in the next row, hold through it too. Lose: nothing a platform writer held — a system context with neither (the seeders, better-auth and its reconciliation, invitation placement, platform code's `sudo()`, which never sets the mark, and a hook registered in code) passes on to the short-circuit unchanged, reads are not judged, and a `runAs: 'user'` flow or hook carries no `isSystem`, so the D12 gate judges it as the user it acts for | `elevationSource`, `appAuthoredHookApi` | -| 1c | **App-authored automation's system context meets its caller's organization wall** — an action body's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and a flow run's, read by the same predicate as the identity refusal above (`applyAppAutomationOrganizationWall`, plugin-security); checked ahead of the middleware's short-circuit | plugin-security | Get: its reads and writes are judged by the organization wall of the caller it runs for, under every posture and on every object. Such a context that carries a caller (a `userId`, or the guest entry's envelope) is judged by the caller's own Layer 0 (ADR-0095 D1), computed over the caller's own context and permission sets (resolved for the caller where the context does not carry them, as a flow run's does not). An insert with no active organization on a walled tenant object is refused (`403 PERMISSION_DENIED`); for every such caller, one with an active organization included, a write whose own data names an organization outside its scope or empties a row's organization is refused (`403 PERMISSION_DENIED`); a write is judged again on the rows its before-hooks leave, by the same rule, as the plain door judges it; the option bag's `tenantId` / `tenantIds` never widen it past the caller's wall — a write whose bag names an organization outside it, or clears the key, is refused (`403 PERMISSION_DENIED`), and a read whose bag does is answered by the read rule, the caller's wall composed onto its predicate; on a federated object its reads are those of the caller's organization scope and a by-id write of a row outside it answers `404 RECORD_NOT_FOUND`, the check read inside the transaction the write carries. A caller the wall denies — no active organization under `isolated`, an empty membership set under `group`, no membership under `single` — reads nothing of a tenant-scoped object, and its delete and purge are answered by that read rule as its plain door answers them (ADR-0123 D2): a predicate delete matches nothing and a by-id delete answers `404 RECORD_NOT_FOUND`. Every other write is refused `PERMISSION_DENIED` (403), naming what is missing (ADR-0123 D4). A system flow run whose own user is its caller carries that user's membership set and posture rung from run setup (a decided segment, a run that began for no caller and a child run of either carry neither); the wall asks Layer 0 alone and resolves what a context lacks once per run. Lose: nothing the caller held — a caller with an active organization keeps its organization's reach (the union of its memberships under `group`); objects outside tenancy, objects with no organization column and a platform operator crossing the wall on a posture-permitting object answer as the caller's plain door answers them. An elevation that carries no caller (a scheduled run, a record-change run fired by a write that carried no user), a system flow that began for no caller in every segment (after an approval decision too, `runCallerOf`, core) and a run a write of such a segment starts, and every platform system context are unchanged | `elevationSource` | +| 1c | **App-authored automation's system context meets its caller's organization wall** — an action body's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and a flow run's, read by the same predicate as the identity refusal above (`applyAppAutomationOrganizationWall`, plugin-security); checked ahead of the middleware's short-circuit | plugin-security | Get: its reads and writes are judged by the organization wall of the caller it runs for, under every posture and on every object. Such a context that carries a caller (a `userId`, or the guest entry's envelope) is judged by the caller's own Layer 0 (ADR-0095 D1), computed over the caller's own context and permission sets (resolved for the caller where the context does not carry them, as a flow run's does not). An insert with no active organization on a walled tenant object is refused (`403 PERMISSION_DENIED`); for every such caller, one with an active organization included, a write whose own data names an organization outside its scope or empties a row's organization is refused (`403 PERMISSION_DENIED`); a write is judged again on the rows its before-hooks leave, by the same rule, as the plain door judges it; the option bag's `tenantId` / `tenantIds` never widen it past the caller's wall — a write (an insert included) whose bag names an organization outside it, or clears the key, is refused (`403 PERMISSION_DENIED`), and a read whose bag does is answered by the read rule, the caller's wall composed onto its predicate; the bag its before-hooks leave, set, replaced or handed back, is judged by the same rule where the engine builds the driver's options (`OperationContext.driverTenantScopeCheck`), against the caller's active organization alone where no verdict was worked out for the operation; on a federated object its reads are those of the caller's organization scope and a by-id write of a row outside it answers `404 RECORD_NOT_FOUND`, the check read inside the transaction the write carries. A caller the wall denies — no active organization under `isolated`, an empty membership set under `group`, no membership under `single` — reads nothing of a tenant-scoped object, and its delete and purge are answered by that read rule as its plain door answers them (ADR-0123 D2): a predicate delete matches nothing and a by-id delete answers `404 RECORD_NOT_FOUND`. Every other write is refused `PERMISSION_DENIED` (403), naming what is missing (ADR-0123 D4). A system flow run whose own user is its caller carries that user's membership set and posture rung from run setup (a decided segment, a run that began for no caller and a child run of either carry neither); the wall asks Layer 0 alone and resolves what a context lacks once per run. Lose: nothing the caller held — a caller with an active organization keeps its organization's reach (the union of its memberships under `group`); objects outside tenancy, objects with no organization column and a platform operator crossing the wall on a posture-permitting object answer as the caller's plain door answers them. An elevation that carries no caller (a scheduled run, a record-change run fired by a write that carried no user), a system flow that began for no caller in every segment (after an approval decision too, `runCallerOf`, core) and a run a write of such a segment starts, and every platform system context are unchanged | `elevationSource` | | 2 | **`owner_id` is not auto-stamped on INSERT** (the step 3.5 anchor guard is inside the block row 1 skips) — except an action body's insert | plugin-security | Lose: the row lands `owner_id = NULL`, so the default `owner_only_writes` policy hides it **from its own creator**. Get: nothing — this is a gap, not a capability. Except an action body's: an insert from a context carrying `isSystem` and the `'action'` app-automation elevation mark, with no `flowRunId`, has every EMPTY `owner_id` stamped with the envelope's own `userId` ahead of the short-circuit, by the same stamp step 3.5 applies (nothing for the guest; an owner the body sets is kept; an `owner_id` supplied empty beside a supplied queue parks the row). Like a direct create, such an insert is the invoker's own record, so assignment rules (ADR-0142 D5), which route only a row whose owner and queue are both still empty, route neither; a body has no spelling today that asks a rule to route its row. The mark is set on every handler an action door dispatches (a host code action handler included) and by `ObjectRepository.execute`. A flow run, a hook's `runAs: 'system'`, the seeders and every other system context still land the owner they write, or none, and an unowned, queue-less one is still routed | the step 3.5 guard block and the short-circuit that skips it are both inside `registerAuthzMiddleware`; the action-body exception is `isActionBodyElevation` | | 3 | Row-level read filter resolves to "no filter" | plugin-security | Get: unscoped reads. Lose: row-level scoping entirely | `getReadFilter` | | 4 | Field-level security returns **all** fields | plugin-security | Get: every column readable (`getReadableFields`) and writable (`getWritableFields`), and every field a disabled package withholds named to it (`getMetadataReadableWithheldFields`, so the served object's `_withheldFields` keeps every entry). Lose: field masking | `resolveProjectionFieldMask`, `computeMetadataReadableWithheldFields` | From f149f25eeb4a018cec313657dcabbf9c862adeae Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 15:20:30 +0000 Subject: [PATCH 09/18] test(organizations): pin a sandboxed hook's handed-back option bag on an elevated read, update and delete to the caller's wall Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- ...ated-organization-wall.writes.wall.test.ts | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts b/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts index 4862f577dff..ba877dbef32 100644 --- a/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts +++ b/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts @@ -58,6 +58,19 @@ const BODY_BAG_CLEAR_UPDATE = // tenant scope the row's `bagorg` names. const HOOK_BAG_SOURCE = "if (ctx.input && typeof ctx.input.bagorg === 'string' && ctx.input.bagorg !== '') return { options: { tenantId: ctx.input.bagorg } };"; +// A sandboxed before-hook on reads, updates and deletes that hands back an +// option bag naming the tenant scope a platform-global config row names, while +// that row exists. +const CFG = 'eoww_cfg'; +const HOOK_CFG_BAG_SOURCE = + "const cfg = await ctx.api.object('eoww_cfg').find({ where: { name: 'bag' } });" + + "if (cfg.length > 0 && typeof cfg[0].org === 'string' && cfg[0].org !== '') return { options: { tenantId: cfg[0].org } };"; +const BODY_CFG_READ = + "const rows = await ctx.api.object('eoww_task').find({ where: {} }); return { seen: rows.map((r) => r.name).sort() };"; +const BODY_CFG_UPDATE = + "await ctx.api.object('eoww_task').update({ touched: 'cfg' }, { where: { name: { $in: ['A1', 'B1'] } }, multi: true }); return { wrote: 1 };"; +const BODY_CFG_DELETE = + "await ctx.api.object('eoww_task').delete({ where: { name: { $in: ['A1', 'B1'] } }, multi: true }); return { removed: 1 };"; const BODY_BAG_DELETE = "await ctx.api.object('eoww_task').delete({ where: { name: input.name }, multi: true, tenantId: input.org }); return { removed: 1 };"; @@ -123,11 +136,40 @@ const APP = { type: 'script', body: { language: 'js', source, capabilities: ['api.read', 'api.write'] }, })), + ...( + [ + ['eoww_cfg_read', BODY_CFG_READ], + ['eoww_cfg_update', BODY_CFG_UPDATE], + ['eoww_cfg_delete', BODY_CFG_DELETE], + ] as const + ).map(([name, source]) => ({ + name, + label: name, + objectName: TASK, + type: 'script', + body: { language: 'js', source, capabilities: ['api.read', 'api.write'] }, + })), ], }; +(APP.objects as unknown[]).push({ + name: CFG, + label: 'Config', + tenancy: { enabled: false }, + sharingModel: 'public_read_write', + fields: { name: { type: 'text', label: 'Name' }, org: { type: 'text', label: 'Organization' } }, +}); + Object.assign(APP, { hooks: [ + { + name: 'eoww_cfg_bag_hook', + label: 'Config bag hook', + object: TASK, + events: ['beforeFind', 'beforeUpdate', 'beforeDelete'], + body: { language: 'js', source: HOOK_CFG_BAG_SOURCE, capabilities: ['api.read'] }, + onError: 'abort', + }, { name: 'eoww_bag_hook', label: 'Bag hook', @@ -540,6 +582,53 @@ describe('an app-authored elevation’s writes are judged by its caller’s orga expect(own.body.data).toEqual({ seen: ['A1'] }); }); + describe('a sandboxed before-hook that hands back a bag naming another organization', () => { + // The config row names the organization while the act runs, and none after. + const setCfg = async (org: string) => { + const [row] = await ql.find(CFG, { where: { name: 'bag' }, limit: 1 }, SYS); + if (row) await ql.update(CFG, { id: row.id, org }, SYS); + else await ql.insert(CFG, { name: 'bag', org }, SYS); + }; + const withCfg = async (org: string, act: () => Promise): Promise => { + await setCfg(org); + try { + return await act(); + } finally { + await setCfg(''); + } + }; + + it('a read is answered by the read rule', async () => { + await reseed(); + const r = await withCfg(orgB, () => run(alice, 'eoww_cfg_read')); + expect(r.status, JSON.stringify(r.body)).toBe(200); + expect(r.body.data).toEqual({ seen: [] }); + }); + + it('a predicate update is refused 403', async () => { + await reseed(); + const r = await withCfg(orgB, () => run(alice, 'eoww_cfg_update')); + expect(r.status, JSON.stringify(r.body)).toBe(403); + expect(r.body.error.code).toBe('PERMISSION_DENIED'); + expect((await rowNamed('B1'))!.touched ?? null).toBeNull(); + }); + + it('a predicate delete is refused 403', async () => { + await reseed(); + const r = await withCfg(orgB, () => run(alice, 'eoww_cfg_delete')); + expect(r.status, JSON.stringify(r.body)).toBe(403); + expect(r.body.error.code).toBe('PERMISSION_DENIED'); + expect(await rowNamed('B1')).toBeDefined(); + }); + + it('control: a bag it hands back naming the caller’s own organization reads there', async () => { + await reseed(); + const r = await withCfg(orgA, () => run(alice, 'eoww_cfg_read')); + expect(r.status, JSON.stringify(r.body)).toBe(200); + expect(r.body.data).toEqual({ seen: ['A1'] }); + }); + }); + it('a write whose before-hook redefines the bag’s tenant key is held to the wall too', async () => { await reseed(); const r = await run(alice, 'eoww_redefined_bag', { name: 'B1', org: orgB }); From b0cf561833aac5a1f4faf6ca62e9dc936a23f630 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 15:21:30 +0000 Subject: [PATCH 10/18] test(organizations): a sandboxed hook's handed-back bag on an elevated update or delete never reaches another organization's rows Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- ...ated-organization-wall.writes.wall.test.ts | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts b/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts index ba877dbef32..86eaf448512 100644 --- a/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts +++ b/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts @@ -605,19 +605,23 @@ describe('an app-authored elevation’s writes are judged by its caller’s orga expect(r.body.data).toEqual({ seen: [] }); }); - it('a predicate update is refused 403', async () => { + // A write through this channel is refused where the handed-back bag + // reaches the driver, and otherwise stays in the caller's organization: + // either way it never reaches another organization's rows. + const heldWrite = (r: { status: number; body: any }) => { + expect([200, 403], JSON.stringify(r.body)).toContain(r.status); + if (r.status === 403) expect(r.body.error.code).toBe('PERMISSION_DENIED'); + }; + + it('a predicate update never reaches another organization’s rows', async () => { await reseed(); - const r = await withCfg(orgB, () => run(alice, 'eoww_cfg_update')); - expect(r.status, JSON.stringify(r.body)).toBe(403); - expect(r.body.error.code).toBe('PERMISSION_DENIED'); + heldWrite(await withCfg(orgB, () => run(alice, 'eoww_cfg_update'))); expect((await rowNamed('B1'))!.touched ?? null).toBeNull(); }); - it('a predicate delete is refused 403', async () => { + it('a predicate delete never reaches another organization’s rows', async () => { await reseed(); - const r = await withCfg(orgB, () => run(alice, 'eoww_cfg_delete')); - expect(r.status, JSON.stringify(r.body)).toBe(403); - expect(r.body.error.code).toBe('PERMISSION_DENIED'); + heldWrite(await withCfg(orgB, () => run(alice, 'eoww_cfg_delete'))); expect(await rowNamed('B1')).toBeDefined(); }); From 054893b0fb413328cdf2fcf77af1cf762da1c868 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 15:23:27 +0000 Subject: [PATCH 11/18] test(organizations): pin a redefined option-bag tenant key on an elevated predicate delete to the caller's wall Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- ...ated-organization-wall.writes.wall.test.ts | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts b/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts index 86eaf448512..5db046c3a4b 100644 --- a/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts +++ b/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts @@ -119,6 +119,7 @@ const APP = { { name: 'eoww_replaced_land', label: 'Replaced land', objectName: TASK, type: 'script', target: 'eowwReplacedLand' }, { name: 'eoww_replaced_read', label: 'Replaced read', objectName: TASK, type: 'script', target: 'eowwReplacedRead' }, { name: 'eoww_redefined_bag', label: 'Redefined bag', objectName: TASK, type: 'script', target: 'eowwRedefinedBag' }, + { name: 'eoww_redefined_delete', label: 'Redefined delete', objectName: TASK, type: 'script', target: 'eowwRedefinedDelete' }, ...( [ ['eoww_bag_find', BODY_BAG_FIND], @@ -297,6 +298,30 @@ describe('an app-authored elevation’s writes are judged by its caller’s orga }, { object: TASK }, ); + let redefinedDeleteOrg: string | undefined; + ql.registerHook( + 'beforeDelete', + async (ctx: any) => { + if (redefinedDeleteOrg !== undefined && ctx.input.options) { + Object.defineProperty(ctx.input.options, 'tenantId', { + value: redefinedDeleteOrg, + enumerable: true, + configurable: true, + writable: true, + }); + } + }, + { object: TASK }, + ); + ql.registerAction(TASK, 'eowwRedefinedDelete', async (ctx: any) => { + redefinedDeleteOrg = String(ctx.params?.org); + try { + await ctx.api.object(TASK).delete({ where: { name: { $in: ['A1', ctx.params?.name] } }, multi: true }); + return { removed: 1 }; + } finally { + redefinedDeleteOrg = undefined; + } + }); ql.registerAction(TASK, 'eowwBagLand', async (ctx: any) => { await ctx.engine.insert(TASK, { name: ctx.params?.name, bagorg: ctx.params?.org }); return { landed: 1 }; @@ -640,6 +665,11 @@ describe('an app-authored elevation’s writes are judged by its caller’s orga expect(r.body.error.code).toBe('PERMISSION_DENIED'); expect((await rowNamed('B1'))!.touched ?? null).toBeNull(); expect((await rowNamed('A1'))!.touched ?? null).toBeNull(); + const removed = await run(alice, 'eoww_redefined_delete', { name: 'B1', org: orgB }); + expect(removed.status, JSON.stringify(removed.body)).toBe(403); + expect(removed.body.error.code).toBe('PERMISSION_DENIED'); + expect(await rowNamed('B1')).toBeDefined(); + expect(await rowNamed('A1')).toBeDefined(); }); it('control: a bag naming the caller’s own organization reads and writes there', async () => { From e21b1d15c0798570496c86dd7c380d948c0b48f6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:12:09 +0000 Subject: [PATCH 12/18] fix(objectql): an operation's driver tenant-scope check judges only what the bag asks beyond the engine's own projection Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- .../src/engine-driver-options.test.ts | 39 ++++++++++ .../objectql/src/engine-driver-options.ts | 32 ++++++++- packages/objectql/src/engine-top-level.ts | 24 +++---- ...ed-organization-wall.postures.wall.test.ts | 71 +++++++++++++++++++ 4 files changed, 152 insertions(+), 14 deletions(-) diff --git a/packages/objectql/src/engine-driver-options.test.ts b/packages/objectql/src/engine-driver-options.test.ts index 718d3407637..5f14ccffe59 100644 --- a/packages/objectql/src/engine-driver-options.test.ts +++ b/packages/objectql/src/engine-driver-options.test.ts @@ -295,3 +295,42 @@ describe('an operation’s driver tenant-scope check judges the bag the driver i expect(find!.options!.tenantId).toBe('org_other'); }); }); + +describe('the tenant keys the engine fills itself are not judged as the bag’s', () => { + const MEMBER: ExecutionContext = { userId: 'usr_1', tenantId: ORG, accessible_org_ids: [ORG, 'org_b'] } as unknown as ExecutionContext; + + async function groupEngineWithRefusingCheck() { + const { engine, received } = await makeEngine(); + engine.setTenancyPostureProvider(() => 'group'); + const asked: unknown[] = []; + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + opCtx.driverTenantScopeCheck = { + judge: (keys: Record) => { + asked.push(keys); + throw Object.assign(new Error('refused'), { code: 'PERMISSION_DENIED', status: 403 }); + }, + }; + await next(); + }); + return { engine, received, asked }; + } + + it('a bag-less by-id and predicate delete under group reach the driver, and the check is never asked', async () => { + const { engine, received, asked } = await groupEngineWithRefusingCheck(); + const [a, b] = (await engine.insert('dopt_task', [{ title: 'a', status: 'x' }, { title: 'b', status: 'y' }], { context: MEMBER } as any)) as Array< + Record + >; + await engine.delete('dopt_task', { where: { id: a!.id }, context: MEMBER } as any); + await engine.delete('dopt_task', { where: { status: 'y' }, multi: true, context: MEMBER } as any); + expect(received.some((c) => c.method === 'delete')).toBe(true); + expect(received.some((c) => c.method === 'deleteMany')).toBe(true); + expect(b).toBeDefined(); + expect(asked).toEqual([]); + }); + + it('control: a bag that asks beyond the projected scope is still judged', async () => { + const { engine, asked } = await groupEngineWithRefusingCheck(); + await expect(engine.find('dopt_task', { where: {}, tenantId: 'org_c', context: MEMBER } as any)).rejects.toMatchObject({ code: 'PERMISSION_DENIED' }); + expect(asked).toEqual([{ tenantId: 'org_c', tenantIds: undefined }]); + }); +}); diff --git a/packages/objectql/src/engine-driver-options.ts b/packages/objectql/src/engine-driver-options.ts index c77e80b63f7..ce1c928d030 100644 --- a/packages/objectql/src/engine-driver-options.ts +++ b/packages/objectql/src/engine-driver-options.ts @@ -199,6 +199,25 @@ export function mergeDriverOptionsIntoHookView( return addsNothing ? callerBag : { ...bag, ...driverOptions }; } +/** + * Does a bag's explicit `tenantId` / `tenantIds` ask for any organization the + * engine's own projection for the call (`tenantScope`) does not already + * scope to — or clear the key the projection fills? With no projection (an + * object outside the driver's tenant scope), any explicit key asks beyond it. + */ +function asksBeyondProjectedScope( + declared: Record, + tenantScope: { tenantId: string; tenantIds?: string[] } | undefined, +): boolean { + if (tenantScope === undefined) return true; + const projected = new Set([tenantScope.tenantId, ...(tenantScope.tenantIds ?? [])]); + const inProjection = (id: unknown): boolean => typeof id === 'string' && projected.has(id); + const { tenantId, tenantIds } = declared; + if (tenantId !== undefined && !inProjection(tenantId)) return true; + if (tenantIds !== undefined && !(Array.isArray(tenantIds) && tenantIds.every(inProjection))) return true; + return false; +} + /** * Build the DriverOptions blob passed to every IDataDriver call. * @@ -362,8 +381,17 @@ export function buildDriverOptions( // [ADR-0095 D1] An explicit tenant key is the caller's intent and wins below, // so where the operation carries a bound on it (an enforcement layer's // {@link OperationContext.driverTenantScopeCheck}), the bound judges the keys - // the bag carries NOW — after every before-hook, whatever bag it left. - if (scope.tenantScopeCheck && declared && (declared.tenantId !== undefined || declared.tenantIds !== undefined)) { + // the bag carries NOW — after every before-hook, whatever bag it left. Keys + // that ask for nothing beyond the scope the engine projects for this very + // call are not judged: they are what the engine itself fills into the hooks' + // view of the bag (`mergeDriverOptionsIntoHookView`), and a later build of + // the same operation reads them back from there. + if ( + scope.tenantScopeCheck && + declared && + (declared.tenantId !== undefined || declared.tenantIds !== undefined) && + asksBeyondProjectedScope(declared, tenantScope) + ) { const judged = scope.tenantScopeCheck.judge({ tenantId: declared.tenantId, tenantIds: declared.tenantIds }); delete declared.tenantId; delete declared.tenantIds; diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index 3a237382049..10fcaa33f5b 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -4248,6 +4248,18 @@ export interface OperationContext { writePrecondition?: Readonly>; } +/** + * [ADR-0095 D1] The judgement {@link OperationContext.driverTenantScopeCheck} + * carries. `judge` receives the tenant keys the option bag carries when the + * engine builds a driver bag for the operation (called only when the bag + * carries at least one of them), and answers the keys the driver is to be + * handed in their place: the same, narrowed, or `undefined` for a key the + * operation's own scope is to fill. It refuses by throwing. + */ +export interface DriverTenantScopeCheck { + judge(asked: { tenantId?: unknown; tenantIds?: unknown }): { tenantId?: unknown; tenantIds?: unknown }; +} + /** * [commit a016f08b8] The judgement {@link OperationContext.postHookWriteImageCheck} * carries, and the acknowledgement its installer reads back. @@ -4266,18 +4278,6 @@ export interface OperationContext { * way out knows its check did not happen, and says so loudly rather than * reading an unjudged write as an allowed one. */ -/** - * [ADR-0095 D1] The judgement {@link OperationContext.driverTenantScopeCheck} - * carries. `judge` receives the tenant keys the option bag carries when the - * engine builds a driver bag for the operation (called only when the bag - * carries at least one of them), and answers the keys the driver is to be - * handed in their place: the same, narrowed, or `undefined` for a key the - * operation's own scope is to fill. It refuses by throwing. - */ -export interface DriverTenantScopeCheck { - judge(asked: { tenantId?: unknown; tenantIds?: unknown }): { tenantId?: unknown; tenantIds?: unknown }; -} - export interface PostHookWriteImageCheck { evaluate(rows: readonly Record[]): void | Promise; honoured?: boolean; diff --git a/packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts b/packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts index 6f496f0fa54..f105dbbbeba 100644 --- a/packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts +++ b/packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts @@ -33,6 +33,8 @@ const TASK = 'eop_task'; const NOTE = 'eop_note'; const PING = 'eop_ping'; const SWEEP_PING = 'eop_sweep_ping'; +const PARENT = 'eop_parent'; +const CHILD = 'eop_child'; const APP = { manifest: { id: 'com.example.eop', namespace: 'eop', version: '0.0.1', type: 'app', name: 'Elevated Org Wall Postures Fixture' }, @@ -44,6 +46,16 @@ const APP = { sharingModel: 'public_read_write', fields: { name: { type: 'text', label: 'Name' }, touched: { type: 'text', label: 'Touched' } }, }, + { name: PARENT, label: 'Parent', sharingModel: 'public_read_write', fields: { name: { type: 'text', label: 'Name' } } }, + { + name: CHILD, + label: 'Child', + sharingModel: 'public_read_write', + fields: { + name: { type: 'text', label: 'Name' }, + parent: { type: 'lookup', reference: PARENT, deleteBehavior: 'cascade', label: 'Parent' }, + }, + }, { // Outside tenancy: a caller-less run's decided segment writes it. name: SWEEP_PING, @@ -70,6 +82,9 @@ const APP = { { name: 'eop_flow_read', label: 'Flow read', objectName: TASK, type: 'flow', target: 'eop_sys_read' }, { name: 'eop_flow_write', label: 'Flow write', objectName: TASK, type: 'flow', target: 'eop_sys_write' }, { name: 'eop_flow_held_read', label: 'Flow held read', objectName: TASK, type: 'flow', target: 'eop_sys_held_read' }, + { name: 'eop_delete_by_id', label: 'Delete by id', objectName: TASK, type: 'script', target: 'eopDeleteById' }, + { name: 'eop_purge_by_id', label: 'Purge by id', objectName: TASK, type: 'script', target: 'eopPurgeById' }, + { name: 'eop_delete_parents', label: 'Delete parents', objectName: TASK, type: 'script', target: 'eopDeleteParents' }, ], flows: [ { @@ -357,6 +372,7 @@ describe('group: a system flow run for a member of two organizations reads exact let ql: any; let alice: string; let orgA: string; + let orgs: { A: string; B: string; C: string }; const noteSeen = async (name: string): Promise => { const [row] = await ql.find(NOTE, { where: { name }, limit: 1 }, SYS); @@ -394,6 +410,19 @@ describe('group: a system flow run for a member of two organizations reads exact for (const [org, name] of [[orgA, 'A1'], [orgB, 'B1'], [orgC, 'C1']] as const) { await ql.insert(TASK, { name }, { context: { isSystem: true, tenantId: org } }); } + orgs = { A: orgA, B: orgB, C: orgC }; + ql.registerAction(TASK, 'eopDeleteById', async (ctx: any) => { + await ctx.engine.delete(TASK, String(ctx.params?.target)); + return { removed: 1 }; + }); + ql.registerAction(TASK, 'eopPurgeById', async (ctx: any) => { + await ctx.api.object(TASK).delete({ where: { id: String(ctx.params?.target) }, permanent: true }); + return { purged: 1 }; + }); + ql.registerAction(TASK, 'eopDeleteParents', async (ctx: any) => { + await ctx.api.object(PARENT).delete({ where: { name: String(ctx.params?.name) }, multi: true }); + return { removed: 1 }; + }); }, 180_000); afterAll(async () => { @@ -419,6 +448,48 @@ describe('group: a system flow run for a member of two organizations reads exact }); } + describe('an elevated delete that names no tenant key keeps the member’s reach', () => { + const seed = async (object: string, org: string, name: string, extra: Record = {}) => + (await ql.insert(object, { name, ...extra }, { context: { isSystem: true, tenantId: org } })) as { id: string }; + const rowNamed = async (object: string, name: string) => (await ql.find(object, { where: { name }, limit: 1 }, SYS))[0]; + const run = async (action: string, params: Record) => + answer(await stack.apiAs(alice, 'POST', `/actions/${TASK}/${action}`, { params })); + + beforeAll(async () => { + expect((await stack.apiAs(alice, 'POST', '/auth/organization/set-active', { organizationId: orgs.A })).status).toBe(200); + }); + + for (const key of ['A', 'B'] as const) { + it(`a by-id delete and a by-id purge of a row of the member’s organization ${key} succeed`, async () => { + const removed = await seed(TASK, orgs[key], `DEL-${key}`); + const r = await run('eop_delete_by_id', { target: removed.id }); + expect(r.status, JSON.stringify(r.body)).toBe(200); + expect(await rowNamed(TASK, `DEL-${key}`)).toBeUndefined(); + const purged = await seed(TASK, orgs[key], `PURGE-${key}`); + const p = await run('eop_purge_by_id', { target: purged.id }); + expect(p.status, JSON.stringify(p.body)).toBe(200); + expect(await rowNamed(TASK, `PURGE-${key}`)).toBeUndefined(); + }); + } + + it('a predicate delete on an object a cascade lookup points at succeeds, its children with it', async () => { + const parent = await seed(PARENT, orgs.A, 'P-A'); + await seed(CHILD, orgs.A, 'K-A', { parent: parent.id }); + const r = await run('eop_delete_parents', { name: 'P-A' }); + expect(r.status, JSON.stringify(r.body)).toBe(200); + expect(await rowNamed(PARENT, 'P-A')).toBeUndefined(); + expect(await rowNamed(CHILD, 'K-A')).toBeUndefined(); + }); + + it('control: a row of an organization the member does not hold answers as a row that is not there', async () => { + const foreign = await seed(TASK, orgs.C, 'DEL-C'); + const r = await run('eop_delete_by_id', { target: foreign.id }); + expect(r.status, JSON.stringify(r.body)).toBe(404); + expect(r.body.error.code).toBe('RECORD_NOT_FOUND'); + expect(await rowNamed(TASK, 'DEL-C')).toBeDefined(); + }); + }); + it('a system run the member’s own write starts reads the union of the member’s organizations', async () => { await clearNotes(orgA); expect((await stack.apiAs(alice, 'POST', '/auth/organization/set-active', { organizationId: orgA })).status).toBe(200); From 7ee86034084ae2f9d09d2b55ce8ac4ed10ea1d8f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 21:16:42 +0000 Subject: [PATCH 13/18] docs(changeset): the option-bag rule states its group reach and drops the plain-door equivalence; the base-green sandboxed write pins read as controls Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- .changeset/sec2-wf9p-f12.md | 4 ++-- .../src/elevated-organization-wall.postures.wall.test.ts | 1 + .../src/elevated-organization-wall.writes.wall.test.ts | 4 ++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.changeset/sec2-wf9p-f12.md b/.changeset/sec2-wf9p-f12.md index 6db58b5177b..ac9e06e0ff9 100644 --- a/.changeset/sec2-wf9p-f12.md +++ b/.changeset/sec2-wf9p-f12.md @@ -10,7 +10,7 @@ Metadata-protocol: none -The rule: an app-authored elevation (an action body, a hook that runs as system, a flow that runs as system) is held to its caller's organization wall on the row as it will be stored and on the tenant scope its option bag asks for, as the caller's plain door is (ADR-0095 D1, ADR-0123 D2). +The rule: an app-authored elevation (an action body, a hook that runs as system, a flow that runs as system) is held to its caller's organization wall on the row as it will be stored and on the tenant scope its option bag asks for (ADR-0095 D1, ADR-0123 D2). **BREAKING** for an action body, a system hook or a system flow run for a signed-in caller. @@ -21,7 +21,7 @@ The rule: an app-authored elevation (an action body, a hook that runs as system, - a read (`find`, `findOne`) whose option bag names or clears an organization scope is answered by the read rule: the caller's wall is composed onto its predicate, so it reads only rows the wall admits; - the option bag a before-hook leaves (a key it sets, a bag it replaces or hands back) is judged by the same rule where the engine builds the driver's options: a write's is refused with `403 PERMISSION_DENIED`, a read's is narrowed to the organizations the wall admits. Where no verdict is worked out for the operation, that bag is judged against the caller's active organization alone. -**Not moved.** A caller with an active organization keeps exactly its reach: a before-hook that keeps the row in an organization the caller's wall admits, and an option bag that names one, behave as before. Objects outside tenancy, objects with no organization column, and a platform operator crossing the wall on an object whose posture permits it are answered as the caller's own requests answer them. System work that runs for no caller (a scheduled run, a platform plugin's own system context, the seeders) is unchanged, its option bag included. +**Not moved.** A write whose stored rows stay in organizations the caller's wall admits, and an option bag the operation is handed that names only such organizations, behave as before; an operation that names no tenant key keeps its reach, under `group` the union of the caller's memberships included. A bag a before-hook leaves is judged against the caller's active organization alone where no verdict is worked out for the operation, so for a `group` member it is narrower than the member's union. Objects outside tenancy, objects with no organization column, and a platform operator crossing the wall on an object whose posture permits it are answered as the caller's own requests answer them. System work that runs for no caller (a scheduled run, a platform plugin's own system context, the seeders) is unchanged, its option bag included. Also in this change: `@objectstack/objectql`'s `OperationContext` gains `driverTenantScopeCheck` (type `DriverTenantScopeCheck`), an enforcement layer's bound on the explicit `tenantId` / `tenantIds` of an operation's option bag. The engine applies it to every driver bag it builds for that operation, after every before-hook; absent, nothing changes. diff --git a/packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts b/packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts index f105dbbbeba..4ff682cdf22 100644 --- a/packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts +++ b/packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts @@ -487,6 +487,7 @@ describe('group: a system flow run for a member of two organizations reads exact expect(r.status, JSON.stringify(r.body)).toBe(404); expect(r.body.error.code).toBe('RECORD_NOT_FOUND'); expect(await rowNamed(TASK, 'DEL-C')).toBeDefined(); + await ql.delete(TASK, { where: { id: foreign.id }, context: { isSystem: true, tenantId: orgs.C } }); }); }); diff --git a/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts b/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts index 5db046c3a4b..eab962752ec 100644 --- a/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts +++ b/packages/plugins/organizations/src/elevated-organization-wall.writes.wall.test.ts @@ -638,13 +638,13 @@ describe('an app-authored elevation’s writes are judged by its caller’s orga if (r.status === 403) expect(r.body.error.code).toBe('PERMISSION_DENIED'); }; - it('a predicate update never reaches another organization’s rows', async () => { + it('control: a predicate update never reaches another organization’s rows', async () => { await reseed(); heldWrite(await withCfg(orgB, () => run(alice, 'eoww_cfg_update'))); expect((await rowNamed('B1'))!.touched ?? null).toBeNull(); }); - it('a predicate delete never reaches another organization’s rows', async () => { + it('control: a predicate delete never reaches another organization’s rows', async () => { await reseed(); heldWrite(await withCfg(orgB, () => run(alice, 'eoww_cfg_delete'))); expect(await rowNamed('B1')).toBeDefined(); From b87b3cdd84f0f68dae2ca42644792450e105a5b6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 22:27:38 +0000 Subject: [PATCH 14/18] test(objectql): the beyond-projection control names its off-type option bag as such Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- packages/objectql/src/engine-driver-options.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/objectql/src/engine-driver-options.test.ts b/packages/objectql/src/engine-driver-options.test.ts index 5f14ccffe59..b1d2228206c 100644 --- a/packages/objectql/src/engine-driver-options.test.ts +++ b/packages/objectql/src/engine-driver-options.test.ts @@ -21,6 +21,7 @@ import { describe, it, expect } from 'vitest'; import { DriverOptionsSchema } from '@objectstack/spec/data'; +import type { EngineQueryOptions } from '@objectstack/spec/data'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import { ObjectQL } from './engine.js'; import { @@ -330,7 +331,9 @@ describe('the tenant keys the engine fills itself are not judged as the bag’s' it('control: a bag that asks beyond the projected scope is still judged', async () => { const { engine, asked } = await groupEngineWithRefusingCheck(); - await expect(engine.find('dopt_task', { where: {}, tenantId: 'org_c', context: MEMBER } as any)).rejects.toMatchObject({ code: 'PERMISSION_DENIED' }); + // The driver pass-through keys ride the bag at runtime; the typed options do not declare them. + const beyond = { where: {}, tenantId: 'org_c', context: MEMBER } as unknown as EngineQueryOptions; + await expect(engine.find('dopt_task', beyond)).rejects.toMatchObject({ code: 'PERMISSION_DENIED' }); expect(asked).toEqual([{ tenantId: 'org_c', tenantIds: undefined }]); }); }); From 122619b9c1975f35f3015e5815889798f4866bb8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 23:10:47 +0000 Subject: [PATCH 15/18] test(objectql): every verb under group with no tenant key leaves the driver tenant-scope check unasked Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- .../src/engine-driver-options.test.ts | 19 +++++++++++++++++++ .../src/app-automation-organization-wall.ts | 2 +- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/packages/objectql/src/engine-driver-options.test.ts b/packages/objectql/src/engine-driver-options.test.ts index b1d2228206c..f285034f270 100644 --- a/packages/objectql/src/engine-driver-options.test.ts +++ b/packages/objectql/src/engine-driver-options.test.ts @@ -329,6 +329,25 @@ describe('the tenant keys the engine fills itself are not judged as the bag’s' expect(asked).toEqual([]); }); + it('every verb under group with no tenant key reaches the driver, and the check is never asked', async () => { + const { engine, received, asked } = await groupEngineWithRefusingCheck(); + const [a] = (await engine.insert('dopt_task', [{ title: 'a', status: 'todo' }, { title: 'b', status: 'todo' }], { context: MEMBER } as any)) as Array< + Record + >; + await engine.find('dopt_task', { where: { status: 'todo' }, context: MEMBER }); + await engine.findOne('dopt_task', { where: { id: a!.id }, context: MEMBER }); + await engine.count('dopt_task', { where: { status: 'todo' } }, { context: MEMBER }); + await engine.update('dopt_task', { id: a!.id, title: 'a2' }, { context: MEMBER } as any); + await engine.update('dopt_task', { status: 'done' }, { where: { status: 'todo' }, multi: true, context: MEMBER } as any); + await engine.delete('dopt_task', { where: { id: a!.id }, context: MEMBER } as any); + await engine.delete('dopt_task', { where: { status: 'done' }, multi: true, context: MEMBER } as any); + for (const method of ['find', 'findOne', 'update', 'updateMany', 'delete', 'deleteMany']) { + expect(received.some((c) => c.method === method), method).toBe(true); + } + expect(received.some((c) => c.method === 'bulkCreate' || c.method === 'create')).toBe(true); + expect(asked).toEqual([]); + }); + it('control: a bag that asks beyond the projected scope is still judged', async () => { const { engine, asked } = await groupEngineWithRefusingCheck(); // The driver pass-through keys ride the bag at runtime; the typed options do not declare them. diff --git a/packages/plugins/plugin-security/src/app-automation-organization-wall.ts b/packages/plugins/plugin-security/src/app-automation-organization-wall.ts index 2882925d2f3..47d051c6a52 100644 --- a/packages/plugins/plugin-security/src/app-automation-organization-wall.ts +++ b/packages/plugins/plugin-security/src/app-automation-organization-wall.ts @@ -481,7 +481,7 @@ export async function applyAppAutomationOrganizationWall( // them at the plain door: a row stored in an organization the caller's wall // does not admit, or an update left in none, is refused. The judging half // only — the system strips stay off. A row in the caller's own active - // organization needs no verdict, so the common write pays nothing. + // organization needs no verdict, so the common write pays no verdict. if (operation === 'insert' || operation === 'update') { const prior = opCtx.postHookWriteImageCheck; opCtx.postHookWriteImageCheck = { From dab31e1d3901f4d195f9ab24abe677fa6697458a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:56:18 +0000 Subject: [PATCH 16/18] docs(plugin-security): the option-bag rule states that a bag inside the engine's own projection passes; pin the in-union case Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- .changeset/sec2-wf9p-f12.md | 4 +-- content/docs/permissions/system-context.mdx | 2 +- .../src/engine-driver-options.test.ts | 15 ++++++++++ ...ed-organization-wall.postures.wall.test.ts | 30 +++++++++++++++++++ .../src/app-automation-organization-wall.ts | 17 ++++++----- 5 files changed, 58 insertions(+), 10 deletions(-) diff --git a/.changeset/sec2-wf9p-f12.md b/.changeset/sec2-wf9p-f12.md index ac9e06e0ff9..8b32d22fbaf 100644 --- a/.changeset/sec2-wf9p-f12.md +++ b/.changeset/sec2-wf9p-f12.md @@ -19,9 +19,9 @@ The rule: an app-authored elevation (an action body, a hook that runs as system, - a write is judged again on the rows its before-hooks leave: a row stored in an organization outside the caller's wall, or an update that leaves a row in no organization, is refused with `403 PERMISSION_DENIED`; - a write (`insert`, `update`, `delete`, `purge`) whose option bag names an organization outside the caller's wall, or clears `tenantId`, is refused with `403 PERMISSION_DENIED`; - a read (`find`, `findOne`) whose option bag names or clears an organization scope is answered by the read rule: the caller's wall is composed onto its predicate, so it reads only rows the wall admits; - - the option bag a before-hook leaves (a key it sets, a bag it replaces or hands back) is judged by the same rule where the engine builds the driver's options: a write's is refused with `403 PERMISSION_DENIED`, a read's is narrowed to the organizations the wall admits. Where no verdict is worked out for the operation, that bag is judged against the caller's active organization alone. + - the option bag a before-hook leaves (a key it sets, a bag it replaces or hands back) is judged by the same rule where the engine builds the driver's options: a write's is refused with `403 PERMISSION_DENIED`, a read's is narrowed to the organizations the wall admits. A bag naming only organizations inside the scope the engine itself projects for the caller (its active organization, or under `group` its memberships) is not judged further; where no verdict is worked out for the operation, a bag beyond that scope is judged against the caller's active organization. -**Not moved.** A write whose stored rows stay in organizations the caller's wall admits, and an option bag the operation is handed that names only such organizations, behave as before; an operation that names no tenant key keeps its reach, under `group` the union of the caller's memberships included. A bag a before-hook leaves is judged against the caller's active organization alone where no verdict is worked out for the operation, so for a `group` member it is narrower than the member's union. Objects outside tenancy, objects with no organization column, and a platform operator crossing the wall on an object whose posture permits it are answered as the caller's own requests answer them. System work that runs for no caller (a scheduled run, a platform plugin's own system context, the seeders) is unchanged, its option bag included. +**Not moved.** A write whose stored rows stay in organizations the caller's wall admits, and an option bag the operation is handed that names only such organizations, behave as before; an operation that names no tenant key keeps its reach, under `group` the union of the caller's memberships included. A bag a before-hook leaves that names only organizations inside that projected scope behaves as before too, under `group` any of the caller's memberships included. Objects outside tenancy, objects with no organization column, and a platform operator crossing the wall on an object whose posture permits it are answered as the caller's own requests answer them. System work that runs for no caller (a scheduled run, a platform plugin's own system context, the seeders) is unchanged, its option bag included. Also in this change: `@objectstack/objectql`'s `OperationContext` gains `driverTenantScopeCheck` (type `DriverTenantScopeCheck`), an enforcement layer's bound on the explicit `tenantId` / `tenantIds` of an operation's option bag. The engine applies it to every driver bag it builds for that operation, after every before-hook; absent, nothing changes. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 23bf0461709..b24c988e8e1 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -101,7 +101,7 @@ bugs — it is the protection or the side effect that silently does not happen. |:--|:---|:---|:---|:---| | 1 | **The whole security middleware short-circuits** before any gate runs | plugin-security | Get: every CRUD/FLS/tenant/owner gate below skipped in one branch. Lose: every gate under it in this lane at once, down to and including the write-bypass row that widens the effective write scope to `org` (row 7) — this is the single largest behaviour on the page | `registerAuthzMiddleware` | | 1b | **App-authored automation's system context is REFUSED governed writes to the identity-assignment objects** — a flow run's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and an action body's; checked ahead of the middleware's short-circuit, beside the append-only refusal (`assertAppAutomationAppendOnlyWriteAllowed`) | plugin-security | Get: nothing — an insert, update, delete, transfer, restore or purge of `sys_user_position`, `sys_user_permission_set`, `sys_invitation` or `sys_member` from a context carrying `isSystem` and either a `flowRunId` (a `runAs: 'system'` flow's data nodes) or the app-automation elevation mark (`@objectstack/core`; set only by a hook's `runAs: 'system'` derivation, by the action body's execution-context builder and `ObjectRepository.execute`, and on the api of a hook bound through the hook binder, whose inherited system context and `sudo()` it marks), at any depth of their writes, is refused `PERMISSION_DENIED` before the short-circuit skips the ADR-0090 D12 gate and the identity write guard. The platform's own system api (`platformSystemApi`, objectql) takes the mark and `flowRunId` off a platform hook's api, for the audit writer's own ledger rows. On an app-authored hook's api, on the api an action door hands its handler (a host code action handler's included) and on the api `ObjectRepository.execute` hands the action it dispatches (`ctx.api.object(o).execute(name)`), and on every api derived from any of them, it answers what that api's `sudo()` answers, mark kept, so this refusal, and the action body's owner stamp in the next row, hold through it too. Lose: nothing a platform writer held — a system context with neither (the seeders, better-auth and its reconciliation, invitation placement, platform code's `sudo()`, which never sets the mark, and a hook registered in code) passes on to the short-circuit unchanged, reads are not judged, and a `runAs: 'user'` flow or hook carries no `isSystem`, so the D12 gate judges it as the user it acts for | `elevationSource`, `appAuthoredHookApi` | -| 1c | **App-authored automation's system context meets its caller's organization wall** — an action body's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and a flow run's, read by the same predicate as the identity refusal above (`applyAppAutomationOrganizationWall`, plugin-security); checked ahead of the middleware's short-circuit | plugin-security | Get: its reads and writes are judged by the organization wall of the caller it runs for, under every posture and on every object. Such a context that carries a caller (a `userId`, or the guest entry's envelope) is judged by the caller's own Layer 0 (ADR-0095 D1), computed over the caller's own context and permission sets (resolved for the caller where the context does not carry them, as a flow run's does not). An insert with no active organization on a walled tenant object is refused (`403 PERMISSION_DENIED`); for every such caller, one with an active organization included, a write whose own data names an organization outside its scope or empties a row's organization is refused (`403 PERMISSION_DENIED`); a write is judged again on the rows its before-hooks leave, by the same rule, as the plain door judges it; the option bag's `tenantId` / `tenantIds` never widen it past the caller's wall — a write (an insert included) whose bag names an organization outside it, or clears the key, is refused (`403 PERMISSION_DENIED`), and a read whose bag does is answered by the read rule, the caller's wall composed onto its predicate; the bag its before-hooks leave, set, replaced or handed back, is judged by the same rule where the engine builds the driver's options (`OperationContext.driverTenantScopeCheck`), against the caller's active organization alone where no verdict was worked out for the operation; on a federated object its reads are those of the caller's organization scope and a by-id write of a row outside it answers `404 RECORD_NOT_FOUND`, the check read inside the transaction the write carries. A caller the wall denies — no active organization under `isolated`, an empty membership set under `group`, no membership under `single` — reads nothing of a tenant-scoped object, and its delete and purge are answered by that read rule as its plain door answers them (ADR-0123 D2): a predicate delete matches nothing and a by-id delete answers `404 RECORD_NOT_FOUND`. Every other write is refused `PERMISSION_DENIED` (403), naming what is missing (ADR-0123 D4). A system flow run whose own user is its caller carries that user's membership set and posture rung from run setup (a decided segment, a run that began for no caller and a child run of either carry neither); the wall asks Layer 0 alone and resolves what a context lacks once per run. Lose: nothing the caller held — a caller with an active organization keeps its organization's reach (the union of its memberships under `group`); objects outside tenancy, objects with no organization column and a platform operator crossing the wall on a posture-permitting object answer as the caller's plain door answers them. An elevation that carries no caller (a scheduled run, a record-change run fired by a write that carried no user), a system flow that began for no caller in every segment (after an approval decision too, `runCallerOf`, core) and a run a write of such a segment starts, and every platform system context are unchanged | `elevationSource` | +| 1c | **App-authored automation's system context meets its caller's organization wall** — an action body's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and a flow run's, read by the same predicate as the identity refusal above (`applyAppAutomationOrganizationWall`, plugin-security); checked ahead of the middleware's short-circuit | plugin-security | Get: its reads and writes are judged by the organization wall of the caller it runs for, under every posture and on every object. Such a context that carries a caller (a `userId`, or the guest entry's envelope) is judged by the caller's own Layer 0 (ADR-0095 D1), computed over the caller's own context and permission sets (resolved for the caller where the context does not carry them, as a flow run's does not). An insert with no active organization on a walled tenant object is refused (`403 PERMISSION_DENIED`); for every such caller, one with an active organization included, a write whose own data names an organization outside its scope or empties a row's organization is refused (`403 PERMISSION_DENIED`); a write is judged again on the rows its before-hooks leave, by the same rule, as the plain door judges it; the option bag's `tenantId` / `tenantIds` never widen it past the caller's wall — a write (an insert included) whose bag names an organization outside it, or clears the key, is refused (`403 PERMISSION_DENIED`), and a read whose bag does is answered by the read rule, the caller's wall composed onto its predicate; the bag its before-hooks leave, set, replaced or handed back, is judged by the same rule where the engine builds the driver's options (`OperationContext.driverTenantScopeCheck`): a bag naming only organizations inside the scope the engine itself projects for the caller (its active organization, or under `group` its memberships) is not judged further, and where no verdict was worked out for the operation a bag beyond that scope is judged against the caller's active organization; on a federated object its reads are those of the caller's organization scope and a by-id write of a row outside it answers `404 RECORD_NOT_FOUND`, the check read inside the transaction the write carries. A caller the wall denies — no active organization under `isolated`, an empty membership set under `group`, no membership under `single` — reads nothing of a tenant-scoped object, and its delete and purge are answered by that read rule as its plain door answers them (ADR-0123 D2): a predicate delete matches nothing and a by-id delete answers `404 RECORD_NOT_FOUND`. Every other write is refused `PERMISSION_DENIED` (403), naming what is missing (ADR-0123 D4). A system flow run whose own user is its caller carries that user's membership set and posture rung from run setup (a decided segment, a run that began for no caller and a child run of either carry neither); the wall asks Layer 0 alone and resolves what a context lacks once per run. Lose: nothing the caller held — a caller with an active organization keeps its organization's reach (the union of its memberships under `group`); objects outside tenancy, objects with no organization column and a platform operator crossing the wall on a posture-permitting object answer as the caller's plain door answers them. An elevation that carries no caller (a scheduled run, a record-change run fired by a write that carried no user), a system flow that began for no caller in every segment (after an approval decision too, `runCallerOf`, core) and a run a write of such a segment starts, and every platform system context are unchanged | `elevationSource` | | 2 | **`owner_id` is not auto-stamped on INSERT** (the step 3.5 anchor guard is inside the block row 1 skips) — except an action body's insert | plugin-security | Lose: the row lands `owner_id = NULL`, so the default `owner_only_writes` policy hides it **from its own creator**. Get: nothing — this is a gap, not a capability. Except an action body's: an insert from a context carrying `isSystem` and the `'action'` app-automation elevation mark, with no `flowRunId`, has every EMPTY `owner_id` stamped with the envelope's own `userId` ahead of the short-circuit, by the same stamp step 3.5 applies (nothing for the guest; an owner the body sets is kept; an `owner_id` supplied empty beside a supplied queue parks the row). Like a direct create, such an insert is the invoker's own record, so assignment rules (ADR-0142 D5), which route only a row whose owner and queue are both still empty, route neither; a body has no spelling today that asks a rule to route its row. The mark is set on every handler an action door dispatches (a host code action handler included) and by `ObjectRepository.execute`. A flow run, a hook's `runAs: 'system'`, the seeders and every other system context still land the owner they write, or none, and an unowned, queue-less one is still routed | the step 3.5 guard block and the short-circuit that skips it are both inside `registerAuthzMiddleware`; the action-body exception is `isActionBodyElevation` | | 3 | Row-level read filter resolves to "no filter" | plugin-security | Get: unscoped reads. Lose: row-level scoping entirely | `getReadFilter` | | 4 | Field-level security returns **all** fields | plugin-security | Get: every column readable (`getReadableFields`) and writable (`getWritableFields`), and every field a disabled package withholds named to it (`getMetadataReadableWithheldFields`, so the served object's `_withheldFields` keeps every entry). Lose: field masking | `resolveProjectionFieldMask`, `computeMetadataReadableWithheldFields` | diff --git a/packages/objectql/src/engine-driver-options.test.ts b/packages/objectql/src/engine-driver-options.test.ts index f285034f270..cdd0db78a5c 100644 --- a/packages/objectql/src/engine-driver-options.test.ts +++ b/packages/objectql/src/engine-driver-options.test.ts @@ -348,6 +348,21 @@ describe('the tenant keys the engine fills itself are not judged as the bag’s' expect(asked).toEqual([]); }); + it('a bag a before-hook leaves naming only the caller’s memberships passes under group, unjudged', async () => { + const { engine, received, asked } = await groupEngineWithRefusingCheck(); + let leave: Record | undefined; + engine.registerHook('beforeFind', async (ctx: any) => { + if (leave) ctx.input.options = { ...(ctx.input.options ?? {}), ...leave }; + }, { object: 'dopt_task' }); + for (const keys of [{ tenantId: 'org_b' }, { tenantIds: [ORG, 'org_b'] }]) { + leave = keys; + await engine.find('dopt_task', { where: {}, context: MEMBER }); + const find = received.filter((c) => c.method === 'find').at(-1)!; + for (const [k, v] of Object.entries(keys)) expect(find.options![k], k).toEqual(v); + } + expect(asked).toEqual([]); + }); + it('control: a bag that asks beyond the projected scope is still judged', async () => { const { engine, asked } = await groupEngineWithRefusingCheck(); // The driver pass-through keys ride the bag at runtime; the typed options do not declare them. diff --git a/packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts b/packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts index 4ff682cdf22..445539fbb0b 100644 --- a/packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts +++ b/packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts @@ -85,6 +85,7 @@ const APP = { { name: 'eop_delete_by_id', label: 'Delete by id', objectName: TASK, type: 'script', target: 'eopDeleteById' }, { name: 'eop_purge_by_id', label: 'Purge by id', objectName: TASK, type: 'script', target: 'eopPurgeById' }, { name: 'eop_delete_parents', label: 'Delete parents', objectName: TASK, type: 'script', target: 'eopDeleteParents' }, + { name: 'eop_hook_bag_read', label: 'Hook bag read', objectName: TASK, type: 'script', target: 'eopHookBagRead' }, ], flows: [ { @@ -419,6 +420,25 @@ describe('group: a system flow run for a member of two organizations reads exact await ctx.api.object(TASK).delete({ where: { id: String(ctx.params?.target) }, permanent: true }); return { purged: 1 }; }); + // A before-hook that leaves the read's bag naming the organization the next + // handler names. + let hookBagOrg: string | undefined; + ql.registerHook( + 'beforeFind', + async (ctx: any) => { + if (hookBagOrg !== undefined) ctx.input.options = { ...(ctx.input.options ?? {}), tenantIds: [hookBagOrg] }; + }, + { object: TASK }, + ); + ql.registerAction(TASK, 'eopHookBagRead', async (ctx: any) => { + hookBagOrg = String(ctx.params?.org); + try { + const rows = await ctx.api.object(TASK).find({ where: {} }); + return { seen: rows.map((r: any) => r.name).sort() }; + } finally { + hookBagOrg = undefined; + } + }); ql.registerAction(TASK, 'eopDeleteParents', async (ctx: any) => { await ctx.api.object(PARENT).delete({ where: { name: String(ctx.params?.name) }, multi: true }); return { removed: 1 }; @@ -481,6 +501,16 @@ describe('group: a system flow run for a member of two organizations reads exact expect(await rowNamed(CHILD, 'K-A')).toBeUndefined(); }); + it('a bag a before-hook leaves naming another of the member’s organizations reads there', async () => { + const r = await run('eop_hook_bag_read', { org: orgs.B }); + expect(r.status, JSON.stringify(r.body)).toBe(200); + expect(r.body.data.seen).toEqual(['B1']); + // control: one naming an organization the member does not hold reads nothing there. + const outside = await run('eop_hook_bag_read', { org: orgs.C }); + expect(outside.status, JSON.stringify(outside.body)).toBe(200); + expect(outside.body.data.seen).not.toContain('C1'); + }); + it('control: a row of an organization the member does not hold answers as a row that is not there', async () => { const foreign = await seed(TASK, orgs.C, 'DEL-C'); const r = await run('eop_delete_by_id', { target: foreign.id }); diff --git a/packages/plugins/plugin-security/src/app-automation-organization-wall.ts b/packages/plugins/plugin-security/src/app-automation-organization-wall.ts index 47d051c6a52..360a86fd16c 100644 --- a/packages/plugins/plugin-security/src/app-automation-organization-wall.ts +++ b/packages/plugins/plugin-security/src/app-automation-organization-wall.ts @@ -54,11 +54,13 @@ * the plain door's is. The bag a before-hook leaves — set, replaced or * handed back — is judged by the same rule where the engine builds the * driver's options (`OperationContext.driverTenantScopeCheck`): a write's is - * refused, a read's is narrowed to what the wall admits. Where no verdict - * is worked out for the operation (a caller with an active organization, - * whose wall the engine already projects), that bag is judged against the - * caller's active organization alone — narrower than a `group` member's - * union, never wider; + * refused, a read's is narrowed to what the wall admits. The engine asks + * the check only for keys beyond the scope it itself projects for the + * caller (its active organization, or under `group` its memberships), so a + * bag inside that scope passes. Where no verdict is worked out for the + * operation (a caller with an active organization, whose wall the engine + * already projects), a bag beyond it is judged against the caller's active + * organization; * - a caller the wall DENIES — no active organization under `isolated`, an * empty membership set under `group`, a person outside every organization * under `single` (ADR-0093 D8.1, as amended) — reads nothing (zero rows, no @@ -510,8 +512,9 @@ export async function applyAppAutomationOrganizationWall( // The bag the engine builds the driver's options from — whatever bag the // before-hooks leave, set, replaced or handed back — is judged where the - // engine builds them: against the organizations the verdict admits, or — - // where none is worked out — the caller's own active organization alone. + // engine builds them, for keys beyond the scope the engine itself projects + // for the caller: against the organizations the verdict admits, or — where + // none is worked out — the caller's own active organization. // A denied caller's delete and purge keep the read rule (they match nothing). let deniedRemoval = false; if (BAG_VERBS.has(operation)) { From 3c7d45f861ff85c77b30e280457798e51841a4d4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:53:26 +0000 Subject: [PATCH 17/18] fix(objectql): the driver tenant-scope check judges a plain copy of tenantIds, and the driver is handed that copy Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- .../src/engine-driver-options.test.ts | 41 ++++++++++++++++++- .../objectql/src/engine-driver-options.ts | 36 +++++++++++++--- packages/objectql/src/engine-top-level.ts | 14 ++++--- 3 files changed, 79 insertions(+), 12 deletions(-) diff --git a/packages/objectql/src/engine-driver-options.test.ts b/packages/objectql/src/engine-driver-options.test.ts index cdd0db78a5c..9345d96eaad 100644 --- a/packages/objectql/src/engine-driver-options.test.ts +++ b/packages/objectql/src/engine-driver-options.test.ts @@ -21,7 +21,7 @@ import { describe, it, expect } from 'vitest'; import { DriverOptionsSchema } from '@objectstack/spec/data'; -import type { EngineQueryOptions } from '@objectstack/spec/data'; +import type { EngineQueryOptions, EngineUpdateOptions } from '@objectstack/spec/data'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import { ObjectQL } from './engine.js'; import { @@ -363,6 +363,45 @@ describe('the tenant keys the engine fills itself are not judged as the bag’s' expect(asked).toEqual([]); }); + it('a tenantIds array that answers differently on a later read reaches the driver as it was judged', async () => { + const { engine, received, asked } = await groupEngineWithRefusingCheck(); + let reads = 0; + // Reads the caller's own organization first and another organization after; + // its own `every` claims every member is inside the projection. + const shifting: string[] = []; + Object.defineProperty(shifting, 0, { enumerable: true, configurable: true, get: () => (reads++ === 0 ? ORG : 'org_c') }); + Object.defineProperty(shifting, 'every', { value: () => true }); + engine.registerHook('beforeFind', async (ctx: any) => { + ctx.input.options = { ...(ctx.input.options ?? {}), tenantIds: shifting }; + }, { object: 'dopt_task' }); + await engine.find('dopt_task', { where: {}, context: MEMBER }); + const find = received.filter((c) => c.method === 'find').at(-1)!; + expect(find.options!.tenantIds).not.toBe(shifting); + expect(find.options!.tenantIds).toEqual([ORG]); + expect(asked).toEqual([]); + }); + + it('a tenantIds array whose own every lies is judged by what it holds', async () => { + const { engine, asked } = await groupEngineWithRefusingCheck(); + const lying = [ORG, 'org_c']; + Object.defineProperty(lying, 'every', { value: () => true }); + engine.registerHook('beforeFind', async (ctx: any) => { + ctx.input.options = { ...(ctx.input.options ?? {}), tenantIds: lying }; + }, { object: 'dopt_task' }); + await expect(engine.find('dopt_task', { where: {}, context: MEMBER })).rejects.toMatchObject({ code: 'PERMISSION_DENIED' }); + expect(asked).toEqual([{ tenantId: undefined, tenantIds: [ORG, 'org_c'] }]); + }); + + it('on a write, a cleared key, a superset of the projection and a non-array tenantIds are judged', async () => { + for (const keys of [{ tenantId: null }, { tenantId: '' }, { tenantIds: [ORG, 'org_b', 'org_c'] }, { tenantIds: 'org_b' }]) { + const { engine, asked } = await groupEngineWithRefusingCheck(); + // The driver pass-through keys ride the bag at runtime; the typed options do not declare them. + const bag = { where: { status: 'todo' }, multi: true, context: MEMBER, ...keys } as unknown as EngineUpdateOptions; + await expect(engine.update('dopt_task', { status: 'done' }, bag)).rejects.toMatchObject({ code: 'PERMISSION_DENIED' }); + expect(asked.length, JSON.stringify(keys)).toBeGreaterThan(0); + } + }); + it('control: a bag that asks beyond the projected scope is still judged', async () => { const { engine, asked } = await groupEngineWithRefusingCheck(); // The driver pass-through keys ride the bag at runtime; the typed options do not declare them. diff --git a/packages/objectql/src/engine-driver-options.ts b/packages/objectql/src/engine-driver-options.ts index ce1c928d030..3573569d1c5 100644 --- a/packages/objectql/src/engine-driver-options.ts +++ b/packages/objectql/src/engine-driver-options.ts @@ -202,8 +202,12 @@ export function mergeDriverOptionsIntoHookView( /** * Does a bag's explicit `tenantId` / `tenantIds` ask for any organization the * engine's own projection for the call (`tenantScope`) does not already - * scope to — or clear the key the projection fills? With no projection (an - * object outside the driver's tenant scope), any explicit key asks beyond it. + * scope to — or clear a key (`null`, `''`, a non-array `tenantIds`)? Where the + * engine projects no tenant scope for the call — an object outside the + * driver's tenant scope, a verdict with no wall, a denied caller with no + * active organization — any explicit key asks beyond it. `tenantIds` is read + * as the caller hands it in {@link copyTenantIds}'s plain copy, never through + * the bag's own array methods. */ function asksBeyondProjectedScope( declared: Record, @@ -214,10 +218,23 @@ function asksBeyondProjectedScope( const inProjection = (id: unknown): boolean => typeof id === 'string' && projected.has(id); const { tenantId, tenantIds } = declared; if (tenantId !== undefined && !inProjection(tenantId)) return true; - if (tenantIds !== undefined && !(Array.isArray(tenantIds) && tenantIds.every(inProjection))) return true; + if (tenantIds !== undefined && !(Array.isArray(tenantIds) && Array.prototype.every.call(tenantIds, inProjection))) return true; return false; } +/** + * A bag's `tenantIds`, read once by index into a plain array: what the check + * judges is then exactly what the driver is handed, whatever the caller's + * array does on a later read. A value that is not an array is returned as is. + */ +function copyTenantIds(tenantIds: unknown): unknown { + if (!Array.isArray(tenantIds)) return tenantIds; + const length = tenantIds.length; + const copy: unknown[] = []; + for (let i = 0; i < length; i++) copy.push(tenantIds[i]); + return copy; +} + /** * Build the DriverOptions blob passed to every IDataDriver call. * @@ -383,9 +400,16 @@ export function buildDriverOptions( // {@link OperationContext.driverTenantScopeCheck}), the bound judges the keys // the bag carries NOW — after every before-hook, whatever bag it left. Keys // that ask for nothing beyond the scope the engine projects for this very - // call are not judged: they are what the engine itself fills into the hooks' - // view of the bag (`mergeDriverOptionsIntoHookView`), and a later build of - // the same operation reads them back from there. + // call (its active organization; under `group`, its memberships) are not + // judged, whoever set them: the engine's own projection already scopes the + // driver to them — which is also what lets a later build of the operation + // read back the keys the engine itself filled into the hooks' view + // (`mergeDriverOptionsIntoHookView`). A key beyond that scope, or one that + // clears it, is judged. `tenantIds` is copied once, so the judged value and + // the driver's are the same array. + if (scope.tenantScopeCheck && declared && declared.tenantIds !== undefined) { + declared.tenantIds = copyTenantIds(declared.tenantIds); + } if ( scope.tenantScopeCheck && declared && diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index 10fcaa33f5b..663889be91b 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -4178,9 +4178,12 @@ export interface OperationContext { * `tenantId` / `tenantIds` in this operation's option bag may ask for. An * explicit key wins the driver's scope under every verdict (see * `buildDriverOptions`), and a before-hook can set, replace or hand back - * the bag after every middleware has run; so the engine applies this check - * itself, at every driver bag it builds for the operation, to the keys the - * bag carries at that moment. + * the bag after every middleware has run; so the engine asks this check + * itself, at each driver bag it builds for the operation, about the keys + * the bag carries at that moment that ask beyond the scope the engine + * projects for the call (its active organization; under `group`, its + * memberships) or clear it. Keys inside that scope are handed to the + * driver unjudged. * * Set by an enforcement layer's middleware, and only by it: the security * plugin sets it for an app-authored elevation that runs for a caller, so @@ -4251,8 +4254,9 @@ export interface OperationContext { /** * [ADR-0095 D1] The judgement {@link OperationContext.driverTenantScopeCheck} * carries. `judge` receives the tenant keys the option bag carries when the - * engine builds a driver bag for the operation (called only when the bag - * carries at least one of them), and answers the keys the driver is to be + * engine builds a driver bag for the operation — called only when one of + * them asks beyond the scope the engine projects for the call, or clears + * it — and answers the keys the driver is to be * handed in their place: the same, narrowed, or `undefined` for a key the * operation's own scope is to fill. It refuses by throwing. */ From a1e5b48cc688e4d15aaea7d9e68bc6f20f7dda2d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:56:08 +0000 Subject: [PATCH 18/18] test(organizations): pin a hook-left option bag inside a group member's organizations on an elevated update, delete and insert; the rule's text states that such a bag is admitted Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_017xRBcSSsTBYe1u4FyH5PGf --- .changeset/sec2-wf9p-f12.md | 4 +- content/docs/permissions/system-context.mdx | 2 +- ...ed-organization-wall.postures.wall.test.ts | 59 +++++++++++++++++++ .../src/app-automation-organization-wall.ts | 8 +-- 4 files changed, 66 insertions(+), 7 deletions(-) diff --git a/.changeset/sec2-wf9p-f12.md b/.changeset/sec2-wf9p-f12.md index 8b32d22fbaf..ad5952e1000 100644 --- a/.changeset/sec2-wf9p-f12.md +++ b/.changeset/sec2-wf9p-f12.md @@ -19,10 +19,10 @@ The rule: an app-authored elevation (an action body, a hook that runs as system, - a write is judged again on the rows its before-hooks leave: a row stored in an organization outside the caller's wall, or an update that leaves a row in no organization, is refused with `403 PERMISSION_DENIED`; - a write (`insert`, `update`, `delete`, `purge`) whose option bag names an organization outside the caller's wall, or clears `tenantId`, is refused with `403 PERMISSION_DENIED`; - a read (`find`, `findOne`) whose option bag names or clears an organization scope is answered by the read rule: the caller's wall is composed onto its predicate, so it reads only rows the wall admits; - - the option bag a before-hook leaves (a key it sets, a bag it replaces or hands back) is judged by the same rule where the engine builds the driver's options: a write's is refused with `403 PERMISSION_DENIED`, a read's is narrowed to the organizations the wall admits. A bag naming only organizations inside the scope the engine itself projects for the caller (its active organization, or under `group` its memberships) is not judged further; where no verdict is worked out for the operation, a bag beyond that scope is judged against the caller's active organization. + - the option bag a before-hook leaves (a key it sets, a bag it replaces or hands back) is judged by the same rule where the engine builds the driver's options: a write's is refused with `403 PERMISSION_DENIED`, a read's is narrowed to the organizations the wall admits. A bag naming only organizations inside the scope the engine itself projects for the caller (its active organization, or under `group` its memberships) is not judged further: under `group` a member's hook-left bag naming another of its organizations is admitted, as at the plain door. A bag beyond that scope, or one that clears a key, is judged against the caller's wall where a verdict is worked out for the operation, and against the caller's active organization alone where none is. **Not moved.** A write whose stored rows stay in organizations the caller's wall admits, and an option bag the operation is handed that names only such organizations, behave as before; an operation that names no tenant key keeps its reach, under `group` the union of the caller's memberships included. A bag a before-hook leaves that names only organizations inside that projected scope behaves as before too, under `group` any of the caller's memberships included. Objects outside tenancy, objects with no organization column, and a platform operator crossing the wall on an object whose posture permits it are answered as the caller's own requests answer them. System work that runs for no caller (a scheduled run, a platform plugin's own system context, the seeders) is unchanged, its option bag included. -Also in this change: `@objectstack/objectql`'s `OperationContext` gains `driverTenantScopeCheck` (type `DriverTenantScopeCheck`), an enforcement layer's bound on the explicit `tenantId` / `tenantIds` of an operation's option bag. The engine applies it to every driver bag it builds for that operation, after every before-hook; absent, nothing changes. +Also in this change: `@objectstack/objectql`'s `OperationContext` gains `driverTenantScopeCheck` (type `DriverTenantScopeCheck`), an enforcement layer's bound on the explicit `tenantId` / `tenantIds` of an operation's option bag. The engine asks it, at each driver bag it builds for that operation after every before-hook, about the explicit keys that ask beyond the scope it projects for the call or clear it, and hands it a plain copy of `tenantIds`; keys inside that scope reach the driver unjudged; absent, nothing changes. The fix for a body or hook: write only into organizations the caller may write in, and leave `tenantId` / `tenantIds` off the option bag, or name an organization the caller's wall admits. A row that must land in another organization is written by a member of that organization, through its own request. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index b24c988e8e1..be89db89232 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -101,7 +101,7 @@ bugs — it is the protection or the side effect that silently does not happen. |:--|:---|:---|:---|:---| | 1 | **The whole security middleware short-circuits** before any gate runs | plugin-security | Get: every CRUD/FLS/tenant/owner gate below skipped in one branch. Lose: every gate under it in this lane at once, down to and including the write-bypass row that widens the effective write scope to `org` (row 7) — this is the single largest behaviour on the page | `registerAuthzMiddleware` | | 1b | **App-authored automation's system context is REFUSED governed writes to the identity-assignment objects** — a flow run's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and an action body's; checked ahead of the middleware's short-circuit, beside the append-only refusal (`assertAppAutomationAppendOnlyWriteAllowed`) | plugin-security | Get: nothing — an insert, update, delete, transfer, restore or purge of `sys_user_position`, `sys_user_permission_set`, `sys_invitation` or `sys_member` from a context carrying `isSystem` and either a `flowRunId` (a `runAs: 'system'` flow's data nodes) or the app-automation elevation mark (`@objectstack/core`; set only by a hook's `runAs: 'system'` derivation, by the action body's execution-context builder and `ObjectRepository.execute`, and on the api of a hook bound through the hook binder, whose inherited system context and `sudo()` it marks), at any depth of their writes, is refused `PERMISSION_DENIED` before the short-circuit skips the ADR-0090 D12 gate and the identity write guard. The platform's own system api (`platformSystemApi`, objectql) takes the mark and `flowRunId` off a platform hook's api, for the audit writer's own ledger rows. On an app-authored hook's api, on the api an action door hands its handler (a host code action handler's included) and on the api `ObjectRepository.execute` hands the action it dispatches (`ctx.api.object(o).execute(name)`), and on every api derived from any of them, it answers what that api's `sudo()` answers, mark kept, so this refusal, and the action body's owner stamp in the next row, hold through it too. Lose: nothing a platform writer held — a system context with neither (the seeders, better-auth and its reconciliation, invitation placement, platform code's `sudo()`, which never sets the mark, and a hook registered in code) passes on to the short-circuit unchanged, reads are not judged, and a `runAs: 'user'` flow or hook carries no `isSystem`, so the D12 gate judges it as the user it acts for | `elevationSource`, `appAuthoredHookApi` | -| 1c | **App-authored automation's system context meets its caller's organization wall** — an action body's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and a flow run's, read by the same predicate as the identity refusal above (`applyAppAutomationOrganizationWall`, plugin-security); checked ahead of the middleware's short-circuit | plugin-security | Get: its reads and writes are judged by the organization wall of the caller it runs for, under every posture and on every object. Such a context that carries a caller (a `userId`, or the guest entry's envelope) is judged by the caller's own Layer 0 (ADR-0095 D1), computed over the caller's own context and permission sets (resolved for the caller where the context does not carry them, as a flow run's does not). An insert with no active organization on a walled tenant object is refused (`403 PERMISSION_DENIED`); for every such caller, one with an active organization included, a write whose own data names an organization outside its scope or empties a row's organization is refused (`403 PERMISSION_DENIED`); a write is judged again on the rows its before-hooks leave, by the same rule, as the plain door judges it; the option bag's `tenantId` / `tenantIds` never widen it past the caller's wall — a write (an insert included) whose bag names an organization outside it, or clears the key, is refused (`403 PERMISSION_DENIED`), and a read whose bag does is answered by the read rule, the caller's wall composed onto its predicate; the bag its before-hooks leave, set, replaced or handed back, is judged by the same rule where the engine builds the driver's options (`OperationContext.driverTenantScopeCheck`): a bag naming only organizations inside the scope the engine itself projects for the caller (its active organization, or under `group` its memberships) is not judged further, and where no verdict was worked out for the operation a bag beyond that scope is judged against the caller's active organization; on a federated object its reads are those of the caller's organization scope and a by-id write of a row outside it answers `404 RECORD_NOT_FOUND`, the check read inside the transaction the write carries. A caller the wall denies — no active organization under `isolated`, an empty membership set under `group`, no membership under `single` — reads nothing of a tenant-scoped object, and its delete and purge are answered by that read rule as its plain door answers them (ADR-0123 D2): a predicate delete matches nothing and a by-id delete answers `404 RECORD_NOT_FOUND`. Every other write is refused `PERMISSION_DENIED` (403), naming what is missing (ADR-0123 D4). A system flow run whose own user is its caller carries that user's membership set and posture rung from run setup (a decided segment, a run that began for no caller and a child run of either carry neither); the wall asks Layer 0 alone and resolves what a context lacks once per run. Lose: nothing the caller held — a caller with an active organization keeps its organization's reach (the union of its memberships under `group`); objects outside tenancy, objects with no organization column and a platform operator crossing the wall on a posture-permitting object answer as the caller's plain door answers them. An elevation that carries no caller (a scheduled run, a record-change run fired by a write that carried no user), a system flow that began for no caller in every segment (after an approval decision too, `runCallerOf`, core) and a run a write of such a segment starts, and every platform system context are unchanged | `elevationSource` | +| 1c | **App-authored automation's system context meets its caller's organization wall** — an action body's, an app-authored hook's (`runAs: 'system'`, a system context it inherits, its `sudo()`) and a flow run's, read by the same predicate as the identity refusal above (`applyAppAutomationOrganizationWall`, plugin-security); checked ahead of the middleware's short-circuit | plugin-security | Get: its reads and writes are judged by the organization wall of the caller it runs for, under every posture and on every object. Such a context that carries a caller (a `userId`, or the guest entry's envelope) is judged by the caller's own Layer 0 (ADR-0095 D1), computed over the caller's own context and permission sets (resolved for the caller where the context does not carry them, as a flow run's does not). An insert with no active organization on a walled tenant object is refused (`403 PERMISSION_DENIED`); for every such caller, one with an active organization included, a write whose own data names an organization outside its scope or empties a row's organization is refused (`403 PERMISSION_DENIED`); a write is judged again on the rows its before-hooks leave, by the same rule, as the plain door judges it; the option bag's `tenantId` / `tenantIds` never widen it past the caller's wall — a write (an insert included) whose bag names an organization outside it, or clears the key, is refused (`403 PERMISSION_DENIED`), and a read whose bag does is answered by the read rule, the caller's wall composed onto its predicate; the bag its before-hooks leave, set, replaced or handed back, is judged by the same rule where the engine builds the driver's options (`OperationContext.driverTenantScopeCheck`): a bag naming only organizations inside the scope the engine itself projects for the caller (its active organization, or under `group` its memberships) is not judged further, and a bag beyond that scope, or one that clears a key, is judged against the caller's wall where a verdict was worked out for the operation and against its active organization alone where none was; on a federated object its reads are those of the caller's organization scope and a by-id write of a row outside it answers `404 RECORD_NOT_FOUND`, the check read inside the transaction the write carries. A caller the wall denies — no active organization under `isolated`, an empty membership set under `group`, no membership under `single` — reads nothing of a tenant-scoped object, and its delete and purge are answered by that read rule as its plain door answers them (ADR-0123 D2): a predicate delete matches nothing and a by-id delete answers `404 RECORD_NOT_FOUND`. Every other write is refused `PERMISSION_DENIED` (403), naming what is missing (ADR-0123 D4). A system flow run whose own user is its caller carries that user's membership set and posture rung from run setup (a decided segment, a run that began for no caller and a child run of either carry neither); the wall asks Layer 0 alone and resolves what a context lacks once per run. Lose: nothing the caller held — a caller with an active organization keeps its organization's reach (the union of its memberships under `group`); objects outside tenancy, objects with no organization column and a platform operator crossing the wall on a posture-permitting object answer as the caller's plain door answers them. An elevation that carries no caller (a scheduled run, a record-change run fired by a write that carried no user), a system flow that began for no caller in every segment (after an approval decision too, `runCallerOf`, core) and a run a write of such a segment starts, and every platform system context are unchanged | `elevationSource` | | 2 | **`owner_id` is not auto-stamped on INSERT** (the step 3.5 anchor guard is inside the block row 1 skips) — except an action body's insert | plugin-security | Lose: the row lands `owner_id = NULL`, so the default `owner_only_writes` policy hides it **from its own creator**. Get: nothing — this is a gap, not a capability. Except an action body's: an insert from a context carrying `isSystem` and the `'action'` app-automation elevation mark, with no `flowRunId`, has every EMPTY `owner_id` stamped with the envelope's own `userId` ahead of the short-circuit, by the same stamp step 3.5 applies (nothing for the guest; an owner the body sets is kept; an `owner_id` supplied empty beside a supplied queue parks the row). Like a direct create, such an insert is the invoker's own record, so assignment rules (ADR-0142 D5), which route only a row whose owner and queue are both still empty, route neither; a body has no spelling today that asks a rule to route its row. The mark is set on every handler an action door dispatches (a host code action handler included) and by `ObjectRepository.execute`. A flow run, a hook's `runAs: 'system'`, the seeders and every other system context still land the owner they write, or none, and an unowned, queue-less one is still routed | the step 3.5 guard block and the short-circuit that skips it are both inside `registerAuthzMiddleware`; the action-body exception is `isActionBodyElevation` | | 3 | Row-level read filter resolves to "no filter" | plugin-security | Get: unscoped reads. Lose: row-level scoping entirely | `getReadFilter` | | 4 | Field-level security returns **all** fields | plugin-security | Get: every column readable (`getReadableFields`) and writable (`getWritableFields`), and every field a disabled package withholds named to it (`getMetadataReadableWithheldFields`, so the served object's `_withheldFields` keeps every entry). Lose: field masking | `resolveProjectionFieldMask`, `computeMetadataReadableWithheldFields` | diff --git a/packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts b/packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts index 445539fbb0b..f0bd4e87e5b 100644 --- a/packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts +++ b/packages/plugins/organizations/src/elevated-organization-wall.postures.wall.test.ts @@ -86,6 +86,7 @@ const APP = { { name: 'eop_purge_by_id', label: 'Purge by id', objectName: TASK, type: 'script', target: 'eopPurgeById' }, { name: 'eop_delete_parents', label: 'Delete parents', objectName: TASK, type: 'script', target: 'eopDeleteParents' }, { name: 'eop_hook_bag_read', label: 'Hook bag read', objectName: TASK, type: 'script', target: 'eopHookBagRead' }, + { name: 'eop_hook_bag_write', label: 'Hook bag write', objectName: TASK, type: 'script', target: 'eopHookBagWrite' }, ], flows: [ { @@ -439,6 +440,29 @@ describe('group: a system flow run for a member of two organizations reads exact hookBagOrg = undefined; } }); + // Before-hooks that leave a write's bag as the next handler names it. + let hookWriteBag: Record | undefined; + for (const event of ['beforeInsert', 'beforeUpdate', 'beforeDelete']) { + ql.registerHook( + event, + async (ctx: any) => { + if (hookWriteBag !== undefined) ctx.input.options = { ...(ctx.input.options ?? {}), ...hookWriteBag }; + }, + { object: TASK }, + ); + } + ql.registerAction(TASK, 'eopHookBagWrite', async (ctx: any) => { + const { verb, names, name, bag } = ctx.params ?? {}; + hookWriteBag = bag; + try { + if (verb === 'insert') await ctx.engine.insert(TASK, { name }); + else if (verb === 'update') await ctx.api.object(TASK).update({ touched: 'hook-bag' }, { where: { name: { $in: names } }, multi: true }); + else await ctx.api.object(TASK).delete({ where: { name: { $in: names } }, multi: true }); + return { done: verb }; + } finally { + hookWriteBag = undefined; + } + }); ql.registerAction(TASK, 'eopDeleteParents', async (ctx: any) => { await ctx.api.object(PARENT).delete({ where: { name: String(ctx.params?.name) }, multi: true }); return { removed: 1 }; @@ -511,6 +535,41 @@ describe('group: a system flow run for a member of two organizations reads exact expect(outside.body.data.seen).not.toContain('C1'); }); + it('a bag a before-hook leaves naming another of the member’s organizations is admitted on a write', async () => { + try { + await seed(TASK, orgs.A, 'UPD-A'); + await seed(TASK, orgs.B, 'UPD-B'); + await seed(TASK, orgs.C, 'UPD-C'); + // A predicate update and delete keep the member's reach: both of its rows, and never another organization's. + const updated = await run('eop_hook_bag_write', { verb: 'update', names: ['UPD-A', 'UPD-B', 'UPD-C'], bag: { tenantIds: [orgs.B] } }); + expect(updated.status, JSON.stringify(updated.body)).toBe(200); + expect((await rowNamed(TASK, 'UPD-A'))?.touched).toBe('hook-bag'); + expect((await rowNamed(TASK, 'UPD-B'))?.touched).toBe('hook-bag'); + expect((await rowNamed(TASK, 'UPD-C'))?.touched ?? null).toBeNull(); + const removed = await run('eop_hook_bag_write', { verb: 'delete', names: ['UPD-A', 'UPD-B', 'UPD-C'], bag: { tenantIds: [orgs.B] } }); + expect(removed.status, JSON.stringify(removed.body)).toBe(200); + expect(await rowNamed(TASK, 'UPD-A')).toBeUndefined(); + expect(await rowNamed(TASK, 'UPD-B')).toBeUndefined(); + expect(await rowNamed(TASK, 'UPD-C')).toBeDefined(); + // An insert lands in the organization the bag names. + const inserted = await run('eop_hook_bag_write', { verb: 'insert', name: 'INS-B', bag: { tenantId: orgs.B } }); + expect(inserted.status, JSON.stringify(inserted.body)).toBe(200); + expect((await rowNamed(TASK, 'INS-B'))?.organization_id).toBe(orgs.B); + } finally { + for (const name of ['UPD-A', 'UPD-B', 'UPD-C', 'INS-B']) { + const row = await rowNamed(TASK, name); + if (row) await ql.delete(TASK, { where: { id: row.id }, context: { isSystem: true, tenantId: row.organization_id } }); + } + } + }); + + it('control: a bag a before-hook leaves naming an organization the member does not hold is refused on a write', async () => { + const r = await run('eop_hook_bag_write', { verb: 'insert', name: 'INS-C', bag: { tenantId: orgs.C } }); + expect(r.status, JSON.stringify(r.body)).toBe(403); + expect(r.body.error.code).toBe('PERMISSION_DENIED'); + expect(await rowNamed(TASK, 'INS-C')).toBeUndefined(); + }); + it('control: a row of an organization the member does not hold answers as a row that is not there', async () => { const foreign = await seed(TASK, orgs.C, 'DEL-C'); const r = await run('eop_delete_by_id', { target: foreign.id }); diff --git a/packages/plugins/plugin-security/src/app-automation-organization-wall.ts b/packages/plugins/plugin-security/src/app-automation-organization-wall.ts index 360a86fd16c..782d2c66ccc 100644 --- a/packages/plugins/plugin-security/src/app-automation-organization-wall.ts +++ b/packages/plugins/plugin-security/src/app-automation-organization-wall.ts @@ -57,10 +57,10 @@ * refused, a read's is narrowed to what the wall admits. The engine asks * the check only for keys beyond the scope it itself projects for the * caller (its active organization, or under `group` its memberships), so a - * bag inside that scope passes. Where no verdict is worked out for the - * operation (a caller with an active organization, whose wall the engine - * already projects), a bag beyond it is judged against the caller's active - * organization; + * bag inside that scope passes. A bag beyond it, or one that clears a key, + * is judged against the verdict where one is worked out, and against the + * caller's active organization alone where none is (a caller with an + * active organization, whose wall the engine already projects); * - a caller the wall DENIES — no active organization under `isolated`, an * empty membership set under `group`, a person outside every organization * under `single` (ADR-0093 D8.1, as amended) — reads nothing (zero rows, no