-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathadmin-user-endpoints.test.ts
More file actions
542 lines (498 loc) · 21 KB
/
Copy pathadmin-user-endpoints.test.ts
File metadata and controls
542 lines (498 loc) · 21 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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { describe, it, expect, vi } from 'vitest';
import {
runAdminCreateUser,
runAdminSetUserPassword,
generateTemporaryPassword,
type AdminUserEndpointDeps,
type AdminActor,
} from './admin-user-endpoints.js';
const ACTOR: AdminActor = { id: 'admin-1', email: 'admin@example.com' };
function makeRequest(body: unknown): Request {
return new Request('http://localhost/api/v1/auth/admin/create-user', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
});
}
function makeDeps(overrides: Partial<Record<string, any>> = {}) {
const createUser = vi.fn(async ({ body }: any) => ({
user: { id: 'user-9', email: body.email, name: body.name },
}));
const engineUpdate = vi.fn(async () => ({}));
const engineCreate = vi.fn(async () => ({}));
const authCtx = {
password: {
hash: vi.fn(async (pw: string) => `hashed(${pw})`),
config: { minPasswordLength: 8, maxPasswordLength: 128 },
},
internalAdapter: {
findUserById: vi.fn(async () => ({ id: 'user-9' })),
findAccounts: vi.fn(async () => [{ providerId: 'credential' }]),
updatePassword: vi.fn(async () => ({})),
createAccount: vi.fn(async () => ({})),
},
};
const warn = vi.fn();
const noteMustChangePasswordIssued = vi.fn();
const deps: AdminUserEndpointDeps = {
getAuthApi: async () => ({ createUser }) as any,
getAuthContext: async () => authCtx as any,
getDataEngine: () => ({ update: engineUpdate, insert: engineCreate }),
assertPasswordComplexity: vi.fn(async () => undefined),
noteMustChangePasswordIssued,
logger: { warn },
...overrides,
};
return { deps, createUser, engineUpdate, engineCreate, authCtx, warn, noteMustChangePasswordIssued };
}
/**
* Security red line (#2766): no mock the endpoint touched may ever have seen
* the plaintext password outside the better-auth hashing surface.
*/
function expectNoPasswordLeak(mocks: ReturnType<typeof makeDeps>, password: string) {
const persistedCalls = [
...mocks.engineCreate.mock.calls, // audit rows
...mocks.warn.mock.calls, // logs
];
for (const call of persistedCalls) {
expect(JSON.stringify(call)).not.toContain(password);
}
// must_change_password stamps must not carry the password either
for (const call of mocks.engineUpdate.mock.calls) {
expect(JSON.stringify(call)).not.toContain(password);
}
}
describe('isLikelyEmail (linear-time, no regex backtracking)', () => {
it('accepts normal addresses and rejects junk', async () => {
const { isLikelyEmail } = await import('./admin-user-endpoints.js');
expect(isLikelyEmail('a@b.co')).toBe(true);
expect(isLikelyEmail('first.last@sub.example.com')).toBe(true);
expect(isLikelyEmail('')).toBe(false);
expect(isLikelyEmail('no-at.example.com')).toBe(false);
expect(isLikelyEmail('a@b')).toBe(false);
expect(isLikelyEmail('a@@b.co')).toBe(false);
expect(isLikelyEmail('a@.co')).toBe(false);
expect(isLikelyEmail('a@b.')).toBe(false);
expect(isLikelyEmail('has space@b.co')).toBe(false);
});
it('is fast on the CodeQL adversarial inputs', async () => {
const { isLikelyEmail } = await import('./admin-user-endpoints.js');
const attack = '!@'.repeat(100_000);
const attack2 = '!@!.' + '!.'.repeat(100_000);
const t0 = Date.now();
expect(isLikelyEmail(attack)).toBe(false);
expect(isLikelyEmail(attack2)).toBe(false);
expect(Date.now() - t0).toBeLessThan(200);
});
});
describe('generateTemporaryPassword', () => {
it('meets the 4-class complexity policy and min length', () => {
for (let i = 0; i < 50; i++) {
const pw = generateTemporaryPassword();
expect(pw.length).toBeGreaterThanOrEqual(16);
expect(/[a-z]/.test(pw)).toBe(true);
expect(/[A-Z]/.test(pw)).toBe(true);
expect(/[0-9]/.test(pw)).toBe(true);
expect(/[^A-Za-z0-9]/.test(pw)).toBe(true);
}
});
it('produces distinct values', () => {
expect(generateTemporaryPassword()).not.toBe(generateTemporaryPassword());
});
});
describe('runAdminCreateUser', () => {
it('rejects a missing/invalid email without calling createUser', async () => {
const m = makeDeps();
const res = await runAdminCreateUser(m.deps, makeRequest({ name: 'x', generatePassword: true }), ACTOR);
expect(res.status).toBe(400);
expect(m.createUser).not.toHaveBeenCalled();
const res2 = await runAdminCreateUser(m.deps, makeRequest({ email: 'not-an-email', generatePassword: true }), ACTOR);
expect(res2.status).toBe(400);
});
it('rejects when neither password nor generatePassword is provided', async () => {
const m = makeDeps();
const res = await runAdminCreateUser(m.deps, makeRequest({ email: 'a@b.co' }), ACTOR);
expect(res.status).toBe(400);
expect(m.createUser).not.toHaveBeenCalled();
});
it('rejects when both password and generatePassword are provided', async () => {
const m = makeDeps();
const res = await runAdminCreateUser(
m.deps,
makeRequest({ email: 'a@b.co', password: 'Explicit1!', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(400);
});
it('creates a user via better-auth, stamps must_change_password, audits, and returns the temp password once', async () => {
const m = makeDeps();
const res = await runAdminCreateUser(
m.deps,
makeRequest({ email: 'New.User@Example.com', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(200);
const data = res.body.data as any;
expect(data.user.id).toBe('user-9');
// email is normalized to lowercase before hitting better-auth
expect(m.createUser.mock.calls[0][0].body.email).toBe('new.user@example.com');
// name defaults to the email local part
expect(m.createUser.mock.calls[0][0].body.name).toBe('New.User');
const temp = data.temporaryPassword as string;
expect(typeof temp).toBe('string');
expect(temp.length).toBeGreaterThanOrEqual(16);
// must_change_password stamped true + gate cache primed
expect(m.engineUpdate).toHaveBeenCalledWith(
'sys_user',
{ id: 'user-9', must_change_password: true },
expect.anything(),
);
expect(m.noteMustChangePasswordIssued).toHaveBeenCalled();
// audit row written without password material
expect(m.engineCreate).toHaveBeenCalledTimes(1);
const [auditObject, auditRow] = m.engineCreate.mock.calls[0];
expect(auditObject).toBe('sys_audit_log');
expect(auditRow.object_name).toBe('sys_user');
expect(auditRow.record_id).toBe('user-9');
expect(JSON.parse(auditRow.metadata).passwordGenerated).toBe(true);
expectNoPasswordLeak(m, temp);
});
it('checks complexity for an explicit password and does not return it', async () => {
const m = makeDeps();
const res = await runAdminCreateUser(
m.deps,
makeRequest({ email: 'a@b.co', password: 'Str0ng!Pass', mustChangePassword: false }),
ACTOR,
);
expect(res.status).toBe(200);
expect(m.deps.assertPasswordComplexity).toHaveBeenCalledWith('Str0ng!Pass');
expect((res.body.data as any).temporaryPassword).toBeUndefined();
// mustChangePassword: false → no stamp
expect(m.engineUpdate).not.toHaveBeenCalled();
expectNoPasswordLeak(m, 'Str0ng!Pass');
});
it('maps a complexity violation to 400 with the policy code', async () => {
const m = makeDeps({
assertPasswordComplexity: vi.fn(async () => {
throw { code: 'PASSWORD_POLICY_VIOLATION', message: 'too weak' };
}),
});
const res = await runAdminCreateUser(m.deps, makeRequest({ email: 'a@b.co', password: 'weak' }), ACTOR);
expect(res.status).toBe(400);
expect(res.body.error?.code).toBe('PASSWORD_POLICY_VIOLATION');
expect(m.createUser).not.toHaveBeenCalled();
});
it('maps USER_ALREADY_EXISTS to 409', async () => {
const m = makeDeps();
m.createUser.mockRejectedValueOnce({
statusCode: 400,
body: { code: 'USER_ALREADY_EXISTS', message: 'User already exists' },
});
const res = await runAdminCreateUser(m.deps, makeRequest({ email: 'a@b.co', generatePassword: true }), ACTOR);
expect(res.status).toBe(409);
expect(res.body.error?.code).toBe('USER_ALREADY_EXISTS');
});
it('reports mustChangePassword: false when the stamp fails (fail-open honesty)', async () => {
const m = makeDeps();
m.engineUpdate.mockRejectedValueOnce(new Error('db down'));
const res = await runAdminCreateUser(m.deps, makeRequest({ email: 'a@b.co', generatePassword: true }), ACTOR);
expect(res.status).toBe(200);
expect((res.body.data as any).mustChangePassword).toBe(false);
expect(m.warn).toHaveBeenCalled();
expectNoPasswordLeak(m, (res.body.data as any).temporaryPassword);
});
// ── #2766 V1.5: phone-only users ────────────────────────────────────────
it('rejects phone-only creation when the phoneNumber plugin is off', async () => {
const m = makeDeps({ phoneNumberEnabled: () => false });
const res = await runAdminCreateUser(
m.deps,
makeRequest({ phoneNumber: '+8613800000000', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(400);
expect(m.createUser).not.toHaveBeenCalled();
});
it('creates a phone-only user with a placeholder email that never contains the phone number', async () => {
const m = makeDeps({ phoneNumberEnabled: () => true });
const res = await runAdminCreateUser(
m.deps,
makeRequest({ phoneNumber: '+86 138-0000-0000', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(200);
const sent = m.createUser.mock.calls[0][0].body;
expect(sent.email).toMatch(/@placeholder\.invalid$/);
expect(sent.email).not.toContain('138');
expect(sent.data.phoneNumber).toBe('+8613800000000'); // normalized
expect(sent.name).toBe('+8613800000000'); // defaults to the phone
expect((res.body.data as any).placeholderEmail).toBe(true);
expectNoPasswordLeak(m, (res.body.data as any).temporaryPassword);
});
it('rejects a malformed phone number', async () => {
const m = makeDeps({ phoneNumberEnabled: () => true });
const res = await runAdminCreateUser(
m.deps,
makeRequest({ phoneNumber: 'not-a-phone', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(400);
});
it('rejects when neither email nor phone is given', async () => {
const m = makeDeps({ phoneNumberEnabled: () => true });
const res = await runAdminCreateUser(m.deps, makeRequest({ generatePassword: true }), ACTOR);
expect(res.status).toBe(400);
});
it('email + phone together: real email wins, phone stored', async () => {
const m = makeDeps({ phoneNumberEnabled: () => true });
const res = await runAdminCreateUser(
m.deps,
makeRequest({ email: 'a@b.co', phoneNumber: '+8613800000000', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(200);
const sent = m.createUser.mock.calls[0][0].body;
expect(sent.email).toBe('a@b.co');
expect(sent.data.phoneNumber).toBe('+8613800000000');
expect((res.body.data as any).placeholderEmail).toBe(false);
});
// ── single-org membership: bind the created user to the sole org ─────────
/**
* Build deps whose data engine also exposes `find`, seeded with a fixed set
* of `sys_organization` / `sys_member` rows. Records `sys_member` inserts so
* a test can assert the membership bind.
*/
function makeDepsWithOrgs(opts: {
orgs?: Array<{ id: string; slug?: string }>;
members?: Array<{ organization_id: string; user_id: string }>;
}) {
const orgs = opts.orgs ?? [];
const members = opts.members ?? [];
const find = vi.fn(async (object: string, query: any) => {
const where = query?.where ?? {};
if (object === 'sys_organization') {
// Honor the slug filter like the real engine — resolveDefaultOrgId
// queries { slug: 'default' } first, then an unfiltered top-2.
const rows = where.slug === undefined ? orgs : orgs.filter((o) => o.slug === where.slug);
return rows.slice(0, query?.limit ?? rows.length);
}
if (object === 'sys_member') {
return members.filter(
(m) =>
(where.organization_id === undefined || m.organization_id === where.organization_id) &&
(where.user_id === undefined || m.user_id === where.user_id),
);
}
return [];
});
const engineUpdate = vi.fn(async () => ({}));
const engineInsert = vi.fn(async () => ({}));
const m = makeDeps({
getDataEngine: () => ({ update: engineUpdate, insert: engineInsert, find }),
});
return { ...m, find, engineUpdate, engineInsert };
}
it('binds the created user to the sole organization (single-org)', async () => {
const m = makeDepsWithOrgs({ orgs: [{ id: 'org_only' }] });
const res = await runAdminCreateUser(
m.deps,
makeRequest({ email: 'a@b.co', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(200);
const data = res.body.data as any;
expect(data.organizationId).toBe('org_only');
expect(data.membershipCreated).toBe(true);
const memberInsert = m.engineInsert.mock.calls.find((c) => c[0] === 'sys_member');
expect(memberInsert).toBeTruthy();
expect(memberInsert![1]).toMatchObject({
organization_id: 'org_only',
user_id: 'user-9',
role: 'member',
});
// audit records the membership outcome
const auditRow = m.engineInsert.mock.calls.find((c) => c[0] === 'sys_audit_log')![1];
const meta = JSON.parse(auditRow.metadata);
expect(meta.organizationId).toBe('org_only');
expect(meta.membershipCreated).toBe(true);
});
it('does NOT bind when the org is ambiguous (multi-org, ≥2 orgs)', async () => {
const m = makeDepsWithOrgs({ orgs: [{ id: 'org_a' }, { id: 'org_b' }] });
const res = await runAdminCreateUser(
m.deps,
makeRequest({ email: 'a@b.co', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(200);
const data = res.body.data as any;
expect(data.organizationId).toBeUndefined();
expect(data.membershipCreated).toBe(false);
expect(m.engineInsert.mock.calls.some((c) => c[0] === 'sys_member')).toBe(false);
});
it('is idempotent when a membership already exists', async () => {
const m = makeDepsWithOrgs({
orgs: [{ id: 'org_only' }],
members: [{ organization_id: 'org_only', user_id: 'user-9' }],
});
const res = await runAdminCreateUser(
m.deps,
makeRequest({ email: 'a@b.co', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(200);
const data = res.body.data as any;
expect(data.organizationId).toBe('org_only');
expect(data.membershipCreated).toBe(false);
expect(m.engineInsert.mock.calls.some((c) => c[0] === 'sys_member')).toBe(false);
});
it('does not fail account creation when the membership bind throws', async () => {
const m = makeDepsWithOrgs({ orgs: [{ id: 'org_only' }] });
m.engineInsert.mockImplementation(async (object: string) => {
if (object === 'sys_member') throw new Error('unique violation');
return {};
});
const res = await runAdminCreateUser(
m.deps,
makeRequest({ email: 'a@b.co', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(200);
const data = res.body.data as any;
expect(data.user.id).toBe('user-9');
expect(data.membershipCreated).toBe(false);
expect(m.warn).toHaveBeenCalled();
});
it('multi-org via tenancy: does NOT bind even when a slug=default org exists (ADR-0093 D3 regression)', async () => {
// A multi-org deployment carries the bootstrap default org NEXT TO real
// tenant orgs. Without the tenancy service the raw resolver would prefer
// slug='default' and mis-bind the new user into it; the tenancy service
// reports multi mode (defaultOrgId → null) and the bind must no-op.
const m = makeDepsWithOrgs({
orgs: [{ id: 'org_default', slug: 'default' }, { id: 'org_tenant_b' }],
});
m.deps.getTenancy = () => ({ defaultOrgId: async () => null });
const res = await runAdminCreateUser(
m.deps,
makeRequest({ email: 'a@b.co', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(200);
const data = res.body.data as any;
expect(data.organizationId).toBeUndefined();
expect(data.membershipCreated).toBe(false);
expect(m.engineInsert.mock.calls.some((c) => c[0] === 'sys_member')).toBe(false);
});
it('single-org via tenancy: binds to the org the tenancy service resolves', async () => {
const m = makeDepsWithOrgs({ orgs: [{ id: 'org_default', slug: 'default' }] });
m.deps.getTenancy = () => ({ defaultOrgId: async () => 'org_default' });
const res = await runAdminCreateUser(
m.deps,
makeRequest({ email: 'a@b.co', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(200);
const data = res.body.data as any;
expect(data.organizationId).toBe('org_default');
expect(data.membershipCreated).toBe(true);
});
it('no-ops the bind (no throw) when the engine has no find surface', async () => {
// Default makeDeps engine exposes only update/insert — the bind must be a
// clean no-op, leaving exactly the audit insert.
const m = makeDeps();
const res = await runAdminCreateUser(
m.deps,
makeRequest({ email: 'a@b.co', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(200);
expect((res.body.data as any).membershipCreated).toBe(false);
expect((res.body.data as any).organizationId).toBeUndefined();
expect(m.engineCreate).toHaveBeenCalledTimes(1); // audit only
});
});
describe('runAdminSetUserPassword', () => {
it('requires userId', async () => {
const m = makeDeps();
const res = await runAdminSetUserPassword(m.deps, makeRequest({ generatePassword: true }), ACTOR);
expect(res.status).toBe(400);
});
it('404s for an unknown user', async () => {
const m = makeDeps();
m.authCtx.internalAdapter.findUserById.mockResolvedValueOnce(null);
const res = await runAdminSetUserPassword(
m.deps,
makeRequest({ userId: 'ghost', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(404);
});
it('updates the credential account when one exists', async () => {
const m = makeDeps();
const res = await runAdminSetUserPassword(
m.deps,
makeRequest({ userId: 'user-9', newPassword: 'Str0ng!Pass' }),
ACTOR,
);
expect(res.status).toBe(200);
expect(m.authCtx.password.hash).toHaveBeenCalledWith('Str0ng!Pass');
expect(m.authCtx.internalAdapter.updatePassword).toHaveBeenCalledWith('user-9', 'hashed(Str0ng!Pass)');
expect(m.authCtx.internalAdapter.createAccount).not.toHaveBeenCalled();
// default mustChangePassword: true
expect(m.engineUpdate).toHaveBeenCalledWith(
'sys_user',
{ id: 'user-9', must_change_password: true },
expect.anything(),
);
expectNoPasswordLeak(m, 'Str0ng!Pass');
});
it('creates a credential account for SSO-onboarded users without one', async () => {
const m = makeDeps();
m.authCtx.internalAdapter.findAccounts.mockResolvedValueOnce([{ providerId: 'oidc' }]);
const res = await runAdminSetUserPassword(
m.deps,
makeRequest({ userId: 'user-9', generatePassword: true }),
ACTOR,
);
expect(res.status).toBe(200);
expect(m.authCtx.internalAdapter.createAccount).toHaveBeenCalledWith(
expect.objectContaining({ userId: 'user-9', providerId: 'credential' }),
);
const temp = (res.body.data as any).temporaryPassword as string;
expect(typeof temp).toBe('string');
expectNoPasswordLeak(m, temp);
});
it('enforces better-auth min password length', async () => {
const m = makeDeps();
const res = await runAdminSetUserPassword(
m.deps,
makeRequest({ userId: 'user-9', newPassword: 'Ab1!' }),
ACTOR,
);
expect(res.status).toBe(400);
expect(m.authCtx.internalAdapter.updatePassword).not.toHaveBeenCalled();
});
it('mustChangePassword: false clears any pending flag instead of setting it', async () => {
const m = makeDeps();
const res = await runAdminSetUserPassword(
m.deps,
makeRequest({ userId: 'user-9', newPassword: 'Str0ng!Pass', mustChangePassword: false }),
ACTOR,
);
expect(res.status).toBe(200);
expect(m.engineUpdate).toHaveBeenCalledWith(
'sys_user',
{ id: 'user-9', must_change_password: false },
expect.anything(),
);
expect((res.body.data as any).mustChangePassword).toBe(false);
});
it('audits without password material', async () => {
const m = makeDeps();
await runAdminSetUserPassword(m.deps, makeRequest({ userId: 'user-9', generatePassword: true }), ACTOR);
const [auditObject, auditRow] = m.engineCreate.mock.calls[0];
expect(auditObject).toBe('sys_audit_log');
const meta = JSON.parse(auditRow.metadata);
expect(meta.event).toBe('user.admin_password_set');
expect(meta.passwordGenerated).toBe(true);
});
});