test: add comprehensive v1.1 security, proxy/SFTP, automation/CLI & bundle tests
This commit is contained in:
parent
f45d128c4f
commit
a5a937850e
4 changed files with 1228 additions and 3 deletions
451
tests/v11-automation-monitoring-cli.test.ts
Normal file
451
tests/v11-automation-monitoring-cli.test.ts
Normal file
|
|
@ -0,0 +1,451 @@
|
|||
import { execFile } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { createGCoordinatorServer } from '../src/server/app.js';
|
||||
import { interpolateShellCommandSafe } from '../src/server/automation/template.js';
|
||||
import { MockSshServer } from './helpers/mock-ssh-server.js';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const CLI_PATH = path.resolve('dist/cli/gcoord.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('; ');
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
while (cleanups.length > 0) {
|
||||
await cleanups.pop()!();
|
||||
}
|
||||
});
|
||||
|
||||
describe('v1.1 Monitoring, Prometheus /metrics, Systems, Workflows, Broadcast History & CLI Tools', () => {
|
||||
it('covers template Go preservation, Prometheus /metrics, rollup/probe history, systems inputs/cancel, http/notify workflows, broadcast export, and CLI tools', async () => {
|
||||
// 1. Go template preservation vs safe shell quoting
|
||||
const goCmd = interpolateShellCommandSafe(
|
||||
"docker ps --format '{{.Names}}' --filter name={{inputs.filter}}",
|
||||
{ inputs: { filter: "web'; rm -rf /; #" } },
|
||||
);
|
||||
expect(goCmd).toContain('{{.Names}}');
|
||||
expect(goCmd).toContain("'web'\\''; rm -rf /; #'");
|
||||
|
||||
let httpStepHit: Record<string, unknown> | null = null;
|
||||
const targetHttp = http.createServer((req, res) => {
|
||||
if (req.url === '/probe') {
|
||||
res.writeHead(200, { 'Content-Type': 'text/plain' });
|
||||
res.end('probe-healthy-ok');
|
||||
return;
|
||||
}
|
||||
if (req.url === '/wf-hook' && req.method === 'POST') {
|
||||
const chunks: Buffer[] = [];
|
||||
req.on('data', (c: Buffer) => chunks.push(c));
|
||||
req.on('end', () => {
|
||||
httpStepHit = {
|
||||
auth: req.headers.authorization,
|
||||
body: Buffer.concat(chunks).toString('utf8'),
|
||||
};
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify({ accepted: true }));
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.writeHead(404).end();
|
||||
});
|
||||
await new Promise<void>((r) => targetHttp.listen(0, '127.0.0.1', () => r()));
|
||||
cleanups.push(() => new Promise<void>((r) => targetHttp.close(() => r())));
|
||||
const httpPort = (targetHttp.address() as { port: number }).port;
|
||||
|
||||
let lastActionCmd = '';
|
||||
const mock = new MockSshServer({
|
||||
username: 'ops',
|
||||
os: 'Linux',
|
||||
onExec: (cmd) => {
|
||||
lastActionCmd = cmd;
|
||||
if (cmd.includes('SYSTEMD_DISCOVER')) {
|
||||
return { stdout: 'demo.service\n', exitCode: 0 };
|
||||
}
|
||||
if (cmd.includes('SYSTEMD_SHOW')) {
|
||||
return {
|
||||
stdout: JSON.stringify({
|
||||
Id: 'demo.service',
|
||||
ActiveState: 'active',
|
||||
SubState: 'running',
|
||||
FragmentPath: '/etc/systemd/system/demo.service',
|
||||
DropInPaths: '/etc/systemd/system/demo.service.d/override.conf',
|
||||
}),
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
if (cmd.includes('echo-secret-action')) {
|
||||
return { stdout: 'action-ok\n', exitCode: 0 };
|
||||
}
|
||||
return null;
|
||||
},
|
||||
});
|
||||
await mock.start();
|
||||
cleanups.push(() => mock.close());
|
||||
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-auto-'));
|
||||
const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-cli-work-'));
|
||||
const server = await createGCoordinatorServer({
|
||||
dataDir,
|
||||
port: 0,
|
||||
host: '127.0.0.1',
|
||||
publicDir: path.resolve('dist/public'),
|
||||
watchConfig: false,
|
||||
});
|
||||
let closedServer = false;
|
||||
cleanups.push(async () => {
|
||||
if (!closedServer) await server.close();
|
||||
fs.rmSync(dataDir, { recursive: true, force: true });
|
||||
fs.rmSync(workDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const baseUrl = `http://127.0.0.1:${server.port}`;
|
||||
const jar = new CookieJar();
|
||||
let csrfToken = '';
|
||||
const api = async (
|
||||
pathname: string,
|
||||
opts: { method?: string; body?: unknown; raw?: boolean; safeMode?: boolean } = {},
|
||||
) => {
|
||||
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;
|
||||
if (opts.safeMode) 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);
|
||||
if (opts.raw) {
|
||||
return { status: res.status, text: await res.text(), data: {} as Record<string, unknown> };
|
||||
}
|
||||
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
return { status: res.status, data, text: '' };
|
||||
};
|
||||
|
||||
const bootInfo = await api('/api/auth/bootstrap');
|
||||
const totp = new OTPAuth.TOTP({
|
||||
issuer: 'GCoordinator',
|
||||
label: 'admin',
|
||||
algorithm: 'SHA1',
|
||||
digits: 6,
|
||||
period: 30,
|
||||
secret: OTPAuth.Secret.fromBase32(String(bootInfo.data.secretBase32)),
|
||||
});
|
||||
const bootRes = await api('/api/auth/bootstrap', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
username: 'admin',
|
||||
password: 'automation-v11-password!',
|
||||
totpCode: totp.generate(),
|
||||
securityPreset: 'relaxed',
|
||||
},
|
||||
});
|
||||
csrfToken = String(bootRes.data.csrfToken);
|
||||
|
||||
await api('/api/vault/init', { method: 'POST', body: {} });
|
||||
const kp = await api('/api/vault/generate-ed25519', {
|
||||
method: 'POST',
|
||||
body: { id: 'main-key', name: 'Main Key' },
|
||||
});
|
||||
mock.authorizedKeys.push(String((kp.data.credential as { publicKey: string }).publicKey));
|
||||
await api('/api/vault/credentials', {
|
||||
method: 'POST',
|
||||
body: { id: 'wf-api-tok', name: 'WF API', type: 'api-token', token: 'Bearer wf-tok-secret' },
|
||||
});
|
||||
|
||||
await api('/api/auth/security-policy', {
|
||||
method: 'PUT',
|
||||
body: { egressAllowedCidrs: ['127.0.0.1/32'] },
|
||||
});
|
||||
|
||||
// Prometheus /metrics disabled initially -> 404; rotate-token enables & secures it
|
||||
expect((await fetch(`${baseUrl}/metrics`)).status).toBe(404);
|
||||
const promRot = await api('/api/config/prometheus-token', {
|
||||
method: 'POST',
|
||||
body: { enable: true },
|
||||
});
|
||||
expect(promRot.status).toBe(200);
|
||||
const promToken = String(promRot.data.token);
|
||||
expect(promToken.length).toBeGreaterThan(20);
|
||||
expect((await fetch(`${baseUrl}/metrics`)).status).toBe(401);
|
||||
const promOk = await fetch(`${baseUrl}/metrics`, {
|
||||
headers: { Authorization: `Bearer ${promToken}` },
|
||||
});
|
||||
expect(promOk.status).toBe(200);
|
||||
const promText = await promOk.text();
|
||||
expect(promText).toContain('gcoordinator_tunnels_active');
|
||||
expect(promText).toContain('gcoordinator_process_resident_memory_bytes');
|
||||
|
||||
// Register server with hub HTTP probe
|
||||
await api('/api/servers', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'srv-1',
|
||||
name: 'Server 1',
|
||||
host: '127.0.0.1',
|
||||
port: mock.port,
|
||||
username: 'ops',
|
||||
credentialId: 'main-key',
|
||||
pollIntervalSec: 120,
|
||||
probes: [
|
||||
{
|
||||
id: 'web-hp',
|
||||
type: 'http',
|
||||
url: `http://127.0.0.1:${httpPort}/probe`,
|
||||
from: 'hub',
|
||||
expectedStatus: 200,
|
||||
bodyIncludes: 'probe-healthy-ok',
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
await api('/api/servers/srv-1/reconnect', { method: 'POST' });
|
||||
await api('/api/servers/srv-1/tofu/approve', {
|
||||
method: 'POST',
|
||||
body: { fingerprint: mock.hostFingerprint },
|
||||
});
|
||||
|
||||
// On-demand probe run + probe history query
|
||||
const runProbe = await api('/api/servers/srv-1/probes/web-hp/run', { method: 'POST', body: {} });
|
||||
expect(runProbe.status).toBe(200);
|
||||
expect((runProbe.data.sample as { ok: boolean }).ok).toBe(true);
|
||||
const probeHist = await api('/api/servers/srv-1/probes/history?range=1h');
|
||||
expect(probeHist.status).toBe(200);
|
||||
expect((probeHist.data.samples as unknown[]).length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// Rollup partial-bucket upsert check: seed older bucket raw rows across two flushes
|
||||
const oldBucketTs = Math.floor((Date.now() - 2 * 3600_000) / 3600_000) * 3600_000;
|
||||
server.db
|
||||
.prepare(
|
||||
`INSERT INTO metrics_raw (ts, server_id, cpu_pct, mem_used_mb, mem_total_mb, net_rx_bps, net_tx_bps, load_1m, uptime_sec)
|
||||
VALUES (?, 'srv-1', 20, 500, 1000, 1000, 2000, 0.5, 100)`,
|
||||
)
|
||||
.run(oldBucketTs + 10_000);
|
||||
server.db
|
||||
.prepare(
|
||||
`INSERT INTO metrics_disks (ts, server_id, mount_point, fs_type, used_mb, total_mb, used_pct)
|
||||
VALUES (?, 'srv-1', '/', 'ext4', 4000, 10000, 40)`,
|
||||
)
|
||||
.run(oldBucketTs + 10_000);
|
||||
server.monitoringService.runMaintenance();
|
||||
|
||||
server.db
|
||||
.prepare(
|
||||
`INSERT INTO metrics_raw (ts, server_id, cpu_pct, mem_used_mb, mem_total_mb, net_rx_bps, net_tx_bps, load_1m, uptime_sec)
|
||||
VALUES (?, 'srv-1', 80, 700, 1000, 3000, 4000, 1.5, 200)`,
|
||||
)
|
||||
.run(oldBucketTs + 20_000);
|
||||
server.monitoringService.runMaintenance();
|
||||
|
||||
const rollupRow = server.db
|
||||
.prepare(
|
||||
`SELECT cpu_min, cpu_max, net_rx_avg_bps, disk_max_pct FROM metrics_rollup
|
||||
WHERE server_id = 'srv-1' AND granularity = '1h' AND bucket_ts = ?`,
|
||||
)
|
||||
.get(oldBucketTs) as {
|
||||
cpu_min: number;
|
||||
cpu_max: number;
|
||||
net_rx_avg_bps: number;
|
||||
disk_max_pct: number;
|
||||
};
|
||||
expect(rollupRow.cpu_min).toBe(20);
|
||||
expect(rollupRow.cpu_max).toBe(80);
|
||||
expect(rollupRow.disk_max_pct).toBe(40);
|
||||
expect(rollupRow.net_rx_avg_bps).toBe(2000);
|
||||
|
||||
// Custom System with systemd editableFiles + action inputs[] secret redaction + Safe-Mode stream cancel
|
||||
await api('/api/config/file', {
|
||||
method: 'PUT',
|
||||
body: {
|
||||
path: 'systems/sys-v11.json',
|
||||
content: JSON.stringify({
|
||||
id: 'sys-v11',
|
||||
name: 'System v1.1 Test',
|
||||
cacheTtlSec: 30,
|
||||
params: [],
|
||||
discovery: { type: 'command', command: 'echo SYSTEMD_DISCOVER', parser: 'lines' },
|
||||
status: { command: 'echo SYSTEMD_SHOW', parser: 'json' },
|
||||
actions: [
|
||||
{
|
||||
id: 'secret-act',
|
||||
label: 'Secret Action',
|
||||
scope: 'item',
|
||||
mode: 'oneshot',
|
||||
inputs: [{ name: 'apiSecret', type: 'secret', required: true }],
|
||||
command: 'echo echo-secret-action "$GCOORD_INPUT_APISECRET"',
|
||||
},
|
||||
],
|
||||
editableFiles: [],
|
||||
}),
|
||||
},
|
||||
});
|
||||
await api('/api/systems/sys-v11/servers/srv-1/attach', { method: 'PUT', body: { params: {} } });
|
||||
const sysSnap = await api('/api/systems/sys-v11?refresh=1&serverId=srv-1');
|
||||
const items = (sysSnap.data.snapshots as Array<{ items: Array<{ editableFiles: string[] }> }>)[0]!.items;
|
||||
expect(items[0]!.editableFiles).toContain('/etc/systemd/system/demo.service');
|
||||
expect(items[0]!.editableFiles).toContain('/etc/systemd/system/demo.service.d/override.conf');
|
||||
|
||||
const actRun = await api('/api/systems/sys-v11/servers/srv-1/actions/secret-act', {
|
||||
method: 'POST',
|
||||
body: { itemName: 'demo.service', inputs: { apiSecret: 'super-secret-input-val' } },
|
||||
});
|
||||
expect(actRun.status).toBe(200);
|
||||
expect(lastActionCmd).toContain('echo-secret-action');
|
||||
const sysAudit = await api('/api/audit?action=system.action&limit=5');
|
||||
expect(JSON.stringify(sysAudit.data.items)).not.toContain('super-secret-input-val');
|
||||
|
||||
// Safe Mode stream cancel exemption works even cleanly
|
||||
const safeCancel = await api('/api/systems/streams/nonexistent-job/cancel', {
|
||||
method: 'POST',
|
||||
safeMode: true,
|
||||
});
|
||||
expect(safeCancel.status).toBe(200);
|
||||
|
||||
// Workflow with http step + secret input masking + lazy step logs
|
||||
await api('/api/workflows', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'wf-v11-http',
|
||||
name: 'Workflow v1.1',
|
||||
enabled: true,
|
||||
trigger: { type: 'manual' },
|
||||
overlapPolicy: 'skip',
|
||||
display: { mode: 'log' },
|
||||
inputs: [{ name: 'secretTok', type: 'secret', required: true }],
|
||||
steps: [
|
||||
{
|
||||
id: 'exec-mask',
|
||||
type: 'exec',
|
||||
target: { serverId: 'srv-1' },
|
||||
command: 'echo got={{inputs.secretTok}}',
|
||||
},
|
||||
{
|
||||
id: 'call-http',
|
||||
type: 'http',
|
||||
dependsOn: ['exec-mask'],
|
||||
url: `http://127.0.0.1:${httpPort}/wf-hook`,
|
||||
method: 'POST',
|
||||
secretRef: 'wf-api-tok',
|
||||
body: '{"event":"done"}',
|
||||
expectedStatus: 200,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const wfRun = await api('/api/workflows/wf-v11-http/run', {
|
||||
method: 'POST',
|
||||
body: { inputs: { secretTok: 'MY-TOP-SECRET-VALUE-77' } },
|
||||
});
|
||||
expect(wfRun.status).toBe(202);
|
||||
const runId = String(wfRun.data.runId);
|
||||
|
||||
for (let i = 0; i < 30; i++) {
|
||||
const st = await api(`/api/workflows/runs/${runId}`);
|
||||
if ((st.data.run as { status: string }).status !== 'running' && (st.data.run as { status: string }).status !== 'queued') {
|
||||
expect((st.data.run as { status: string }).status).toBe('succeeded');
|
||||
break;
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 80));
|
||||
}
|
||||
expect(httpStepHit).not.toBeNull();
|
||||
const stepLogRes = await api(`/api/workflows/runs/${runId}/steps/exec-mask/logs`);
|
||||
expect(stepLogRes.status).toBe(200);
|
||||
expect(JSON.stringify(stepLogRes.data)).not.toContain('MY-TOP-SECRET-VALUE-77');
|
||||
|
||||
// Broadcast history + JSON/CSV export
|
||||
const bcastRes = await api('/api/workflows/broadcast', {
|
||||
method: 'POST',
|
||||
body: { command: 'echo broadcast-v11', target: { serverIds: ['srv-1'] } },
|
||||
});
|
||||
expect(bcastRes.status).toBe(202);
|
||||
const jobId = String((bcastRes.data.job as { jobId: string }).jobId);
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const pollB = await api(`/api/workflows/broadcast/${jobId}`);
|
||||
if ((pollB.data.job as { done: boolean }).done) break;
|
||||
await new Promise((r) => setTimeout(r, 60));
|
||||
}
|
||||
const histRes = await api('/api/workflows/broadcast/history?limit=10');
|
||||
expect(histRes.status).toBe(200);
|
||||
expect((histRes.data.jobs as Array<{ jobId: string }>).some((j) => j.jobId === jobId)).toBe(true);
|
||||
const bCsv = await api(`/api/workflows/broadcast/${jobId}/export?format=csv`, { raw: true });
|
||||
expect(bCsv.status).toBe(200);
|
||||
expect(bCsv.text).toContain('srv-1');
|
||||
|
||||
// Scheduled Backup runNow
|
||||
const schedRun = await api('/api/backup/schedule/run', { method: 'POST', body: {} });
|
||||
expect(schedRun.status).toBe(200);
|
||||
expect(schedRun.data.ok).toBe(true);
|
||||
|
||||
// Close server before offline CLI tests
|
||||
await server.close();
|
||||
closedServer = true;
|
||||
|
||||
const statusOut = await execFileAsync(process.execPath, [
|
||||
CLI_PATH,
|
||||
'status',
|
||||
'--data-dir',
|
||||
dataDir,
|
||||
'--json',
|
||||
]);
|
||||
const stJson = JSON.parse(statusOut.stdout) as { bootstrapped: boolean; auditLogRows: number };
|
||||
expect(stJson.bootstrapped).toBe(true);
|
||||
expect(stJson.auditLogRows).toBeGreaterThan(0);
|
||||
|
||||
const newPwFile = path.join(workDir, 'newpw.txt');
|
||||
fs.writeFileSync(newPwFile, 'offline-reset-password-2026!', { mode: 0o600 });
|
||||
const resetPwOut = await execFileAsync(process.execPath, [
|
||||
CLI_PATH,
|
||||
'reset-password',
|
||||
'--data-dir',
|
||||
dataDir,
|
||||
'--password-file',
|
||||
newPwFile,
|
||||
]);
|
||||
expect(resetPwOut.stdout).toContain('reset cleanly');
|
||||
|
||||
const reset2faOut = await execFileAsync(process.execPath, [
|
||||
CLI_PATH,
|
||||
'reset-2fa',
|
||||
'--data-dir',
|
||||
dataDir,
|
||||
'--json',
|
||||
]);
|
||||
expect((JSON.parse(reset2faOut.stdout) as { reset: boolean }).reset).toBe(true);
|
||||
|
||||
const panicOut = await execFileAsync(process.execPath, [
|
||||
CLI_PATH,
|
||||
'panic-lock',
|
||||
'--data-dir',
|
||||
dataDir,
|
||||
]);
|
||||
expect(panicOut.stdout).toContain('Panic Lock engaged cleanly');
|
||||
expect(fs.existsSync(path.join(dataDir, 'vault.enc.panic-locked'))).toBe(true);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue