test(phase-2): add ssh2.Server test harness and end-to-end SSH, ProxyJump, key rotation, and monitoring tests

This commit is contained in:
tyuXX 2026-11-26 18:57:07 +00:00
parent 75b969f044
commit 4ac7b5d1b4
5 changed files with 1026 additions and 0 deletions

View 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);
});
});