GCoordinator/tests/auth-and-guards.test.ts

230 lines
7.7 KiB
TypeScript

import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import * as OTPAuth from 'otpauth';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { openDatabase } from '../src/server/db/database.js';
import { SecuritySettingsSchema } from '../src/shared/schemas/settings.schema.js';
import { AuthService } from '../src/server/security/auth.js';
import { RateLimiter, resolveClientIp } from '../src/server/security/guards.js';
const tempDirs: string[] = [];
function makeTempDb() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-auth-test-'));
tempDirs.push(dir);
return openDatabase(path.join(dir, 'gcoord.db'));
}
function generateTotp(secretBase32: string, timestampMs = Date.now()): string {
return new OTPAuth.TOTP({
issuer: 'GCoordinator',
label: 'admin',
algorithm: 'SHA1',
digits: 6,
period: 30,
secret: OTPAuth.Secret.fromBase32(secretBase32),
}).generate({ timestamp: timestampMs });
}
afterEach(() => {
vi.useRealTimers();
while (tempDirs.length > 0) {
fs.rmSync(tempDirs.pop()!, { recursive: true, force: true });
}
});
describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
it('completes Argon2id + TOTP bootstrap, issues single-use recovery codes, and blocks TOTP replay', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
const t0 = 1_700_000_010_000;
vi.setSystemTime(t0);
const db = makeTempDb();
const auth = new AuthService(db);
expect(auth.isBootstrapped()).toBe(false);
const enroll = await auth.beginBootstrap('admin');
expect(enroll.qrSvg).toContain('<svg');
const code0 = generateTotp(enroll.secretBase32, t0);
const boot = await auth.completeBootstrap({
username: 'admin',
password: 'correct-horse-battery-staple',
totpCode: code0,
ip: '127.0.0.1',
userAgent: 'vitest',
});
expect(auth.isBootstrapped()).toBe(true);
expect(boot.recoveryCodes).toHaveLength(8);
// Same 30s TOTP step must be rejected as replay on login
const replayLogin = await auth.login({
username: 'admin',
password: 'correct-horse-battery-staple',
code: code0,
ip: '127.0.0.1',
userAgent: 'vitest',
});
expect(replayLogin).toBeNull();
// Advancing +31s produces next valid TOTP window
const t1 = t0 + 31_000;
vi.setSystemTime(t1);
const code1 = generateTotp(enroll.secretBase32, t1);
const okLogin = await auth.login({
username: 'admin',
password: 'correct-horse-battery-staple',
code: code1,
ip: '127.0.0.1',
userAgent: 'vitest',
});
expect(okLogin).not.toBeNull();
// Recovery code succeeds once, fails on reuse
const recCode = boot.recoveryCodes[0]!;
const recLogin1 = await auth.login({
username: 'admin',
password: 'correct-horse-battery-staple',
code: recCode,
ip: '127.0.0.1',
userAgent: 'vitest',
});
expect(recLogin1).not.toBeNull();
const recLogin2 = await auth.login({
username: 'admin',
password: 'correct-horse-battery-staple',
code: recCode,
ip: '127.0.0.1',
userAgent: 'vitest',
});
expect(recLogin2).toBeNull();
db.close();
});
it('enforces 5-minute step-up elevation, step-up replay block, and drops elevation on Safe Mode when configured strictly', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
const t0 = 1_700_000_010_000;
vi.setSystemTime(t0);
const strictSecurity = SecuritySettingsSchema.parse({
stepUpPolicy: '5m',
elevateOnLogin: false,
keepElevationOnSafeMode: false,
});
const db = makeTempDb();
const auth = new AuthService(db, { getSecuritySettings: () => strictSecurity });
const enroll = await auth.beginBootstrap('admin');
const code0 = generateTotp(enroll.secretBase32, t0);
const boot = await auth.completeBootstrap({
username: 'admin',
password: 'strong-admin-password-123',
totpCode: code0,
ip: '127.0.0.1',
userAgent: 'vitest',
});
expect(boot.session.elevatedUntil).toBeNull();
// Unified monotonic TOTP step blocks replaying bootstrap code for step-up
const replayBootCode = await auth.stepUp(boot.session.idHash, code0);
expect(replayBootCode).toEqual({ ok: false, reason: 'totp_replayed' });
const t1 = t0 + 31_000;
vi.setSystemTime(t1);
const code1 = generateTotp(enroll.secretBase32, t1);
const stepUp1 = await auth.stepUp(boot.session.idHash, code1);
expect(stepUp1).toEqual({
ok: true,
elevatedUntil: t1 + 5 * 60 * 1000,
});
// Replaying exact same step-up code is denied
const stepUpReplay = await auth.stepUp(boot.session.idHash, code1);
expect(stepUpReplay).toEqual({ ok: false, reason: 'totp_replayed' });
// Enabling Safe Mode clears elevatedUntil immediately
const safeSession = auth.setSafeMode(boot.session.idHash, true);
expect(safeSession?.safeMode).toBe(true);
expect(safeSession?.elevatedUntil).toBeNull();
// Step-up is blocked while Safe Mode is ON
const t2 = t1 + 31_000;
vi.setSystemTime(t2);
const code2 = generateTotp(enroll.secretBase32, t2);
const whileSafe = await auth.stepUp(boot.session.idHash, code2);
expect(whileSafe).toEqual({ ok: false, reason: 'safe_mode_active' });
// Turning Safe Mode OFF allows step-up again
auth.setSafeMode(boot.session.idHash, false);
const stepUp2 = await auth.stepUp(boot.session.idHash, code2);
expect(stepUp2.ok).toBe(true);
// Elevation expires automatically after 5 minutes
vi.setSystemTime(t2 + 5 * 60 * 1000 + 1000);
const expiredSession = auth.getSessionByToken(boot.sessionToken);
expect(expiredSession?.elevatedUntil).toBeNull();
db.close();
});
it('keeps elevateOnLogin disabled by default (15m step-up policy) and preserves elevation across Safe Mode toggle', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
const t0 = 1_700_000_010_000;
vi.setSystemTime(t0);
const db = makeTempDb();
const auth = new AuthService(db);
const enroll = await auth.beginBootstrap('admin');
const boot = await auth.completeBootstrap({
username: 'admin',
password: 'balanced-default-password',
totpCode: generateTotp(enroll.secretBase32, t0),
ip: '127.0.0.1',
userAgent: 'vitest',
});
expect(boot.session.elevatedUntil).toBeNull();
vi.setSystemTime(t0 + 31_000);
const step = await auth.stepUp(boot.session.idHash, generateTotp(enroll.secretBase32, t0 + 31_000));
expect(step).toEqual({
ok: true,
elevatedUntil: t0 + 31_000 + 15 * 60 * 1000,
});
const safeSession = auth.setSafeMode(boot.session.idHash, true);
expect(safeSession?.safeMode).toBe(true);
expect(safeSession?.elevatedUntil).toBe(t0 + 31_000 + 15 * 60 * 1000);
db.close();
});
it('applies exponential rate-limit backoff and honors CF-Connecting-IP only when trusted', () => {
const limiter = new RateLimiter();
for (let i = 0; i < 4; i++) {
limiter.recordFailure('login', '198.51.100.10');
expect(limiter.check('login', '198.51.100.10').allowed).toBe(true);
}
limiter.recordFailure('login', '198.51.100.10');
const blocked = limiter.check('login', '198.51.100.10');
expect(blocked.allowed).toBe(false);
expect(blocked.retryAfterSec).toBeGreaterThanOrEqual(1);
limiter.recordSuccess('login', '198.51.100.10');
expect(limiter.check('login', '198.51.100.10').allowed).toBe(true);
const fakeReq = {
headers: { 'cf-connecting-ip': '203.0.113.55' },
ip: '127.0.0.1',
socket: { remoteAddress: '127.0.0.1' },
} as never;
expect(resolveClientIp(fakeReq, false)).toBe('127.0.0.1');
expect(resolveClientIp(fakeReq, true)).toBe('203.0.113.55');
});
});