-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathresolve-execution-context.test.ts
More file actions
218 lines (196 loc) · 7.77 KB
/
Copy pathresolve-execution-context.test.ts
File metadata and controls
218 lines (196 loc) · 7.77 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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { describe, it, expect } from 'vitest';
import { resolveExecutionContext } from './resolve-execution-context.js';
import { hashApiKey } from './api-key.js';
/**
* Minimal ObjectQL stub. Only `sys_api_key` is populated; every other object
* (sys_member, permission-set link tables, …) resolves to an empty set so the
* tests isolate the API-key verify path.
*/
function makeQl(apiKeyRows: any[]) {
return {
async find(object: string, opts: any) {
const where = opts?.where ?? {};
if (object !== 'sys_api_key') return [];
return apiKeyRows.filter((row) => {
for (const [k, v] of Object.entries(where)) {
if (row[k] !== v) return false;
}
return true;
});
},
};
}
function makeOpts(apiKeyRows: any[], headers: Record<string, string>) {
return {
// No auth service wired — exercises the hand-rolled path only and lets the
// session fallback degrade to anonymous.
getService: async () => undefined,
getQl: async () => makeQl(apiKeyRows),
request: { headers },
};
}
const FUTURE = '2999-01-01T00:00:00Z';
const PAST = '2000-01-01T00:00:00Z';
describe('resolveExecutionContext — API key verify path', () => {
it('resolves a valid key to its owner via x-api-key', async () => {
const raw = 'osk_valid_key';
const rows = [
{ id: 'k1', key: hashApiKey(raw), revoked: false, user_id: 'u1', expires_at: FUTURE },
];
const ctx = await resolveExecutionContext(makeOpts(rows, { 'x-api-key': raw }));
expect(ctx.userId).toBe('u1');
expect(ctx.isSystem).toBe(false);
});
it('resolves a valid key via Authorization: ApiKey <token>', async () => {
const raw = 'osk_valid_key';
const rows = [{ id: 'k1', key: hashApiKey(raw), revoked: false, user_id: 'u1' }];
const ctx = await resolveExecutionContext(
makeOpts(rows, { authorization: `ApiKey ${raw}` }),
);
expect(ctx.userId).toBe('u1');
});
it('rejects a revoked key', async () => {
const raw = 'osk_revoked';
const rows = [{ id: 'k1', key: hashApiKey(raw), revoked: true, user_id: 'u1' }];
const ctx = await resolveExecutionContext(makeOpts(rows, { 'x-api-key': raw }));
expect(ctx.userId).toBeUndefined();
});
it('rejects an expired key', async () => {
const raw = 'osk_expired';
const rows = [
{ id: 'k1', key: hashApiKey(raw), revoked: false, user_id: 'u1', expires_at: PAST },
];
const ctx = await resolveExecutionContext(makeOpts(rows, { 'x-api-key': raw }));
expect(ctx.userId).toBeUndefined();
});
it('rejects an unknown key', async () => {
const rows = [
{ id: 'k1', key: hashApiKey('osk_real'), revoked: false, user_id: 'u1' },
];
const ctx = await resolveExecutionContext(makeOpts(rows, { 'x-api-key': 'osk_wrong' }));
expect(ctx.userId).toBeUndefined();
});
it('does NOT match a plaintext-stored key (only hashed lookup)', async () => {
// A row whose `key` was (wrongly) stored as the raw value must never
// authenticate — the resolver only ever queries by sha256(raw).
const raw = 'osk_plaintext';
const rows = [{ id: 'k1', key: raw, revoked: false, user_id: 'u1' }];
const ctx = await resolveExecutionContext(makeOpts(rows, { 'x-api-key': raw }));
expect(ctx.userId).toBeUndefined();
});
it('parses JSON-string scopes into ctx.permissions', async () => {
const raw = 'osk_scoped';
const rows = [
{
id: 'k1',
key: hashApiKey(raw),
revoked: false,
user_id: 'u1',
scopes: '["data:read","data:write"]',
},
];
const ctx = await resolveExecutionContext(makeOpts(rows, { 'x-api-key': raw }));
expect(ctx.permissions).toContain('data:read');
expect(ctx.permissions).toContain('data:write');
});
it('carries an organization_id through to tenantId when present', async () => {
const raw = 'osk_org';
const rows = [
{
id: 'k1',
key: hashApiKey(raw),
revoked: false,
user_id: 'u1',
organization_id: 'org1',
},
];
const ctx = await resolveExecutionContext(makeOpts(rows, { 'x-api-key': raw }));
expect(ctx.userId).toBe('u1');
expect(ctx.tenantId).toBe('org1');
});
it('returns an anonymous context when no auth header is present', async () => {
const ctx = await resolveExecutionContext(makeOpts([], {}));
expect(ctx.userId).toBeUndefined();
expect(ctx.isSystem).toBe(false);
expect(ctx.roles).toEqual([]);
expect(ctx.permissions).toEqual([]);
});
it('ignores Bearer tokens on the API-key path (no key resolution)', async () => {
const raw = 'osk_valid';
const rows = [{ id: 'k1', key: hashApiKey(raw), revoked: false, user_id: 'u1' }];
// Bearer is a session token, not an API key — must not resolve here.
const ctx = await resolveExecutionContext(
makeOpts(rows, { authorization: `Bearer ${raw}` }),
);
expect(ctx.userId).toBeUndefined();
});
});
/**
* Reference-timezone resolution (ADR-0053 Phase 2, #1978): user preference →
* org default → UTC. Authenticate via API key so a userId is present, then
* seed `sys_user_preference` / `sys_setting` and assert `ctx.timezone`.
*/
describe('resolveExecutionContext — reference timezone (#1978)', () => {
const RAW = 'osk_tz';
const apiKeyRows = [{ id: 'k1', key: hashApiKey(RAW), revoked: false, user_id: 'u1', expires_at: FUTURE }];
function makeTzOpts({ prefs = [], settings = [] }: { prefs?: any[]; settings?: any[] }) {
const tables: Record<string, any[]> = {
sys_api_key: apiKeyRows,
sys_user_preference: prefs,
sys_setting: settings,
};
const ql = {
async find(object: string, opts: any) {
const rows = tables[object] ?? [];
const where = opts?.where ?? {};
return rows.filter((row) => {
for (const [k, v] of Object.entries(where)) {
if (v !== null && typeof v === 'object') continue; // skip $in/operators
if (row[k] !== v) return false;
}
return true;
});
},
};
return {
getService: async () => undefined,
getQl: async () => ql,
request: { headers: { 'x-api-key': RAW } },
};
}
it('prefers the user preference over the org default', async () => {
const ctx = await resolveExecutionContext(makeTzOpts({
prefs: [{ user_id: 'u1', key: 'timezone', value: 'America/New_York' }],
settings: [{ namespace: 'localization', key: 'timezone', scope: 'tenant', value: 'Europe/Paris' }],
}));
expect(ctx.userId).toBe('u1');
expect(ctx.timezone).toBe('America/New_York');
});
it('falls back to the tenant-scoped org default when no user preference', async () => {
const ctx = await resolveExecutionContext(makeTzOpts({
settings: [{ namespace: 'localization', key: 'timezone', scope: 'tenant', value: 'Europe/Paris' }],
}));
expect(ctx.timezone).toBe('Europe/Paris');
});
it('defaults to UTC when neither is set', async () => {
const ctx = await resolveExecutionContext(makeTzOpts({}));
expect(ctx.timezone).toBe('UTC');
});
it('ignores an invalid zone and continues down the chain', async () => {
const ctx = await resolveExecutionContext(makeTzOpts({
prefs: [{ user_id: 'u1', key: 'timezone', value: 'Not/AZone' }],
settings: [{ namespace: 'localization', key: 'timezone', scope: 'tenant', value: 'Asia/Tokyo' }],
}));
expect(ctx.timezone).toBe('Asia/Tokyo');
});
it('leaves timezone unset for anonymous requests', async () => {
const ctx = await resolveExecutionContext({
getService: async () => undefined,
getQl: async () => ({ async find() { return []; } }),
request: { headers: {} },
});
expect(ctx.userId).toBeUndefined();
expect(ctx.timezone).toBeUndefined();
});
});