Skip to content

Commit 9a0e40a

Browse files
committed
wip(security): resolve current_user.queues kernel-side and reserve the key
Claude-Session: https://claude.ai/code/session_01WGufzhD6Fqfyavauv2KoGA Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 7eb613c commit 9a0e40a

15 files changed

Lines changed: 442 additions & 18 deletions

‎packages/lint/src/rule-explanations.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1422,8 +1422,8 @@ const RLS_PREDICATE_UNENFORCEABLE_EXPLANATION: RuleExplanation = {
14221422
RLS_UNCOMPILABLE_DROP,
14231423
// The two key lists are held equal to the rule's per-key probe types by the rule's test.
14241424
'A predicate can pass that shape check and still be refused for the TYPE of the value a `current_user` ' +
1425-
'reference holds on every request. `ExecutionContext` declares, and the kernel resolves, the membership ' +
1426-
'sets `accessible_org_ids`, `org_user_ids` and `positions` as LISTS and `email`, `id` and ' +
1425+
'reference holds on every request. The kernel resolves the membership sets `accessible_org_ids`, ' +
1426+
'`org_user_ids`, `positions` and `queues` as LISTS and `email`, `id` and ' +
14271427
'`organization_id` as one value each, and `current_user` alone is the whole caller context object. A ' +
14281428
'list under `==` / `!=` or handed to a string method, one value on the right of `in`, or the whole ' +
14291429
'context object where one value or one set belongs is refused on EVERY request, so `RLSCompiler` drops ' +
@@ -1478,7 +1478,7 @@ const RLS_PREDICATE_UNENFORCEABLE_EXPLANATION: RuleExplanation = {
14781478
'(`startsWith` / `endsWith` / `contains`) runs only on a field that holds a string, and a date or datetime ' +
14791479
'field only against a value its storage can read. A `{…}` placeholder is saved-filter syntax, and an RLS ' +
14801480
'predicate does not use it: the predicate is CEL, and the caller\'s values are the `current_user` keys ' +
1481-
'(accessible_org_ids, email, id, org_user_ids, organization_id, positions).',
1481+
'(accessible_org_ids, email, id, org_user_ids, organization_id, positions, queues).',
14821482
],
14831483
};
14841484

@@ -1523,7 +1523,7 @@ const RLS_PREDICATE_UNKNOWN_USER_VARIABLE_EXPLANATION: RuleExplanation = {
15231523
paragraphs: [
15241524
// Held equal to `RESERVED_RLS_MEMBERSHIP_KEYS` by the rule's test.
15251525
'The kernel-resolved `current_user` keys are exactly accessible_org_ids, email, id, org_user_ids, ' +
1526-
'organization_id, positions. The only other keys that can EVER appear are §7.3.1 membership sets, which ' +
1526+
'organization_id, positions, queues. The only other keys that can EVER appear are §7.3.1 membership sets, which ' +
15271527
'the runtime stages as ARRAYS and which are therefore usable only as `field in current_user.KEY`. A key ' +
15281528
'outside that list in a scalar position — compared with `==` / `!=` / `<` / `>` or handed to a string ' +
15291529
'method — can therefore never be supplied by any request.',

‎packages/lint/src/validate-rls-predicate-enforceability.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -811,7 +811,9 @@ describe('validateRlsPredicateEnforceability — the messages name the COST, not
811811
* `userId`, `organization_id` ← `tenantId`, the rest by name), and
812812
* `ExecutionContextSchema` declares `userId`, `tenantId` and `email` as strings
813813
* and `positions`, `org_user_ids` and `accessible_org_ids` as string arrays;
814-
* `resolveAuthzContext` produces the same types.
814+
* `resolveAuthzContext` produces the same types. `queues` (ADR-0142 D3) has no
815+
* `ExecutionContext` field: the security plugin stages it as a string array of
816+
* queue names, and the probe binds it as one.
815817
*/
816818
const KERNEL_KEY_RUNTIME_TYPE: Record<string, 'scalar' | 'array'> = {
817819
id: 'scalar',
@@ -820,6 +822,7 @@ const KERNEL_KEY_RUNTIME_TYPE: Record<string, 'scalar' | 'array'> = {
820822
positions: 'array',
821823
org_user_ids: 'array',
822824
accessible_org_ids: 'array',
825+
queues: 'array',
823826
};
824827

825828
describe('validateRlsPredicateEnforceability — the `current_user` set is DERIVED, not transcribed', () => {

‎packages/lint/src/validate-rls-predicate-enforceability.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -561,7 +561,7 @@ export function refusalVerdict(detail: string): string {
561561
* list `IRlsMembershipResolver` is forbidden to supply *because the kernel
562562
* already owns them* — "keys … must not collide with the named context fields
563563
* (`id`, `organization_id`, `positions`, `org_user_ids`, `accessible_org_ids`,
564-
* `email`) — the compiler never lets a membership key clobber those." That is
564+
* `email`, `queues`) — the compiler never lets a membership key clobber those." That is
565565
* the same set `RLSCompiler.compileFilter` builds its `RLSUserContext` from,
566566
* and it is in `@objectstack/spec`, which this package may read (the RLS
567567
* compiler itself is a runtime it may not).
Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
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+
});
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0142 D3] `current_user.queues` — the machine names of the ownership
5+
* queues the caller belongs to in the active organization, resolved by the
6+
* platform and by nothing else.
7+
*
8+
* ## One producer
9+
*
10+
* `queues` is a {@link RESERVED_RLS_MEMBERSHIP_KEYS} key: the registered
11+
* `rls-membership-resolver` is screened off it, the compiler's merge refuses it
12+
* from any `rlsMembership` bag, and `membershipKeys` may not declare it. The
13+
* value comes from here alone, and here it comes from the ownership-queue
14+
* service's `queuesOf` — the same membership answer (`plugin-sharing`'s one
15+
* expander, `access` purpose) the claim gate's `isMember` and the sharing
16+
* owner match read, so an RLS policy and the claim gate cannot disagree about
17+
* who sits in a queue.
18+
*
19+
* ## Where the value lives
20+
*
21+
* On the execution context, under a module-private symbol, together with the
22+
* principal and organization it was resolved for. A caller cannot forge it (no
23+
* string key reaches it, and `context.queues` is never read), and a context
24+
* copied for ANOTHER principal (a delegator's, say) does not carry the first
25+
* one's queues: {@link kernelQueuesOf} answers only for the identity the set
26+
* was resolved for.
27+
*
28+
* ## Lazily, and fail closed
29+
*
30+
* Resolved once per request, and only when a policy about to compile reads the
31+
* key (`stageRlsMembership`): a request that reads none pays nothing. With no
32+
* signed-in user, no ownership-queue service, or a `queuesOf` that throws, the
33+
* key stays unresolved, so every policy reading it drops on the compiler's
34+
* existing path and fails closed. A caller in no queue resolves to `[]`, which
35+
* matches nothing.
36+
*/
37+
38+
import type { IOwnershipQueueService } from '@objectstack/spec/contracts';
39+
40+
/** The members of the security plugin the kernel queue read uses. */
41+
export interface KernelQueueStagingHost {
42+
readonly logger: { warn?: (message: string, meta?: Record<string, unknown>) => void } | undefined;
43+
/** The ownership-queue service, or `null` when no plugin registers it. */
44+
ownershipQueueMembership(): Pick<IOwnershipQueueService, 'queuesOf'> | null;
45+
}
46+
47+
interface StagedQueues {
48+
readonly userId: string;
49+
readonly organizationId: string | null;
50+
readonly queues: readonly string[];
51+
}
52+
53+
const KERNEL_QUEUES = Symbol('objectstack.security.kernelQueues');
54+
55+
/** Per execution context: the one resolution in flight or settled. */
56+
const PENDING = new WeakMap<object, Promise<void>>();
57+
58+
function organizationOf(context: any): string | null {
59+
return context?.tenantId ? String(context.tenantId) : null;
60+
}
61+
62+
/**
63+
* The kernel's `current_user.queues` for this context, or `undefined` when it
64+
* was not resolved for this context's principal and organization.
65+
*/
66+
export function kernelQueuesOf(context: unknown): string[] | undefined {
67+
if (!context || typeof context !== 'object') return undefined;
68+
const staged = (context as Record<symbol, StagedQueues | undefined>)[KERNEL_QUEUES];
69+
if (!staged) return undefined;
70+
const userId = (context as { userId?: unknown }).userId;
71+
if (userId == null || staged.userId !== String(userId)) return undefined;
72+
if (staged.organizationId !== organizationOf(context)) return undefined;
73+
return [...staged.queues];
74+
}
75+
76+
/** Resolve `current_user.queues` onto `context`, once per request. */
77+
export async function stageKernelQueues(host: KernelQueueStagingHost, context: any): Promise<void> {
78+
if (!context || typeof context !== 'object' || context.userId == null) return;
79+
if (kernelQueuesOf(context) !== undefined) return;
80+
let pending = PENDING.get(context);
81+
if (!pending) {
82+
pending = resolveOnto(host, context);
83+
PENDING.set(context, pending);
84+
}
85+
await pending;
86+
}
87+
88+
async function resolveOnto(host: KernelQueueStagingHost, context: any): Promise<void> {
89+
const service = host.ownershipQueueMembership();
90+
if (!service) return;
91+
const userId = String(context.userId);
92+
const organizationId = organizationOf(context);
93+
let names: unknown;
94+
try {
95+
names = await service.queuesOf(userId, organizationId);
96+
} catch (e) {
97+
host.logger?.warn?.(
98+
'[security/ADR-0142] queue membership could not be resolved — policies reading current_user.queues ' +
99+
'fail closed for this request',
100+
{ userId, error: (e as Error)?.message },
101+
);
102+
return;
103+
}
104+
if (!Array.isArray(names)) return;
105+
const staged: StagedQueues = {
106+
userId,
107+
organizationId,
108+
queues: Object.freeze(names.filter((n): n is string => typeof n === 'string')),
109+
};
110+
try {
111+
context[KERNEL_QUEUES] = staged;
112+
} catch {
113+
// A frozen context keeps the key unresolved: fail closed.
114+
}
115+
}

0 commit comments

Comments
 (0)