Study/tests/lockout.test.ts
Elijah 917954d12d
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 29s
Sign-in lockout with console unlock, and forgotten-password reset
- Wrong passwords in a row are counted across every device and kept in
  the database. The first 3 are free; from the 3rd the next attempt
  waits 15 s, 30 s, 1, 2, 5, 15 and 30 minutes; the 10th locks sign-in
  until the unlock code printed to the server log (and saved to
  unlock-code.txt) is entered. Signed-in devices keep working. Only one
  password check runs at a time, so parallel guesses cannot skip a wait.
- "Forgot password?" prints a reset code to the log (reset-code.txt),
  valid once for 15 minutes. It sets a new password, signs out every
  device, lifts any lockout and signs in. Asking again while a code is
  valid prints nothing new.
- Codes are stored hashed; wrong codes count toward the per-address
  limit. RESET_ADMIN_PASSWORD also lifts a lockout.
- Sign-in page: a live countdown during a wait, an unlock step and a
  reset step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 15:46:16 -07:00

138 lines
6.3 KiB
TypeScript

import fs from 'node:fs';
import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { LOGIN_WAITS, LOCKOUT_AFTER } from '../server/auth.ts';
import { createTestApp, PASSWORD, type TestApp } from './helpers.ts';
const apps: TestApp[] = [];
async function newApp(): Promise<TestApp> {
const app = await createTestApp();
apps.push(app);
return app;
}
afterEach(() => {
vi.restoreAllMocks();
for (const app of apps.splice(0)) {
app.close();
fs.rmSync(app.dir, { recursive: true, force: true });
}
});
/** A clock the tests can move forward past each wait. */
function clock() {
let at = Date.now();
vi.spyOn(Date, 'now').mockImplementation(() => at);
return { advance: (seconds: number) => (at += seconds * 1000 + 1) };
}
const login = (t: TestApp, password: string) => t.api('POST', '/api/auth/login', { password }, { cookie: null });
const codeFile = (t: TestApp, kind: 'unlock' | 'reset') => path.join(t.ctx.config.dataDir, `${kind}-code.txt`);
describe('sign-in lockout', () => {
it('allows 3 wrong passwords, then waits longer each time, and locks after 10 until the console code', async () => {
const t = await newApp();
const time = clock();
for (let i = 1; i <= 2; i += 1) expect((await login(t, 'wrong')).status).toBe(401);
// The third wrong password starts the first wait; the next attempt is refused without checking.
const third = await login(t, 'wrong');
expect(third.status).toBe(401);
expect(third.body.error.message).toMatch(/Wait 15 seconds/);
const early = await login(t, PASSWORD);
expect(early.status).toBe(429);
expect(early.headers.get('retry-after')).toBe('15');
// Waits grow with each failure.
for (let failures = 3; failures < LOCKOUT_AFTER - 1; failures += 1) {
time.advance(LOGIN_WAITS[failures]!);
const res = await login(t, 'wrong');
expect(res.status).toBe(401);
expect(res.body.error.details.retryAfter).toBe(LOGIN_WAITS[failures + 1]);
}
expect((await login(t, 'wrong')).status).toBe(429);
time.advance(LOGIN_WAITS[LOCKOUT_AFTER - 1]!);
// The tenth locks sign-in, even for the right password, until the console code is entered.
expect((await login(t, 'wrong')).status).toBe(423);
time.advance(3600);
expect((await login(t, PASSWORD)).status).toBe(423);
expect((await t.api('GET', '/api/auth/status', undefined, { cookie: null })).body.locked).toBe(true);
const code = fs.readFileSync(codeFile(t, 'unlock'), 'utf8').trim();
expect(code).toMatch(/^[0-9A-F]{5}-[0-9A-F]{5}$/);
expect((await t.api('POST', '/api/auth/unlock', { code: 'AAAAA-AAAAA' }, { cookie: null })).status).toBe(403);
expect((await t.api('POST', '/api/auth/unlock', { code: code.toLowerCase().replace('-', '') }, { cookie: null })).status).toBe(200);
expect(fs.existsSync(codeFile(t, 'unlock'))).toBe(false);
expect((await login(t, PASSWORD)).status).toBe(200);
});
it('starts the count again after a correct password, and keeps it across a restart', async () => {
const t = await newApp();
clock();
await login(t, 'wrong');
await login(t, 'wrong');
expect((await login(t, PASSWORD)).status).toBe(200);
await login(t, 'wrong');
await login(t, 'wrong');
expect((await login(t, 'wrong')).status).toBe(401);
expect((await login(t, 'wrong')).status).toBe(429);
// Kept in the database: a fresh server on the same data folder still makes the client wait.
const again = await createTestApp({ dir: t.dir, login: false });
try {
expect((await login(again, PASSWORD)).status).toBe(429);
} finally {
again.close();
}
});
it('keeps devices that are already signed in working while sign-in is locked', async () => {
const t = await newApp();
const time = clock();
for (let i = 0; i < LOCKOUT_AFTER; i += 1) {
await login(t, 'wrong');
time.advance(LOGIN_WAITS[LOGIN_WAITS.length - 1]!);
}
expect((await login(t, PASSWORD)).status).toBe(423);
expect((await t.api('GET', '/api/classes')).status).toBe(200);
});
});
describe('forgotten password reset', () => {
it('sets a new password with the console code, signs out every device and lifts a lockout', async () => {
const t = await newApp();
const time = clock();
for (let i = 0; i < LOCKOUT_AFTER; i += 1) {
await login(t, 'wrong');
time.advance(LOGIN_WAITS[LOGIN_WAITS.length - 1]!);
}
const first = await t.api('POST', '/api/auth/reset/request', {}, { cookie: null });
expect(first.status).toBe(200);
const code = fs.readFileSync(codeFile(t, 'reset'), 'utf8').trim();
// Asking again while the code is valid keeps the same code.
await t.api('POST', '/api/auth/reset/request', {}, { cookie: null });
expect(fs.readFileSync(codeFile(t, 'reset'), 'utf8').trim()).toBe(code);
expect((await t.api('POST', '/api/auth/reset', { code: 'AAAAA-AAAAA', password: 'a brand new password' }, { cookie: null })).status).toBe(403);
expect((await t.api('POST', '/api/auth/reset', { code, password: 'short' }, { cookie: null })).status).toBe(422);
const done = await t.raw('POST', '/api/auth/reset', { cookie: null, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code, password: 'a brand new password' }) });
expect(done.status).toBe(200);
expect(done.headers.get('set-cookie')).toMatch(/sd_session=/);
expect(fs.existsSync(codeFile(t, 'reset'))).toBe(false);
// The old session is gone, the old password no longer works, the lockout is lifted.
expect((await t.api('GET', '/api/classes')).status).toBe(401);
expect((await login(t, PASSWORD)).status).toBe(401);
expect((await login(t, 'a brand new password')).status).toBe(200);
// A used code cannot be used again.
expect((await t.api('POST', '/api/auth/reset', { code, password: 'another new password' }, { cookie: null })).status).toBe(410);
});
it('expires the reset code after 15 minutes', async () => {
const t = await newApp();
const time = clock();
await t.api('POST', '/api/auth/reset/request', {}, { cookie: null });
const code = fs.readFileSync(codeFile(t, 'reset'), 'utf8').trim();
time.advance(15 * 60);
expect((await t.api('POST', '/api/auth/reset', { code, password: 'a brand new password' }, { cookie: null })).status).toBe(410);
expect((await login(t, PASSWORD)).status).toBe(200);
});
});