Files

204 lines
14 KiB
TypeScript

import assert from 'node:assert/strict';
import { after, before, test } from 'node:test';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { closeDatabases, getDatabase, type AccountRow } from '../lib/server/database.ts';
import { hashPassword, verifyPassword } from '../lib/server/password.ts';
import {
AuthError, authenticateSession, changeAccountPassword, createAccount, isSameOrigin,
listAccounts, loginWithPassword, revokeSession, sessionCookie, updateAccount,
} from '../lib/server/auth.ts';
const directory = mkdtempSync(join(tmpdir(), 'demand-auth-tests-'));
const originalEnvironment = { ...process.env };
const initialPassword = 'Initial test password 9274';
let adminId: string;
let adminToken: string;
before(() => {
process.env.DATA_DIR = directory;
process.env.APP_URL = 'https://demands.example.test';
process.env.INITIAL_ADMIN_USERNAME = 'test.admin';
process.env.INITIAL_ADMIN_PASSWORD = initialPassword;
process.env.INITIAL_ADMIN_DISPLAY_NAME = '测试管理员';
delete process.env.LOGIN_CLIENT_IP_HEADER;
});
after(() => {
closeDatabases();
rmSync(directory, { recursive: true, force: true });
process.env = originalEnvironment;
});
test('scrypt hashes are salted and reject altered or malformed values', async () => {
const first = await hashPassword(initialPassword);
const second = await hashPassword(initialPassword);
assert.notEqual(first, second);
assert.equal(await verifyPassword(initialPassword, first), true);
assert.equal(await verifyPassword('different long password', first), false);
assert.equal(await verifyPassword(initialPassword, 'scrypt$999999999$8$1$abc$def'), false);
await assert.rejects(() => hashPassword('short'));
});
test('bootstrap is once-only, stores no plaintext and rotates sessions on first password change', async () => {
const login = await loginWithPassword('TEST.ADMIN', initialPassword);
assert.equal(login.user.mustChangePassword, true);
assert.equal(login.user.role, 'admin');
adminId = login.user.userId;
const stored = getDatabase().prepare('SELECT * FROM accounts WHERE id = ?').bind(adminId).first<AccountRow>()!;
assert.notEqual(stored.password_hash, initialPassword);
const session = getDatabase().prepare('SELECT token_hash FROM sessions WHERE account_id = ?').bind(adminId).first<{ token_hash: string }>()!;
assert.notEqual(session.token_hash, login.token);
assert.equal(authenticateSession(login.token)?.userId, adminId);
const changed = await changeAccountPassword(adminId, initialPassword, 'Changed administrator password 9274');
adminToken = changed.token;
assert.equal(changed.user.mustChangePassword, false);
assert.equal(authenticateSession(login.token), null);
assert.equal(authenticateSession(changed.token)?.userId, adminId);
closeDatabases();
process.env.INITIAL_ADMIN_PASSWORD = 'Different environment secret 1234';
assert.equal(authenticateSession(changed.token)?.userId, adminId, 'session survives DB connection restart');
assert.equal(getDatabase().prepare('SELECT COUNT(*) AS count FROM accounts').first<{ count: number }>()!.count, 1);
assert.equal(await verifyPassword('Changed administrator password 9274', getDatabase().prepare('SELECT password_hash FROM accounts WHERE id = ?').bind(adminId).first<{ password_hash: string }>()!.password_hash), true);
});
test('specified-user provisioning, disable/enable, reset and access guards work', async () => {
const created = await createAccount(adminId, { username: 'business.user', displayName: '业务同事', password: 'First business password 9812', role: 'user' });
assert.equal(created.mustChangePassword, true);
let login = await loginWithPassword('business.user', 'First business password 9812');
assert.equal(authenticateSession(login.token)?.userId, created.userId);
await assert.rejects(() => createAccount(created.userId, { username: 'unauthorized', displayName: '不可创建', password: 'Unauthorized password 123', role: 'admin' }), error => error instanceof AuthError && error.status === 403);
await updateAccount(adminId, { id: created.userId, action: 'disable' });
assert.equal(authenticateSession(login.token), null);
await assert.rejects(() => loginWithPassword('business.user', 'First business password 9812'), error => error instanceof AuthError && error.status === 401);
await updateAccount(adminId, { id: created.userId, action: 'enable' });
login = await loginWithPassword('business.user', 'First business password 9812');
await updateAccount(adminId, { id: created.userId, action: 'reset-password', password: 'Reset business password 5234' });
assert.equal(authenticateSession(login.token), null);
await assert.rejects(() => loginWithPassword('business.user', 'First business password 9812'), error => error instanceof AuthError && error.status === 401);
const resetLogin = await loginWithPassword('business.user', 'Reset business password 5234');
assert.equal(resetLogin.user.mustChangePassword, true);
const listed = listAccounts(adminId);
assert.equal(listed.length, 2);
assert.equal(JSON.stringify(listed).includes('password_hash'), false);
assert.equal(JSON.stringify(listed).includes('token_hash'), false);
await assert.rejects(() => updateAccount(adminId, { id: adminId, action: 'disable' }));
await assert.rejects(() => updateAccount(adminId, { id: adminId, action: 'reset-password', password: 'Unsafe admin reset 99999' }));
await assert.rejects(() => createAccount(adminId, { username: 'BUSINESS.USER', displayName: '重复', password: 'Repeated account password 123', role: 'user' }), error => error instanceof AuthError && error.status === 409);
});
test('persistent login limit stops repeated password guesses', async () => {
for (let attempt = 0; attempt < 5; attempt++) {
await assert.rejects(() => loginWithPassword('nonexistent.user', 'An invalid password 5922'), error => error instanceof AuthError && error.status === 401);
}
closeDatabases();
await assert.rejects(() => loginWithPassword('nonexistent.user', 'An invalid password 5922'), error => error instanceof AuthError && error.status === 429);
});
test('default configuration ignores forwarded headers and has no global login quota', async () => {
const request = new Request('https://demands.example.test/api/auth/login', {
headers: { 'x-forwarded-for': '203.0.113.5', 'x-real-ip': '203.0.113.5' },
});
// A leftover global bucket from an earlier application version must have no effect.
getDatabase().prepare('INSERT INTO login_limits (key, window_start, attempts) VALUES (?, ?, ?)').bind('global', Date.now(), 1000).run();
for (let attempt = 0; attempt < 61; attempt++) {
await assert.rejects(() => loginWithPassword(`default.unknown.${attempt}`, 'An invalid password 5922', request), error => error instanceof AuthError && error.status === 401);
}
const login = await loginWithPassword('test.admin', 'Changed administrator password 9274', request);
assert.equal(login.user.userId, adminId);
revokeSession(login.token);
assert.equal(getDatabase().prepare("SELECT COUNT(*) AS count FROM login_limits WHERE key LIKE 'source:%'").first<{ count: number }>()!.count, 0);
});
test('trusted source limit isolates sources and cannot be bypassed through other headers', async () => {
process.env.LOGIN_CLIENT_IP_HEADER = 'X-Trusted-Client-IP';
const request = (address: string, extra: Record<string, string> = {}) => new Request('https://demands.example.test/api/auth/login', {
headers: { 'x-trusted-client-ip': address, ...extra },
});
try {
for (let attempt = 0; attempt < 60; attempt++) {
await assert.rejects(() => loginWithPassword(`source.unknown.${attempt}`, 'An invalid password 5922', request('192.0.2.10')), error => error instanceof AuthError && error.status === 401);
}
closeDatabases();
await assert.rejects(() => loginWithPassword('test.admin', 'Changed administrator password 9274', request('192.0.2.10')), error => error instanceof AuthError && error.status === 429);
await assert.rejects(() => loginWithPassword('test.admin', 'Changed administrator password 9274', request('192.0.2.10', { 'x-forwarded-for': '198.51.100.9', 'x-real-ip': '198.51.100.9' })), error => error instanceof AuthError && error.status === 429);
await assert.rejects(() => loginWithPassword('test.admin', 'Changed administrator password 9274', request('::ffff:192.0.2.10')), error => error instanceof AuthError && error.status === 429);
const otherSource = await loginWithPassword('test.admin', 'Changed administrator password 9274', request('192.0.2.11'));
assert.equal(otherSource.user.userId, adminId);
revokeSession(otherSource.token);
const buckets = getDatabase().prepare("SELECT key, attempts FROM login_limits WHERE key LIKE 'source:%'").all<{ key: string; attempts: number }>().results;
assert.equal(buckets.length, 2);
assert.deepEqual(buckets.map(bucket => bucket.attempts).sort((a, b) => a - b), [1, 60]);
assert.ok(buckets.every(bucket => /^source:[a-f0-9]{64}$/.test(bucket.key)), 'source IPs are hashed before persistence');
} finally { delete process.env.LOGIN_CLIENT_IP_HEADER; }
});
test('enabled source limit rejects missing, malformed and list-valued trusted headers', async () => {
process.env.LOGIN_CLIENT_IP_HEADER = 'X-Trusted-Client-IP';
try {
for (const address of [undefined, '', 'unknown', '127.1', '192.0.2.1, 192.0.2.2', '192.0.2.1:8080', '[2001:db8::1]', 'fe80::1%eth0']) {
const request = new Request('https://demands.example.test/api/auth/login', {
headers: { 'x-forwarded-for': '192.0.2.99', ...(address === undefined ? {} : { 'x-trusted-client-ip': address }) },
});
await assert.rejects(() => loginWithPassword('test.admin', 'Changed administrator password 9274', request), error => error instanceof AuthError && error.status === 403);
}
await assert.rejects(() => loginWithPassword('test.admin', 'Changed administrator password 9274'), error => error instanceof AuthError && error.status === 403);
process.env.LOGIN_CLIENT_IP_HEADER = 'invalid header name';
await assert.rejects(() => loginWithPassword('test.admin', 'Changed administrator password 9274'), error => error instanceof AuthError && error.status === 503);
} finally { delete process.env.LOGIN_CLIENT_IP_HEADER; }
});
test('equivalent IPv6 source representations use the same quota', async () => {
process.env.LOGIN_CLIENT_IP_HEADER = 'X-Trusted-Client-IP';
try {
const addresses = ['2001:db8::1', '2001:0DB8:0000:0000:0000:0000:0000:0001'];
const countBefore = getDatabase().prepare("SELECT COUNT(*) AS count FROM login_limits WHERE key LIKE 'source:%'").first<{ count: number }>()!.count;
for (let index = 0; index < addresses.length; index++) {
const request = new Request('https://demands.example.test/api/auth/login', { headers: { 'x-trusted-client-ip': addresses[index] } });
await assert.rejects(() => loginWithPassword(`ipv6.unknown.${index}`, 'An invalid password 5922', request), error => error instanceof AuthError && error.status === 401);
}
assert.equal(getDatabase().prepare("SELECT COUNT(*) AS count FROM login_limits WHERE key LIKE 'source:%'").first<{ count: number }>()!.count, countBefore + 1);
} finally { delete process.env.LOGIN_CLIENT_IP_HEADER; }
});
test('administrator reset immediately clears account lockout while retaining source attempts', async () => {
const created = await createAccount(adminId, { username: 'locked.user', displayName: '密码恢复测试', password: 'Locked user initial password 1234', role: 'user' });
process.env.LOGIN_CLIENT_IP_HEADER = 'X-Trusted-Client-IP';
const request = new Request('https://demands.example.test/api/auth/login', { headers: { 'x-trusted-client-ip': '198.51.100.44' } });
try {
for (let attempt = 0; attempt < 5; attempt++) {
await assert.rejects(() => loginWithPassword('locked.user', 'An invalid password 5922', request), error => error instanceof AuthError && error.status === 401);
}
await assert.rejects(() => loginWithPassword('locked.user', 'Locked user initial password 1234', request), error => error instanceof AuthError && error.status === 429);
const sourcesBefore = getDatabase().prepare("SELECT key, window_start, attempts FROM login_limits WHERE key LIKE 'source:%' ORDER BY key").all().results;
await updateAccount(adminId, { id: created.userId, action: 'reset-password', password: 'Locked user reset password 5678' });
const sourcesAfter = getDatabase().prepare("SELECT key, window_start, attempts FROM login_limits WHERE key LIKE 'source:%' ORDER BY key").all().results;
assert.deepEqual(sourcesAfter, sourcesBefore, 'reset only clears the account quota, never the source quota');
const recovered = await loginWithPassword('locked.user', 'Locked user reset password 5678', request);
assert.equal(recovered.user.userId, created.userId);
assert.equal(recovered.user.mustChangePassword, true);
} finally { delete process.env.LOGIN_CLIENT_IP_HEADER; }
});
test('sessions expire and logout invalidates the server-side session', () => {
getDatabase().prepare('UPDATE sessions SET expires_at = 0 WHERE account_id = ?').bind(adminId).run();
assert.equal(authenticateSession(adminToken), null);
assert.equal(authenticateSession('not-a-token'), null);
revokeSession(adminToken);
assert.equal(getDatabase().prepare('SELECT COUNT(*) AS count FROM sessions WHERE account_id = ?').bind(adminId).first<{ count: number }>()!.count, 0);
});
test('CSRF checks require configured origin; sessions use secure HttpOnly cookies', () => {
const request = (headers: Record<string, string>) => new Request('http://internal-container:3000/api/auth/login', { method: 'POST', headers });
assert.equal(isSameOrigin(request({ origin: 'https://demands.example.test' })), true);
assert.equal(isSameOrigin(request({ origin: 'https://attacker.example', 'x-forwarded-host': 'demands.example.test' })), false);
assert.equal(isSameOrigin(request({ 'x-openai-user-id': adminId })), false);
assert.equal(isSameOrigin(request({ origin: 'https://demands.example.test', 'sec-fetch-site': 'cross-site' })), false);
assert.equal(isSameOrigin(request({})), false);
const cookie = sessionCookie('some-token');
assert.match(cookie, /HttpOnly/);
assert.match(cookie, /SameSite=Lax/);
assert.match(cookie, /Secure/);
assert.match(sessionCookie(''), /Max-Age=0/);
});