GCoordinator/tests/api-ws-smoke.test.ts

317 lines
11 KiB
TypeScript

import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import zlib from 'node:zlib';
import * as OTPAuth from 'otpauth';
import { afterEach, describe, expect, it, vi } from 'vitest';
import WebSocket from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js';
const tempDirs: string[] = [];
function makeTempDir(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-smoke-test-'));
tempDirs.push(dir);
return dir;
}
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('; ');
}
}
async function openWs(
url: string,
headers: Record<string, string>,
): Promise<{ ws: WebSocket; frames: Array<Record<string, unknown>> }> {
return new Promise((resolve, reject) => {
const frames: Array<Record<string, unknown>> = [];
const ws = new WebSocket(url, { headers });
ws.on('message', (raw) => {
frames.push(JSON.parse(raw.toString()));
});
ws.once('open', () => resolve({ ws, frames }));
ws.once('unexpected-response', (_req, res) => {
reject(new Error(`WS_HTTP_${res.statusCode}`));
});
ws.once('error', reject);
});
}
afterEach(() => {
while (tempDirs.length > 0) {
fs.rmSync(tempDirs.pop()!, { recursive: true, force: true });
}
});
describe('Bundle size budget & full-stack Express + WS lifecycle', () => {
it('keeps built core frontend bundle under 50KB gzipped', () => {
const pubDir = path.resolve('dist/public');
const coreFiles = ['index.html', 'themes.css', 'base.css', 'main.js'];
let gzipBytes = 0;
for (const f of coreFiles) {
const buf = fs.readFileSync(path.join(pubDir, f));
gzipBytes += zlib.gzipSync(buf, { level: 9 }).length;
}
expect(gzipBytes).toBeLessThan(50 * 1024);
});
it('enforces auth, CSRF, Safe Mode, Step-Up, hot-reload WS push, Panic Lock, and recovery unlock', async () => {
const dataDir = makeTempDir();
const server = await createGCoordinatorServer({
dataDir,
port: 0,
host: '127.0.0.1',
publicDir: path.resolve('dist/public'),
});
const baseUrl = `http://127.0.0.1:${server.port}`;
const wsUrl = `ws://127.0.0.1:${server.port}/ws`;
const jar = new CookieJar();
let csrfToken = '';
const api = async (
pathname: string,
opts: { method?: string; body?: unknown; csrf?: string | null; safeHeader?: boolean } = {},
) => {
const headers: Record<string, string> = {};
if (jar.header()) headers.Cookie = jar.header();
if (opts.body !== undefined) headers['Content-Type'] = 'application/json';
const tokenToSend = opts.csrf === undefined ? csrfToken : opts.csrf;
if (tokenToSend) headers['X-CSRF-Token'] = tokenToSend;
if (opts.safeHeader) headers['X-GCoord-Safe-Mode'] = '1';
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(() => ({}));
return { status: res.status, data: data as Record<string, unknown> };
};
try {
// 1. Health check & unauthenticated WS blocked
const health = await api('/api/healthz');
expect(health.status).toBe(200);
await expect(openWs(wsUrl, {})).rejects.toThrow('WS_HTTP_401');
// 2. Bootstrap Admin + TOTP (offset 65s back so step-up tests below have fresh TOTP steps)
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 65_000);
const bootInfo = await api('/api/auth/bootstrap');
expect(bootInfo.status).toBe(200);
const secretBase32 = String(bootInfo.data.secretBase32);
const totpGen = new OTPAuth.TOTP({
issuer: 'GCoordinator',
label: 'admin',
algorithm: 'SHA1',
digits: 6,
period: 30,
secret: OTPAuth.Secret.fromBase32(secretBase32),
});
const bootDone = await api('/api/auth/bootstrap', {
method: 'POST',
body: {
username: 'admin',
password: 'integration-password-123',
totpCode: totpGen.generate(),
secretBase32,
initialSafeMode: false,
},
});
vi.setSystemTime(Date.now() + 31_000);
expect(bootDone.status).toBe(201);
csrfToken = String(bootDone.data.csrfToken);
const recoveryCodes = bootDone.data.recoveryCodes as string[];
expect(recoveryCodes).toHaveLength(8);
// 3. Cross-origin WS rejected with 403; same-origin WS receives hello
await expect(
openWs(wsUrl, {
Cookie: jar.header(),
Host: `127.0.0.1:${server.port}`,
Origin: 'https://evil.example',
}),
).rejects.toThrow('WS_HTTP_403');
const { ws, frames } = await openWs(wsUrl, {
Cookie: jar.header(),
Host: `127.0.0.1:${server.port}`,
Origin: baseUrl,
});
await new Promise((r) => setTimeout(r, 80));
expect(frames[0]?.type).toBe('hello');
// 4. CSRF check
const badCsrf = await api('/api/vault/init', {
method: 'POST',
body: {},
csrf: null,
});
expect(badCsrf.status).toBe(403);
// 5. Safe Mode blocks mutating REST & WS pty:input
expect(
(await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: true } })).status,
).toBe(200);
const safeBlocked = await api('/api/config/file', {
method: 'PUT',
body: {
path: 'servers/prod-01.json',
content: JSON.stringify({
id: 'prod-01',
name: 'Prod 01',
host: '10.0.0.99',
username: 'ops',
credentialId: 'prod-key',
}),
},
});
expect(safeBlocked.status).toBe(423);
ws.send(JSON.stringify({ type: 'pty:input', sessionId: 's1', data: 'ls\n' }));
await new Promise((r) => setTimeout(r, 80));
expect(frames.some((f) => f.type === 'error' && f.code === 'SAFE_MODE_ACTIVE')).toBe(true);
// Disable Safe Mode
expect(
(await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: false } })).status,
).toBe(200);
// 6. Vault Init + Step-Up guard + Drop Elevation + Generate Ed25519 key
// v1.1 defaults elevateOnLogin=false; verify non-elevated session cannot init vault
const statusInitial = await api('/api/auth/status');
expect(statusInitial.data.elevatedUntil).toBeNull();
const vInitDenied = await api('/api/vault/init', { method: 'POST', body: {} });
expect(vInitDenied.status).toBe(403);
expect(vInitDenied.data.error).toBe('STEP_UP_REQUIRED');
const stepUpRes = await api('/api/auth/step-up', {
method: 'POST',
body: { code: totpGen.generate() },
});
expect(stepUpRes.status).toBe(200);
const vInit = await api('/api/vault/init', { method: 'POST', body: {} });
expect(vInit.status).toBe(201);
const generatedMasterKey = String(vInit.data.generatedKeyHex);
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 afterDropDenied = await api('/api/vault/generate-ed25519', {
method: 'POST',
body: { id: 'prod-key', name: 'Prod Key' },
});
expect(afterDropDenied.status).toBe(403);
vi.useRealTimers();
expect(
(await api('/api/auth/step-up', { method: 'POST', body: { code: totpGen.generate() } })).status,
).toBe(200);
const genRes = await api('/api/vault/generate-ed25519', {
method: 'POST',
body: { id: 'prod-key', name: 'Prod Key' },
});
expect(genRes.status).toBe(201);
// 7. Save server JSON and confirm WS receives config:updated
const saveServer = await api('/api/config/file', {
method: 'PUT',
body: {
path: 'servers/prod-01.json',
content: JSON.stringify({
id: 'prod-01',
name: 'Prod 01',
host: '10.0.0.99',
username: 'ops',
credentialId: 'prod-key',
}),
},
});
expect(saveServer.status).toBe(200);
await new Promise((r) => setTimeout(r, 80));
expect(
frames.some((f) => f.type === 'config:updated' && f.id === 'prod-01'),
).toBe(true);
// 8. Re-enable Safe Mode and verify Panic Lock STILL executes immediately
await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: true } });
let wsCloseCode = 0;
const wsClosed = new Promise<void>((resolve) => {
ws.once('close', (code) => {
wsCloseCode = code;
resolve();
});
});
const panicRes = await api('/api/security/panic-lock', { method: 'POST' });
expect(panicRes.status).toBe(200);
await wsClosed;
expect(wsCloseCode).toBe(4001);
expect(frames.some((f) => f.type === 'security:panic-lock')).toBe(true);
// Old session must now be revoked (401)
const afterPanic = await api('/api/vault/status');
expect(afterPanic.status).toBe(401);
// 9. Re-login using a single-use recovery code and unlock vault manually
const relogin = await api('/api/auth/login', {
method: 'POST',
body: {
username: 'admin',
password: 'integration-password-123',
code: recoveryCodes[0]!,
},
csrf: null,
});
expect(relogin.status).toBe(200);
csrfToken = String(relogin.data.csrfToken);
expect(relogin.data.vaultState).toBe('locked');
const unlockRes = await api('/api/vault/unlock', {
method: 'POST',
body: { masterKey: generatedMasterKey },
});
expect(unlockRes.status).toBe(200);
expect(unlockRes.data.state).toBe('unlocked');
const credsAfter = await api('/api/vault/credentials');
expect(credsAfter.status).toBe(200);
expect(
(credsAfter.data.credentials as Array<{ id: string }>).map((c) => c.id),
).toContain('prod-key');
} finally {
await server.close();
}
});
});