test: add comprehensive v1.1 security, proxy/SFTP, automation/CLI & bundle tests

This commit is contained in:
tyuXX 2026-11-28 05:31:16 +00:00
parent f45d128c4f
commit a5a937850e
4 changed files with 1228 additions and 3 deletions

View file

@ -26,9 +26,29 @@ describe('Phase 5: 8 Theme Presets, Code-Splitting Budgets & Galaxy J7 Mobile Op
}
});
it('meets <50KB core gzipped bundle, splits lazy chunks, preserves PWA & mobile CSS, and caps DOM streams', () => {
it('meets <50KB core gzipped bundle (including static sync chunks), splits lazy chunks, preserves PWA & mobile CSS, and caps DOM streams', () => {
const publicDir = path.resolve('dist/public');
const coreFiles = ['index.html', 'themes.css', 'base.css', 'main.js'];
// Recursively follow static ESM imports from main.js to measure true eager core bundle
const visitedJs = new Set<string>(['main.js']);
const queue = ['main.js'];
while (queue.length > 0) {
const rel = queue.shift()!;
const abs = path.join(publicDir, rel);
if (!fs.existsSync(abs)) continue;
const code = fs.readFileSync(abs, 'utf8');
const importRe = /\bfrom\s*["']\.\/(chunks\/[^"']+\.js)["']|\bimport\s*["']\.\/(chunks\/[^"']+\.js)["']/g;
let m: RegExpExecArray | null;
while ((m = importRe.exec(code)) !== null) {
const target = m[1] ?? m[2]!;
if (!visitedJs.has(target)) {
visitedJs.add(target);
queue.push(target);
}
}
}
const coreFiles = ['index.html', 'themes.css', 'base.css', ...visitedJs];
let totalCoreGzip = 0;
for (const f of coreFiles) {
@ -37,13 +57,18 @@ describe('Phase 5: 8 Theme Presets, Code-Splitting Budgets & Galaxy J7 Mobile Op
}
expect(totalCoreGzip).toBeLessThan(50 * 1024);
// Heavy/optional UI stays code-split out of main.js
// Heavy/optional views & overlays stay code-split out of main.js
const mainJs = fs.readFileSync(path.join(publicDir, 'main.js'), 'utf8');
expect(mainJs).not.toContain('ai-drawer-dialog');
expect(mainJs).not.toContain('xterm-helper-textarea');
expect(mainJs).not.toContain('Fleet Monitor');
const chunks = fs.readdirSync(path.join(publicDir, 'chunks'));
expect(chunks.some((c) => c.startsWith('ai-drawer-') && c.endsWith('.js'))).toBe(true);
expect(chunks.some((c) => c.startsWith('command-palette-') && c.endsWith('.js'))).toBe(true);
expect(chunks.some((c) => c.startsWith('dashboard-view-') && c.endsWith('.js'))).toBe(true);
expect(chunks.some((c) => c.startsWith('settings-view-') && c.endsWith('.js'))).toBe(true);
expect(chunks.some((c) => c.startsWith('settings-ops-panel-') && c.endsWith('.js'))).toBe(true);
expect(chunks.some((c) => c.startsWith('terminal-view-') && c.endsWith('.js'))).toBe(true);
expect(chunks.some((c) => c.startsWith('workflows-view-') && c.endsWith('.js'))).toBe(true);
expect(chunks.some((c) => c.startsWith('alerts-view-') && c.endsWith('.js'))).toBe(true);

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

View file

@ -0,0 +1,388 @@
import fs from 'node:fs';
import http from 'node:http';
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 { redactSecrets } from '../src/server/ai/redactor.js';
import { createGCoordinatorServer } from '../src/server/app.js';
import { resolveRuntimeLimits } from '../src/server/config/runtime-limits.js';
import { openDatabase } from '../src/server/db/database.js';
import { AuditService } from '../src/server/security/audit.js';
import {
EgressBlockedError,
assertEgressUrlAllowed,
fetchWithEgressGuard,
} from '../src/server/security/egress-guard.js';
import { RateLimiter } from '../src/server/security/guards.js';
import { EmergencyRecoveryService } from '../src/server/security/recovery-store.js';
import { VaultService } from '../src/server/security/vault.js';
import { AlertChannelSchema } from '../src/shared/schemas/alerts.schema.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 Security Hardening Suite', () => {
it('enforces Zero-Trust Egress Guard, CIDR allowlist, and redirect blocking', async () => {
await expect(assertEgressUrlAllowed('http://127.0.0.1:8080/api')).rejects.toBeInstanceOf(
EgressBlockedError,
);
await expect(
assertEgressUrlAllowed('http://169.254.169.254/latest/meta-data/'),
).rejects.toBeInstanceOf(EgressBlockedError);
await expect(assertEgressUrlAllowed('http://10.0.0.5/hook')).rejects.toBeInstanceOf(
EgressBlockedError,
);
let internalRedirectFollowed = false;
const srv = http.createServer((req, res) => {
if (req.url === '/ok') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('hello-egress');
return;
}
if (req.url === '/redir') {
res.writeHead(302, { Location: `http://127.0.0.1:${port}/never-hit` });
res.end();
return;
}
if (req.url === '/never-hit') {
internalRedirectFollowed = true;
res.writeHead(200).end('leaked');
return;
}
res.writeHead(404).end();
});
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r()));
cleanups.push(() => new Promise<void>((r) => srv.close(() => r())));
const port = (srv.address() as { port: number }).port;
const okRes = await fetchWithEgressGuard(
`http://127.0.0.1:${port}/ok`,
{ method: 'GET' },
{ allowedCidrs: ['127.0.0.1/32'], timeoutMs: 3000 },
);
expect(okRes.status).toBe(200);
expect(await okRes.text()).toBe('hello-egress');
await expect(
fetchWithEgressGuard(
`http://127.0.0.1:${port}/redir`,
{ method: 'GET' },
{ allowedCidrs: ['127.0.0.1/32'], timeoutMs: 3000 },
),
).rejects.toThrow();
expect(internalRedirectFollowed).toBe(false);
});
it('persists SQLite RateLimiter lockouts across instances and removes legacy recovery passwords', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-rl-'));
cleanups.push(() => fs.rmSync(dir, { recursive: true, force: true }));
const dbPath = path.join(dir, 'gcoord.db');
const db1 = openDatabase(dbPath);
const rl1 = new RateLimiter({ db: db1 });
for (let i = 0; i < 6; i++) {
rl1.recordFailure('login', '198.51.100.77');
}
expect(rl1.check('login', '198.51.100.77').allowed).toBe(false);
db1.close();
const db2 = openDatabase(dbPath);
const rl2 = new RateLimiter({ db: db2 });
expect(rl2.check('login', '198.51.100.77').allowed).toBe(false);
db2.close();
// Passwordless emergency recovery + chmod 0600 Vault keyfile + seal()
const vault = new VaultService(path.join(dir, 'vault.enc'), {
keyFilePath: path.join(dir, 'vault.key'),
allowLocalKeyFile: true,
});
vault.initRuntime({ autoCreateIfMissing: true });
const keyMode = fs.statSync(path.join(dir, 'vault.key')).mode & 0o777;
expect(keyMode).toBe(0o600);
vault.unlockForModifications();
vault.upsertCredential({
id: 'wh-1',
name: 'Webhook Sec',
type: 'webhook-secret',
secret: 'super-secret-wh-value',
});
const recovery = new EmergencyRecoveryService(dir);
const bundle = recovery.syncState({
enabled: true,
vault,
username: 'admin',
passwordMetaList: [{ id: 'pw-1', label: 'Primary', createdAt: Date.now() }],
});
expect(bundle).not.toBeNull();
const recMode = fs.statSync(recovery.filePath).mode & 0o777;
expect(recMode).toBe(0o600);
const serialized = fs.readFileSync(recovery.filePath, 'utf8');
expect(serialized).not.toContain('passwordHash');
expect(serialized).not.toContain('plaintext');
let panicTriggered = false;
vault.onPanicLock(() => {
panicTriggered = true;
});
vault.seal();
expect(vault.sealState).toBe('sealed');
expect(vault.isRuntimeReady).toBe(false);
expect(panicTriggered).toBe(false);
const keyHex = fs.readFileSync(path.join(dir, 'vault.key'), 'utf8').trim();
vault.unlock(keyHex);
expect(vault.sealState).toBe('unlocked');
expect(vault.isRuntimeReady).toBe(true);
});
it('scales AI redactor linearly O(n) on huge malformed inputs and strips truncated PEM & Vault secrets', () => {
const bigPem = `-----BEGIN RSA PRIVATE KEY-----\n${'MIIEowIBAAKCAQEA'.repeat(8000)}\n`;
const sampleJson = `{"password":"my-db-pass-123","api_key":"sk-live-secret-999","token":"tok-abc"}`;
const payload = `${bigPem}\n${sampleJson}\nAuthorization: Bearer topsecretbearer\n`;
const started = Date.now();
const res = redactSecrets(payload, ['topsecretbearer', 'xy99']);
const elapsed = Date.now() - started;
expect(elapsed).toBeLessThan(1000);
expect(res.text).toContain('[REDACTED_PRIVATE_KEY]');
expect(res.text).not.toContain('my-db-pass-123');
expect(res.text).not.toContain('sk-live-secret-999');
expect(res.text).not.toContain('topsecretbearer');
expect(res.redactedCount).toBeGreaterThanOrEqual(3);
});
it('enforces idle timeout, real-time WS revocation, audit CSV formula neutralization, alert security events & throttle presets', async () => {
const low = resolveRuntimeLimits('low-resource');
const bal = resolveRuntimeLimits('balanced');
const unth = resolveRuntimeLimits('unthrottled');
expect(low.maxConcurrentMetricPolls).toBeLessThan(bal.maxConcurrentMetricPolls);
expect(unth.maxConcurrentMetricPolls).toBe(0); // 0 = unthrottled unlimited polls
expect(low.maxConcurrentWorkflows).toBeLessThan(bal.maxConcurrentWorkflows);
expect(bal.maxConcurrentWorkflows).toBeLessThan(unth.maxConcurrentWorkflows);
expect(low.argon2Concurrency).toBe(1);
// Non-webhook-secret creds are rejected by alerts test or config runtime check cleanly; schema parses valid channel
expect(() =>
AlertChannelSchema.parse({
id: 'ch1',
name: 'Ch',
type: 'generic',
url: 'https://hooks.example.com/1',
secretRef: 'wh-sec',
}),
).not.toThrow();
let receivedWebhook: Record<string, unknown> | null = null;
const whSrv = http.createServer((req, res) => {
const chunks: Buffer[] = [];
req.on('data', (c: Buffer) => chunks.push(c));
req.on('end', () => {
try {
receivedWebhook = JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record<string, unknown>;
} catch {
receivedWebhook = { raw: Buffer.concat(chunks).toString('utf8') };
}
res.writeHead(200).end('ok');
});
});
await new Promise<void>((r) => whSrv.listen(0, '127.0.0.1', () => r()));
cleanups.push(() => new Promise<void>((r) => whSrv.close(() => r())));
const whPort = (whSrv.address() as { port: number }).port;
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-sec-e2e-'));
const server = await createGCoordinatorServer({
dataDir,
port: 0,
host: '127.0.0.1',
publicDir: path.resolve('dist/public'),
watchConfig: false,
});
cleanups.push(async () => {
await server.close();
fs.rmSync(dataDir, { 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 } = {},
) => {
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);
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: 'v11-hardening-password!',
totpCode: totp.generate(),
securityPreset: 'relaxed',
},
});
expect(bootRes.status).toBe(201);
csrfToken = String(bootRes.data.csrfToken);
// Initialize Vault + allow localhost egress for webhook test
await api('/api/vault/init', { method: 'POST', body: {} });
await api('/api/vault/credentials', {
method: 'POST',
body: { id: 'tok-not-wh', name: 'API Token', type: 'api-token', token: 'bearer-xyz' },
});
await api('/api/vault/credentials', {
method: 'POST',
body: { id: 'wh-valid', name: 'Webhook', type: 'webhook-secret', secret: 'wh-tok-1' },
});
await api('/api/auth/security-policy', {
method: 'PUT',
body: { egressAllowedCidrs: ['127.0.0.1/32'], sessionIdleTimeoutMin: 60 },
});
// Reject referencing non-webhook-secret credential in channel test
await api('/api/alerts/config', {
method: 'PUT',
body: {
channels: [
{
id: 'bad-ch',
name: 'Bad Channel',
type: 'generic',
url: `http://127.0.0.1:${whPort}/hook`,
secretRef: 'tok-not-wh',
enabled: true,
},
{
id: 'good-ch',
name: 'Good Channel',
type: 'generic',
url: `http://127.0.0.1:${whPort}/hook`,
secretRef: 'wh-valid',
enabled: true,
},
],
rules: [
{
id: 'sec-lockout',
name: 'Auth Lockout Event',
kind: 'security-event',
events: ['auth.lockout'],
severity: 'critical',
forConsecutivePolls: 1,
cooldownSec: 0,
channelIds: ['good-ch'],
enabled: true,
},
],
},
});
const badTest = await api('/api/alerts/channels/bad-ch/test', { method: 'POST' });
expect(badTest.status === 400 || badTest.data.ok === false).toBe(true);
// Trigger security-event alert -> webhook receives notification
await server.alertEngine.emitSecurityEvent('auth.lockout', {
message: 'Repeated login failure from 203.0.113.9',
});
expect(receivedWebhook).not.toBeNull();
// Audit formula-injection neutralization + filtering + CSV/NDJSON export
server.auditService.log({
action: 'custom.formula',
actorIp: '127.0.0.1',
target: '=CMD|calc',
status: 'denied',
details: 'formula-needle',
});
const filteredAudit = await api('/api/audit?action=custom.formula&status=denied&q=formula-needle');
expect(filteredAudit.status).toBe(200);
expect(filteredAudit.data.total).toBe(1);
const csvRes = await api('/api/audit/export?format=csv&action=custom.formula', { raw: true });
expect(csvRes.status).toBe(200);
expect(csvRes.text).toContain('"\'=CMD|calc"');
const ndjsonRes = await api('/api/audit/export?format=ndjson&action=custom.formula', { raw: true });
expect(ndjsonRes.status).toBe(200);
const firstRow = JSON.parse(ndjsonRes.text.trim().split('\n')[0]!) as { action: string };
expect(firstRow.action).toBe('custom.formula');
// Real-time WS close with 4001 on logout/revocation
const wsCloseCode = await new Promise<number>((resolve, reject) => {
const ws = new WebSocket(`ws://127.0.0.1:${server.port}/ws`, {
headers: { Cookie: jar.header() },
});
ws.once('open', () => {
void api('/api/auth/logout', { method: 'POST' });
});
ws.once('close', (code) => resolve(code));
ws.once('error', reject);
});
expect(wsCloseCode).toBe(4001);
// Log back in and verify sliding sessionIdleTimeoutMin invalidates idle session
await new Promise((r) => setTimeout(r, 20));
const reLogin = await api('/api/auth/login', {
method: 'POST',
body: { username: 'admin', passwords: ['v11-hardening-password!'], codes: [] },
});
expect(reLogin.status).toBe(200);
server.db.prepare('UPDATE sessions SET last_seen_at = ?').run(Date.now() - 120 * 60_000);
const afterIdle = await api('/api/auth/status');
expect(afterIdle.status).toBe(200);
expect(afterIdle.data.authenticated).toBe(false);
});
});

View file

@ -0,0 +1,361 @@
import fs from 'node:fs';
import net from 'node:net';
import os from 'node:os';
import path from 'node:path';
import * as OTPAuth from 'otpauth';
import { afterEach, describe, expect, it } from 'vitest';
import { createGCoordinatorServer } from '../src/server/app.js';
import { formatRemoteCd } from '../src/server/ssh/pty-manager.js';
import { parseOpenSshConfig } from '../src/server/ssh/ssh-config-import.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('; ');
}
}
afterEach(async () => {
while (cleanups.length > 0) {
await cleanups.pop()!();
}
});
describe('v1.1 SSH Import, Multi-Algo known_hosts, PTY Security/.cast, SFTP v1.1 & Isolated Proxy / SOCKS5', () => {
it('parses & imports OpenSSH config, manages multi-algo known_hosts, enforces PTY/SFTP v1.1 ops, and validates proxy/SOCKS5/TTL', async () => {
const seenExecs: string[] = [];
const mock = new MockSshServer({
username: 'ops',
os: 'Linux',
allowTcpForward: true,
onExec: (cmd) => {
seenExecs.push(cmd);
if (cmd.startsWith('chown ')) {
return { stdout: '', exitCode: 0 };
}
if (cmd.startsWith('find ') && cmd.includes('needle')) {
return { stdout: '/sub/needle.conf\n', exitCode: 0 };
}
return null;
},
});
await mock.start();
cleanups.push(() => mock.close());
// Populate mock sftp root files
fs.writeFileSync(path.join(mock.sftpRootDir, 'alpha.log'), 'hello-alpha\n');
fs.mkdirSync(path.join(mock.sftpRootDir, 'sub'), { recursive: true });
fs.writeFileSync(path.join(mock.sftpRootDir, 'sub', 'needle.conf'), 'port=8080\n');
const outsideSecret = path.join(os.tmpdir(), `outside-secret-${Date.now()}.txt`);
fs.writeFileSync(outsideSecret, 'TOP_SECRET');
cleanups.push(() => fs.rmSync(outsideSecret, { force: true }));
fs.symlinkSync(outsideSecret, path.join(mock.sftpRootDir, 'escape-link'));
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-ssh-'));
// First start WITHOUT proxyPort to test strict PROXY_ORIGIN_ISOLATION_REQUIRED enforcement
const serverNoIso = await createGCoordinatorServer({
dataDir,
port: 0,
host: '127.0.0.1',
publicDir: path.resolve('dist/public'),
watchConfig: false,
});
const baseUrl = `http://127.0.0.1:${serverNoIso.port}`;
const jar = new CookieJar();
let csrfToken = '';
const api = async (
pathname: string,
opts: { method?: string; body?: unknown; raw?: 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;
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: '' };
};
try {
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: 'ssh-proxy-v11-password!',
totpCode: totp.generate(),
securityPreset: 'relaxed',
},
});
expect(bootRes.status).toBe(201);
csrfToken = String(bootRes.data.csrfToken);
await api('/api/vault/init', { method: 'POST', body: {} });
const genKey = await api('/api/vault/generate-ed25519', {
method: 'POST',
body: { id: 'ssh-main', name: 'Main Key' },
});
mock.authorizedKeys.push(
String((genKey.data.credential as { publicKey: string }).publicKey),
);
// OpenSSH parser + /api/servers/import-ssh-config preview & apply
const sshConfigText = [
'Host *',
' User ignored',
'Host bastion',
' HostName 127.0.0.1',
` Port ${mock.port}`,
' User ops',
'Host app-behind-bastion',
' HostName 127.0.0.1',
` Port ${mock.port}`,
' User ops',
' ProxyJump bastion',
].join('\n');
const parsed = parseOpenSshConfig(sshConfigText);
expect(parsed.entries.map((e) => e.alias)).toEqual(['bastion', 'app-behind-bastion']);
const prevRes = await api('/api/servers/import-ssh-config', {
method: 'POST',
body: { configText: sshConfigText, apply: false },
});
expect(prevRes.status).toBe(200);
expect((prevRes.data.createdIds as string[]).length).toBe(0);
const applyRes = await api('/api/servers/import-ssh-config', {
method: 'POST',
body: { configText: sshConfigText, defaultCredentialId: 'ssh-main', apply: true },
});
expect(applyRes.status).toBe(201);
expect(applyRes.data.createdIds).toEqual(['bastion', 'app-behind-bastion']);
// Reconnect + approve TOFU on bastion
await api('/api/servers/bastion/reconnect', { method: 'POST' });
const approve = await api('/api/servers/bastion/tofu/approve', {
method: 'POST',
body: { fingerprint: mock.hostFingerprint },
});
expect(approve.status).toBe(200);
// Multi-algorithm known_hosts CRUD
const curKnown = serverNoIso.knownHosts.listKnownHosts();
serverNoIso.knownHosts.replaceAllKnownHosts([
...curKnown,
{
hostPort: `127.0.0.1:${mock.port}`,
algorithm: 'ssh-rsa',
fingerprint: 'SHA256:fakeRsaFp',
},
]);
const khList = await api('/api/servers/known-hosts');
expect(khList.status).toBe(200);
const matching = (khList.data.knownHosts as Array<{ hostPort: string; algorithm: string }>).filter(
(x) => x.hostPort === `127.0.0.1:${mock.port}`,
);
expect(matching.length).toBeGreaterThanOrEqual(2);
const delRsa = await api(
`/api/servers/known-hosts?hostPort=${encodeURIComponent(`127.0.0.1:${mock.port}`)}&algorithm=ssh-rsa`,
{ method: 'DELETE' },
);
expect(delRsa.status).toBe(200);
// PTY cwd injection defense (control chars blocked 400 + single-quoted shell cwd) + .cast export + reconnect
expect(formatRemoteCd("/tmp'; rm -rf /")).toBe("cd -- '/tmp'\\''; rm -rf /'");
expect(formatRemoteCd('~/My Dir')).toBe('cd -- "$HOME/"\'My Dir\'');
const badCtrlPty = await api('/api/terminal/sessions', {
method: 'POST',
body: { serverId: 'bastion', cwd: '/tmp\nbad', cols: 80, rows: 24 },
});
expect(badCtrlPty.status).toBe(400);
const quotedCwdPty = await api('/api/terminal/sessions', {
method: 'POST',
body: { serverId: 'bastion', cwd: '/tmp; rm -rf /', cols: 80, rows: 24 },
});
expect(quotedCwdPty.status).toBe(201);
const qPtyId = String((quotedCwdPty.data.session as { sessionId: string }).sessionId);
await new Promise((r) => setTimeout(r, 80));
const qExport = await api(`/api/terminal/sessions/${qPtyId}/export?format=plain`, { raw: true });
expect(qExport.text).toContain("cd -- '/tmp; rm -rf /'");
await api(`/api/terminal/sessions/${qPtyId}`, { method: 'DELETE' });
const ptyRes = await api('/api/terminal/sessions', {
method: 'POST',
body: { serverId: 'bastion', cwd: '/tmp', cols: 80, rows: 24 },
});
expect(ptyRes.status).toBe(201);
const ptyId = String((ptyRes.data.session as { sessionId: string }).sessionId);
await new Promise((r) => setTimeout(r, 150));
const castRes = await api(`/api/terminal/sessions/${ptyId}/export?format=cast`, { raw: true });
expect(castRes.status).toBe(200);
const header = JSON.parse(castRes.text.trim().split('\n')[0]!) as { version: number; width: number };
expect(header.version).toBe(2);
expect(header.width).toBe(80);
const reconPty = await api(`/api/terminal/sessions/${ptyId}/reconnect`, {
method: 'POST',
body: {},
});
expect(reconPty.status).toBe(200);
expect((reconPty.data.session as { exited: boolean }).exited).toBe(false);
await api(`/api/terminal/sessions/${ptyId}`, { method: 'DELETE' });
// SFTP v1.1: touch, chown (sudo via MockSshServer), search, bulk-delete, symlink escape refusal
const touchRes = await api('/api/servers/bastion/sftp/touch', {
method: 'POST',
body: { path: '/touched.txt' },
});
expect(touchRes.status).toBe(201);
expect(fs.existsSync(path.join(mock.sftpRootDir, 'touched.txt'))).toBe(true);
const chownRes = await api('/api/servers/bastion/sftp/chown', {
method: 'POST',
body: { path: '/touched.txt', uid: 1000, gid: 1000, sudo: true },
});
expect(chownRes.status).toBe(200);
expect(seenExecs.some((c) => c.includes('chown 1000:1000'))).toBe(true);
const searchRes = await api('/api/servers/bastion/sftp/search?path=/&q=needle');
expect(searchRes.status).toBe(200);
expect(searchRes.data.matches).toContain('/sub/needle.conf');
expect(seenExecs.some((c) => c.startsWith("find '/' -maxdepth 5 -iname '*needle*'"))).toBe(
true,
);
const bulkDel = await api('/api/servers/bastion/sftp/bulk-delete', {
method: 'POST',
body: { paths: ['/touched.txt', '/alpha.log'], recursive: false },
});
expect(bulkDel.status).toBe(200);
expect((bulkDel.data.deleted as string[]).length).toBe(2);
// Symlink inspection + safe symlink deletion (lstat unlinks symlink without touching target dir)
const targetDir = path.join(mock.sftpRootDir, 'keep-dir');
fs.mkdirSync(targetDir, { recursive: true });
fs.writeFileSync(path.join(targetDir, 'precious.txt'), 'do-not-delete');
fs.symlinkSync(targetDir, path.join(mock.sftpRootDir, 'link-to-dir'));
const symStat = await api('/api/servers/bastion/sftp/stat?path=/escape-link');
expect(symStat.status).toBe(200);
expect((symStat.data.entry as { type: string }).type).toBe('symlink');
const delLink = await api(
'/api/servers/bastion/sftp/entry?path=/link-to-dir&recursive=1',
{ method: 'DELETE' },
);
expect(delLink.status).toBe(200);
expect(fs.existsSync(path.join(targetDir, 'precious.txt'))).toBe(true);
expect(fs.existsSync(path.join(mock.sftpRootDir, 'link-to-dir'))).toBe(false);
const nullPath = await api('/api/servers/bastion/sftp/text?path=/bad%00path');
expect(nullPath.status).toBeGreaterThanOrEqual(400);
// SOCKS5 tunnel without targetPort + TTL countdown metadata
const socksCreate = await api('/api/tunnels', {
method: 'POST',
body: {
serverId: 'bastion',
tunnel: {
id: 'socks-tun',
name: 'SOCKS5 Local',
mode: 'socks5',
targetHost: '127.0.0.1',
targetPort: 0,
ttlSec: 120,
autoStart: false,
},
start: true,
},
});
expect(socksCreate.status).toBe(201);
const tList = await api('/api/tunnels');
const socksItem = (tList.data.tunnels as Array<{
tunnel: { id: string; mode: string; ttlSec?: number };
active: boolean;
localBoundPort?: number;
expiresAt?: number;
}>).find((t) => t.tunnel.id === 'socks-tun');
expect(socksItem?.active).toBe(true);
expect(socksItem?.expiresAt).toBeGreaterThan(Date.now());
// SOCKS5 method negotiation (0x05 0x01 0x00 -> 0x05 0x00)
const socksReply = await new Promise<Buffer>((resolve, reject) => {
const sock = net.connect(socksItem!.localBoundPort!, '127.0.0.1', () => {
sock.write(Buffer.from([0x05, 0x01, 0x00]));
});
sock.once('data', (d) => {
sock.destroy();
resolve(d);
});
sock.once('error', reject);
});
expect(socksReply[0]).toBe(0x05);
expect(socksReply[1]).toBe(0x00);
// Without isolated proxyPort/subdomain & allowSameOriginProxy=false -> 403 PROXY_ORIGIN_ISOLATION_REQUIRED
const proxyCreate = await api('/api/tunnels', {
method: 'POST',
body: {
serverId: 'bastion',
tunnel: {
id: 'web-noiso',
name: 'NoIso Web',
mode: 'http-proxy',
targetHost: '127.0.0.1',
targetPort: 9999,
autoStart: false,
},
start: true,
},
});
expect(proxyCreate.status).toBe(201);
const noIsoTicket = await api('/api/tunnels/bastion/web-noiso/proxy-ticket', {
method: 'POST',
body: {},
});
expect(noIsoTicket.status).toBe(403);
expect(noIsoTicket.data.error).toBe('PROXY_ISOLATION_NOT_CONFIGURED');
} finally {
await serverNoIso.close();
fs.rmSync(dataDir, { recursive: true, force: true });
}
});
});