-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathresolve-authz-context.test.ts
More file actions
468 lines (432 loc) · 20.7 KB
/
Copy pathresolve-authz-context.test.ts
File metadata and controls
468 lines (432 loc) · 20.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { describe, it, expect } from 'vitest';
import { resolveAuthzContext, resolveUserAuthzGrants, resolveLocalizationContext } from './resolve-authz-context.js';
import { POSTURE_RANK } from './posture-ladder.js';
import type { AuthzPosture } from '@objectstack/spec/security';
/**
* Contract test for the SINGLE authorization resolver. Every authorization
* source MUST be honored here — this is the regression net that would have
* caught the REST-vs-dispatcher drift (the REST copy had silently dropped
* sys_user_position / sys_position_permission_set / platform_admin / ai_seat).
*/
// Minimal in-memory ObjectQL: find(object, { where }) with `===` + `$in` match.
function makeQl(tables: Record<string, any[]>) {
return {
async find(object: string, opts: any) {
const rows = tables[object] ?? [];
const where = opts?.where ?? {};
return rows.filter((r) =>
Object.entries(where).every(([k, v]) => {
if (v && typeof v === 'object' && '$in' in (v as any)) return (v as any).$in.includes(r[k]);
return r[k] === v;
}),
);
},
};
}
const session = (userId: string, opts: { email?: string; org?: string } = {}) =>
async () => ({ user: { id: userId, email: opts.email }, session: { activeOrganizationId: opts.org ?? null } });
const H = () => new Headers();
describe('resolveAuthzContext — single source of truth', () => {
it('resolves a custom role granted via sys_user_position (the REST-drift bug)', async () => {
const ql = makeQl({
sys_user: [{ id: 'u1', email: 'ada@x.com' }],
sys_member: [],
sys_user_position: [{ user_id: 'u1', position: 'contributor', organization_id: null }],
sys_user_permission_set: [],
});
const ctx = await resolveAuthzContext({ ql, headers: H(), getSession: session('u1') });
expect(ctx.positions).toContain('contributor');
});
it('normalizes sys_member org roles (owner -> org_owner)', async () => {
const ql = makeQl({
sys_user: [{ id: 'u1' }],
sys_member: [{ user_id: 'u1', role: 'owner', organization_id: 'o1' }],
sys_user_position: [],
sys_user_permission_set: [],
});
const ctx = await resolveAuthzContext({ ql, headers: H(), getSession: session('u1', { org: 'o1' }) });
expect(ctx.positions).toContain('org_owner');
});
it('resolves role-bound permission sets (sys_position_permission_set)', async () => {
const ql = makeQl({
sys_user: [{ id: 'u1' }],
sys_member: [],
sys_user_position: [{ user_id: 'u1', position: 'contributor', organization_id: null }],
sys_user_permission_set: [],
sys_position: [{ id: 'r1', name: 'contributor' }],
sys_position_permission_set: [{ position_id: 'r1', permission_set_id: 'ps1' }],
sys_permission_set: [{ id: 'ps1', name: 'contributor_ps', system_permissions: ['cap_x'] }],
});
const ctx = await resolveAuthzContext({ ql, headers: H(), getSession: session('u1') });
expect(ctx.permissions).toContain('contributor_ps');
expect(ctx.systemPermissions).toContain('cap_x');
});
it('derives platform_admin from an UNSCOPED admin_full_access user grant', async () => {
const ql = makeQl({
sys_user: [{ id: 'u1' }],
sys_member: [],
sys_user_position: [],
sys_user_permission_set: [{ user_id: 'u1', permission_set_id: 'psA', organization_id: null }],
sys_permission_set: [{ id: 'psA', name: 'admin_full_access' }],
});
const ctx = await resolveAuthzContext({ ql, headers: H(), getSession: session('u1') });
expect(ctx.positions).toContain('platform_admin');
});
it('does NOT derive platform_admin from an ORG-scoped admin_full_access grant', async () => {
const ql = makeQl({
sys_user: [{ id: 'u1' }],
sys_member: [],
sys_user_position: [],
sys_user_permission_set: [{ user_id: 'u1', permission_set_id: 'psA', organization_id: 'o1' }],
sys_permission_set: [{ id: 'psA', name: 'admin_full_access' }],
});
const ctx = await resolveAuthzContext({ ql, headers: H(), getSession: session('u1', { org: 'o1' }) });
expect(ctx.positions).not.toContain('platform_admin');
});
it('synthesizes ai_seat from sys_user.ai_access (sqlite integer 1)', async () => {
const ql = makeQl({
sys_user: [{ id: 'u1', ai_access: 1 }],
sys_member: [],
sys_user_position: [],
sys_user_permission_set: [],
});
const ctx = await resolveAuthzContext({ ql, headers: H(), getSession: session('u1') });
expect(ctx.permissions).toContain('ai_seat');
});
it('anonymous (no session, no api key) → empty context', async () => {
const ctx = await resolveAuthzContext({ ql: makeQl({}), headers: H(), getSession: async () => undefined });
expect(ctx.userId).toBeUndefined();
expect(ctx.positions).toEqual([]);
expect(ctx.permissions).toEqual([]);
});
});
// A counting ObjectQL: records how many find() calls hit each object so we can
// assert the de-duplication of redundant authz/localization reads (#2409).
function makeCountingQl(tables: Record<string, any[]>) {
const counts: Record<string, number> = {};
return {
counts,
async find(object: string, opts: any) {
counts[object] = (counts[object] ?? 0) + 1;
const rows = tables[object] ?? [];
const where = opts?.where ?? {};
return rows.filter((r) =>
Object.entries(where).every(([k, v]) => {
if (v && typeof v === 'object' && '$in' in (v as any)) return (v as any).$in.includes(r[k]);
return r[k] === v;
}),
);
},
};
}
describe('resolveAuthzContext — request-scoped read de-duplication (#2409)', () => {
it('reads sys_user at most once even when both email fallback and ai_seat need it', async () => {
// No email in the session → email fallback reads sys_user; ai_seat synthesis
// also needs sys_user. Previously these were two separate queries.
const ql = makeCountingQl({
sys_user: [{ id: 'u1', email: 'ada@x.com', ai_access: 1 }],
sys_member: [],
sys_user_position: [],
sys_user_permission_set: [],
});
const ctx = await resolveAuthzContext({ ql, headers: H(), getSession: session('u1') });
expect(ctx.email).toBe('ada@x.com');
expect(ctx.permissions).toContain('ai_seat');
expect(ql.counts.sys_user).toBe(1);
});
});
describe('resolveLocalizationContext — batched fallback read (#2409)', () => {
it('reads sys_setting once (all three keys) when no settings service is wired', async () => {
const ql = makeCountingQl({
sys_setting: [
{ namespace: 'localization', key: 'timezone', scope: 'tenant', value: 'Asia/Tokyo' },
{ namespace: 'localization', key: 'locale', scope: 'tenant', value: 'ja-JP' },
{ namespace: 'localization', key: 'currency', scope: 'tenant', value: 'JPY' },
],
});
const loc = await resolveLocalizationContext({ ql, tenantId: 'o1' });
expect(loc).toEqual({ timezone: 'Asia/Tokyo', locale: 'ja-JP', currency: 'JPY' });
expect(ql.counts.sys_setting).toBe(1);
});
it('falls back to UTC / en-US when no rows exist', async () => {
const ql = makeCountingQl({ sys_setting: [] });
const loc = await resolveLocalizationContext({ ql });
expect(loc.timezone).toBe('UTC');
expect(loc.locale).toBe('en-US');
expect(loc.currency).toBeUndefined();
});
});
describe('grant validity windows (ADR-0091 D1/D2)', () => {
const NOW = Date.parse('2026-07-10T12:00:00Z');
const PAST = '2026-07-01T00:00:00Z';
const FUTURE = '2026-08-01T00:00:00Z';
it('an expired sys_user_position row does not resolve', async () => {
const ql = makeQl({
sys_user: [{ id: 'u1' }],
sys_member: [],
sys_user_position: [
{ user_id: 'u1', position: 'approver', organization_id: null, valid_until: PAST },
{ user_id: 'u1', position: 'contributor', organization_id: null },
],
sys_user_permission_set: [],
});
const ctx = await resolveAuthzContext({ ql, headers: H(), getSession: session('u1'), nowMs: NOW });
expect(ctx.positions).not.toContain('approver');
expect(ctx.positions).toContain('contributor'); // null bounds = unbounded, unchanged
});
it('a not-yet-active sys_user_position row (future valid_from) does not resolve', async () => {
const ql = makeQl({
sys_user: [{ id: 'u1' }],
sys_member: [],
sys_user_position: [{ user_id: 'u1', position: 'approver', organization_id: null, valid_from: FUTURE }],
sys_user_permission_set: [],
});
const ctx = await resolveAuthzContext({ ql, headers: H(), getSession: session('u1'), nowMs: NOW });
expect(ctx.positions).not.toContain('approver');
});
it('a row inside its [from, until) window resolves; until is exclusive', async () => {
const ql = makeQl({
sys_user: [{ id: 'u1' }],
sys_member: [],
sys_user_position: [
{ user_id: 'u1', position: 'stand_in', organization_id: null, valid_from: PAST, valid_until: FUTURE },
// Boundary: valid_until exactly NOW → inactive AT the bound (half-open).
{ user_id: 'u1', position: 'boundary', organization_id: null, valid_until: '2026-07-10T12:00:00Z' },
],
sys_user_permission_set: [],
});
const ctx = await resolveAuthzContext({ ql, headers: H(), getSession: session('u1'), nowMs: NOW });
expect(ctx.positions).toContain('stand_in');
expect(ctx.positions).not.toContain('boundary');
});
it('an expired direct permission-set grant resolves to nothing — including platform_admin derivation', async () => {
const ql = makeQl({
sys_user: [{ id: 'u1' }],
sys_member: [],
sys_user_position: [],
sys_user_permission_set: [
{ user_id: 'u1', permission_set_id: 'psA', organization_id: null, valid_until: PAST },
],
sys_permission_set: [{ id: 'psA', name: 'admin_full_access' }],
});
const ctx = await resolveAuthzContext({ ql, headers: H(), getSession: session('u1'), nowMs: NOW });
expect(ctx.permissions).not.toContain('admin_full_access');
expect(ctx.positions).not.toContain('platform_admin');
});
it('fails closed on an unparseable valid_until', async () => {
const ql = makeQl({
sys_user: [{ id: 'u1' }],
sys_member: [],
sys_user_position: [{ user_id: 'u1', position: 'approver', organization_id: null, valid_until: 'not-a-date' }],
sys_user_permission_set: [],
});
const ctx = await resolveAuthzContext({ ql, headers: H(), getSession: session('u1'), nowMs: NOW });
expect(ctx.positions).not.toContain('approver');
});
});
describe('audience anchors in the resolver (ADR-0090 D5)', () => {
it('every authenticated principal implicitly holds `everyone` (additive, no cliff)', async () => {
const ql = makeQl({
sys_member: [{ user_id: 'u1', role: 'member', organization_id: 'o1' }],
sys_user_position: [{ user_id: 'u1', position: 'contributor', organization_id: null }],
});
const ctx = await resolveAuthzContext({ ql, headers: H(), getSession: session('u1', { org: 'o1' }) });
// holding an explicit position must NOT cost the baseline anchor
expect(ctx.positions).toContain('contributor');
expect(ctx.positions).toContain('everyone');
});
it('anonymous resolution never gains `everyone`', async () => {
const ql = makeQl({});
const ctx = await resolveAuthzContext({ ql, headers: H(), getSession: async () => undefined });
expect(ctx.positions).not.toContain('everyone');
expect(ctx.userId).toBeUndefined();
});
});
/**
* [ADR-0095 D2/D3] Posture-ladder resolution. A `principal × grants → posture`
* matrix asserting the rung is DERIVED from held capability grants
* (`admin_full_access` → PLATFORM_ADMIN; `organization_admin` → TENANT_ADMIN;
* otherwise MEMBER), never from a better-auth role, plus the strict-nesting
* ordering (PLATFORM_ADMIN > TENANT_ADMIN > MEMBER). `EXTERNAL` is never
* resolved — no external principal type exists yet.
*/
describe('resolveAuthzContext — posture ladder (ADR-0095 D2/D3)', () => {
// Each fixture returns the ql tables + the session getter for one principal.
const FIXTURES: Record<string, { ql: any; getSession: any }> = {
// Unscoped admin_full_access grant → the platform-admin capability.
platform_admin: {
ql: makeQl({
sys_user: [{ id: 'pa' }],
sys_member: [],
sys_user_position: [],
sys_user_permission_set: [{ user_id: 'pa', permission_set_id: 'psA', organization_id: null }],
sys_permission_set: [{ id: 'psA', name: 'admin_full_access' }],
}),
getSession: session('pa'),
},
// Org-scoped organization_admin grant (auto-provisioned from role=admin).
tenant_admin: {
ql: makeQl({
sys_user: [{ id: 'ta' }],
sys_member: [{ user_id: 'ta', role: 'admin', organization_id: 'o1' }],
sys_user_position: [],
sys_user_permission_set: [{ user_id: 'ta', permission_set_id: 'psO', organization_id: 'o1' }],
sys_permission_set: [{ id: 'psO', name: 'organization_admin' }],
}),
getSession: session('ta', { org: 'o1' }),
},
// Ordinary member — no admin capability grant.
member: {
ql: makeQl({
sys_user: [{ id: 'm' }],
sys_member: [{ user_id: 'm', role: 'member', organization_id: 'o1' }],
sys_user_position: [],
sys_user_permission_set: [],
sys_permission_set: [],
}),
getSession: session('m', { org: 'o1' }),
},
// Authenticated but no active org — still the MEMBER floor, not EXTERNAL.
no_org_member: {
ql: makeQl({
sys_user: [{ id: 'n' }],
sys_member: [],
sys_user_position: [],
sys_user_permission_set: [],
}),
getSession: session('n'),
},
};
const EXPECTED_POSTURE: Record<string, AuthzPosture> = {
platform_admin: 'PLATFORM_ADMIN',
tenant_admin: 'TENANT_ADMIN',
member: 'MEMBER',
no_org_member: 'MEMBER',
};
it('resolves the principal × grants → posture matrix', async () => {
const actual: Record<string, AuthzPosture | undefined> = {};
for (const [name, fx] of Object.entries(FIXTURES)) {
const ctx = await resolveAuthzContext({ ql: fx.ql, headers: H(), getSession: fx.getSession });
actual[name] = ctx.posture;
}
expect(actual).toEqual(EXPECTED_POSTURE);
});
it('posture is strictly nested: PLATFORM_ADMIN > TENANT_ADMIN > MEMBER', async () => {
const rank = async (name: string) => {
const fx = FIXTURES[name];
const ctx = await resolveAuthzContext({ ql: fx.ql, headers: H(), getSession: fx.getSession });
return POSTURE_RANK[ctx.posture!];
};
expect(await rank('platform_admin')).toBeGreaterThan(await rank('tenant_admin'));
expect(await rank('tenant_admin')).toBeGreaterThan(await rank('member'));
});
it('platform-admin grant wins over a co-held org-admin grant (capability, not role)', async () => {
// A principal who is BOTH an org admin (role) AND holds the unscoped
// platform grant resolves PLATFORM_ADMIN — derivation reads the capability,
// so the higher rung wins regardless of the better-auth role.
const ql = makeQl({
sys_user: [{ id: 'both' }],
sys_member: [{ user_id: 'both', role: 'admin', organization_id: 'o1' }],
sys_user_position: [],
sys_user_permission_set: [
{ user_id: 'both', permission_set_id: 'psA', organization_id: null },
{ user_id: 'both', permission_set_id: 'psO', organization_id: 'o1' },
],
sys_permission_set: [
{ id: 'psA', name: 'admin_full_access' },
{ id: 'psO', name: 'organization_admin' },
],
});
const ctx = await resolveAuthzContext({ ql, headers: H(), getSession: session('both', { org: 'o1' }) });
expect(ctx.posture).toBe('PLATFORM_ADMIN');
});
it('anonymous principal carries no posture rung', async () => {
const ctx = await resolveAuthzContext({ ql: makeQl({}), headers: H(), getSession: async () => undefined });
expect(ctx.posture).toBeUndefined();
});
});
/**
* #3356 — the userId-driven core, callable WITHOUT an HTTP request. A
* `runAs:'user'` automation run knows the triggering user's id (the record-change
* hook session carries only that) and must build the SAME positions/permissions
* envelope a direct REST request from that user would resolve, so its data ops
* enforce RLS as that user — not the bare member/everyone fallback.
*/
describe('resolveUserAuthzGrants — userId-driven authz for non-HTTP surfaces (#3356)', () => {
it("resolves a known user's positions + permission-set names from the DB", async () => {
const ql = makeQl({
sys_user: [{ id: 'u1', email: 'ada@x.com' }],
sys_member: [{ user_id: 'u1', role: 'admin', organization_id: 'o1' }],
sys_user_position: [{ user_id: 'u1', position: 'approver', organization_id: null }],
sys_user_permission_set: [{ user_id: 'u1', permission_set_id: 'psA', organization_id: null }],
sys_permission_set: [{ id: 'psA', name: 'ehr_all', system_permissions: ['cap_ehr'] }],
});
const grants = await resolveUserAuthzGrants(ql, 'u1', { tenantId: 'o1' });
expect(grants.positions).toContain('org_admin'); // sys_member owner/admin normalized
expect(grants.positions).toContain('approver'); // sys_user_position
expect(grants.positions).toContain('everyone'); // implicit audience anchor
expect(grants.permissions).toContain('ehr_all'); // user-scoped permission set
expect(grants.systemPermissions).toContain('cap_ehr');
expect(grants.email).toBe('ada@x.com');
});
it('matches resolveAuthzContext for the same user — one resolver, one envelope', async () => {
const tables = {
sys_user: [{ id: 'u1', email: 'ada@x.com' }],
sys_member: [],
sys_user_position: [{ user_id: 'u1', position: 'contributor', organization_id: null }],
sys_user_permission_set: [{ user_id: 'u1', permission_set_id: 'ps1', organization_id: null }],
sys_position: [{ id: 'r1', name: 'contributor' }],
sys_position_permission_set: [{ position_id: 'r1', permission_set_id: 'ps1' }],
sys_permission_set: [{ id: 'ps1', name: 'contributor_ps', system_permissions: ['cap_x'] }],
};
const viaHttp = await resolveAuthzContext({ ql: makeQl(tables), headers: H(), getSession: session('u1') });
const viaUser = await resolveUserAuthzGrants(makeQl(tables), 'u1');
expect([...viaUser.positions].sort()).toEqual([...viaHttp.positions].sort());
expect([...viaUser.permissions].sort()).toEqual([...viaHttp.permissions].sort());
expect([...viaUser.systemPermissions].sort()).toEqual([...viaHttp.systemPermissions].sort());
expect(viaUser.posture).toBe(viaHttp.posture);
});
it('seeds caller-supplied permissions FIRST, then appends resolved set names', async () => {
const ql = makeQl({
sys_user: [{ id: 'u1' }],
sys_member: [],
sys_user_position: [],
sys_user_permission_set: [{ user_id: 'u1', permission_set_id: 'ps1', organization_id: null }],
sys_permission_set: [{ id: 'ps1', name: 'sales_ps' }],
});
const grants = await resolveUserAuthzGrants(ql, 'u1', { seedPermissions: ['api:scope'] });
expect(grants.permissions[0]).toBe('api:scope');
expect(grants.permissions).toContain('sales_ps');
});
it('a caller-supplied email wins over the sys_user read', async () => {
const ql = makeQl({ sys_user: [{ id: 'u1', email: 'db@x.com' }], sys_member: [], sys_user_position: [], sys_user_permission_set: [] });
const grants = await resolveUserAuthzGrants(ql, 'u1', { seedEmail: 'session@x.com' });
expect(grants.email).toBe('session@x.com');
});
it('a user with no grants gets the implicit everyone anchor, empty permissions (never null)', async () => {
const ql = makeQl({ sys_user: [{ id: 'u1' }], sys_member: [], sys_user_position: [], sys_user_permission_set: [] });
const grants = await resolveUserAuthzGrants(ql, 'u1');
expect(grants.positions).toEqual(['everyone']);
expect(grants.permissions).toEqual([]);
expect(grants.org_user_ids).toEqual(['u1']);
});
it('fail-closed: no data engine yields an empty-but-valid envelope and never throws', async () => {
const grants = await resolveUserAuthzGrants(undefined, 'u1', { seedPermissions: ['api:scope'] });
expect(grants.positions).toEqual([]);
expect(grants.permissions).toEqual(['api:scope']);
expect(grants.org_user_ids).toEqual(['u1']);
});
it('drops permission-set grants outside their validity window (ADR-0091)', async () => {
const past = new Date(Date.now() - 86_400_000).toISOString();
const ql = makeQl({
sys_user: [{ id: 'u1' }],
sys_member: [],
sys_user_position: [],
sys_user_permission_set: [{ user_id: 'u1', permission_set_id: 'psA', organization_id: null, valid_until: past }],
sys_permission_set: [{ id: 'psA', name: 'expired_ps' }],
});
const grants = await resolveUserAuthzGrants(ql, 'u1');
expect(grants.permissions).not.toContain('expired_ps');
});
});