368 lines
13 KiB
TypeScript
368 lines
13 KiB
TypeScript
import { execFileSync } from 'node:child_process';
|
|
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 3: CustomSystemsEngine (Presets, Overlays, TTL Cache, Actions & Debug Shell)', () => {
|
|
it('runs folder-scan + command discovery, multi-file activeFiles[], TTL caching + invalidation, oneshot/stream/interactive actions, and sudo systems', async () => {
|
|
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p3-systems-'));
|
|
const mockHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p3-home-'));
|
|
const webappDir = path.join(mockHome, 'My Stacks', 'webapp');
|
|
fs.mkdirSync(webappDir, { recursive: true });
|
|
fs.writeFileSync(path.join(webappDir, 'compose.yml'), 'services:\n web:\n image: nginx\n');
|
|
fs.writeFileSync(
|
|
path.join(webappDir, 'compose.prod.yml'),
|
|
'services:\n worker:\n image: alpine\n',
|
|
);
|
|
fs.writeFileSync(path.join(webappDir, '.env'), 'PORT=8080\n');
|
|
|
|
let workerHealthy = false;
|
|
let composeStatusCalls = 0;
|
|
const seenComposeFlags: string[] = [];
|
|
|
|
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 });
|
|
fs.rmSync(mockHome, { 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> };
|
|
};
|
|
|
|
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 boot = await api('/api/auth/bootstrap', {
|
|
method: 'POST',
|
|
body: {
|
|
username: 'admin',
|
|
password: 'phase3-systems-password',
|
|
totpCode: totp.generate(),
|
|
secretBase32,
|
|
initialSafeMode: false,
|
|
},
|
|
});
|
|
csrfToken = String(boot.data.csrfToken);
|
|
|
|
await api('/api/vault/init', { method: 'POST', body: {} });
|
|
const keyRes = await api('/api/vault/generate-ed25519', {
|
|
method: 'POST',
|
|
body: { id: 'sys-key', name: 'Sys Key' },
|
|
});
|
|
const pubKey = String((keyRes.data.credential as { publicKey: string }).publicKey);
|
|
|
|
await api('/api/vault/credentials', {
|
|
method: 'POST',
|
|
body: {
|
|
id: 'sys-sudo',
|
|
name: 'Sys Sudo',
|
|
type: 'sudo-password',
|
|
password: 'sudo-secret-pw',
|
|
},
|
|
});
|
|
|
|
const mock = new MockSshServer({
|
|
username: 'ops',
|
|
os: 'Linux',
|
|
sudoPassword: 'sudo-secret-pw',
|
|
authorizedKeys: [pubKey],
|
|
onExec: (cmd) => {
|
|
// Real POSIX /bin/sh execution of generated folder-scan discovery script against mockHome
|
|
if (cmd.includes('printf \'D\\t%s\\n\' "$d"') || cmd.includes("printf 'D\\t%s\\n'")) {
|
|
const out = execFileSync('/bin/sh', ['-c', cmd], {
|
|
env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: mockHome },
|
|
encoding: 'utf8',
|
|
});
|
|
return { stdout: out, exitCode: 0 };
|
|
}
|
|
|
|
// Compose status check
|
|
if (cmd.includes('ps --all --format json')) {
|
|
composeStatusCalls += 1;
|
|
const m = /GCOORD_COMPOSE_FILES='([^']*)'/.exec(cmd);
|
|
if (m?.[1]) seenComposeFlags.push(m[1]);
|
|
const rows = [
|
|
JSON.stringify({ Service: 'web', State: 'running' }),
|
|
JSON.stringify({ Service: 'worker', State: workerHealthy ? 'running' : 'exited' }),
|
|
];
|
|
return { stdout: `${rows.join('\n')}\n`, exitCode: 0 };
|
|
}
|
|
|
|
// Compose oneshot up
|
|
if (cmd.includes(' up -d') && !cmd.includes('pull')) {
|
|
workerHealthy = true;
|
|
return { stdout: 'Container webapp-worker Started\n', exitCode: 0 };
|
|
}
|
|
|
|
// Compose streamed logs
|
|
if (cmd.includes(' logs -f')) {
|
|
return {
|
|
stdout: '2026-11-26 webapp log line 1\n2026-11-26 webapp log line 2\n',
|
|
exitCode: 0,
|
|
};
|
|
}
|
|
|
|
// Compose interactive debug-shell
|
|
if (cmd.includes(' exec "$GCOORD_SUBITEM"')) {
|
|
return { stdout: 'root@webapp-web:/app# \n', exitCode: 0 };
|
|
}
|
|
|
|
// systemd discovery & status & sudo action
|
|
if (cmd.includes('systemctl list-units')) {
|
|
expect(cmd).toContain("GCOORD_PARAM_UNITFILTER='nginx'");
|
|
return { stdout: 'nginx.service\n', exitCode: 0 };
|
|
}
|
|
if (cmd.includes('systemctl show')) {
|
|
return {
|
|
stdout: JSON.stringify({
|
|
Id: 'nginx.service',
|
|
LoadState: 'loaded',
|
|
ActiveState: 'active',
|
|
SubState: 'running',
|
|
}),
|
|
exitCode: 0,
|
|
};
|
|
}
|
|
if (cmd.includes('systemctl restart')) {
|
|
return { stdout: 'restarted nginx.service\n', exitCode: 0 };
|
|
}
|
|
|
|
return null;
|
|
},
|
|
});
|
|
const sshPort = await mock.start();
|
|
cleanups.push(() => mock.close());
|
|
|
|
await api('/api/servers', {
|
|
method: 'POST',
|
|
body: {
|
|
id: 'app1',
|
|
name: 'App 1',
|
|
host: '127.0.0.1',
|
|
port: sshPort,
|
|
username: 'ops',
|
|
credentialId: 'sys-key',
|
|
sudoCredentialId: 'sys-sudo',
|
|
pollIntervalSec: 300,
|
|
},
|
|
});
|
|
await api('/api/servers/app1/reconnect', { method: 'POST' });
|
|
await api('/api/servers/app1/tofu/approve', {
|
|
method: 'POST',
|
|
body: { fingerprint: mock.hostFingerprint },
|
|
});
|
|
|
|
// Attach docker-compose with space in rootDir path + systemd with filter
|
|
expect(
|
|
(
|
|
await api('/api/systems/docker-compose/servers/app1/attach', {
|
|
method: 'PUT',
|
|
body: { params: { rootDirs: ['~/My Stacks'] } },
|
|
})
|
|
).status,
|
|
).toBe(200);
|
|
expect(
|
|
(
|
|
await api('/api/systems/systemd/servers/app1/attach', {
|
|
method: 'PUT',
|
|
body: { params: { unitFilter: 'nginx' } },
|
|
})
|
|
).status,
|
|
).toBe(200);
|
|
|
|
// 1. Discover compose stacks across space-containing dir + verify TTL caching
|
|
const sys1 = await api('/api/systems/docker-compose');
|
|
expect(sys1.status).toBe(200);
|
|
const snap1 = (
|
|
sys1.data.snapshots as Array<{
|
|
cached: boolean;
|
|
systemHealth: string;
|
|
items: Array<{
|
|
name: string;
|
|
dir: string;
|
|
activeFiles: string[];
|
|
selectableFiles: string[];
|
|
editableFiles: string[];
|
|
status: { health: string; subItems: Array<{ name: string; health: string }> };
|
|
}>;
|
|
}>
|
|
)[0]!;
|
|
expect(snap1.cached).toBe(false);
|
|
expect(snap1.systemHealth).toBe('down');
|
|
expect(snap1.items).toHaveLength(1);
|
|
const item = snap1.items[0]!;
|
|
expect(item.name).toBe('webapp');
|
|
expect(item.dir).toBe(webappDir);
|
|
expect(item.selectableFiles).toContain('compose.prod.yml');
|
|
expect(item.editableFiles.some((p) => p.endsWith('/.env'))).toBe(true);
|
|
expect(item.status.subItems).toHaveLength(2);
|
|
const callsAfterFirst = composeStatusCalls;
|
|
|
|
// 2nd fetch within TTL hits cache
|
|
const sysCached = await api('/api/systems/docker-compose');
|
|
expect((sysCached.data.snapshots as Array<{ cached: boolean }>)[0]!.cached).toBe(true);
|
|
expect(composeStatusCalls).toBe(callsAfterFirst);
|
|
|
|
// 2. Update multi-file activeFiles[] overlay -> invalidates cache and passes both -f flags
|
|
const overlayRes = await api(
|
|
'/api/systems/docker-compose/servers/app1/items/webapp/files',
|
|
{
|
|
method: 'PUT',
|
|
body: { activeFiles: ['compose.yml', 'compose.prod.yml'] },
|
|
},
|
|
);
|
|
expect(overlayRes.status).toBe(200);
|
|
|
|
const sysAfterOverlay = await api('/api/systems/docker-compose');
|
|
const snapOverlay = (sysAfterOverlay.data.snapshots as Array<typeof snap1>)[0]!;
|
|
expect(snapOverlay.cached).toBe(false);
|
|
expect(snapOverlay.items[0]!.activeFiles).toEqual(['compose.yml', 'compose.prod.yml']);
|
|
expect(seenComposeFlags.at(-1)).toBe('-f compose.yml -f compose.prod.yml');
|
|
|
|
// 3. Oneshot action 'up' invalidates cache and transitions system health to 'ok'
|
|
const upAct = await api('/api/systems/docker-compose/servers/app1/actions/up', {
|
|
method: 'POST',
|
|
body: { itemName: 'webapp' },
|
|
});
|
|
expect(upAct.status).toBe(200);
|
|
expect(upAct.data.mode).toBe('oneshot');
|
|
|
|
const sysHealthy = await api('/api/systems/docker-compose');
|
|
expect((sysHealthy.data.snapshots as Array<typeof snap1>)[0]!.systemHealth).toBe('ok');
|
|
|
|
// 4. Stream action 'logs' emits WS stream:<jobId> chunks + exit meta
|
|
const { ws, frames } = await openWs(wsUrl, {
|
|
Cookie: jar.header(),
|
|
Host: `127.0.0.1:${server.port}`,
|
|
Origin: baseUrl,
|
|
});
|
|
const streamRes = await api('/api/systems/docker-compose/servers/app1/actions/logs', {
|
|
method: 'POST',
|
|
body: { itemName: 'webapp' },
|
|
});
|
|
expect(streamRes.status).toBe(200);
|
|
expect(streamRes.data.mode).toBe('stream');
|
|
const jobId = String(streamRes.data.jobId);
|
|
|
|
ws.send(JSON.stringify({ type: 'sub', channels: [`stream:${jobId}`] }));
|
|
await new Promise((r) => setTimeout(r, 120));
|
|
const logChunks = frames
|
|
.filter((f) => f.type === 'stream:chunk' && f.jobId === jobId && f.stream === 'stdout')
|
|
.map((f) => String(f.data))
|
|
.join('');
|
|
expect(logChunks).toContain('webapp log line 1');
|
|
|
|
// 5. Interactive subitem action 'debug-shell' opens a PTY session in PTYManager
|
|
const dbgRes = await api(
|
|
'/api/systems/docker-compose/servers/app1/actions/debug-shell',
|
|
{
|
|
method: 'POST',
|
|
body: { itemName: 'webapp', subItemName: 'web', cols: 88, rows: 24 },
|
|
},
|
|
);
|
|
expect(dbgRes.status).toBe(200);
|
|
expect(dbgRes.data.mode).toBe('interactive');
|
|
const dbgSess = dbgRes.data.session as { sessionId: string; serverId: string };
|
|
expect(dbgSess.serverId).toBe('app1');
|
|
expect(
|
|
server.ptyManager.listSessions().some((s) => s.sessionId === dbgSess.sessionId),
|
|
).toBe(true);
|
|
|
|
// 6. systemd preset with command discovery + sudo action
|
|
const systemdRes = await api('/api/systems/systemd');
|
|
expect(systemdRes.status).toBe(200);
|
|
const sdSnap = (systemdRes.data.snapshots as Array<typeof snap1>)[0]!;
|
|
expect(sdSnap.items[0]!.name).toBe('nginx.service');
|
|
expect(sdSnap.items[0]!.status.health).toBe('ok');
|
|
|
|
const sdRestart = await api('/api/systems/systemd/servers/app1/actions/restart', {
|
|
method: 'POST',
|
|
body: { itemName: 'nginx.service' },
|
|
});
|
|
expect(sdRestart.status).toBe(200);
|
|
expect(mock.lastSudoStdin).toBe('sudo-secret-pw');
|
|
|
|
ws.close();
|
|
});
|
|
});
|