test(security): persist panic-lock across restarts and add multi-auth/recovery E2E tests
This commit is contained in:
parent
90a8bf8553
commit
21176265aa
4 changed files with 559 additions and 13 deletions
|
|
@ -107,7 +107,24 @@ export class VaultService {
|
|||
private wasPanicLocked = false;
|
||||
private readonly panicListeners = new Set<() => void>();
|
||||
|
||||
constructor(private readonly vaultFilePath: string) {}
|
||||
constructor(private readonly vaultFilePath: string) {
|
||||
this.wasPanicLocked = fs.existsSync(this.panicLockMarkerPath());
|
||||
}
|
||||
|
||||
private panicLockMarkerPath(): string {
|
||||
return `${this.vaultFilePath}.panic-locked`;
|
||||
}
|
||||
|
||||
private setPanicLockMarker(active: boolean): void {
|
||||
this.wasPanicLocked = active;
|
||||
const markerPath = this.panicLockMarkerPath();
|
||||
if (active) {
|
||||
fs.mkdirSync(path.dirname(markerPath), { recursive: true });
|
||||
fs.writeFileSync(markerPath, `${Date.now()}\n`, { mode: 0o600 });
|
||||
} else {
|
||||
fs.rmSync(markerPath, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
get filePath(): string {
|
||||
return this.vaultFilePath;
|
||||
|
|
@ -119,7 +136,7 @@ export class VaultService {
|
|||
}
|
||||
|
||||
get isPanicLocked(): boolean {
|
||||
return this.wasPanicLocked;
|
||||
return this.wasPanicLocked || fs.existsSync(this.panicLockMarkerPath());
|
||||
}
|
||||
|
||||
onPanicLock(listener: () => void): () => void {
|
||||
|
|
@ -134,7 +151,7 @@ export class VaultService {
|
|||
envKey?: string;
|
||||
}): { unlocked: boolean; initialized?: boolean; reason?: string } {
|
||||
// Security invariant: never silently re-read disk secrets after Emergency Panic Lock
|
||||
if (this.wasPanicLocked) {
|
||||
if (this.isPanicLocked) {
|
||||
return { unlocked: false, reason: 'panic_locked' };
|
||||
}
|
||||
|
||||
|
|
@ -178,7 +195,7 @@ export class VaultService {
|
|||
this.zeroizeMasterKey();
|
||||
this.masterKey = keyBuf;
|
||||
this.credentials.clear();
|
||||
this.wasPanicLocked = false;
|
||||
this.setPanicLockMarker(false);
|
||||
|
||||
return masterKeyInput ? {} : { generatedKeyHex: keyBuf.toString('hex') };
|
||||
}
|
||||
|
|
@ -197,7 +214,7 @@ export class VaultService {
|
|||
this.zeroizeMasterKey();
|
||||
this.masterKey = keyBuf;
|
||||
this.credentials = new Map(Object.entries(payload.credentials));
|
||||
this.wasPanicLocked = false;
|
||||
this.setPanicLockMarker(false);
|
||||
} catch (err) {
|
||||
keyBuf.fill(0);
|
||||
throw err;
|
||||
|
|
@ -207,7 +224,7 @@ export class VaultService {
|
|||
panicLock(): void {
|
||||
this.zeroizeMasterKey();
|
||||
this.credentials.clear();
|
||||
this.wasPanicLocked = true;
|
||||
this.setPanicLockMarker(true);
|
||||
|
||||
for (const listener of this.panicListeners) {
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -198,11 +198,18 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => {
|
|||
(await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: false } })).status,
|
||||
).toBe(200);
|
||||
|
||||
// 6. Vault Init + Step-Up guard + Generate Ed25519 key
|
||||
// 6. Vault Init + Drop Elevation -> Step-Up guard + Generate Ed25519 key
|
||||
const vInit = await api('/api/vault/init', { method: 'POST', body: {} });
|
||||
expect(vInit.status).toBe(201);
|
||||
const generatedMasterKey = String(vInit.data.generatedKeyHex);
|
||||
|
||||
// Default balanced mode elevates on bootstrap/login; drop elevation to verify guard enforcement
|
||||
const statusBeforeDrop = await api('/api/auth/status');
|
||||
expect(typeof statusBeforeDrop.data.elevatedUntil).toBe('number');
|
||||
const dropped = await api('/api/auth/drop-elevation', { method: 'POST' });
|
||||
expect(dropped.status).toBe(200);
|
||||
expect(dropped.data.elevatedUntil).toBeNull();
|
||||
|
||||
const noStepUp = await api('/api/vault/generate-ed25519', {
|
||||
method: 'POST',
|
||||
body: { id: 'prod-key', name: 'Prod Key' },
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ 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';
|
||||
|
||||
|
|
@ -104,13 +105,19 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
|
|||
db.close();
|
||||
});
|
||||
|
||||
it('enforces 5-minute step-up elevation, step-up replay block, and drops elevation on Safe Mode', async () => {
|
||||
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);
|
||||
const auth = new AuthService(db, { getSecuritySettings: () => strictSecurity });
|
||||
const enroll = await auth.beginBootstrap('admin');
|
||||
const code0 = generateTotp(enroll.secretBase32, t0);
|
||||
const boot = await auth.completeBootstrap({
|
||||
|
|
@ -120,16 +127,17 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
|
|||
ip: '127.0.0.1',
|
||||
userAgent: 'vitest',
|
||||
});
|
||||
expect(boot.session.elevatedUntil).toBeNull();
|
||||
|
||||
// Step-up tracks replay independently from login step
|
||||
const stepUp1 = auth.stepUp(boot.session.idHash, code0);
|
||||
const stepUp1 = await auth.stepUp(boot.session.idHash, code0);
|
||||
expect(stepUp1).toEqual({
|
||||
ok: true,
|
||||
elevatedUntil: t0 + 5 * 60 * 1000,
|
||||
});
|
||||
|
||||
// Replaying exact same step-up code is denied
|
||||
const stepUpReplay = auth.stepUp(boot.session.idHash, code0);
|
||||
const stepUpReplay = await auth.stepUp(boot.session.idHash, code0);
|
||||
expect(stepUpReplay).toEqual({ ok: false, reason: 'totp_replayed' });
|
||||
|
||||
// Enabling Safe Mode clears elevatedUntil immediately
|
||||
|
|
@ -140,12 +148,12 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
|
|||
// Step-up is blocked while Safe Mode is ON
|
||||
vi.setSystemTime(t0 + 31_000);
|
||||
const code1 = generateTotp(enroll.secretBase32, t0 + 31_000);
|
||||
const whileSafe = auth.stepUp(boot.session.idHash, code1);
|
||||
const whileSafe = await auth.stepUp(boot.session.idHash, code1);
|
||||
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 = auth.stepUp(boot.session.idHash, code1);
|
||||
const stepUp2 = await auth.stepUp(boot.session.idHash, code1);
|
||||
expect(stepUp2.ok).toBe(true);
|
||||
|
||||
// Elevation expires automatically after 5 minutes
|
||||
|
|
@ -156,6 +164,31 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
|
|||
db.close();
|
||||
});
|
||||
|
||||
it('grants default 1h elevation on bootstrap/login 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).toBe(t0 + 60 * 60 * 1000);
|
||||
|
||||
const safeSession = auth.setSafeMode(boot.session.idHash, true);
|
||||
expect(safeSession?.safeMode).toBe(true);
|
||||
expect(safeSession?.elevatedUntil).toBe(t0 + 60 * 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++) {
|
||||
|
|
|
|||
489
tests/multi-auth-and-recovery.test.ts
Normal file
489
tests/multi-auth-and-recovery.test.ts
Normal file
|
|
@ -0,0 +1,489 @@
|
|||
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);
|
||||
|
||||
// Initialize vault & generate key while default 1h login elevation is active
|
||||
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 + 31_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
|
||||
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 + 62_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 + 93_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 + 124_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;
|
||||
}
|
||||
});
|
||||
|
||||
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[];
|
||||
|
||||
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.plaintextPassword === password)).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 + 31_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('unlocked');
|
||||
|
||||
const vStatus = await api.call('/api/vault/status');
|
||||
expect(vStatus.status).toBe(200);
|
||||
expect(vStatus.data.state).toBe('unlocked');
|
||||
|
||||
// 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');
|
||||
|
||||
// Unlock manually, then wipe and disable recovery backup
|
||||
expect(
|
||||
(
|
||||
await api.call('/api/vault/unlock', {
|
||||
method: 'POST',
|
||||
body: { masterKey: masterKeyHex },
|
||||
})
|
||||
).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);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue