|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [ADR-0142 D3] `current_user.queues` is resolved by the security plugin from |
| 5 | + * the ownership-queue service, and by nothing else: a member reads the records |
| 6 | + * sitting in their queues, a non-member reads none, and an app resolver that |
| 7 | + * answers `queues` is screened off the reserved key and fails closed. |
| 8 | + * |
| 9 | + * Driven through the whole plugin (`getReadFilter`), so the staging, the |
| 10 | + * resolver screen and the compiler merge are the real ones. |
| 11 | + */ |
| 12 | + |
| 13 | +import { describe, it, expect, vi } from 'vitest'; |
| 14 | +import type { PermissionSet } from '@objectstack/spec/security'; |
| 15 | +import { OWNERSHIP_QUEUE_SERVICE, RESERVED_RLS_MEMBERSHIP_KEYS } from '@objectstack/spec/contracts'; |
| 16 | + |
| 17 | +import { RLS_DENY_FILTER } from './rls-compiler.js'; |
| 18 | +import { SecurityPlugin } from './security-plugin.js'; |
| 19 | +import { kernelQueuesOf, stageKernelQueues } from './kernel-queue-membership.js'; |
| 20 | + |
| 21 | +const bytes = (v: unknown): string => JSON.stringify(v); |
| 22 | + |
| 23 | +const QUEUE_POLICY = { name: 'sitting', object: 'case', operation: 'select', using: 'queue in current_user.queues' }; |
| 24 | +const OWNER_POLICY = { name: 'own', object: 'case', operation: 'select', using: 'owner_id == current_user.id' }; |
| 25 | + |
| 26 | +/** Who sits in which queue, per organization — the fake service's one answer. */ |
| 27 | +const MEMBERSHIP: Record<string, Record<string, string[]>> = { |
| 28 | + org_a: { u_member: ['billing', 'support_tier1'] }, |
| 29 | + org_b: { u_member: ['org_b_only'] }, |
| 30 | +}; |
| 31 | + |
| 32 | +function queueService(overrides: Partial<{ queuesOf: (u: string, o: string | null) => Promise<string[]> }> = {}) { |
| 33 | + const queuesOf = vi.fn( |
| 34 | + overrides.queuesOf ?? (async (userId: string, org: string | null) => MEMBERSHIP[org ?? '']?.[userId] ?? []), |
| 35 | + ); |
| 36 | + return { |
| 37 | + queuesOf, |
| 38 | + resolveQueue: async () => null, |
| 39 | + isMember: async (userId: string, name: string, org: string | null) => |
| 40 | + (MEMBERSHIP[org ?? '']?.[userId] ?? []).includes(name), |
| 41 | + }; |
| 42 | +} |
| 43 | + |
| 44 | +function makeHost(opts: { queues?: unknown; resolver?: unknown; warn?: (...a: unknown[]) => void; policies?: unknown[] }) { |
| 45 | + const schema = { |
| 46 | + name: 'case', |
| 47 | + fields: { id: { name: 'id' }, queue: { name: 'queue' }, owner_id: { name: 'owner_id' } }, |
| 48 | + }; |
| 49 | + const permSet: PermissionSet = { |
| 50 | + name: 'member_default', |
| 51 | + label: 'Member', |
| 52 | + objects: { '*': { allowRead: true } }, |
| 53 | + rowLevelSecurity: opts.policies ?? [QUEUE_POLICY], |
| 54 | + } as never; |
| 55 | + const services: Record<string, unknown> = { |
| 56 | + manifest: { register: () => {} }, |
| 57 | + objectql: { registerMiddleware: () => {}, getSchema: () => schema, findOne: async () => null }, |
| 58 | + metadata: { get: async () => schema, list: async () => [permSet] }, |
| 59 | + }; |
| 60 | + if (opts.queues) services[OWNERSHIP_QUEUE_SERVICE] = opts.queues; |
| 61 | + if (opts.resolver) services['rls-membership-resolver'] = opts.resolver; |
| 62 | + return { |
| 63 | + logger: { info: () => {}, warn: opts.warn ?? (() => {}), error: () => {}, debug: () => {} }, |
| 64 | + registerService: () => {}, |
| 65 | + getService: (name: string) => { |
| 66 | + if (!(name in services)) throw new Error(`service not registered: ${name}`); |
| 67 | + return services[name]; |
| 68 | + }, |
| 69 | + } as never; |
| 70 | +} |
| 71 | + |
| 72 | +async function startedPlugin(opts: Parameters<typeof makeHost>[0]) { |
| 73 | + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' }); |
| 74 | + const host = makeHost(opts); |
| 75 | + await plugin.init(host); |
| 76 | + await plugin.start(host); |
| 77 | + return plugin as unknown as { getReadFilter(object: string, ctx: unknown): Promise<unknown> }; |
| 78 | +} |
| 79 | + |
| 80 | +async function readFilter(opts: Parameters<typeof makeHost>[0], context: Record<string, unknown>) { |
| 81 | + return (await startedPlugin(opts)).getReadFilter('case', context); |
| 82 | +} |
| 83 | + |
| 84 | +describe('current_user.queues — the kernel resolves it from the ownership-queue service', () => { |
| 85 | + it('is a reserved key', () => { |
| 86 | + expect(RESERVED_RLS_MEMBERSHIP_KEYS).toContain('queues'); |
| 87 | + }); |
| 88 | + |
| 89 | + it('⭐ a member reads the records sitting in their queues, in the active organization', async () => { |
| 90 | + const queues = queueService(); |
| 91 | + const filter = await readFilter({ queues }, { userId: 'u_member', tenantId: 'org_a' }); |
| 92 | + expect(filter).toEqual({ queue: { $in: ['billing', 'support_tier1'] } }); |
| 93 | + expect(queues.queuesOf).toHaveBeenCalledWith('u_member', 'org_a'); |
| 94 | + }); |
| 95 | + |
| 96 | + it('⭐ the organization decides the set: the same member in another organization reads that one\'s queues', async () => { |
| 97 | + const filter = await readFilter({ queues: queueService() }, { userId: 'u_member', tenantId: 'org_b' }); |
| 98 | + expect(filter).toEqual({ queue: { $in: ['org_b_only'] } }); |
| 99 | + }); |
| 100 | + |
| 101 | + it('⭐ a non-member reads no sitting record — byte-identical to no queue service at all', async () => { |
| 102 | + const nonMember = await readFilter({ queues: queueService() }, { userId: 'u_outsider', tenantId: 'org_a' }); |
| 103 | + const noService = await readFilter({}, { userId: 'u_outsider', tenantId: 'org_a' }); |
| 104 | + expect(nonMember).toEqual(RLS_DENY_FILTER); |
| 105 | + expect(bytes(nonMember)).toBe(bytes(noService)); |
| 106 | + }); |
| 107 | + |
| 108 | + it('⭐ the set is the same answer the claim gate\'s isMember gives', async () => { |
| 109 | + const queues = queueService(); |
| 110 | + const filter = (await readFilter({ queues }, { userId: 'u_member', tenantId: 'org_a' })) as { |
| 111 | + queue: { $in: string[] }; |
| 112 | + }; |
| 113 | + for (const name of filter.queue.$in) expect(await queues.isMember('u_member', name, 'org_a')).toBe(true); |
| 114 | + }); |
| 115 | + |
| 116 | + it('resolves once per request, and only when a policy reads the key', async () => { |
| 117 | + const queues = queueService(); |
| 118 | + const plugin = await startedPlugin({ queues }); |
| 119 | + const ctx = { userId: 'u_member', tenantId: 'org_a' }; |
| 120 | + await plugin.getReadFilter('case', ctx); |
| 121 | + await plugin.getReadFilter('case', ctx); |
| 122 | + expect(queues.queuesOf).toHaveBeenCalledTimes(1); |
| 123 | + |
| 124 | + const unread = queueService(); |
| 125 | + await readFilter({ queues: unread, policies: [OWNER_POLICY] }, { userId: 'u_member', tenantId: 'org_a' }); |
| 126 | + expect(unread.queuesOf).not.toHaveBeenCalled(); |
| 127 | + }); |
| 128 | + |
| 129 | + it('⛔ fails closed with no signed-in user, and when the service throws (one WARN)', async () => { |
| 130 | + const anonymous = queueService(); |
| 131 | + expect(await readFilter({ queues: anonymous }, { tenantId: 'org_a' })).toEqual(RLS_DENY_FILTER); |
| 132 | + expect(anonymous.queuesOf).not.toHaveBeenCalled(); |
| 133 | + |
| 134 | + const warn = vi.fn(); |
| 135 | + const throwing = queueService({ queuesOf: async () => { throw new Error('sys_queue unavailable'); } }); |
| 136 | + expect(await readFilter({ queues: throwing, warn }, { userId: 'u_member', tenantId: 'org_a' })).toEqual( |
| 137 | + RLS_DENY_FILTER, |
| 138 | + ); |
| 139 | + expect(warn.mock.calls.some(([m]) => String(m).includes('queue membership could not be resolved'))).toBe(true); |
| 140 | + }); |
| 141 | +}); |
| 142 | + |
| 143 | +describe('current_user.queues — no source but the kernel', () => { |
| 144 | + /** An app resolver that claims the reserved key and seats every caller in a VIP queue. */ |
| 145 | + const hostileResolver = { |
| 146 | + keys: ['queues', 'territory_ids'], |
| 147 | + resolve: async () => ({ queues: ['vip_escalations'], territory_ids: ['t1'] }), |
| 148 | + }; |
| 149 | + |
| 150 | + it('⭐ an app resolver answering `queues` is screened (WARN) — the kernel set stands', async () => { |
| 151 | + const warn = vi.fn(); |
| 152 | + const withResolver = await readFilter( |
| 153 | + { queues: queueService(), resolver: hostileResolver, warn }, |
| 154 | + { userId: 'u_member', tenantId: 'org_a' }, |
| 155 | + ); |
| 156 | + const without = await readFilter({ queues: queueService() }, { userId: 'u_member', tenantId: 'org_a' }); |
| 157 | + expect(bytes(withResolver)).toBe(bytes(without)); |
| 158 | + expect(withResolver).toEqual({ queue: { $in: ['billing', 'support_tier1'] } }); |
| 159 | + expect(warn).toHaveBeenCalledWith(expect.stringContaining('RESERVED context key'), { key: 'queues' }); |
| 160 | + }); |
| 161 | + |
| 162 | + it('⭐ …and a non-member it tried to seat still reads nothing — fail closed', async () => { |
| 163 | + const filter = await readFilter( |
| 164 | + { queues: queueService(), resolver: hostileResolver }, |
| 165 | + { userId: 'u_outsider', tenantId: 'org_a' }, |
| 166 | + ); |
| 167 | + expect(filter).toEqual(RLS_DENY_FILTER); |
| 168 | + }); |
| 169 | + |
| 170 | + it('⭐ with no queue service, the resolver\'s `queues` does not fill the gap', async () => { |
| 171 | + const filter = await readFilter({ resolver: hostileResolver }, { userId: 'u_member', tenantId: 'org_a' }); |
| 172 | + expect(filter).toEqual(RLS_DENY_FILTER); |
| 173 | + }); |
| 174 | + |
| 175 | + it('⛔ a `queues` field or bag entry the caller puts on the context is never read', async () => { |
| 176 | + const filter = await readFilter( |
| 177 | + {}, |
| 178 | + { userId: 'u_outsider', tenantId: 'org_a', queues: ['vip_escalations'], rlsMembership: { queues: ['vip_escalations'] } }, |
| 179 | + ); |
| 180 | + expect(filter).toEqual(RLS_DENY_FILTER); |
| 181 | + }); |
| 182 | + |
| 183 | + it('⛔ a context copied for another principal or organization does not carry the staged set', async () => { |
| 184 | + const host = { logger: undefined, ownershipQueueMembership: () => queueService() }; |
| 185 | + const ctx: Record<string, unknown> = { userId: 'u_member', tenantId: 'org_a' }; |
| 186 | + await stageKernelQueues(host, ctx); |
| 187 | + expect(kernelQueuesOf(ctx)).toEqual(['billing', 'support_tier1']); |
| 188 | + expect(kernelQueuesOf({ ...ctx })).toEqual(['billing', 'support_tier1']); |
| 189 | + expect(kernelQueuesOf({ ...ctx, userId: 'u_delegator' })).toBeUndefined(); |
| 190 | + expect(kernelQueuesOf({ ...ctx, tenantId: 'org_b' })).toBeUndefined(); |
| 191 | + }); |
| 192 | +}); |
0 commit comments