diff --git a/tests/alerts-engine.test.ts b/tests/alerts-engine.test.ts new file mode 100644 index 0000000..59d0fd8 --- /dev/null +++ b/tests/alerts-engine.test.ts @@ -0,0 +1,664 @@ +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 { createGCoordinatorServer } from '../src/server/app.js'; +import { MockSshServer } from './helpers/mock-ssh-server.js'; + +const cleanups: Array<() => Promise | void> = []; + +class CookieJar { + private cookies = new Map(); + 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) { + return new Promise<{ ws: WebSocket; frames: Array> }>((resolve, reject) => { + const frames: Array> = []; + 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); + }); +} + +async function waitFor( + fn: () => T | undefined | null | false, + timeoutMs = 5000, + intervalMs = 30, +): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const val = fn(); + if (val) return val; + await new Promise((r) => setTimeout(r, intervalMs)); + } + throw new Error('Timed out waiting for condition'); +} + +interface RecordedWebhook { + url: string; + method: string; + headers: http.IncomingHttpHeaders; + body: string; +} + +afterEach(async () => { + while (cleanups.length > 0) { + await cleanups.pop()!(); + } +}); + +describe('Phase 4: AlertEngine, Webhooks, Silences & Maintenance Windows', () => { + it( + 'evaluates all 5 rule kinds with hysteresis/cooldown/recovery, dispatches all 4 webhook formats while Vault is write-locked, triggers remediation & event workflows, and honours silences & cron maintenance windows', + { timeout: 25_000 }, + async () => { + const webhooks: RecordedWebhook[] = []; + const webhookServer = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on('data', (c: Buffer) => chunks.push(c)); + req.on('end', () => { + webhooks.push({ + url: req.url ?? '/', + method: req.method ?? 'POST', + headers: req.headers, + body: Buffer.concat(chunks).toString('utf8'), + }); + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end('{"ok":true}'); + }); + }); + await new Promise((resolve) => webhookServer.listen(0, '127.0.0.1', resolve)); + const whAddr = webhookServer.address() as { port: number }; + const whBase = `http://127.0.0.1:${whAddr.port}`; + cleanups.push( + () => new Promise((resolve) => webhookServer.close(() => resolve())), + ); + + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p4-alerts-')); + 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 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 = {}; + 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(() => ({}))) as Record; + return { status: res.status, data }; + }; + + 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: 'phase4-alert-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: 'alert-key', name: 'Alert Key' }, + }); + const pubKey = String((keyRes.data.credential as { publicKey: string }).publicKey); + + for (const [id, secret] of [ + ['wh-discord', 'discord-bearer-secret'], + ['wh-tg', '123456:telegram-bot-token'], + ['wh-ntfy', 'ntfy-secret-token'], + ['wh-generic', 'generic-hmac-bearer'], + ] as const) { + await api('/api/vault/credentials', { + method: 'POST', + body: { id, name: id, type: 'webhook-secret', secret }, + }); + } + + const mock = new MockSshServer({ + username: 'ops', + os: 'Linux', + authorizedKeys: [pubKey], + onExec: (cmd) => { + if (cmd.includes('REMEDIATE:')) { + return { stdout: 'remediated-ok\n', exitCode: 0 }; + } + return { stdout: 'event-ok\n', exitCode: 0 }; + }, + }); + const sshPort = await mock.start(); + cleanups.push(() => mock.close()); + + await api('/api/servers', { + method: 'POST', + body: { + id: 'srv-1', + name: 'Prod 1', + host: '127.0.0.1', + port: sshPort, + username: 'ops', + credentialId: 'alert-key', + tags: ['prod'], + pollIntervalSec: 3600, + }, + }); + await api('/api/servers/srv-1/reconnect', { method: 'POST' }); + const approveRes = await api('/api/servers/srv-1/tofu/approve', { + method: 'POST', + body: { fingerprint: mock.hostFingerprint }, + }); + expect(approveRes.status).toBe(200); + await waitFor(() => server.sshPool.getState('srv-1')?.status === 'connected'); + + // Remediation + Event workflows + for (const wf of [ + { + id: 'wf-remediate', + name: 'Auto Remediate', + enabled: true, + trigger: { type: 'manual' }, + overlapPolicy: 'skip', + display: { mode: 'log' }, + inputs: [{ name: 'serverId', type: 'string', required: false }], + steps: [ + { + id: 'rem', + type: 'exec', + target: { serverId: 'srv-1' }, + command: 'echo REMEDIATE: {{inputs.serverId}}', + }, + ], + }, + { + id: 'wf-on-alert', + name: 'On Alert Fired', + enabled: true, + trigger: { type: 'event', event: 'alert.fired' }, + overlapPolicy: 'queue', + display: { mode: 'log' }, + inputs: [], + steps: [ + { + id: 'evt', + type: 'exec', + target: { serverId: 'srv-1' }, + command: 'echo ALERT_EVT {{event.ruleId}}', + }, + ], + }, + { + id: 'wf-on-probe', + name: 'On Probe Failed', + enabled: true, + trigger: { type: 'event', event: 'probe.failed' }, + overlapPolicy: 'skip', + display: { mode: 'log' }, + inputs: [], + steps: [ + { + id: 'evt', + type: 'exec', + target: { serverId: 'srv-1' }, + command: 'echo PROBE_EVT {{event.probeId}}', + }, + ], + }, + { + id: 'wf-on-sys', + name: 'On System Unhealthy', + enabled: true, + trigger: { type: 'event', event: 'system.unhealthy' }, + overlapPolicy: 'skip', + display: { mode: 'log' }, + inputs: [], + steps: [ + { + id: 'evt', + type: 'exec', + target: { serverId: 'srv-1' }, + command: 'echo SYS_EVT {{event.systemId}}', + }, + ], + }, + ]) { + expect((await api('/api/workflows', { method: 'POST', body: wf })).status).toBe(201); + } + + // Configure 4 channels + 5 rule kinds + scheduled maintenance window + const alertsCfgRes = await api('/api/alerts/config', { + method: 'PUT', + body: { + channels: [ + { + id: 'ch-discord', + name: 'Discord Ops', + type: 'discord', + url: `${whBase}/discord`, + secretRef: 'wh-discord', + enabled: true, + }, + { + id: 'ch-tg', + name: 'Telegram Ops', + type: 'telegram', + url: `${whBase}/tg`, + secretRef: 'wh-tg', + chatId: '-1009988', + enabled: true, + }, + { + id: 'ch-ntfy', + name: 'Ntfy Ops', + type: 'ntfy', + url: `${whBase}/ntfy`, + secretRef: 'wh-ntfy', + topic: 'ops-alerts', + enabled: true, + }, + { + id: 'ch-generic', + name: 'Generic Ops', + type: 'generic', + url: `${whBase}/generic`, + secretRef: 'wh-generic', + enabled: true, + }, + ], + rules: [ + { + id: 'rule-cpu', + name: 'High CPU', + kind: 'metric', + metric: 'cpuPct', + operator: 'gt', + threshold: 80, + severity: 'critical', + target: { tags: ['prod'] }, + forConsecutivePolls: 2, + cooldownSec: 300, + channelIds: ['ch-discord', 'ch-generic'], + remediationWorkflowId: 'wf-remediate', + enabled: true, + }, + { + id: 'rule-disk', + name: 'Root Disk High', + kind: 'disk', + mountPoint: '/', + thresholdPct: 90, + severity: 'warn', + target: { serverId: 'srv-1' }, + forConsecutivePolls: 1, + cooldownSec: 60, + channelIds: ['ch-ntfy'], + enabled: true, + }, + { + id: 'rule-offline', + name: 'Server Offline', + kind: 'offline', + offlineSec: 10, + severity: 'critical', + target: { all: true }, + forConsecutivePolls: 1, + cooldownSec: 60, + channelIds: ['ch-tg'], + enabled: true, + }, + { + id: 'rule-probe', + name: 'Probe Failed', + kind: 'probe', + probeId: 'http-root', + severity: 'warn', + target: { all: true }, + forConsecutivePolls: 1, + cooldownSec: 60, + channelIds: ['ch-generic'], + enabled: true, + }, + { + id: 'rule-sys', + name: 'Nginx Unhealthy', + kind: 'system', + systemId: 'systemd', + item: 'nginx.service', + severity: 'critical', + target: { serverId: 'srv-1' }, + forConsecutivePolls: 1, + cooldownSec: 60, + channelIds: ['ch-discord'], + enabled: true, + }, + ], + maintenanceWindows: [ + { + id: 'mw-nightly', + name: 'Nightly Maint', + cron: `0 ${(new Date().getUTCHours() + 3) % 24} * * *`, + timezone: 'UTC', + durationMinutes: 60, + target: { tags: ['prod'] }, + enabled: true, + }, + ], + }, + }); + expect(alertsCfgRes.status).toBe(200); + + // Lock Vault for modifications -> write-only lock must still allow webhook tests using established secrets + const lockRes = await api('/api/vault/lock', { method: 'POST' }); + expect(lockRes.data.state).toBe('locked'); + expect(lockRes.data.runtimeReady).toBe(true); + + // --- 1. Send Test Alert for all 4 channel types while Vault is write-locked --- + for (const chId of ['ch-discord', 'ch-tg', 'ch-ntfy', 'ch-generic']) { + const tRes = await api(`/api/alerts/channels/${chId}/test`, { method: 'POST' }); + expect(tRes.status).toBe(200); + expect(tRes.data.ok).toBe(true); + expect(tRes.data.statusCode).toBe(200); + } + expect(webhooks).toHaveLength(4); + const byUrl = new Map(webhooks.map((w) => [w.url, w])); + expect(JSON.parse(byUrl.get('/discord')!.body).content).toContain('[TEST]'); + expect(byUrl.get('/discord')!.headers.authorization).toBe('Bearer discord-bearer-secret'); + expect(byUrl.get('/tg/sendMessage')!.headers['x-telegram-bot-token']).toBe( + '123456:telegram-bot-token', + ); + expect(JSON.parse(byUrl.get('/tg/sendMessage')!.body).chat_id).toBe('-1009988'); + expect(byUrl.get('/ntfy/ops-alerts')!.headers.authorization).toBe('Bearer ntfy-secret-token'); + expect(byUrl.get('/ntfy/ops-alerts')!.headers.title).toContain('[TEST]'); + expect(byUrl.get('/generic')!.headers.authorization).toBe('Bearer generic-hmac-bearer'); + + webhooks.length = 0; + + // Subscribe WS to alerts channel + const { ws, frames } = await openWs(wsUrl, { + Cookie: jar.header(), + Host: `127.0.0.1:${server.port}`, + Origin: baseUrl, + }); + cleanups.push(() => ws.close()); + ws.send(JSON.stringify({ type: 'sub', channels: ['alerts'] })); + await new Promise((r) => setTimeout(r, 40)); + + const makeTick = (cpuPct: number, diskUsedPct: number, ts: number) => ({ + serverId: 'srv-1', + sample: { + ts, + cpuPct, + memUsedMb: 1000, + memTotalMb: 16000, + netRxBps: 100, + netTxBps: 50, + load1m: 0.5, + uptimeSec: 1000, + }, + disks: [ + { + mountPoint: '/', + fsType: 'ext4', + usedMb: diskUsedPct * 100, + totalMb: 10000, + usedPct: diskUsedPct, + }, + ], + probes: [], + }); + + // Use monotonic timestamps outside maintenance window + const t0 = Date.now(); + const mwHour = (new Date(t0).getUTCHours() + 3) % 24; + + // --- 2. Metric hysteresis (forConsecutivePolls: 2), remediation + alert.fired, recovery & cooldown --- + await server.alertEngine.evaluateTick(makeTick(95, 40, t0), t0); + expect((await api('/api/alerts')).data.activeCount).toBe(0); + expect(webhooks).toHaveLength(0); + + await server.alertEngine.evaluateTick(makeTick(95, 40, t0 + 5000), t0 + 5000); + expect((await api('/api/alerts')).data.activeCount).toBe(1); + expect(webhooks.map((w) => w.url).sort()).toEqual(['/discord', '/generic']); + await waitFor(() => + frames.some((f) => f.type === 'alerts:update' && f.activeCount === 1), + ); + await waitFor(() => server.workflowEngine.listRuns('wf-remediate')[0]?.status === 'succeeded'); + await waitFor(() => server.workflowEngine.listRuns('wf-on-alert')[0]?.status === 'succeeded'); + + webhooks.length = 0; + + // Healthy poll resolves metric incident and sends recovery notice + await server.alertEngine.evaluateTick(makeTick(20, 40, t0 + 10_000), t0 + 10_000); + expect((await api('/api/alerts')).data.activeCount).toBe(0); + expect(webhooks.map((w) => w.url).sort()).toEqual(['/discord', '/generic']); + expect(JSON.parse(webhooks.find((w) => w.url === '/discord')!.body).content).toContain( + 'RESOLVED', + ); + + webhooks.length = 0; + + // Re-breach inside cooldownSec (300s): incident fires with webhookStatus='cooldown', zero webhook spam + await server.alertEngine.evaluateTick(makeTick(95, 40, t0 + 15_000), t0 + 15_000); + await server.alertEngine.evaluateTick(makeTick(95, 40, t0 + 20_000), t0 + 20_000); + const cooldownSummary = await api('/api/alerts?limit=10'); + expect(cooldownSummary.data.activeCount).toBe(1); + expect( + (cooldownSummary.data.activeEvents as Array<{ ruleId: string; webhookStatus: string }>)[0] + ?.webhookStatus, + ).toBe('cooldown'); + expect(webhooks).toHaveLength(0); + // Resolve metric incident cleanly + await server.alertEngine.evaluateTick(makeTick(20, 40, t0 + 25_000), t0 + 25_000); + webhooks.length = 0; + + // --- 3. Disk, Probe, System, and Offline rule kinds --- + await server.alertEngine.evaluateTick(makeTick(20, 95, t0 + 30_000), t0 + 30_000); + expect(webhooks.some((w) => w.url === '/ntfy/ops-alerts')).toBe(true); + await server.alertEngine.evaluateTick(makeTick(20, 40, t0 + 35_000), t0 + 35_000); + webhooks.length = 0; + + await server.alertEngine.evaluateProbe( + 'srv-1', + { probeId: 'http-root', ok: false, statusCode: 502, latencyMs: 120, error: 'Bad Gateway' }, + t0 + 40_000, + ); + expect(webhooks.some((w) => w.url === '/generic')).toBe(true); + await waitFor(() => server.workflowEngine.listRuns('wf-on-probe')[0]?.status === 'succeeded'); + await server.alertEngine.evaluateProbe( + 'srv-1', + { probeId: 'http-root', ok: true, statusCode: 200, latencyMs: 12 }, + t0 + 45_000, + ); + webhooks.length = 0; + + await server.alertEngine.evaluateSystemSnapshot( + { + serverId: 'srv-1', + systemId: 'systemd', + params: {}, + fetchedAt: t0 + 50_000, + cached: false, + systemHealth: 'down', + items: [ + { + name: 'nginx.service', + dir: '', + activeFiles: [], + selectableFiles: [], + editableFiles: [], + status: { health: 'down', rawSummary: 'failed', exitCode: 1, subItems: [] }, + }, + ], + }, + t0 + 50_000, + ); + expect(webhooks.some((w) => w.url === '/discord')).toBe(true); + await waitFor(() => server.workflowEngine.listRuns('wf-on-sys')[0]?.status === 'succeeded'); + await server.alertEngine.evaluateSystemSnapshot( + { + serverId: 'srv-1', + systemId: 'systemd', + params: {}, + fetchedAt: t0 + 55_000, + cached: false, + systemHealth: 'ok', + items: [ + { + name: 'nginx.service', + dir: '', + activeFiles: [], + selectableFiles: [], + editableFiles: [], + status: { health: 'ok', rawSummary: 'active', exitCode: 0, subItems: [] }, + }, + ], + }, + t0 + 55_000, + ); + webhooks.length = 0; + + // Offline rule check via sshPool closeServer + sweepOfflineRules + server.sshPool.closeServer('srv-1'); + const tOffline = Date.now(); + await server.alertEngine.sweepOfflineRules(tOffline + 100); + expect(webhooks).toHaveLength(0); + await server.alertEngine.sweepOfflineRules(tOffline + 15_000); + expect(webhooks.some((w) => w.url === '/tg/sendMessage')).toBe(true); + await api('/api/servers/srv-1/reconnect', { method: 'POST' }); + await waitFor(() => server.sshPool.getState('srv-1')?.status === 'connected'); + await server.alertEngine.sweepOfflineRules(Date.now() + 20_000); + webhooks.length = 0; + + // --- 4. Alert Silences + Cron Maintenance Windows (verified strictly monotonically in future UTC) --- + const silRes = await api('/api/alerts/silences', { + method: 'POST', + body: { + scopeType: 'rule', + targetId: 'rule-disk', + durationMinutes: 2880, + reason: 'Disk rebalance', + }, + }); + expect(silRes.status).toBe(201); + const silenceId = String((silRes.data.silence as { id: string }).id); + + const d1 = new Date(Date.now() + 86_400_000); + const dayPlusOneSafe = Date.UTC( + d1.getUTCFullYear(), + d1.getUTCMonth(), + d1.getUTCDate(), + (mwHour + 6) % 24, + 0, + 0, + ); + await server.alertEngine.evaluateTick(makeTick(20, 95, dayPlusOneSafe), dayPlusOneSafe); + const silencedSummary = await api('/api/alerts?limit=5'); + expect( + (silencedSummary.data.activeEvents as Array<{ ruleId: string; webhookStatus: string }>).find( + (e) => e.ruleId === 'rule-disk', + )?.webhookStatus, + ).toBe('suppressed'); + expect(webhooks).toHaveLength(0); + + await server.alertEngine.evaluateTick( + makeTick(20, 40, dayPlusOneSafe + 5000), + dayPlusOneSafe + 5000, + ); + expect((await api(`/api/alerts/silences/${silenceId}`, { method: 'DELETE' })).status).toBe( + 200, + ); + webhooks.length = 0; + + // Scheduled cron maintenance window (0 * * * UTC for 60 minutes) + const d2 = new Date(Date.now() + 2 * 86_400_000); + const insideWindowMs = Date.UTC( + d2.getUTCFullYear(), + d2.getUTCMonth(), + d2.getUTCDate(), + mwHour, + 30, + 0, + ); + const outsideWindowMs = insideWindowMs + 3_600_000; + expect(server.alertEngine.getActiveMaintenanceWindowIds(insideWindowMs)).toContain( + 'mw-nightly', + ); + expect(server.alertEngine.getActiveMaintenanceWindowIds(outsideWindowMs)).toEqual([]); + + await server.alertEngine.evaluateTick(makeTick(20, 95, insideWindowMs), insideWindowMs); + const mwSummary = await api('/api/alerts?limit=5'); + expect( + (mwSummary.data.activeEvents as Array<{ ruleId: string; webhookStatus: string }>).find( + (e) => e.ruleId === 'rule-disk', + )?.webhookStatus, + ).toBe('suppressed'); + expect(webhooks).toHaveLength(0); + + await server.alertEngine.evaluateTick( + makeTick(20, 40, insideWindowMs + 1000), + insideWindowMs + 1000, + ); + webhooks.length = 0; + + await server.alertEngine.evaluateTick(makeTick(20, 95, outsideWindowMs), outsideWindowMs); + expect(webhooks.some((w) => w.url === '/ntfy/ops-alerts')).toBe(true); + }, + ); +}); diff --git a/tests/helpers/mock-ssh-server.ts b/tests/helpers/mock-ssh-server.ts index 4507984..67a03df 100644 --- a/tests/helpers/mock-ssh-server.ts +++ b/tests/helpers/mock-ssh-server.ts @@ -4,7 +4,10 @@ import net from 'node:net'; import os from 'node:os'; import path from 'node:path'; import ssh2, { type Attributes, type Connection, type Server } from 'ssh2'; -import { computeOpenSshFingerprint } from '../../src/server/security/vault.js'; +import { + computeOpenSshFingerprint, + generateValidEd25519KeyPair, +} from '../../src/server/security/vault.js'; export interface MockSshOptions { username: string; @@ -77,9 +80,9 @@ export class MockSshServer { this.sftpRootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mock-ssh-sftp-')); this.ownsSftpRoot = true; } - const kp = ssh2.utils.generateKeyPairSync('ed25519', { comment: 'mock-host' }); - this.hostPrivateKey = kp.private; - this.hostFingerprint = computeOpenSshFingerprint(kp.public.trim()); + const kp = generateValidEd25519KeyPair({ comment: 'mock-host' }); + this.hostPrivateKey = kp.privateKey; + this.hostFingerprint = kp.fingerprint; } private resolveVirtualPath(vPath: string): { normPosix: string; absPath: string } { @@ -129,9 +132,9 @@ export class MockSshServer { async swapHostKey(): Promise { const prevPort = this.port; await this.close(); - const kp = ssh2.utils.generateKeyPairSync('ed25519', { comment: 'mitm-host' }); - this.hostPrivateKey = kp.private; - this.hostFingerprint = computeOpenSshFingerprint(kp.public.trim()); + const kp = generateValidEd25519KeyPair({ comment: 'mitm-host' }); + this.hostPrivateKey = kp.privateKey; + this.hostFingerprint = kp.fingerprint; await this.start(prevPort); return this.hostFingerprint; } diff --git a/tests/workflows-and-transfer.test.ts b/tests/workflows-and-transfer.test.ts new file mode 100644 index 0000000..41ee12e --- /dev/null +++ b/tests/workflows-and-transfer.test.ts @@ -0,0 +1,790 @@ +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { PassThrough } from 'node:stream'; +import * as OTPAuth from 'otpauth'; +import type { ClientChannel } from 'ssh2'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import WebSocket from 'ws'; +import { createGCoordinatorServer, type GCoordinatorInstance } from '../src/server/app.js'; +import { MockSshServer } from './helpers/mock-ssh-server.js'; + +const cleanups: Array<() => Promise | void> = []; + +class CookieJar { + private cookies = new Map(); + 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) { + return new Promise<{ ws: WebSocket; frames: Array> }>((resolve, reject) => { + const frames: Array> = []; + 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); + }); +} + +async function waitFor( + fn: () => Promise | T | undefined | null | false, + timeoutMs = 5000, + intervalMs = 30, +): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const val = await fn(); + if (val) return val; + await new Promise((r) => setTimeout(r, intervalMs)); + } + throw new Error('Timed out waiting for condition'); +} + +async function waitForWorkflowRun(server: GCoordinatorInstance, runId: string, timeoutMs = 4000) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const detail = server.workflowEngine.getRunDetail(runId); + if (detail && detail.run.status !== 'running' && detail.run.status !== 'queued') { + return detail; + } + await new Promise((r) => setTimeout(r, 30)); + } + const latest = server.workflowEngine.getRunDetail(runId); + const streamFrames = server.workflowEngine.getStreamReplayFrames(`wf:${runId}`); + throw new Error( + `Workflow run ${runId} timed out: run=${JSON.stringify(latest?.run)} steps=${JSON.stringify(latest?.stepLogs)} frames=${JSON.stringify(streamFrames.slice(-10))}`, + ); +} + +afterEach(async () => { + while (cleanups.length > 0) { + await cleanups.pop()!(); + } +}); + +describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers', () => { + it( + 'supports Snippets CRUD, Safe Mode blocks, Ad-Hoc Fleet Broadcast with safe shell quoting, WS streaming & cancel, Full DAG + steps + transfers, Overlap policies, Timeouts, and Cron', + { timeout: 25_000 }, + async () => { + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p4-wf-')); + const sftpRootA = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p4-sftpa-')); + const sftpRootB = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p4-sftpb-')); + + fs.mkdirSync(path.join(sftpRootA, 'logs'), { recursive: true }); + fs.writeFileSync(path.join(sftpRootA, 'logs', 'app.log'), 'l1\nl2\nl3\nl4\n'); + fs.writeFileSync(path.join(sftpRootA, 'single.txt'), 'single-file-payload\n'); + fs.mkdirSync(path.join(sftpRootA, 'bundle', 'nested'), { recursive: true }); + fs.writeFileSync(path.join(sftpRootA, 'bundle', 'top.txt'), 'top-content'); + fs.writeFileSync(path.join(sftpRootA, 'bundle', 'nested', 'deep.txt'), 'deep-content'); + + const seenExecA: string[] = []; + const seenExecB: string[] = []; + const directRsyncCmds: 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(sftpRootA, { recursive: true, force: true }); + fs.rmSync(sftpRootB, { 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; safeMode?: boolean } = {}, + ) => { + const headers: Record = {}; + 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); + const data = (await res.json().catch(() => ({}))) as Record; + return { status: res.status, data }; + }; + + 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: 'phase4-workflow-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: 'wf-key', name: 'Workflow Key' }, + }); + const pubKey = String((keyRes.data.credential as { publicKey: string }).publicKey); + await api('/api/vault/credentials', { + method: 'POST', + body: { + id: 'wf-sudo', + name: 'WF Sudo', + type: 'sudo-password', + password: 'sudo-wf-pw', + }, + }); + + const makeMockExec = + (serverTag: 'A' | 'B', sink: string[]) => (cmd: string) => { + sink.push(cmd); + if (cmd.includes('REAL_SH_QUOTE_TEST')) { + const out = execFileSync('/bin/sh', ['-c', cmd], { encoding: 'utf8' }); + return { stdout: out, exitCode: 0 }; + } + if (cmd.includes('systemctl list-units')) { + 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 on ${serverTag}\n`, exitCode: 0 }; + } + if (cmd.includes('rsync -az ')) { + directRsyncCmds.push(cmd); + return { stdout: 'sent 128 bytes\n', exitCode: 0 }; + } + if (cmd.includes('FAIL_NOW')) { + return { stdout: '', stderr: 'intentional step failure', exitCode: 42 }; + } + if (cmd.includes('PRINT_CAP')) { + const out = execFileSync('/bin/sh', ['-c', cmd], { encoding: 'utf8' }); + return { stdout: out, exitCode: 0 }; + } + if (cmd.includes('CRON_TICK')) { + return { stdout: `cron-ok-${serverTag}\n`, exitCode: 0 }; + } + if (cmd.includes('ECHO_STEP')) { + const out = execFileSync('/bin/sh', ['-c', cmd], { encoding: 'utf8' }); + return { stdout: out, exitCode: 0 }; + } + return { stdout: `ok:${serverTag}\n`, exitCode: 0 }; + }; + + const mockA = new MockSshServer({ + username: 'ops', + os: 'Linux', + sudoPassword: 'sudo-wf-pw', + authorizedKeys: [pubKey], + sftpRootDir: sftpRootA, + onExec: makeMockExec('A', seenExecA), + }); + const mockB = new MockSshServer({ + username: 'ops', + os: 'Linux', + sudoPassword: 'sudo-wf-pw', + authorizedKeys: [pubKey], + sftpRootDir: sftpRootB, + onExec: makeMockExec('B', seenExecB), + }); + + const portA = await mockA.start(); + const portB = await mockB.start(); + cleanups.push(async () => { + await mockA.close(); + await mockB.close(); + }); + + await api('/api/servers', { + method: 'POST', + body: { + id: 'srv-a', + name: 'Server A', + host: '127.0.0.1', + port: portA, + username: 'ops', + credentialId: 'wf-key', + sudoCredentialId: 'wf-sudo', + tags: ['web'], + pollIntervalSec: 3600, + }, + }); + await api('/api/servers', { + method: 'POST', + body: { + id: 'srv-b', + name: 'Server B', + host: '127.0.0.1', + port: portB, + username: 'ops', + credentialId: 'wf-key', + sudoCredentialId: 'wf-sudo', + tags: ['backup'], + pollIntervalSec: 3600, + }, + }); + await api('/api/servers/srv-a/reconnect', { method: 'POST' }); + await api('/api/servers/srv-b/reconnect', { method: 'POST' }); + expect( + ( + await api('/api/servers/srv-a/tofu/approve', { + method: 'POST', + body: { fingerprint: mockA.hostFingerprint }, + }) + ).status, + ).toBe(200); + expect( + ( + await api('/api/servers/srv-b/tofu/approve', { + method: 'POST', + body: { fingerprint: mockB.hostFingerprint }, + }) + ).status, + ).toBe(200); + await waitFor( + () => + server.sshPool.getState('srv-a')?.status === 'connected' && + server.sshPool.getState('srv-b')?.status === 'connected', + ); + + // Attach systemd to srv-a for system-action step + expect( + ( + await api('/api/systems/systemd/servers/srv-a/attach', { + method: 'PUT', + body: { params: { unitFilter: 'nginx' } }, + }) + ).status, + ).toBe(200); + + // Wrap execStream ONLY for deterministic slow steps (__SLOW_250__ / __SLOW_2S__) + const origExecStream = server.sshPool.execStream.bind(server.sshPool); + vi.spyOn(server.sshPool, 'execStream').mockImplementation(async (serverId, cmd, opts) => { + if (!cmd.includes('__SLOW_')) { + return origExecStream(serverId, cmd, opts); + } + const ch = new PassThrough() as PassThrough & { stderr: PassThrough; close: () => void }; + const stderrStream = new PassThrough(); + ch.stderr = stderrStream; + let timer: NodeJS.Timeout | undefined; + let settled = false; + let resolveDone!: (res: { exitCode: number | null; signal?: string }) => void; + const done = new Promise<{ exitCode: number | null; signal?: string }>((resolve) => { + resolveDone = resolve; + }); + const finish = (res: { exitCode: number | null; signal?: string }) => { + if (settled) return; + settled = true; + if (timer) clearTimeout(timer); + ch.end(); + stderrStream.end(); + resolveDone(res); + }; + const abort = () => { + finish({ exitCode: null, signal: 'TERM' }); + }; + ch.close = abort; + const delayMs = cmd.includes('__SLOW_2S__') ? 2500 : 300; + ch.write(`slow-start:${serverId}\n`); + timer = setTimeout(() => { + ch.write(`slow-end:${serverId}\n`); + finish({ exitCode: 0 }); + }, delayMs); + return { channel: ch as unknown as ClientChannel, done, abort }; + }); + + // --- 1. Snippets CRUD & Safe Mode enforcement --- + const safeBlocked = await api('/api/snippets', { + method: 'POST', + safeMode: true, + body: { id: 'snip-safe', name: 'Safe', command: 'echo hi' }, + }); + expect(safeBlocked.status).toBe(423); + expect(safeBlocked.data.error).toBe('SAFE_MODE_ACTIVE'); + + const snipCreate = await api('/api/snippets', { + method: 'POST', + body: { + id: 'snip-quote', + name: 'Safe Quoting Check', + command: + 'echo REAL_SH_QUOTE_TEST && printf "ARG=%s ENV=%s" {{inputs.arg}} "$GCOORD_INPUT_ARG"', + tags: ['diagnostics'], + inputs: [{ name: 'arg', type: 'string', required: true }], + sudo: false, + confirm: false, + }, + }); + expect(snipCreate.status).toBe(201); + + const snipDup = await api('/api/snippets', { + method: 'POST', + body: { id: 'snip-quote', name: 'Dup', command: 'echo dup' }, + }); + expect(snipDup.status).toBe(409); + + const snipUpd = await api('/api/snippets/snip-quote', { + method: 'PUT', + body: { + name: 'Safe Quoting Updated', + command: + 'echo REAL_SH_QUOTE_TEST && printf "ARG=%s|ENV=%s" {{inputs.arg}} "$GCOORD_INPUT_ARG"', + tags: ['diagnostics'], + inputs: [{ name: 'arg', type: 'string', required: true }], + sudo: false, + confirm: false, + }, + }); + expect(snipUpd.status).toBe(200); + expect( + ((await api('/api/snippets')).data.snippets as Array<{ id: string }>).some( + (s) => s.id === 'snip-quote', + ), + ).toBe(true); + + // Temporary snippet to verify DELETE + await api('/api/snippets', { + method: 'POST', + body: { id: 'snip-del', name: 'Temp', command: 'echo bye' }, + }); + expect((await api('/api/snippets/snip-del', { method: 'DELETE' })).status).toBe(200); + + // --- 2. Ad-Hoc Fleet Broadcast (safe quoting, WS replay, cancellation) --- + const dangerousArg = "hello'; touch /tmp/should-not-run; echo INJECTED"; + const { ws, frames } = await openWs(wsUrl, { + Cookie: jar.header(), + Host: `127.0.0.1:${server.port}`, + Origin: baseUrl, + }); + cleanups.push(() => ws.close()); + + const bcastRes = await api('/api/workflows/broadcast', { + method: 'POST', + body: { + snippetId: 'snip-quote', + inputs: { arg: dangerousArg }, + concurrency: 2, + target: { all: true }, + }, + }); + expect(bcastRes.status).toBe(202); + const jobId = String((bcastRes.data.job as { jobId: string }).jobId); + + const bcastDone = await waitFor(async () => { + const g = await api(`/api/workflows/broadcast/${jobId}`); + const j = g.data.job as { + done: boolean; + targets: Array<{ serverId: string; stdout: string; exitCode: number | null; status: string }>; + }; + return j?.done ? j : undefined; + }); + expect(bcastDone.targets).toHaveLength(2); + for (const t of bcastDone.targets) { + expect(t.status).toBe('ok'); + expect(t.exitCode).toBe(0); + // POSIX single-quoting prevents shell injection; literal payload reaches printf unchanged + expect(t.stdout).toContain(`ARG=${dangerousArg}|ENV=${dangerousArg}`); + expect(t.stdout).not.toContain('\nINJECTED'); + } + + // Subscribe AFTER broadcast finished to verify BufferedStreamEmitter replay frames + ws.send(JSON.stringify({ type: 'sub', channels: [`stream:${jobId}`] })); + await waitFor(() => + frames.some((f) => { + if (f.type !== 'stream:chunk' || f.jobId !== jobId || f.stream !== 'meta') return false; + try { + return (JSON.parse(String(f.data)) as { event?: string }).event === 'done'; + } catch { + return false; + } + }), + ); + + // Broadcast cancellation + const slowBcast = await api('/api/workflows/broadcast', { + method: 'POST', + body: { + command: 'echo __SLOW_2S__', + target: { serverId: 'srv-a' }, + }, + }); + expect(slowBcast.status).toBe(202); + const slowJobId = String((slowBcast.data.job as { jobId: string }).jobId); + const cancelBcast = await api(`/api/workflows/broadcast/${slowJobId}/cancel`, { + method: 'POST', + }); + expect(cancelBcast.status).toBe(200); + expect(cancelBcast.data.cancelled).toBe(true); + const abortedJob = await waitFor(() => { + const j = server.broadcastService.getBroadcastResult(slowJobId); + return j?.done ? j : undefined; + }); + expect(abortedJob.cancelled).toBe(true); + expect(abortedJob.targets[0]?.status).toBe('cancelled'); + + // --- 3. Workflow Dry-Run, Pinned summary, Full DAG + failure/always + read-file + system-action + hub-relayed & direct transfers --- + const dagWf = { + id: 'wf-dag-full', + name: 'Full DAG Verification', + enabled: true, + trigger: { type: 'manual' }, + overlapPolicy: 'skip', + stopOnError: false, + concurrency: 2, + display: { mode: 'summary', pinToDashboard: true }, + inputs: [{ name: 'tag', type: 'string', required: true }], + steps: [ + { + id: 'gen-token', + type: 'exec', + target: { serverId: 'srv-a' }, + command: ': ECHO_STEP; printf "tok-%s" {{inputs.tag}}', + captureAs: 'tok', + }, + { + id: 'tail-log', + type: 'read-file', + target: { serverId: 'srv-a' }, + path: '/logs/app.log', + tailLines: 2, + }, + { + id: 'svc-restart', + type: 'system-action', + dependsOn: ['gen-token'], + target: { serverId: 'srv-a' }, + systemId: 'systemd', + action: 'restart', + item: 'nginx.service', + }, + { + id: 'xfer-file', + type: 'transfer', + dependsOn: ['gen-token'], + mode: 'hub-relayed', + source: { serverId: 'srv-a', path: '/single.txt' }, + destination: { serverId: 'srv-b', path: '/dst-single.txt' }, + }, + { + id: 'xfer-dir', + type: 'transfer', + dependsOn: ['xfer-file'], + mode: 'hub-relayed', + source: { serverId: 'srv-a', path: '/bundle' }, + destination: { serverId: 'srv-b', path: '/dst-bundle' }, + }, + { + id: 'xfer-direct', + type: 'transfer', + dependsOn: ['gen-token'], + mode: 'direct', + source: { serverId: 'srv-a', path: '/single.txt' }, + destination: { serverId: 'srv-b', path: '/direct-copy.txt' }, + }, + { + id: 'will-fail', + type: 'exec', + dependsOn: ['gen-token'], + target: { serverId: 'srv-b' }, + command: 'echo FAIL_NOW', + onFailure: 'continue', + }, + { + id: 'on-fail-branch', + type: 'exec', + dependsOn: [{ stepId: 'will-fail', on: 'failure' }], + target: { serverId: 'srv-a' }, + command: ': PRINT_CAP; printf "CAP=%s|STEP=%s" {{captures.tok}} {{steps.gen-token.stdout}}', + }, + { + id: 'on-always-cleanup', + type: 'exec', + dependsOn: [ + { stepId: 'on-fail-branch', on: 'always' }, + { stepId: 'xfer-dir', on: 'success' }, + ], + target: { serverId: 'srv-b' }, + command: 'echo cleanup-done', + }, + ], + }; + + expect( + (await api('/api/workflows', { method: 'POST', body: dagWf })).status, + ).toBe(201); + + const pinnedRes = await api('/api/workflows?pinnedOnly=1'); + expect(pinnedRes.status).toBe(200); + expect( + (pinnedRes.data.workflows as Array<{ workflow: { id: string } }>).map( + (w) => w.workflow.id, + ), + ).toEqual(['wf-dag-full']); + + // Dry-run works even under Safe Mode + const dryRes = await api('/api/workflows/wf-dag-full/dry-run', { + method: 'POST', + safeMode: true, + body: { inputs: { tag: 'v42' } }, + }); + expect(dryRes.status).toBe(200); + const plan = dryRes.data.plan as { + steps: Array<{ + stepId: string; + wave: number; + renderedCommand?: string; + renderedPath?: string; + }>; + }; + const tailPlan = plan.steps.find((s) => s.stepId === 'tail-log'); + expect(tailPlan?.renderedPath).toBe('/logs/app.log'); + const genPlan = plan.steps.find((s) => s.stepId === 'gen-token'); + expect(genPlan?.renderedCommand).toContain("'v42'"); + + const dagStart = await api('/api/workflows/wf-dag-full/run', { + method: 'POST', + body: { inputs: { tag: 'v42' } }, + }); + expect(dagStart.status).toBe(202); + const dagRunId = String(dagStart.data.runId); + const dagDetail = await waitForWorkflowRun(server, dagRunId, 10_000); + expect(dagDetail.run.status).toBe('succeeded'); + + const logByStep = new Map(dagDetail.stepLogs.map((l) => [l.stepId, l])); + expect(logByStep.get('gen-token')?.stdout).toBe('tok-v42'); + expect(logByStep.get('tail-log')?.stdout.trim()).toBe('l3\nl4'); + expect(logByStep.get('svc-restart')?.stdout).toContain('restarted nginx on A'); + expect(logByStep.get('will-fail')?.exitCode).toBe(42); + expect(logByStep.get('on-fail-branch')?.stdout).toBe('CAP=tok-v42|STEP=tok-v42'); + expect(logByStep.get('on-always-cleanup')?.exitCode).toBe(0); + + // Verify hub-relayed SFTP transfer files landed on srvB without touching local disk + expect(fs.readFileSync(path.join(sftpRootB, 'dst-single.txt'), 'utf8')).toBe( + 'single-file-payload\n', + ); + expect(fs.readFileSync(path.join(sftpRootB, 'dst-bundle', 'top.txt'), 'utf8')).toBe( + 'top-content', + ); + expect( + fs.readFileSync(path.join(sftpRootB, 'dst-bundle', 'nested', 'deep.txt'), 'utf8'), + ).toBe('deep-content'); + expect(directRsyncCmds.some((c) => c.includes(`ops@127.0.0.1:/direct-copy.txt`))).toBe( + true, + ); + + // Verify WS workflow:run + stream:wf: replay frames + ws.send(JSON.stringify({ type: 'sub', channels: [`stream:wf:${dagRunId}`] })); + await waitFor(() => + frames.some((f) => { + if (f.type !== 'stream:chunk' || f.jobId !== `wf:${dagRunId}` || f.stream !== 'meta') { + return false; + } + try { + return (JSON.parse(String(f.data)) as { event?: string }).event === 'done'; + } catch { + return false; + } + }), + ); + + // --- 4. Overlap Policies ('skip', 'queue', 'cancel-previous'), Timeout & Manual Cancel --- + await api('/api/workflows', { + method: 'POST', + body: { + id: 'wf-overlap-skip', + name: 'Overlap Skip', + enabled: true, + trigger: { type: 'manual' }, + overlapPolicy: 'skip', + display: { mode: 'log' }, + inputs: [], + steps: [{ id: 's1', type: 'exec', target: { serverId: 'srv-a' }, command: 'echo __SLOW_250__' }], + }, + }); + const rSkip1 = await api('/api/workflows/wf-overlap-skip/run', { method: 'POST', body: {} }); + expect(rSkip1.status).toBe(202); + const rSkip2 = await api('/api/workflows/wf-overlap-skip/run', { method: 'POST', body: {} }); + expect(rSkip2.status).toBe(200); + expect(rSkip2.data.status).toBe('skipped'); + expect((await waitForWorkflowRun(server, String(rSkip1.data.runId))).run.status).toBe('succeeded'); + + await api('/api/workflows', { + method: 'POST', + body: { + id: 'wf-overlap-queue', + name: 'Overlap Queue', + enabled: true, + trigger: { type: 'manual' }, + overlapPolicy: 'queue', + display: { mode: 'log' }, + inputs: [], + steps: [{ id: 's1', type: 'exec', target: { serverId: 'srv-a' }, command: 'echo __SLOW_250__' }], + }, + }); + const rQ1 = await api('/api/workflows/wf-overlap-queue/run', { method: 'POST', body: {} }); + const rQ2 = await api('/api/workflows/wf-overlap-queue/run', { method: 'POST', body: {} }); + expect(rQ1.status).toBe(202); + expect(rQ2.status).toBe(202); + expect(rQ2.data.status).toBe('queued'); + expect((await waitForWorkflowRun(server, String(rQ1.data.runId))).run.status).toBe('succeeded'); + expect((await waitForWorkflowRun(server, String(rQ2.data.runId))).run.status).toBe('succeeded'); + + await api('/api/workflows', { + method: 'POST', + body: { + id: 'wf-overlap-cancel', + name: 'Overlap Cancel Prev', + enabled: true, + trigger: { type: 'manual' }, + overlapPolicy: 'cancel-previous', + display: { mode: 'log' }, + inputs: [], + steps: [{ id: 's1', type: 'exec', target: { serverId: 'srv-a' }, command: 'echo __SLOW_250__' }], + }, + }); + const rC1 = await api('/api/workflows/wf-overlap-cancel/run', { method: 'POST', body: {} }); + const rC2 = await api('/api/workflows/wf-overlap-cancel/run', { method: 'POST', body: {} }); + expect(rC2.status).toBe(202); + expect((await waitForWorkflowRun(server, String(rC1.data.runId))).run.status).toBe('cancelled'); + expect((await waitForWorkflowRun(server, String(rC2.data.runId))).run.status).toBe('succeeded'); + + // Step timeoutSec: 1 + manual run cancel + await api('/api/workflows', { + method: 'POST', + body: { + id: 'wf-timeout', + name: 'Timeout Test', + enabled: true, + trigger: { type: 'manual' }, + overlapPolicy: 'skip', + display: { mode: 'log' }, + inputs: [], + steps: [ + { + id: 'slow', + type: 'exec', + target: { serverId: 'srv-a' }, + command: 'echo __SLOW_2S__', + timeoutSec: 1, + }, + ], + }, + }); + const rTimeout = await api('/api/workflows/wf-timeout/run', { method: 'POST', body: {} }); + const dTimeout = await waitForWorkflowRun(server, String(rTimeout.data.runId)); + expect(dTimeout.run.status).toBe('failed'); + expect(dTimeout.stepLogs[0]?.stderr).toMatch(/timed out/i); + + const rToCancel = await api('/api/workflows', { + method: 'POST', + body: { + id: 'wf-manual-cancel', + name: 'Manual Cancel', + enabled: true, + trigger: { type: 'manual' }, + overlapPolicy: 'skip', + display: { mode: 'log' }, + inputs: [], + steps: [{ id: 'slow', type: 'exec', target: { serverId: 'srv-a' }, command: 'echo __SLOW_2S__' }], + }, + }); + expect(rToCancel.status).toBe(201); + const rManStart = await api('/api/workflows/wf-manual-cancel/run', { method: 'POST', body: {} }); + const manCancelRes = await api(`/api/workflows/runs/${String(rManStart.data.runId)}/cancel`, { + method: 'POST', + }); + expect(manCancelRes.data.cancelled).toBe(true); + const dCancelled = await waitForWorkflowRun(server, String(rManStart.data.runId)); + expect(dCancelled.run.status).toBe('cancelled'); + expect(dCancelled.run.cancelledBy).toBe('admin'); + + // --- 5. Cron Workflow Scheduling --- + await api('/api/workflows', { + method: 'POST', + body: { + id: 'wf-cron-sec', + name: 'Every Second Cron', + enabled: true, + trigger: { type: 'cron', expression: '* * * * * *', timezone: 'UTC' }, + overlapPolicy: 'skip', + display: { mode: 'log' }, + inputs: [], + steps: [{ id: 'tick', type: 'exec', target: { serverId: 'srv-b' }, command: 'echo CRON_TICK' }], + }, + }); + + const listSummary = await api('/api/workflows'); + const cronSummary = ( + listSummary.data.workflows as Array<{ + workflow: { id: string }; + nextRunAt: number | null; + }> + ).find((w) => w.workflow.id === 'wf-cron-sec'); + expect(typeof cronSummary?.nextRunAt).toBe('number'); + expect(cronSummary!.nextRunAt!).toBeGreaterThan(Date.now() - 2000); + + const cronRun = await waitFor( + () => { + const runs = server.workflowEngine.listRuns('wf-cron-sec'); + return runs.find((r) => r.triggerSource === 'cron' && r.status === 'succeeded'); + }, + 5000, + ); + expect(cronRun.triggerSource).toBe('cron'); + await api('/api/workflows/wf-cron-sec', { method: 'DELETE' }); + }, + ); +});