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
338
tests/helpers/mock-ssh-server.ts
Normal file
338
tests/helpers/mock-ssh-server.ts
Normal file
|
|
@ -0,0 +1,338 @@
|
|||
import net from 'node:net';
|
||||
import ssh2, { type Connection, type Server } from 'ssh2';
|
||||
import { computeOpenSshFingerprint } from '../../src/server/security/vault.js';
|
||||
|
||||
export interface MockSshOptions {
|
||||
username: string;
|
||||
password?: string;
|
||||
sudoPassword?: string;
|
||||
os?: 'Linux' | 'FreeBSD' | 'Darwin';
|
||||
authorizedKeys?: string[];
|
||||
allowTcpForward?: boolean;
|
||||
onExec?: (
|
||||
command: string,
|
||||
stdin: string,
|
||||
) => { stdout: string; stderr?: string; exitCode: number } | null;
|
||||
}
|
||||
|
||||
function unquoteSinglePosix(quoted: string): string {
|
||||
const s = quoted.trim();
|
||||
if (s.startsWith("'") && s.endsWith("'")) {
|
||||
return s.slice(1, -1).replace(/'\\''/g, "'");
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
export class MockSshServer {
|
||||
public port = 0;
|
||||
public hostFingerprint = '';
|
||||
public authorizedKeys: string[];
|
||||
public pollCount = 0;
|
||||
public lastSudoStdin = '';
|
||||
|
||||
private hostPrivateKey: string;
|
||||
private server: Server | null = null;
|
||||
private readonly activeConns = new Set<Connection>();
|
||||
|
||||
constructor(public readonly options: MockSshOptions) {
|
||||
this.authorizedKeys = [...(options.authorizedKeys ?? [])];
|
||||
const kp = ssh2.utils.generateKeyPairSync('ed25519', { comment: 'mock-host' });
|
||||
this.hostPrivateKey = kp.private;
|
||||
this.hostFingerprint = computeOpenSshFingerprint(kp.public.trim());
|
||||
}
|
||||
|
||||
async start(listenPort = 0): Promise<number> {
|
||||
if (this.server) return this.port;
|
||||
|
||||
const srv = new ssh2.Server(
|
||||
{ hostKeys: [this.hostPrivateKey] },
|
||||
(client) => this.handleClient(client),
|
||||
);
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
srv.once('error', reject);
|
||||
srv.listen(listenPort, '127.0.0.1', () => {
|
||||
srv.off('error', reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
this.server = srv;
|
||||
const addr = srv.address();
|
||||
this.port = typeof addr === 'object' && addr ? addr.port : listenPort;
|
||||
return this.port;
|
||||
}
|
||||
|
||||
async swapHostKey(): Promise<string> {
|
||||
const prevPort = this.port;
|
||||
await this.close();
|
||||
const kp = ssh2.utils.generateKeyPairSync('ed25519', { comment: 'mitm-host' });
|
||||
this.hostPrivateKey = kp.private;
|
||||
this.hostFingerprint = computeOpenSshFingerprint(kp.public.trim());
|
||||
await this.start(prevPort);
|
||||
return this.hostFingerprint;
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
for (const c of this.activeConns) {
|
||||
try {
|
||||
c.end();
|
||||
} catch {
|
||||
// Ignore close errors
|
||||
}
|
||||
}
|
||||
this.activeConns.clear();
|
||||
if (this.server) {
|
||||
const s = this.server;
|
||||
this.server = null;
|
||||
await new Promise<void>((resolve) => s.close(() => resolve()));
|
||||
}
|
||||
}
|
||||
|
||||
get activeConnectionCount(): number {
|
||||
return this.activeConns.size;
|
||||
}
|
||||
|
||||
private handleClient(client: Connection): void {
|
||||
this.activeConns.add(client);
|
||||
client.on('close', () => {
|
||||
this.activeConns.delete(client);
|
||||
});
|
||||
client.on('error', () => {
|
||||
this.activeConns.delete(client);
|
||||
});
|
||||
|
||||
client.on('authentication', (ctx) => {
|
||||
if (ctx.username !== this.options.username) {
|
||||
ctx.reject(['publickey', 'password']);
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.method === 'password' && this.options.password) {
|
||||
if (ctx.password === this.options.password) {
|
||||
ctx.accept();
|
||||
return;
|
||||
}
|
||||
ctx.reject(['publickey', 'password']);
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.method === 'publickey') {
|
||||
for (const line of this.authorizedKeys) {
|
||||
const parsed = ssh2.utils.parseKey(line.trim());
|
||||
if (parsed instanceof Error || Array.isArray(parsed)) continue;
|
||||
if (
|
||||
ctx.key.algo === parsed.type &&
|
||||
ctx.key.data.equals(parsed.getPublicSSH())
|
||||
) {
|
||||
if (!ctx.signature) {
|
||||
ctx.accept();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
ctx.blob &&
|
||||
parsed.verify(ctx.blob, ctx.signature, ctx.hashAlgo) === true
|
||||
) {
|
||||
ctx.accept();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.reject(['publickey', 'password']);
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.reject(['publickey', 'password']);
|
||||
});
|
||||
|
||||
client.on('ready', () => {
|
||||
client.on('tcpip', (accept, reject, info) => {
|
||||
if (this.options.allowTcpForward === false) {
|
||||
reject();
|
||||
return;
|
||||
}
|
||||
const upstream = net.connect(info.destPort, info.destIP, () => {
|
||||
const channel = accept();
|
||||
channel.pipe(upstream).pipe(channel);
|
||||
channel.on('close', () => upstream.destroy());
|
||||
upstream.on('close', () => channel.destroy());
|
||||
});
|
||||
upstream.on('error', () => {
|
||||
reject();
|
||||
});
|
||||
});
|
||||
|
||||
client.on('session', (accept) => {
|
||||
const session = accept();
|
||||
session.on('exec', (acceptExec, _rejectExec, info) => {
|
||||
const stream = acceptExec();
|
||||
const stdinChunks: Buffer[] = [];
|
||||
stream.on('data', (chunk: Buffer) => {
|
||||
stdinChunks.push(chunk);
|
||||
});
|
||||
stream.on('end', () => {
|
||||
const stdinText = Buffer.concat(stdinChunks).toString('utf8');
|
||||
const result = this.evaluateCommand(info.command, stdinText);
|
||||
if (!stream.writable || stream.writableEnded) return;
|
||||
if (result.stdout) stream.write(result.stdout);
|
||||
if (result.stderr && stream.stderr.writable && !stream.stderr.writableEnded) {
|
||||
stream.stderr.write(result.stderr);
|
||||
}
|
||||
stream.exit(result.exitCode);
|
||||
stream.end();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private evaluateCommand(
|
||||
rawCommand: string,
|
||||
rawStdin: string,
|
||||
): { stdout: string; stderr?: string; exitCode: number } {
|
||||
let command = rawCommand.trim();
|
||||
let stdin = rawStdin;
|
||||
|
||||
// Handle sudo wrappers produced by prepareSudoExecution
|
||||
if (command.startsWith("sudo -S -p '' sh -c ")) {
|
||||
const nl = stdin.indexOf('\n');
|
||||
const suppliedPw = nl >= 0 ? stdin.slice(0, nl) : stdin;
|
||||
this.lastSudoStdin = suppliedPw;
|
||||
stdin = nl >= 0 ? stdin.slice(nl + 1) : '';
|
||||
if (this.options.sudoPassword && suppliedPw !== this.options.sudoPassword) {
|
||||
return { stdout: '', stderr: 'sudo: incorrect password', exitCode: 1 };
|
||||
}
|
||||
command = unquoteSinglePosix(command.slice("sudo -S -p '' sh -c ".length));
|
||||
} else if (command.startsWith('sudo -n sh -c ')) {
|
||||
command = unquoteSinglePosix(command.slice('sudo -n sh -c '.length));
|
||||
}
|
||||
|
||||
if (this.options.onExec) {
|
||||
const custom = this.options.onExec(command, stdin);
|
||||
if (custom) return custom;
|
||||
}
|
||||
|
||||
if (command === 'echo gcoord-key-ok') {
|
||||
return { stdout: 'gcoord-key-ok\n', exitCode: 0 };
|
||||
}
|
||||
|
||||
if (command === 'uname -s') {
|
||||
return { stdout: `${this.options.os ?? 'Linux'}\n`, exitCode: 0 };
|
||||
}
|
||||
|
||||
if (command.includes('cat ~/.ssh/authorized_keys')) {
|
||||
const body =
|
||||
this.authorizedKeys.length > 0
|
||||
? `${this.authorizedKeys.join('\n')}\n`
|
||||
: '';
|
||||
return { stdout: body, exitCode: 0 };
|
||||
}
|
||||
|
||||
if (command.includes('mv ~/.ssh/authorized_keys.gcoord.tmp')) {
|
||||
this.authorizedKeys = stdin
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.trim())
|
||||
.filter(Boolean);
|
||||
return { stdout: '', exitCode: 0 };
|
||||
}
|
||||
|
||||
// Metrics commands
|
||||
if (command.includes('===STAT===')) {
|
||||
this.pollCount += 1;
|
||||
const busy = 1000 + this.pollCount * 150;
|
||||
const idle = 9000 + this.pollCount * 850;
|
||||
const rx = 100_000 + this.pollCount * 25_000;
|
||||
const tx = 50_000 + this.pollCount * 10_000;
|
||||
const stdout = [
|
||||
'===STAT===',
|
||||
`cpu ${busy} 0 100 ${idle} 50 0 0 0 0 0`,
|
||||
'===MEM===',
|
||||
'MemTotal: 16384000 kB',
|
||||
'MemAvailable: 10240000 kB',
|
||||
'===LOAD===',
|
||||
'0.42 0.35 0.28 1/200 1234',
|
||||
'===UPTIME===',
|
||||
'86400.50 172000.00',
|
||||
'===NET===',
|
||||
'Inter-| Receive | Transmit',
|
||||
' face |bytes packets errs drop fifo frame compressed multicast|bytes packets',
|
||||
' lo: 999999 100 0 0 0 0 0 0 999999 100',
|
||||
` eth0: ${rx} 500 0 0 0 0 0 0 ${tx} 400`,
|
||||
'===DF===',
|
||||
'Filesystem Type 1024-blocks Used Available Capacity Mounted on',
|
||||
'tmpfs tmpfs 102400 10240 92160 10% /run',
|
||||
'/dev/sda1 ext4 104857600 41943040 62914560 40% /',
|
||||
'/dev/sdb1 xfs 52428800 10485760 41943040 20% /data',
|
||||
].join('\n');
|
||||
return { stdout: `${stdout}\n`, exitCode: 0 };
|
||||
}
|
||||
|
||||
if (command.includes('===SYSCTL===') && this.options.os === 'FreeBSD') {
|
||||
this.pollCount += 1;
|
||||
const bootSec = Math.floor(Date.now() / 1000) - 3600;
|
||||
const stdout = [
|
||||
'===SYSCTL===',
|
||||
'8589934592',
|
||||
'4096',
|
||||
'{ 0.31 0.25 0.19 }',
|
||||
`{ sec = ${bootSec}, usec = 0 }`,
|
||||
`${500 + this.pollCount * 20} 0 100 5 ${4000 + this.pollCount * 80}`,
|
||||
'===VMSTAT===',
|
||||
' procs memory page',
|
||||
' 1 0 0 200000 500000 0 0 0',
|
||||
'===NET===',
|
||||
'Name Mtu Network Address Ipkts Ierrs Idrop Ibytes Opkts Oerrs Obytes Coll',
|
||||
`vtnet0 1500 <Link#1> 52:54:00:12:34:56 100 0 0 ${10000 + this.pollCount * 1000} 100 0 ${5000 + this.pollCount * 500} 0`,
|
||||
'===DF===',
|
||||
'Filesystem Type 1K-blocks Used Avail Capacity Mounted on',
|
||||
'devfs devfs 1 1 0 100% /dev',
|
||||
'/dev/vtbd0p2 ufs 41943040 16777216 25165824 40% /',
|
||||
].join('\n');
|
||||
return { stdout: `${stdout}\n`, exitCode: 0 };
|
||||
}
|
||||
|
||||
if (command.includes('===TOP===') && this.options.os === 'Darwin') {
|
||||
this.pollCount += 1;
|
||||
const bootSec = Math.floor(Date.now() / 1000) - 7200;
|
||||
const stdout = [
|
||||
'===SYSCTL===',
|
||||
'17179869184',
|
||||
'16384',
|
||||
'{ 1.15 0.90 0.75 }',
|
||||
`{ sec = ${bootSec}, usec = 0 }`,
|
||||
'===VMSTAT===',
|
||||
'Pages active: 250000.',
|
||||
'Pages wired down: 100000.',
|
||||
'Pages occupied by compressor: 50000.',
|
||||
'===TOP===',
|
||||
'CPU usage: 18.50% user, 6.50% sys, 75.00% idle',
|
||||
'===NET===',
|
||||
'Name Mtu Network Address Ipkts Ierrs Ibytes Opkts Oerrs Obytes Coll',
|
||||
`en0 1500 <Link#4> aa:bb:cc:dd:ee:ff 100 0 ${20000 + this.pollCount * 2000} 100 0 ${8000 + this.pollCount * 800} 0`,
|
||||
'===DF===',
|
||||
'Filesystem 1024-blocks Used Available Capacity Mounted on',
|
||||
'/dev/disk3s1 488245288 195298115 292947173 40% /',
|
||||
].join('\n');
|
||||
return { stdout: `${stdout}\n`, exitCode: 0 };
|
||||
}
|
||||
|
||||
// Inspector command
|
||||
if (command.includes('===PROCS===')) {
|
||||
const stdout = [
|
||||
'===PROCS===',
|
||||
' PID USER %CPU %MEM RSS COMMAND',
|
||||
' 101 root 12.4 1.8 65536 /usr/bin/node server.js',
|
||||
' 202 postgres 4.1 3.2 131072 postgres: main process',
|
||||
'===PORTS===',
|
||||
'Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port Process',
|
||||
'tcp LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=10,fd=3))',
|
||||
'tcp LISTEN 0 511 127.0.0.1:5432 0.0.0.0:* users:(("postgres",pid=202,fd=5))',
|
||||
'===THERMAL===',
|
||||
'x86_pkg_temp:46500',
|
||||
].join('\n');
|
||||
return { stdout: `${stdout}\n`, exitCode: 0 };
|
||||
}
|
||||
|
||||
return { stdout: `ok:${command}\n`, exitCode: 0 };
|
||||
}
|
||||
}
|
||||
247
tests/monitoring-and-probes.test.ts
Normal file
247
tests/monitoring-and-probes.test.ts
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
import http from 'node:http';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { ConfigManager } from '../src/server/config/config-manager.js';
|
||||
import { openDatabase } from '../src/server/db/database.js';
|
||||
import {
|
||||
parseBsdOutput,
|
||||
parseLinuxOutput,
|
||||
parseMacOsOutput,
|
||||
} from '../src/server/monitoring/collectors.js';
|
||||
import {
|
||||
parseInspectorOutput,
|
||||
ServerInspector,
|
||||
} from '../src/server/monitoring/inspector.js';
|
||||
import { MonitoringService } from '../src/server/monitoring/monitoring-service.js';
|
||||
import { ProbeRunner } from '../src/server/monitoring/probes.js';
|
||||
import { AuditService } from '../src/server/security/audit.js';
|
||||
import { VaultService } from '../src/server/security/vault.js';
|
||||
import { KnownHostsService } from '../src/server/ssh/known-hosts.js';
|
||||
import { SSHPool } from '../src/server/ssh/ssh-pool.js';
|
||||
import { MockSshServer } from './helpers/mock-ssh-server.js';
|
||||
|
||||
const cleanups: Array<() => Promise<void> | void> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
while (cleanups.length > 0) {
|
||||
await cleanups.pop()!();
|
||||
}
|
||||
});
|
||||
|
||||
describe('OS Collectors, ServerInspector, Health Probes & MonitoringService', () => {
|
||||
it('parses Linux, BSD, and macOS telemetry and filters virtual filesystems', () => {
|
||||
const linux1 = [
|
||||
'===STAT===',
|
||||
'cpu 1000 0 200 8800 0 0 0 0 0 0',
|
||||
'===MEM===',
|
||||
'MemTotal: 8192000 kB',
|
||||
'MemAvailable: 4096000 kB',
|
||||
'===LOAD===',
|
||||
'1.25 0.90 0.80 1/120 55',
|
||||
'===UPTIME===',
|
||||
'12000.12 24000.00',
|
||||
'===NET===',
|
||||
' lo: 50000 10 0 0 0 0 0 0 50000 10',
|
||||
' eth0: 1000000 100 0 0 0 0 0 0 500000 80',
|
||||
'===DF===',
|
||||
'Filesystem Type 1024-blocks Used Available Capacity Mounted on',
|
||||
'tmpfs tmpfs 102400 100 102300 1% /run',
|
||||
'overlay overlay 102400 100 102300 1% /var/lib/docker',
|
||||
'/dev/vda1 ext4 10485760 5242880 5242880 50% /',
|
||||
].join('\n');
|
||||
|
||||
const p1 = parseLinuxOutput(linux1, undefined, undefined, 10_000);
|
||||
expect(p1.sample.memTotalMb).toBe(8000);
|
||||
expect(p1.sample.memUsedMb).toBe(4000);
|
||||
expect(p1.sample.load1m).toBe(1.25);
|
||||
expect(p1.disks).toEqual([
|
||||
{ mountPoint: '/', fsType: 'ext4', usedMb: 5120, totalMb: 10240, usedPct: 50 },
|
||||
]);
|
||||
|
||||
const linux2 = linux1
|
||||
.replace('cpu 1000 0 200 8800', 'cpu 1500 0 300 9200')
|
||||
.replace('eth0: 1000000 100 0 0 0 0 0 0 500000', 'eth0: 1050000 110 0 0 0 0 0 0 520000');
|
||||
|
||||
const p2 = parseLinuxOutput(linux2, p1.nextState, undefined, 12_000);
|
||||
expect(p2.sample.cpuPct).toBe(60); // 600 busy / 1000 total delta
|
||||
expect(p2.sample.netRxBps).toBe(25_000);
|
||||
expect(p2.sample.netTxBps).toBe(10_000);
|
||||
|
||||
// BSD parser
|
||||
const bsd1 = [
|
||||
'===SYSCTL===',
|
||||
'4294967296',
|
||||
'4096',
|
||||
'{ 0.50 0.40 0.30 }',
|
||||
'{ sec = 1000, usec = 0 }',
|
||||
'100 0 50 0 850',
|
||||
'===VMSTAT===',
|
||||
' 1 0 0 1000 262144 0',
|
||||
'===NET===',
|
||||
'vtnet0 1500 <Link#1> 52:54:00 10 0 0 5000 10 0 2000 0',
|
||||
'===DF===',
|
||||
'Filesystem Type 1K-blocks Used Avail Capacity Mounted on',
|
||||
'devfs devfs 1 1 0 100% /dev',
|
||||
'/dev/ada0p2 ufs 10485760 2097152 8388608 20% /',
|
||||
].join('\n');
|
||||
const bsdOut = parseBsdOutput(bsd1, undefined, undefined, 5000_000);
|
||||
expect(bsdOut.sample.memTotalMb).toBe(4096);
|
||||
expect(bsdOut.sample.memUsedMb).toBe(3072);
|
||||
expect(bsdOut.disks).toHaveLength(1);
|
||||
|
||||
// macOS parser
|
||||
const mac = [
|
||||
'===SYSCTL===',
|
||||
'8589934592',
|
||||
'4096',
|
||||
'{ 2.10 1.90 1.50 }',
|
||||
'{ sec = 1000, usec = 0 }',
|
||||
'===VMSTAT===',
|
||||
'Pages active: 262144.',
|
||||
'Pages wired down: 262144.',
|
||||
'Pages occupied by compressor: 0.',
|
||||
'===TOP===',
|
||||
'CPU usage: 20.00% user, 5.00% sys, 75.00% idle',
|
||||
'===NET===',
|
||||
'en0 1500 <Link#4> aa:bb 10 0 10000 10 0 4000 0',
|
||||
'===DF===',
|
||||
'Filesystem 1024-blocks Used Available Capacity Mounted on',
|
||||
'devfs 100 100 0 100% /dev',
|
||||
'/dev/disk1s1 20971520 10485760 10485760 50% /',
|
||||
].join('\n');
|
||||
const macOut = parseMacOsOutput(mac, undefined, undefined, 5000_000);
|
||||
expect(macOut.sample.cpuPct).toBe(25);
|
||||
expect(macOut.sample.memUsedMb).toBe(2048);
|
||||
expect(macOut.disks).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('parses Inspector snapshots and runs hub & target HTTP/TCP probes + SQLite rollups', async () => {
|
||||
const parsedInspect = parseInspectorOutput(
|
||||
'srv-1',
|
||||
'linux',
|
||||
[
|
||||
'===PROCS===',
|
||||
'PID USER %CPU %MEM RSS COMMAND',
|
||||
'101 ops 25.5 2.0 32768 /usr/bin/node app.js',
|
||||
'===PORTS===',
|
||||
'Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port Process',
|
||||
'tcp LISTEN 0 128 127.0.0.1:8080 0.0.0.0:* users:(("node",pid=101,fd=4))',
|
||||
'===THERMAL===',
|
||||
'acpitz:42000',
|
||||
].join('\n'),
|
||||
);
|
||||
expect(parsedInspect.processes[0]?.pid).toBe(101);
|
||||
expect(parsedInspect.ports[0]?.localAddress).toBe('127.0.0.1:8080');
|
||||
expect(parsedInspect.thermals[0]).toEqual({ zone: 'acpitz', tempC: 42 });
|
||||
|
||||
// Local HTTP endpoint for probes
|
||||
const probeHttp = http.createServer((req, res) => {
|
||||
if (req.url === '/healthz') {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.end('STATUS_GREEN');
|
||||
} else {
|
||||
res.writeHead(503);
|
||||
res.end('DOWN');
|
||||
}
|
||||
});
|
||||
await new Promise<void>((resolve) => probeHttp.listen(0, '127.0.0.1', resolve));
|
||||
const httpPort = (probeHttp.address() as { port: number }).port;
|
||||
cleanups.push(() => new Promise<void>((r) => probeHttp.close(() => r())));
|
||||
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-mon-test-'));
|
||||
const db = openDatabase(path.join(dir, 'gcoord.db'));
|
||||
const audit = new AuditService(db);
|
||||
const vault = new VaultService(path.join(dir, 'vault.enc'));
|
||||
vault.initializeNewVault();
|
||||
const cred = vault.generateEd25519Credential({ id: 'mon-cred', name: 'Mon' });
|
||||
|
||||
const mock = new MockSshServer({
|
||||
username: 'ops',
|
||||
os: 'Linux',
|
||||
authorizedKeys: [cred.publicKey!],
|
||||
allowTcpForward: true,
|
||||
});
|
||||
const sshPort = await mock.start();
|
||||
cleanups.push(() => mock.close());
|
||||
|
||||
const cfg = new ConfigManager(path.join(dir, 'config'), db, vault);
|
||||
await cfg.init({ watch: false });
|
||||
const knownHosts = new KnownHostsService(db, audit);
|
||||
const sshPool = new SSHPool(cfg, vault, knownHosts);
|
||||
const probeRunner = new ProbeRunner(sshPool);
|
||||
const inspector = new ServerInspector(sshPool, cfg);
|
||||
const monitoring = new MonitoringService(db, cfg, vault, sshPool, probeRunner);
|
||||
|
||||
cleanups.push(async () => {
|
||||
monitoring.close();
|
||||
sshPool.closeAll('shutdown');
|
||||
await cfg.close();
|
||||
db.close();
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
cfg.saveConfigText(
|
||||
'servers/linux-01.json',
|
||||
JSON.stringify({
|
||||
id: 'linux-01',
|
||||
name: 'Linux 01',
|
||||
host: '127.0.0.1',
|
||||
port: sshPort,
|
||||
username: 'ops',
|
||||
credentialId: 'mon-cred',
|
||||
hostKeyFingerprint: mock.hostFingerprint,
|
||||
pollIntervalSec: 60,
|
||||
probes: [
|
||||
{
|
||||
id: 'hub-http',
|
||||
type: 'http',
|
||||
url: `http://127.0.0.1:${httpPort}/healthz`,
|
||||
from: 'hub',
|
||||
expectedStatus: 200,
|
||||
bodyIncludes: 'STATUS_GREEN',
|
||||
},
|
||||
{
|
||||
id: 'target-http',
|
||||
type: 'http',
|
||||
url: `http://127.0.0.1:${httpPort}/healthz`,
|
||||
from: 'target',
|
||||
expectedStatus: 200,
|
||||
bodyIncludes: 'STATUS_GREEN',
|
||||
},
|
||||
{
|
||||
id: 'target-tcp',
|
||||
type: 'tcp',
|
||||
host: '127.0.0.1',
|
||||
port: httpPort,
|
||||
from: 'target',
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const serverCfg = cfg.getServer('linux-01')!;
|
||||
for (const p of serverCfg.probes) {
|
||||
const sample = await probeRunner.runProbe('linux-01', p);
|
||||
expect(sample.ok).toBe(true);
|
||||
}
|
||||
|
||||
const tick1 = await monitoring.pollServerNow('linux-01');
|
||||
const tick2 = await monitoring.pollServerNow('linux-01');
|
||||
expect(tick1).not.toBeNull();
|
||||
expect(tick2!.disks.map((d) => d.mountPoint)).toEqual(['/', '/data']);
|
||||
|
||||
const insp = await inspector.inspect('linux-01');
|
||||
expect(insp.os).toBe('linux');
|
||||
expect(insp.processes.length).toBeGreaterThan(0);
|
||||
|
||||
// Run rollup & query 7d aggregated series
|
||||
monitoring.runMaintenance(Date.now());
|
||||
const historyRaw = monitoring.queryHistory('linux-01', '1h');
|
||||
expect(historyRaw.points.length).toBeGreaterThanOrEqual(2);
|
||||
const history7d = monitoring.queryHistory('linux-01', '7d');
|
||||
expect(history7d.granularity).toBe('1h');
|
||||
expect(history7d.points.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
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);
|
||||
});
|
||||
});
|
||||
234
tests/ssh-pool-and-keys.test.ts
Normal file
234
tests/ssh-pool-and-keys.test.ts
Normal file
|
|
@ -0,0 +1,234 @@
|
|||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { ConfigManager } from '../src/server/config/config-manager.js';
|
||||
import { openDatabase } from '../src/server/db/database.js';
|
||||
import { AuditService } from '../src/server/security/audit.js';
|
||||
import { VaultService } from '../src/server/security/vault.js';
|
||||
import { KeyManager } from '../src/server/ssh/key-manager.js';
|
||||
import { KnownHostsService } from '../src/server/ssh/known-hosts.js';
|
||||
import { SSHPool } from '../src/server/ssh/ssh-pool.js';
|
||||
import { MockSshServer } from './helpers/mock-ssh-server.js';
|
||||
|
||||
const cleanups: Array<() => Promise<void> | void> = [];
|
||||
|
||||
async function setupEnv() {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-ssh-test-'));
|
||||
const db = openDatabase(path.join(dir, 'gcoord.db'));
|
||||
const audit = new AuditService(db);
|
||||
const vault = new VaultService(path.join(dir, 'vault.enc'));
|
||||
vault.initializeNewVault();
|
||||
const cfg = new ConfigManager(path.join(dir, 'config'), db, vault);
|
||||
await cfg.init({ watch: false });
|
||||
const knownHosts = new KnownHostsService(db, audit);
|
||||
const sshPool = new SSHPool(cfg, vault, knownHosts);
|
||||
const keyManager = new KeyManager(sshPool, vault, cfg, audit);
|
||||
|
||||
cleanups.push(async () => {
|
||||
sshPool.closeAll('shutdown');
|
||||
await cfg.close();
|
||||
db.close();
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
return { dir, db, audit, vault, cfg, knownHosts, sshPool, keyManager };
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
while (cleanups.length > 0) {
|
||||
await cleanups.pop()!();
|
||||
}
|
||||
});
|
||||
|
||||
describe('SSHPool TOFU/MITM, ProxyJump, sudo, and Atomic Key Rotation', () => {
|
||||
it('enforces strict TOFU, hard-blocks host key mismatch, and recovers via step-up reset', async () => {
|
||||
const { vault, cfg, knownHosts, sshPool } = await setupEnv();
|
||||
const cred = vault.generateEd25519Credential({ id: 'cred-main', name: 'Main' });
|
||||
|
||||
const mock = new MockSshServer({
|
||||
username: 'ops',
|
||||
authorizedKeys: [cred.publicKey!],
|
||||
});
|
||||
const port = await mock.start();
|
||||
cleanups.push(() => mock.close());
|
||||
|
||||
cfg.saveConfigText(
|
||||
'servers/app-01.json',
|
||||
JSON.stringify({
|
||||
id: 'app-01',
|
||||
name: 'App 01',
|
||||
host: '127.0.0.1',
|
||||
port,
|
||||
username: 'ops',
|
||||
credentialId: 'cred-main',
|
||||
}),
|
||||
);
|
||||
|
||||
// 1. Initial connection must block awaiting TOFU approval
|
||||
await expect(sshPool.exec('app-01', 'echo hello')).rejects.toThrow();
|
||||
const state1 = sshPool.getState('app-01');
|
||||
expect(state1?.status).toBe('tofu_pending');
|
||||
expect(state1?.tofuPending?.fingerprint).toBe(mock.hostFingerprint);
|
||||
|
||||
// 2. Approve TOFU and connect cleanly
|
||||
knownHosts.approveTofu('app-01', mock.hostFingerprint);
|
||||
const res = await sshPool.exec('app-01', 'echo hello');
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout.trim()).toBe('ok:echo hello');
|
||||
expect(sshPool.getState('app-01')?.status).toBe('connected');
|
||||
|
||||
// 3. Simulate MITM host key swap
|
||||
const newHostFp = await mock.swapHostKey();
|
||||
sshPool.closeServer('app-01');
|
||||
|
||||
await expect(sshPool.exec('app-01', 'echo blocked')).rejects.toThrow();
|
||||
const stateMismatch = sshPool.getState('app-01');
|
||||
expect(stateMismatch?.status).toBe('host_key_mismatch');
|
||||
expect(stateMismatch?.hostKeyMismatch?.actualFingerprint).toBe(newHostFp);
|
||||
|
||||
// 4. Reset mismatch and verify restored connection
|
||||
knownHosts.resetMismatch('app-01', newHostFp);
|
||||
const resAfter = await sshPool.exec('app-01', 'echo recovered');
|
||||
expect(resAfter.stdout.trim()).toBe('ok:echo recovered');
|
||||
});
|
||||
|
||||
it('chains multi-hop ProxyJump bastions and runs sudo -S via stdin without leaking secrets in command', async () => {
|
||||
const { vault, cfg, knownHosts, sshPool } = await setupEnv();
|
||||
const cred = vault.generateEd25519Credential({ id: 'cred-hop', name: 'Hop Key' });
|
||||
vault.upsertCredential({
|
||||
id: 'sudo-ops',
|
||||
name: 'Sudo PW',
|
||||
type: 'sudo-password',
|
||||
password: 'vault-sudo-secret-pw',
|
||||
});
|
||||
|
||||
const bastion = new MockSshServer({
|
||||
username: 'bastion-user',
|
||||
authorizedKeys: [cred.publicKey!],
|
||||
allowTcpForward: true,
|
||||
});
|
||||
const bastionPort = await bastion.start();
|
||||
cleanups.push(() => bastion.close());
|
||||
|
||||
const privateTarget = new MockSshServer({
|
||||
username: 'ops',
|
||||
authorizedKeys: [cred.publicKey!],
|
||||
sudoPassword: 'vault-sudo-secret-pw',
|
||||
});
|
||||
const targetPort = await privateTarget.start();
|
||||
cleanups.push(() => privateTarget.close());
|
||||
|
||||
cfg.saveConfigText(
|
||||
'servers/bastion.json',
|
||||
JSON.stringify({
|
||||
id: 'bastion',
|
||||
name: 'Bastion',
|
||||
host: '127.0.0.1',
|
||||
port: bastionPort,
|
||||
username: 'bastion-user',
|
||||
credentialId: 'cred-hop',
|
||||
hostKeyFingerprint: bastion.hostFingerprint,
|
||||
}),
|
||||
);
|
||||
|
||||
cfg.saveConfigText(
|
||||
'servers/priv-01.json',
|
||||
JSON.stringify({
|
||||
id: 'priv-01',
|
||||
name: 'Private Target',
|
||||
host: '127.0.0.1',
|
||||
port: targetPort,
|
||||
username: 'ops',
|
||||
credentialId: 'cred-hop',
|
||||
jumpHostId: 'bastion',
|
||||
sudoCredentialId: 'sudo-ops',
|
||||
hostKeyFingerprint: privateTarget.hostFingerprint,
|
||||
}),
|
||||
);
|
||||
|
||||
// First hop + second hop both use pre-seeded hostKeyFingerprint & forwardOut tunnel
|
||||
const res = await sshPool.exec('priv-01', 'id -u', { sudo: true });
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout.trim()).toBe('ok:id -u');
|
||||
expect(privateTarget.lastSudoStdin).toBe('vault-sudo-secret-pw');
|
||||
|
||||
// Verify independent known_hosts key includes jumpHostId prefix
|
||||
const kh = knownHosts.listKnownHosts().map((k) => k.hostPort);
|
||||
expect(kh).toContain(`127.0.0.1:${bastionPort}`);
|
||||
expect(kh).toContain(`bastion->127.0.0.1:${targetPort}`);
|
||||
});
|
||||
|
||||
it('deploys/revokes authorized_keys and performs atomic zero-lockout rotation with rollback on failure', async () => {
|
||||
const { vault, cfg, keyManager } = await setupEnv();
|
||||
const initialCred = vault.generateEd25519Credential({
|
||||
id: 'cred-initial',
|
||||
name: 'Initial Key',
|
||||
comment: 'initial@hub',
|
||||
});
|
||||
const extraCred = vault.generateEd25519Credential({
|
||||
id: 'cred-extra',
|
||||
name: 'Extra Key',
|
||||
comment: 'extra@hub',
|
||||
});
|
||||
|
||||
let failVerificationOnce = true;
|
||||
const mock = new MockSshServer({
|
||||
username: 'ops',
|
||||
authorizedKeys: [initialCred.publicKey!],
|
||||
onExec: (cmd) => {
|
||||
if (cmd === 'echo gcoord-key-ok' && failVerificationOnce) {
|
||||
failVerificationOnce = false;
|
||||
return { stdout: '', stderr: 'simulated auth verify failure', exitCode: 1 };
|
||||
}
|
||||
return null;
|
||||
},
|
||||
});
|
||||
const port = await mock.start();
|
||||
cleanups.push(() => mock.close());
|
||||
|
||||
cfg.saveConfigText(
|
||||
'servers/rot-01.json',
|
||||
JSON.stringify({
|
||||
id: 'rot-01',
|
||||
name: 'Rot 01',
|
||||
host: '127.0.0.1',
|
||||
port,
|
||||
username: 'ops',
|
||||
credentialId: 'cred-initial',
|
||||
hostKeyFingerprint: mock.hostFingerprint,
|
||||
}),
|
||||
);
|
||||
|
||||
// 1. Deploy extra key and refuse active key revocation without force
|
||||
const dep = await keyManager.deployVaultKey('rot-01', 'cred-extra');
|
||||
expect(dep.deployed).toBe(true);
|
||||
await expect(
|
||||
keyManager.revokeAuthorizedKey('rot-01', initialCred.fingerprint!),
|
||||
).rejects.toThrow(/active/i);
|
||||
|
||||
const revExtra = await keyManager.revokeAuthorizedKey('rot-01', extraCred.fingerprint!);
|
||||
expect(revExtra.removedCount).toBe(1);
|
||||
|
||||
// 2. Rotation failure must roll back authorized_keys and preserve cred-initial
|
||||
const failedRot = await keyManager.rotateKeys({ serverIds: ['rot-01'] });
|
||||
expect(failedRot[0]).toMatchObject({
|
||||
serverId: 'rot-01',
|
||||
ok: false,
|
||||
rolledBack: true,
|
||||
});
|
||||
expect(cfg.getServer('rot-01')?.credentialId).toBe('cred-initial');
|
||||
expect(mock.authorizedKeys).toEqual([initialCred.publicKey!]);
|
||||
|
||||
// 3. Successful rotation switches server JSON and removes old public key
|
||||
const okRot = await keyManager.rotateKeys({ serverIds: ['rot-01'] });
|
||||
expect(okRot[0]?.ok).toBe(true);
|
||||
const newCredId = okRot[0]!.newCredentialId!;
|
||||
expect(cfg.getServer('rot-01')?.credentialId).toBe(newCredId);
|
||||
|
||||
const afterKeys = await keyManager.inspectAuthorizedKeys('rot-01');
|
||||
expect(afterKeys.entries).toHaveLength(1);
|
||||
expect(afterKeys.entries[0]?.matchedVaultCredentialId).toBe(newCredId);
|
||||
expect(afterKeys.entries[0]?.isCurrentServerKey).toBe(true);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue