GCoordinator/tests/vault-runtime-and-collectors.test.ts

302 lines
10 KiB
TypeScript

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 { createGCoordinatorServer, type GCoordinatorInstance } 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('; ');
}
}
function createApiClient(server: GCoordinatorInstance) {
const baseUrl = `http://127.0.0.1:${server.port}`;
const jar = new CookieJar();
let csrfToken = '';
const call = async (
pathname: string,
opts: { method?: string; body?: unknown; csrf?: string | null } = {},
) => {
const headers: Record<string, string> = {};
if (jar.header()) headers.Cookie = jar.header();
if (opts.body !== undefined) headers['Content-Type'] = 'application/json';
const token = opts.csrf === undefined ? csrfToken : opts.csrf;
if (token) headers['X-CSRF-Token'] = token;
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>;
if (typeof data.csrfToken === 'string' && data.csrfToken) {
csrfToken = data.csrfToken;
}
return { status: res.status, data };
};
return {
call,
clearCsrf: () => {
csrfToken = '';
},
};
}
async function waitFor<T>(fn: () => T | undefined | null | false, timeoutMs = 4000): Promise<T> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const val = fn();
if (val) return val;
await new Promise((r) => setTimeout(r, 40));
}
throw new Error('Timed out waiting for condition');
}
afterEach(async () => {
while (cleanups.length > 0) {
await cleanups.pop()!();
}
});
describe('Always-on background collectors & write-only Vault lock', () => {
it('collects metrics before login across restarts while keeping Vault locked against modifications and reveals', async () => {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-runtime-vault-test-'));
cleanups.push(() => {
fs.rmSync(dataDir, { recursive: true, force: true });
});
let activeServer: GCoordinatorInstance | null = await createGCoordinatorServer({
dataDir,
port: 0,
host: '127.0.0.1',
publicDir: path.resolve('dist/public'),
watchConfig: false,
});
cleanups.push(async () => {
if (activeServer) {
await activeServer.close();
activeServer = null;
}
});
let api = createApiClient(activeServer);
const bootInfo = await api.call('/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 password = 'always-on-collectors-pw-1';
const bootRes = await api.call('/api/auth/bootstrap', {
method: 'POST',
body: {
username: 'admin',
password,
totpCode: totp.generate(),
secretBase32,
},
});
expect(bootRes.status).toBe(201);
const recoveryCodes = bootRes.data.recoveryCodes as string[];
expect(recoveryCodes.length).toBeGreaterThan(0);
// Explicitly initialize & add SSH key, register server, then lock Vault
expect((await api.call('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201);
const keyRes = await api.call('/api/vault/generate-ed25519', {
method: 'POST',
body: { id: 'srv-key', name: 'Server Key' },
});
expect(keyRes.status).toBe(201);
const pubKey = String((keyRes.data.credential as { publicKey: string }).publicKey);
const mock = new MockSshServer({
username: 'ops',
os: 'Linux',
authorizedKeys: [pubKey],
});
const sshPort = await mock.start();
cleanups.push(() => mock.close());
const reg = await api.call('/api/servers', {
method: 'POST',
body: {
id: 'srv-1',
name: 'Always-On Node',
host: '127.0.0.1',
port: sshPort,
username: 'ops',
credentialId: 'srv-key',
hostKeyFingerprint: mock.hostFingerprint,
pollIntervalSec: 5,
},
});
expect(reg.status).toBe(201);
const lockRes = await api.call('/api/vault/lock', { method: 'POST' });
expect(lockRes.status).toBe(200);
expect(lockRes.data.state).toBe('locked');
expect(lockRes.data.runtimeReady).toBe(true);
// Restart server cleanly
await activeServer.close();
activeServer = null;
activeServer = await createGCoordinatorServer({
dataDir,
port: 0,
host: '127.0.0.1',
publicDir: path.resolve('dist/public'),
watchConfig: false,
});
api = createApiClient(activeServer);
// Before ANY user logs in, status is unauthenticated + write-locked, 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);
const latestBeforeLogin = await waitFor(
() => activeServer!.monitoringService.getLatest('srv-1')?.sample,
);
expect(latestBeforeLogin.ts).toBeGreaterThan(0);
expect(mock.activeConnectionCount).toBeGreaterThanOrEqual(1);
// Log in without unlocking the Vault: dashboard metrics, inspect, SFTP, and metadata listing all work
const login = await api.call('/api/auth/login', {
method: 'POST',
body: {
username: 'admin',
password,
code: recoveryCodes[0]!,
},
csrf: null,
});
expect(login.status).toBe(200);
expect(login.data.vaultState).toBe('locked');
expect(login.data.vaultRuntimeReady).toBe(true);
const serversRes = await api.call('/api/servers');
expect(serversRes.status).toBe(200);
const srvEntry = (
serversRes.data.servers as Array<{
runtime: { status: string };
telemetry: { sample?: { ts: number }; disks: unknown[] } | null;
}>
)[0]!;
expect(srvEntry.runtime.status).toBe('connected');
expect(srvEntry.telemetry?.sample?.ts).toBeGreaterThan(0);
expect(srvEntry.telemetry?.disks.length).toBeGreaterThan(0);
const credsMeta = await api.call('/api/vault/credentials');
expect(credsMeta.status).toBe(200);
expect(credsMeta.data.state).toBe('locked');
expect(credsMeta.data.runtimeReady).toBe(true);
expect((credsMeta.data.credentials as Array<{ id: string }>).map((c) => c.id)).toContain(
'srv-key',
);
expect((await api.call('/api/servers/srv-1/inspect')).status).toBe(200);
expect((await api.call('/api/servers/srv-1/sftp/list?path=/')).status).toBe(200);
// Modifications and secret reveals must still be blocked with 423 VAULT_LOCKED while locked
const addBlocked = await api.call('/api/vault/credentials', {
method: 'POST',
body: { id: 'tok-1', name: 'Token', type: 'api-token', token: 'abc' },
});
expect(addBlocked.status).toBe(423);
expect(addBlocked.data.error).toBe('VAULT_LOCKED');
const genBlocked = await api.call('/api/vault/generate-ed25519', {
method: 'POST',
body: { id: 'k2', name: 'Key 2' },
});
expect(genBlocked.status).toBe(423);
expect(genBlocked.data.error).toBe('VAULT_LOCKED');
const delBlocked = await api.call('/api/vault/credentials/srv-key', {
method: 'DELETE',
});
expect(delBlocked.status).toBe(423);
expect(delBlocked.data.error).toBe('VAULT_LOCKED');
const revealBlocked = await api.call('/api/vault/credentials/srv-key/reveal');
expect(revealBlocked.status).toBe(423);
expect(revealBlocked.data.error).toBe('VAULT_LOCKED');
const rotateBlocked = await api.call('/api/servers/rotate-keys', {
method: 'POST',
body: { serverIds: ['srv-1'] },
});
expect(rotateBlocked.status).toBe(423);
expect(rotateBlocked.data.error).toBe('VAULT_LOCKED');
// Unlock for modifications using session unlock ({}, no raw 64-hex master key required)
const unlockSession = await api.call('/api/vault/unlock', {
method: 'POST',
body: {},
});
expect(unlockSession.status).toBe(200);
expect(unlockSession.data.state).toBe('unlocked');
expect(unlockSession.data.runtimeReady).toBe(true);
expect(
(
await api.call('/api/vault/credentials', {
method: 'POST',
body: { id: 'tok-1', name: 'Token', type: 'api-token', token: 'abc' },
})
).status,
).toBe(201);
expect((await api.call('/api/vault/credentials/srv-key/reveal')).status).toBe(200);
const rotOk = await api.call('/api/servers/rotate-keys', {
method: 'POST',
body: { serverIds: ['srv-1'] },
});
expect(rotOk.status).toBe(200);
expect((rotOk.data.results as Array<{ ok: boolean }>)[0]?.ok).toBe(true);
// Re-lock against modifications without disconnecting runtime SSH
const relock = await api.call('/api/vault/lock', { method: 'POST' });
expect(relock.status).toBe(200);
expect(relock.data.state).toBe('locked');
expect(relock.data.runtimeReady).toBe(true);
const serversAfterRelock = await api.call('/api/servers');
expect(
(serversAfterRelock.data.servers as Array<{ runtime: { status: string } }>)[0]?.runtime.status,
).toBe('connected');
});
});