test(phase-2): add ssh2.Server test harness and end-to-end SSH, ProxyJump, key rotation, and monitoring tests
This commit is contained in:
parent
75b969f044
commit
4ac7b5d1b4
5 changed files with 1026 additions and 0 deletions
193
tests/servers-api-e2e.test.ts
Normal file
193
tests/servers-api-e2e.test.ts
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
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 } from 'vitest';
|
||||
import WebSocket from 'ws';
|
||||
import { createGCoordinatorServer } from '../src/server/app.js';
|
||||
import { MockSshServer } from './helpers/mock-ssh-server.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('; ');
|
||||
}
|
||||
}
|
||||
|
||||
async function openWs(url: string, headers: Record<string, string>) {
|
||||
return new Promise<{ ws: WebSocket; frames: Array<Record<string, unknown>> }>((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(async () => {
|
||||
while (cleanups.length > 0) {
|
||||
await cleanups.pop()!();
|
||||
}
|
||||
});
|
||||
|
||||
describe('Phase 2 E2E: /api/servers, TOFU, Live Metrics WS, Key Rotation & Panic Lock Teardown', () => {
|
||||
it('registers target server, approves TOFU, streams metrics over /ws, inspects, rotates keys, and drops SSH on Panic Lock', async () => {
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p2-e2e-'));
|
||||
const server = await createGCoordinatorServer({
|
||||
dataDir,
|
||||
port: 0,
|
||||
host: '127.0.0.1',
|
||||
publicDir: path.resolve('dist/public'),
|
||||
});
|
||||
cleanups.push(async () => {
|
||||
await server.close();
|
||||
fs.rmSync(dataDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
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 } = {},
|
||||
) => {
|
||||
const headers: Record<string, string> = {};
|
||||
if (jar.header()) headers.Cookie = jar.header();
|
||||
if (opts.body !== undefined) headers['Content-Type'] = 'application/json';
|
||||
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(() => ({}));
|
||||
return { status: res.status, data: data as Record<string, unknown> };
|
||||
};
|
||||
|
||||
// Bootstrap + Auth + Vault + Ed25519 Key
|
||||
const bootInfo = await api('/api/auth/bootstrap');
|
||||
const secretBase32 = String(bootInfo.data.secretBase32);
|
||||
const totp = new OTPAuth.TOTP({
|
||||
issuer: 'GCoordinator',
|
||||
label: 'admin',
|
||||
algorithm: 'SHA1',
|
||||
digits: 6,
|
||||
period: 30,
|
||||
secret: OTPAuth.Secret.fromBase32(secretBase32),
|
||||
});
|
||||
|
||||
const bootRes = await api('/api/auth/bootstrap', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
username: 'admin',
|
||||
password: 'phase2-e2e-password',
|
||||
totpCode: totp.generate(),
|
||||
secretBase32,
|
||||
},
|
||||
});
|
||||
expect(bootRes.status).toBe(201);
|
||||
csrfToken = String(bootRes.data.csrfToken);
|
||||
|
||||
const { ws, frames } = await openWs(wsUrl, {
|
||||
Cookie: jar.header(),
|
||||
Host: `127.0.0.1:${server.port}`,
|
||||
Origin: baseUrl,
|
||||
});
|
||||
ws.send(JSON.stringify({ type: 'sub', channels: ['metrics', 'alerts', 'config'] }));
|
||||
|
||||
expect((await api('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201);
|
||||
expect(
|
||||
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
|
||||
).toBe(200);
|
||||
|
||||
const keyRes = await api('/api/vault/generate-ed25519', {
|
||||
method: 'POST',
|
||||
body: { id: 'fleet-key', name: 'Fleet Key' },
|
||||
});
|
||||
expect(keyRes.status).toBe(201);
|
||||
const pubKey = String((keyRes.data.credential as { publicKey: string }).publicKey);
|
||||
|
||||
// Start mock target SSH server
|
||||
const mock = new MockSshServer({
|
||||
username: 'ops',
|
||||
os: 'Linux',
|
||||
authorizedKeys: [pubKey],
|
||||
});
|
||||
const sshPort = await mock.start();
|
||||
cleanups.push(() => mock.close());
|
||||
|
||||
// Register server -> initial handshake stops at TOFU pending
|
||||
const reg = await api('/api/servers', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'web-01',
|
||||
name: 'Web 01',
|
||||
host: '127.0.0.1',
|
||||
port: sshPort,
|
||||
username: 'ops',
|
||||
credentialId: 'fleet-key',
|
||||
pollIntervalSec: 60,
|
||||
},
|
||||
});
|
||||
expect(reg.status).toBe(201);
|
||||
|
||||
const reconn = await api('/api/servers/web-01/reconnect', { method: 'POST' });
|
||||
expect((reconn.data.state as { status: string }).status).toBe('tofu_pending');
|
||||
|
||||
// Approve TOFU -> immediate connection + metrics:tick broadcast over /ws
|
||||
const approve = await api('/api/servers/web-01/tofu/approve', {
|
||||
method: 'POST',
|
||||
body: { fingerprint: mock.hostFingerprint },
|
||||
});
|
||||
expect(approve.status).toBe(200);
|
||||
expect((approve.data.state as { status: string }).status).toBe('connected');
|
||||
expect(mock.activeConnectionCount).toBe(1);
|
||||
|
||||
await new Promise((r) => setTimeout(r, 80));
|
||||
expect(
|
||||
frames.some((f) => f.type === 'metrics:tick' && f.serverId === 'web-01'),
|
||||
).toBe(true);
|
||||
|
||||
// Inspect processes & ports on demand
|
||||
const inspect = await api('/api/servers/web-01/inspect');
|
||||
expect(inspect.status).toBe(200);
|
||||
expect((inspect.data.processes as unknown[]).length).toBeGreaterThan(0);
|
||||
|
||||
// Atomic zero-lockout key rotation via /api/servers/rotate-keys
|
||||
const rot = await api('/api/servers/rotate-keys', {
|
||||
method: 'POST',
|
||||
body: { serverIds: ['web-01'] },
|
||||
});
|
||||
expect(rot.status).toBe(200);
|
||||
expect((rot.data.results as Array<{ ok: boolean }>)[0]?.ok).toBe(true);
|
||||
|
||||
// Panic Lock must immediately close pooled SSH connections
|
||||
const panic = await api('/api/security/panic-lock', { method: 'POST' });
|
||||
expect(panic.status).toBe(200);
|
||||
await new Promise((r) => setTimeout(r, 120));
|
||||
expect(mock.activeConnectionCount).toBe(0);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue