security(auth,ws): fix Auth/TOTP/WebAuthn/bootstrap vulnerabilities, session idle TTL & real-time WS revocation
This commit is contained in:
parent
e3f716d24f
commit
1b2e425a00
13 changed files with 1248 additions and 477 deletions
|
|
@ -129,15 +129,21 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
|
|||
});
|
||||
expect(boot.session.elevatedUntil).toBeNull();
|
||||
|
||||
// Step-up tracks replay independently from login step
|
||||
const stepUp1 = await auth.stepUp(boot.session.idHash, code0);
|
||||
// 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: t0 + 5 * 60 * 1000,
|
||||
elevatedUntil: t1 + 5 * 60 * 1000,
|
||||
});
|
||||
|
||||
// Replaying exact same step-up code is denied
|
||||
const stepUpReplay = await auth.stepUp(boot.session.idHash, code0);
|
||||
const stepUpReplay = await auth.stepUp(boot.session.idHash, code1);
|
||||
expect(stepUpReplay).toEqual({ ok: false, reason: 'totp_replayed' });
|
||||
|
||||
// Enabling Safe Mode clears elevatedUntil immediately
|
||||
|
|
@ -146,18 +152,19 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
|
|||
expect(safeSession?.elevatedUntil).toBeNull();
|
||||
|
||||
// Step-up is blocked while Safe Mode is ON
|
||||
vi.setSystemTime(t0 + 31_000);
|
||||
const code1 = generateTotp(enroll.secretBase32, t0 + 31_000);
|
||||
const whileSafe = await auth.stepUp(boot.session.idHash, code1);
|
||||
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, code1);
|
||||
const stepUp2 = await auth.stepUp(boot.session.idHash, code2);
|
||||
expect(stepUp2.ok).toBe(true);
|
||||
|
||||
// Elevation expires automatically after 5 minutes
|
||||
vi.setSystemTime(t0 + 31_000 + 5 * 60 * 1000 + 1000);
|
||||
vi.setSystemTime(t2 + 5 * 60 * 1000 + 1000);
|
||||
const expiredSession = auth.getSessionByToken(boot.sessionToken);
|
||||
expect(expiredSession?.elevatedUntil).toBeNull();
|
||||
|
||||
|
|
|
|||
|
|
@ -453,7 +453,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
|
|||
activeServer = server;
|
||||
api = createApiClient(server);
|
||||
|
||||
vi.setSystemTime(t0 + 31_000);
|
||||
vi.setSystemTime(t0 + 62_000);
|
||||
const relogin = await api.call('/api/auth/login', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
|
|
@ -510,7 +510,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
|
|||
).status,
|
||||
).toBe(200);
|
||||
|
||||
vi.setSystemTime(t0 + 62_000);
|
||||
vi.setSystemTime(t0 + 93_000);
|
||||
expect(
|
||||
(await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
|
||||
).toBe(200);
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
|
|
@ -152,6 +153,7 @@ function buildSyntheticAuthenticator(rpID: string, expectedOrigin: string) {
|
|||
}
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers();
|
||||
while (cleanups.length > 0) {
|
||||
await cleanups.pop()!();
|
||||
}
|
||||
|
|
@ -172,7 +174,6 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => {
|
|||
fs.rmSync(dataDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const baseUrl = `http://127.0.0.1:${server.port}`;
|
||||
const origin = `http://localhost:${server.port}`;
|
||||
const jar = new CookieJar();
|
||||
let csrfToken = '';
|
||||
|
|
@ -186,16 +187,57 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => {
|
|||
Host: `localhost:${server.port}`,
|
||||
};
|
||||
if (jar.header()) headers.Cookie = jar.header();
|
||||
if (opts.body !== undefined) headers['Content-Type'] = 'application/json';
|
||||
const payload = opts.body !== undefined ? JSON.stringify(opts.body) : undefined;
|
||||
if (payload !== undefined) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
headers['Content-Length'] = String(Buffer.byteLength(payload));
|
||||
}
|
||||
if (csrfToken) headers['X-CSRF-Token'] = csrfToken;
|
||||
|
||||
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>;
|
||||
const res = await new Promise<{ status: number; setCookies: string[]; text: string }>(
|
||||
(resolve, reject) => {
|
||||
const req = http.request(
|
||||
{
|
||||
host: '127.0.0.1',
|
||||
port: server.port,
|
||||
path: pathname,
|
||||
method: opts.method ?? 'GET',
|
||||
headers,
|
||||
},
|
||||
(incoming) => {
|
||||
const chunks: Buffer[] = [];
|
||||
incoming.on('data', (c) => chunks.push(Buffer.from(c)));
|
||||
incoming.on('end', () => {
|
||||
const rawSetCookie = incoming.headers['set-cookie'];
|
||||
resolve({
|
||||
status: incoming.statusCode ?? 0,
|
||||
setCookies: Array.isArray(rawSetCookie) ? rawSetCookie : [],
|
||||
text: Buffer.concat(chunks).toString('utf8'),
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
req.on('error', reject);
|
||||
if (payload !== undefined) req.write(payload);
|
||||
req.end();
|
||||
},
|
||||
);
|
||||
for (const line of res.setCookies) {
|
||||
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 === '') jar['cookies'].delete(name);
|
||||
else jar['cookies'].set(name, val);
|
||||
}
|
||||
}
|
||||
let data: Record<string, unknown> = {};
|
||||
try {
|
||||
data = JSON.parse(res.text) as Record<string, unknown>;
|
||||
} catch {
|
||||
data = {};
|
||||
}
|
||||
if (typeof data.csrfToken === 'string' && data.csrfToken) {
|
||||
csrfToken = data.csrfToken;
|
||||
}
|
||||
|
|
@ -316,7 +358,38 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => {
|
|||
});
|
||||
expect(loginVerify2.status).toBe(200);
|
||||
|
||||
// 3. Step-Up Verification via Passkey
|
||||
// 3. Step-Up Verification via Passkey requires stepUpMethod === 'passkey'
|
||||
await api('/api/auth/drop-elevation', { method: 'POST' });
|
||||
expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(403);
|
||||
|
||||
const deniedOpts = await api('/api/auth/passkeys/step-up/options', { method: 'POST', body: {} });
|
||||
expect(deniedOpts.status).toBe(200);
|
||||
const deniedVerify = await api('/api/auth/passkeys/step-up/verify', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
challengeId: String(deniedOpts.data.challengeId),
|
||||
response: authn.createAuthenticationResponse(
|
||||
String((deniedOpts.data.options as { challenge: string }).challenge),
|
||||
),
|
||||
},
|
||||
});
|
||||
expect(deniedVerify.status).toBe(403);
|
||||
expect(deniedVerify.data.reason).toBe('passkey_stepup_not_enabled');
|
||||
|
||||
// Step up with TOTP in next step, enable stepUpMethod = 'passkey', then drop & verify passkey step-up
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
vi.setSystemTime(Date.now() + 35_000);
|
||||
expect(
|
||||
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
|
||||
).toBe(200);
|
||||
expect(
|
||||
(
|
||||
await api('/api/auth/security-policy', {
|
||||
method: 'PUT',
|
||||
body: { stepUpMethod: 'passkey' },
|
||||
})
|
||||
).status,
|
||||
).toBe(200);
|
||||
await api('/api/auth/drop-elevation', { method: 'POST' });
|
||||
expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(403);
|
||||
|
||||
|
|
@ -335,7 +408,22 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => {
|
|||
expect(typeof stepVerify.data.elevatedUntil).toBe('number');
|
||||
expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(200);
|
||||
|
||||
// 4. Delete passkey factor
|
||||
// 4. Cannot delete the last passkey while stepUpMethod === 'passkey'
|
||||
const blockedDel = await api(`/api/auth/factors/passkeys/${encodeURIComponent(authn.credId)}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
expect(blockedDel.status).toBe(400);
|
||||
|
||||
// Switch stepUpMethod back to 'totp', then delete passkey cleanly
|
||||
expect(
|
||||
(
|
||||
await api('/api/auth/security-policy', {
|
||||
method: 'PUT',
|
||||
body: { stepUpMethod: 'totp' },
|
||||
})
|
||||
).status,
|
||||
).toBe(200);
|
||||
|
||||
const delRes = await api(`/api/auth/factors/passkeys/${encodeURIComponent(authn.credId)}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
|
|
|||
|
|
@ -188,12 +188,12 @@ describe('Always-on background collectors & write-only Vault lock', () => {
|
|||
});
|
||||
api = createApiClient(activeServer);
|
||||
|
||||
// Before ANY user logs in, status is unauthenticated + write-locked, yet runtime collectors run immediately
|
||||
// Before ANY user logs in, status is unauthenticated and omits internal vault state, yet runtime collectors run immediately
|
||||
const preLoginStatus = await api.call('/api/auth/status');
|
||||
expect(preLoginStatus.status).toBe(200);
|
||||
expect(preLoginStatus.data.authenticated).toBe(false);
|
||||
expect(preLoginStatus.data.vaultState).toBe('locked');
|
||||
expect(preLoginStatus.data.vaultRuntimeReady).toBe(true);
|
||||
expect(preLoginStatus.data.vaultState).toBeUndefined();
|
||||
expect(preLoginStatus.data.vaultRuntimeReady).toBeUndefined();
|
||||
|
||||
const latestBeforeLogin = await waitFor(
|
||||
() => activeServer!.monitoringService.getLatest('srv-1')?.sample,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue