Files
shared/packages/node-backend/test/authclient.test.js
T

304 lines
12 KiB
JavaScript
Raw Normal View History

import test from 'node:test';
import assert from 'node:assert/strict';
import { APIError, AuthClient, InvalidSessionError } from '../src/authclient.js';
function fakeFetch(responses) {
let call = 0;
return async () => {
const res = responses[Math.min(call, responses.length - 1)];
call += 1;
const bodyText = res.body === undefined ? '' : JSON.stringify(res.body);
return {
status: res.status,
ok: res.status >= 200 && res.status < 300,
json: async () => res.body,
text: async () => bodyText,
headers: { getSetCookie: () => res.cookies ?? [] },
};
};
}
// Records every (url, init) pair a fakeFetch call received, for assertions
// on method/headers/body without a full fetch mock library.
function recordingFetch(responses) {
const calls = [];
const inner = fakeFetch(responses);
const wrapped = async (url, init) => {
calls.push({ url, init });
return inner(url, init);
};
wrapped.calls = calls;
return wrapped;
}
test('constructor assumes https for a bare host', () => {
assert.equal(new AuthClient('auth.example.com').baseUrl, 'https://auth.example.com');
assert.equal(new AuthClient('192.168.1.50:8080').baseUrl, 'https://192.168.1.50:8080');
});
test('constructor leaves an explicit scheme alone', () => {
assert.equal(new AuthClient('http://auth.example.com').baseUrl, 'http://auth.example.com');
assert.equal(new AuthClient('https://auth.example.com').baseUrl, 'https://auth.example.com');
assert.equal(new AuthClient('HTTP://auth.example.com').baseUrl, 'HTTP://auth.example.com');
});
test('constructor strips a trailing slash before checking the scheme', () => {
assert.equal(new AuthClient('auth.example.com/').baseUrl, 'https://auth.example.com');
});
test('constructor trims whitespace and leaves an empty base URL empty', () => {
assert.equal(new AuthClient(' auth.example.com ').baseUrl, 'https://auth.example.com');
assert.equal(new AuthClient('').baseUrl, '');
});
test('validate resolves the user on a valid session', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 7, username: 'gabriel', role: 'admin' } }]),
});
const user = await client.validate('good-token');
assert.deepEqual(user, { id: 7, username: 'gabriel', role: 'admin' });
});
test('validate throws InvalidSessionError on an empty token', async () => {
const client = new AuthClient('https://auth.example.com', { fetchImpl: fakeFetch([{ status: 200, body: {} }]) });
await assert.rejects(() => client.validate(''), InvalidSessionError);
await assert.rejects(() => client.validate(' '), InvalidSessionError);
});
test('validate throws InvalidSessionError when AuthGuard reports invalid', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 401, body: { valid: false } }]),
});
await assert.rejects(() => client.validate('bad-token'), InvalidSessionError);
});
test('tokenFromRequest prefers the Authorization header over the cookie', () => {
const client = new AuthClient('https://auth.example.com');
const req = {
headers: {
authorization: 'Bearer header-token',
cookie: 'auth_session=cookie-token; other=1',
},
};
assert.equal(client.tokenFromRequest(req), 'header-token');
});
test('tokenFromRequest falls back to the auth_session cookie', () => {
const client = new AuthClient('https://auth.example.com');
const req = { headers: { cookie: 'other=1; auth_session=cookie-token' } };
assert.equal(client.tokenFromRequest(req), 'cookie-token');
});
test('middleware attaches authUser on success and 401s on failure', async () => {
const okClient = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 1, username: 'a', role: 'user' } }]),
});
const req = { headers: { authorization: 'Bearer t' } };
let nextCalled = false;
await okClient.middleware()(req, { status: () => ({ json: () => {} }) }, () => {
nextCalled = true;
});
assert.equal(nextCalled, true);
assert.deepEqual(req.authUser, { id: 1, username: 'a', role: 'user' });
const badClient = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 401, body: { valid: false } }]),
});
let statusCode = null;
let jsonBody = null;
const res = {
status(code) {
statusCode = code;
return { json: (body) => (jsonBody = body) };
},
};
await badClient.middleware()({ headers: {} }, res, () => {
throw new Error('next should not be called');
});
assert.equal(statusCode, 401);
assert.deepEqual(jsonBody, { error: 'authentication required' });
});
// --- register/login/.../setupStatus: the additional surface a service that
// runs its own login/admin screens proxied to AuthGuard needs, beyond the
// original validate()-only surface. ---
test('setupStatus reflects AuthGuard setup_required', async () => {
for (const setupRequired of [true, false]) {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 200, body: { setup_required: setupRequired } }]),
});
assert.equal(await client.setupStatus(), setupRequired);
}
});
test('register returns the user and forwards Set-Cookie values', async () => {
const fetchImpl = recordingFetch([
{
status: 201,
body: { user: { id: 1, username: 'root', email: 'root@example.com', role: 'superadmin', totp_enabled: false } },
cookies: ['auth_session=abc; HttpOnly'],
},
]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
const result = await client.register('root', 'root@example.com', 'correct horse battery staple');
assert.deepEqual(result.user, {
id: 1,
username: 'root',
email: 'root@example.com',
role: 'superadmin',
totpEnabled: false,
});
assert.deepEqual(result.cookies, ['auth_session=abc; HttpOnly']);
const sent = JSON.parse(fetchImpl.calls[0].init.body);
assert.deepEqual(sent, { username: 'root', email: 'root@example.com', password: 'correct horse battery staple' });
});
test('login success reports totpEnabled from AuthGuard', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([
{
status: 200,
body: { user: { id: 2, username: 'alice', email: 'alice@example.com', role: 'user', totp_enabled: true } },
cookies: ['auth_session=xyz'],
},
]),
});
const result = await client.login('alice', 'correct horse battery staple', '123456');
assert.equal(result.user.username, 'alice');
assert.equal(result.user.totpEnabled, true);
assert.deepEqual(result.cookies, ['auth_session=xyz']);
});
test('login raises APIError with totpRequired on a 401 asking for a code', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([
{ status: 401, body: { error: 'two-factor authentication code required', totp_required: true } },
]),
});
await assert.rejects(
() => client.login('alice', 'correct horse battery staple'),
(err) => err instanceof APIError && err.statusCode === 401 && err.totpRequired === true,
);
});
test('login raises APIError without totpRequired on invalid credentials', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 401, body: { error: 'invalid username/email or password' } }]),
});
await assert.rejects(
() => client.login('alice', 'wrong password'),
(err) => err instanceof APIError && err.totpRequired === false && err.detailMessage === 'invalid username/email or password',
);
});
test('logout returns the clearing cookies', async () => {
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true }, cookies: ['auth_session=; Max-Age=0'] }]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
const cookies = await client.logout('a-token');
assert.deepEqual(cookies, ['auth_session=; Max-Age=0']);
assert.equal(fetchImpl.calls[0].init.headers.Authorization, 'Bearer a-token');
});
test('me resolves the public user', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([
{ status: 200, body: { user: { id: 3, username: 'bob', email: 'bob@example.com', role: 'admin', totp_enabled: false } } },
]),
});
const user = await client.me('a-token');
assert.equal(user.id, 3);
assert.equal(user.role, 'admin');
});
test('totpEnable returns the provisioned secret', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([{ status: 200, body: { secret: 'SECRET', otpauth_url: 'otpauth://...', enabled: false } }]),
});
const result = await client.totpEnable('a-token');
assert.equal(result.secret, 'SECRET');
assert.equal(result.enabled, false);
});
test('totpVerify and totpDisable send the code as {token}', async () => {
let fetchImpl = recordingFetch([{ status: 200, body: { enabled: true } }]);
let client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.totpVerify('a-token', '123456');
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { token: '123456' });
fetchImpl = recordingFetch([{ status: 200, body: { enabled: false } }]);
client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.totpDisable('a-token', '654321');
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { token: '654321' });
});
test('requestPasswordReset with no identifier sends an empty body (targets the superadmin)', async () => {
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.requestPasswordReset();
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), {});
});
test('confirmPasswordReset sends the code and new password', async () => {
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.confirmPasswordReset('ABCD1234', 'a brand new passphrase');
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { code: 'ABCD1234', password: 'a brand new passphrase' });
});
test('listManagedUsers maps every row', async () => {
const client = new AuthClient('https://auth.example.com', {
fetchImpl: fakeFetch([
{
status: 200,
body: {
users: [
{ id: 1, username: 'root', email: 'root@example.com', role: 'superadmin', created_at: '2026-01-01T00:00:00Z' },
{ id: 2, username: 'bob', email: 'bob@example.com', role: 'user', created_at: '2026-01-02T00:00:00Z' },
],
},
},
]),
});
const users = await client.listManagedUsers('a-token');
assert.equal(users.length, 2);
assert.deepEqual(users[0], {
id: 1,
username: 'root',
email: 'root@example.com',
role: 'superadmin',
createdAt: '2026-01-01T00:00:00Z',
});
});
test('createManagedUser sends only the given fields', async () => {
const fetchImpl = recordingFetch([
{ status: 201, body: { user: { id: 4, username: 'carol', email: 'carol@example.com', role: 'user', created_at: '' } } },
]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
const created = await client.createManagedUser('a-token', {
username: 'carol',
email: 'carol@example.com',
password: 'correct horse battery staple',
});
assert.equal(created.username, 'carol');
const sent = JSON.parse(fetchImpl.calls[0].init.body);
assert.equal('role' in sent, false);
});
test('updateManagedUser PUTs to /api/admin/users/{id}', async () => {
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.updateManagedUser('a-token', 5, { email: 'new@example.com' });
assert.equal(fetchImpl.calls[0].init.method, 'PUT');
assert.equal(fetchImpl.calls[0].url, 'https://auth.example.com/api/admin/users/5');
assert.deepEqual(JSON.parse(fetchImpl.calls[0].init.body), { email: 'new@example.com' });
});
test('deleteManagedUser DELETEs /api/admin/users/{id}', async () => {
const fetchImpl = recordingFetch([{ status: 200, body: { ok: true } }]);
const client = new AuthClient('https://auth.example.com', { fetchImpl });
await client.deleteManagedUser('a-token', 6);
assert.equal(fetchImpl.calls[0].init.method, 'DELETE');
assert.equal(fetchImpl.calls[0].url, 'https://auth.example.com/api/admin/users/6');
});