GCoordinator/tests/multi-auth-and-recovery.test.ts

529 lines
17 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 { createGCoordinatorServer, type GCoordinatorInstance } from '../src/server/app.js';
import type { EmergencySecretsBundle } from '../src/server/security/recovery-store.js';
const cleanups: Array<() => Promise<void> | void> = [];
class CookieJar {
private cookies = new Map<string, string>();
updateFrom(res: Response): void {
const getSetCookie = (res.headers as unknown as { getSetCookie?: () => string[] }).getSetCookie;
const rawList = typeof getSetCookie === 'function' ? getSetCookie.call(res.headers) : [];
for (const line of rawList) {
const first = line.split(';')[0] ?? '';
const eq = first.indexOf('=');
if (eq > 0) {
const name = first.slice(0, eq).trim();
const val = first.slice(eq + 1).trim();
if (val === '') this.cookies.delete(name);
else this.cookies.set(name, val);
}
}
}
header(): string {
return [...this.cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; ');
}
}
function makeTotp(secretBase32: string): OTPAuth.TOTP {
return new OTPAuth.TOTP({
issuer: 'GCoordinator',
label: 'admin',
algorithm: 'SHA1',
digits: 6,
period: 30,
secret: OTPAuth.Secret.fromBase32(secretBase32),
});
}
function createApiClient(server: GCoordinatorInstance) {
const baseUrl = `http://127.0.0.1:${server.port}`;
const jar = new CookieJar();
let csrfToken = '';
const call = async (
pathname: string,
opts: { method?: string; body?: unknown; csrf?: string | null } = {},
) => {
const headers: Record<string, string> = {};
if (jar.header()) headers.Cookie = jar.header();
if (opts.body !== undefined) headers['Content-Type'] = 'application/json';
const token = opts.csrf === undefined ? csrfToken : opts.csrf;
if (token) headers['X-CSRF-Token'] = token;
const res = await fetch(`${baseUrl}${pathname}`, {
method: opts.method ?? 'GET',
headers,
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
});
jar.updateFrom(res);
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
if (typeof data.csrfToken === 'string' && data.csrfToken) {
csrfToken = data.csrfToken;
}
return { status: res.status, data };
};
return {
call,
clearCsrf: () => {
csrfToken = '';
},
};
}
afterEach(async () => {
vi.useRealTimers();
while (cleanups.length > 0) {
await cleanups.pop()!();
}
});
describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secrets Backup', () => {
it('supports Relaxed Phone Mode: password-only login and no step-up prompts', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
const t0 = 1_700_000_010_000;
vi.setSystemTime(t0);
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-relaxed-test-'));
const server = await createGCoordinatorServer({
dataDir,
port: 0,
host: '127.0.0.1',
publicDir: path.resolve('dist/public'),
watchConfig: false,
});
cleanups.push(async () => {
await server.close();
fs.rmSync(dataDir, { recursive: true, force: true });
});
const api = createApiClient(server);
const bootInfo = await api.call('/api/auth/bootstrap');
const secret1 = String(bootInfo.data.secretBase32);
const boot = await api.call('/api/auth/bootstrap', {
method: 'POST',
body: {
username: 'admin',
password: 'relaxed-phone-password-123',
totpCode: makeTotp(secret1).generate(),
secretBase32: secret1,
securityPreset: 'relaxed',
},
});
expect(boot.status).toBe(201);
const status1 = await api.call('/api/auth/status');
expect(status1.status).toBe(200);
expect((status1.data.authRequirements as { requireTotpOnLogin: boolean }).requireTotpOnLogin).toBe(
false,
);
expect((status1.data.authRequirements as { stepUpPolicy: string }).stepUpPolicy).toBe('off');
// Logout and log back in with password only (no TOTP required)
expect((await api.call('/api/auth/logout', { method: 'POST' })).status).toBe(200);
api.clearCsrf();
const pwOnlyLogin = await api.call('/api/auth/login', {
method: 'POST',
body: {
username: 'admin',
password: 'relaxed-phone-password-123',
},
csrf: null,
});
expect(pwOnlyLogin.status).toBe(200);
expect(pwOnlyLogin.data.elevatedUntil).toBeNull();
// Init vault, generate Ed25519 key, and reveal secret without needing any /api/auth/step-up call
expect((await api.call('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201);
const keyRes = await api.call('/api/vault/generate-ed25519', {
method: 'POST',
body: { id: 'phone-key', name: 'Phone Key' },
});
expect(keyRes.status).toBe(201);
expect((await api.call('/api/vault/credentials/phone-key/reveal')).status).toBe(200);
});
it('enforces multi-password + multi-TOTP any/all modes, every-action policy, and password step-up', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
const t0 = 1_700_000_010_000;
vi.setSystemTime(t0);
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-multiauth-test-'));
const server = await createGCoordinatorServer({
dataDir,
port: 0,
host: '127.0.0.1',
publicDir: path.resolve('dist/public'),
watchConfig: false,
});
cleanups.push(async () => {
await server.close();
fs.rmSync(dataDir, { recursive: true, force: true });
});
const api = createApiClient(server);
const pw1 = 'primary-admin-password-1';
const pw2 = 'secondary-admin-password-2';
const bootInfo = await api.call('/api/auth/bootstrap');
const secret1 = String(bootInfo.data.secretBase32);
const totp1 = makeTotp(secret1);
expect(
(
await api.call('/api/auth/bootstrap', {
method: 'POST',
body: {
username: 'admin',
password: pw1,
totpCode: totp1.generate(),
secretBase32: secret1,
},
})
).status,
).toBe(201);
// Explicitly step up before vault mutations (v1.1 default elevateOnLogin=false)
vi.setSystemTime(t0 + 31_000);
expect(
(await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp1.generate() } })).status,
).toBe(200);
// Initialize vault & generate key while elevated
expect((await api.call('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201);
expect(
(
await api.call('/api/vault/generate-ed25519', {
method: 'POST',
body: { id: 'prod-key', name: 'Prod Key' },
})
).status,
).toBe(201);
// Enroll 2nd password & 2nd TOTP
const addPwRes = await api.call('/api/auth/factors/passwords', {
method: 'POST',
body: { label: 'Backup Key', password: pw2 },
});
expect(addPwRes.status).toBe(201);
const enrollTotp2 = await api.call('/api/auth/factors/totps/enroll', {
method: 'POST',
body: { label: 'Hardware TOTP' },
});
expect(enrollTotp2.status).toBe(200);
const secret2 = String(enrollTotp2.data.secretBase32);
const totp2 = makeTotp(secret2);
const confirmTotp2 = await api.call('/api/auth/factors/totps/confirm', {
method: 'POST',
body: {
enrollmentId: String(enrollTotp2.data.enrollmentId),
code: totp2.generate(),
},
});
expect(confirmTotp2.status).toBe(201);
// In default 'any' mode, 2nd password + 2nd TOTP can log in
expect((await api.call('/api/auth/logout', { method: 'POST' })).status).toBe(200);
api.clearCsrf();
vi.setSystemTime(t0 + 62_000);
const anyLogin = await api.call('/api/auth/login', {
method: 'POST',
body: {
username: 'admin',
password: pw2,
code: totp2.generate(),
},
csrf: null,
});
expect(anyLogin.status).toBe(200);
// Switch settings.json to strict multi-factor 'all' + 'every-action' + password step-up
expect(
(await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp1.generate() } })).status,
).toBe(200);
const rawSettings = await api.call('/api/config/file?path=settings.json');
expect(rawSettings.status).toBe(200);
const parsedSettings = JSON.parse(String(rawSettings.data.rawContent)) as Record<
string,
unknown
>;
const updatedSettings = {
...parsedSettings,
security: {
...(parsedSettings.security as Record<string, unknown>),
requireTotpOnLogin: true,
passwordMode: 'all',
totpMode: 'all',
stepUpPolicy: 'every-action',
stepUpMethod: 'password',
elevateOnLogin: true,
keepElevationOnSafeMode: false,
},
};
const saveSettings = await api.call('/api/config/file', {
method: 'PUT',
body: {
path: 'settings.json',
content: JSON.stringify(updatedSettings, null, 2),
},
});
expect(saveSettings.status).toBe(200);
// Logout and test 'all' enforcement
expect((await api.call('/api/auth/logout', { method: 'POST' })).status).toBe(200);
api.clearCsrf();
vi.setSystemTime(t0 + 93_000);
const partialPw = await api.call('/api/auth/login', {
method: 'POST',
body: {
username: 'admin',
passwords: [pw1],
codes: [totp1.generate(), totp2.generate()],
},
csrf: null,
});
expect(partialPw.status).toBe(401);
vi.setSystemTime(t0 + 124_000);
const partialTotp = await api.call('/api/auth/login', {
method: 'POST',
body: {
username: 'admin',
passwords: [pw1, pw2],
codes: [totp1.generate()],
},
csrf: null,
});
expect(partialTotp.status).toBe(401);
vi.setSystemTime(t0 + 155_000);
const fullAllLogin = await api.call('/api/auth/login', {
method: 'POST',
body: {
username: 'admin',
passwords: [pw1, pw2],
codes: [totp1.generate(), totp2.generate()],
},
csrf: null,
});
expect(fullAllLogin.status).toBe(200);
// 'every-action' never grants implicit login elevation: even the first reveal requires explicit step-up
const reveal1 = await api.call('/api/vault/credentials/prod-key/reveal');
expect(reveal1.status).toBe(403);
expect(reveal1.data.error).toBe('STEP_UP_REQUIRED');
// Step-up requires BOTH passwords in passwordMode='all', stepUpMethod='password'
const badStepUp = await api.call('/api/auth/step-up', {
method: 'POST',
body: { password: pw1 },
});
expect(badStepUp.status).toBe(403);
const goodStepUp = await api.call('/api/auth/step-up', {
method: 'POST',
body: { passwords: [pw1, pw2] },
});
expect(goodStepUp.status).toBe(200);
// One sensitive call succeeds, then 'every-action' consumes the single-use elevation
const reveal2 = await api.call('/api/vault/credentials/prod-key/reveal');
expect(reveal2.status).toBe(200);
const reveal3 = await api.call('/api/vault/credentials/prod-key/reveal');
expect(reveal3.status).toBe(403);
expect(reveal3.data.error).toBe('STEP_UP_REQUIRED');
});
it('writes chmod 0600 emergency-secrets.json, auto-unlocks on restart, honors Panic Lock, and wipes on request', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
const t0 = 1_700_000_010_000;
vi.setSystemTime(t0);
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-recovery-test-'));
cleanups.push(() => {
fs.rmSync(dataDir, { recursive: true, force: true });
});
let server = await createGCoordinatorServer({
dataDir,
port: 0,
host: '127.0.0.1',
publicDir: path.resolve('dist/public'),
watchConfig: false,
});
let activeServer: GCoordinatorInstance | null = server;
cleanups.push(async () => {
if (activeServer) {
await activeServer.close();
activeServer = null;
}
});
const curSettings = server.configManager.getSettings();
server.configManager.saveConfigText(
'settings.json',
JSON.stringify(
{
...curSettings,
security: {
...curSettings.security,
enableEmergencySecretsBackup: true,
},
},
null,
2,
),
'ui',
'Enable emergency recovery for test',
);
let api = createApiClient(server);
const bootInfo = await api.call('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32);
const totp = makeTotp(secretBase32);
const password = 'emergency-backup-password-1';
const boot = await api.call('/api/auth/bootstrap', {
method: 'POST',
body: {
username: 'admin',
password,
totpCode: totp.generate(),
secretBase32,
},
});
expect(boot.status).toBe(201);
const recoveryCodes = boot.data.recoveryCodes as string[];
vi.setSystemTime(t0 + 31_000);
expect(
(await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200);
const vInit = await api.call('/api/vault/init', { method: 'POST', body: {} });
expect(vInit.status).toBe(201);
const masterKeyHex = String(vInit.data.generatedKeyHex);
expect(
(
await api.call('/api/vault/generate-ed25519', {
method: 'POST',
body: { id: 'backup-key', name: 'Backup Key' },
})
).status,
).toBe(201);
const bundlePath = path.join(dataDir, 'recovery', 'emergency-secrets.json');
expect(fs.existsSync(bundlePath)).toBe(true);
expect(fs.statSync(bundlePath).mode & 0o777).toBe(0o600);
const bundle = JSON.parse(fs.readFileSync(bundlePath, 'utf8')) as EmergencySecretsBundle;
expect(bundle.vaultMasterKeyHex).toBe(masterKeyHex);
expect(bundle.admin.username).toBe('admin');
expect(bundle.admin.passwords.some((p) => p.label === 'Primary Password' && !('plaintextPassword' in p))).toBe(true);
expect(bundle.admin.totps.some((t) => t.secretBase32 === secretBase32)).toBe(true);
expect(bundle.admin.recoveryCodes).toEqual(recoveryCodes);
expect(bundle.vaultCredentials['backup-key']).toBeDefined();
// Restart server with NO env/secretFile master key -> auto-unlocks from emergency-secrets.json
await server.close();
activeServer = null;
server = await createGCoordinatorServer({
dataDir,
port: 0,
host: '127.0.0.1',
publicDir: path.resolve('dist/public'),
watchConfig: false,
});
activeServer = server;
api = createApiClient(server);
vi.setSystemTime(t0 + 62_000);
const relogin = await api.call('/api/auth/login', {
method: 'POST',
body: {
username: 'admin',
password,
code: totp.generate(),
},
});
expect(relogin.status).toBe(200);
expect(relogin.data.vaultState).toBe('locked');
expect(relogin.data.vaultRuntimeReady).toBe(true);
const vStatus = await api.call('/api/vault/status');
expect(vStatus.status).toBe(200);
expect(vStatus.data.state).toBe('locked');
expect(vStatus.data.runtimeReady).toBe(true);
// Trigger Panic Lock -> locks vault while keeping backup file intact; restart must stay locked
expect((await api.call('/api/security/panic-lock', { method: 'POST' })).status).toBe(200);
expect(fs.existsSync(bundlePath)).toBe(true);
await server.close();
activeServer = null;
server = await createGCoordinatorServer({
dataDir,
port: 0,
host: '127.0.0.1',
publicDir: path.resolve('dist/public'),
watchConfig: false,
});
activeServer = server;
api = createApiClient(server);
const loginAfterPanic = await api.call('/api/auth/login', {
method: 'POST',
body: {
username: 'admin',
password,
code: recoveryCodes[0]!,
},
});
expect(loginAfterPanic.status).toBe(200);
expect(loginAfterPanic.data.vaultState).toBe('locked');
expect(loginAfterPanic.data.vaultRuntimeReady).toBe(false);
// Unlock manually, then wipe and disable recovery backup
expect(
(
await api.call('/api/vault/unlock', {
method: 'POST',
body: { masterKey: masterKeyHex },
})
).status,
).toBe(200);
vi.setSystemTime(t0 + 93_000);
expect(
(await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200);
const wipeRes = await api.call('/api/auth/recovery-backup?disable=1', {
method: 'DELETE',
});
expect(wipeRes.status).toBe(200);
expect(wipeRes.data.wiped).toBe(true);
expect(fs.existsSync(bundlePath)).toBe(false);
expect((wipeRes.data.recoveryBackup as { enabled: boolean; exists: boolean }).enabled).toBe(
false,
);
expect((wipeRes.data.recoveryBackup as { exists: boolean }).exists).toBe(false);
});
});