From 2b878c1d9983d533595cb1ca54675d63f9c52371 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sat, 28 Nov 2026 05:06:04 +0000 Subject: [PATCH] feat(workflows,transfers,broadcast): harden templates/rsync/SFTP-transfer, add http/notify steps, retries, secret inputs & broadcast history --- src/server/alerts/alert-engine.ts | 6 +- src/server/api/routes/workflows.routes.ts | 45 +- src/server/app.ts | 5 +- src/server/automation/broadcast-service.ts | 280 ++++++++- src/server/automation/template.ts | 239 ++++++- src/server/automation/transfer-engine.ts | 101 ++- src/server/automation/workflow-engine.ts | 690 ++++++++++++++++++--- src/server/ssh/known-hosts.ts | 19 + 8 files changed, 1217 insertions(+), 168 deletions(-) diff --git a/src/server/alerts/alert-engine.ts b/src/server/alerts/alert-engine.ts index 93bd169..ba8189f 100644 --- a/src/server/alerts/alert-engine.ts +++ b/src/server/alerts/alert-engine.ts @@ -83,10 +83,10 @@ export class AlertEngine { this.stopped = false; this.hydrateOpenIncidents(); - this.workflowEngine.setFailureNotifier(async (channelId, message, _workflowId) => { + this.workflowEngine.setFailureNotifier(async (channelId, message, _workflowId, meta) => { await this.sendDirectChannelMessage(channelId, { - severity: 'critical', - title: 'Workflow Execution Failure', + severity: meta?.severity ?? 'critical', + title: meta?.title ?? 'Workflow Execution Failure', message, state: 'firing', }); diff --git a/src/server/api/routes/workflows.routes.ts b/src/server/api/routes/workflows.routes.ts index 34c7809..cea3718 100644 --- a/src/server/api/routes/workflows.routes.ts +++ b/src/server/api/routes/workflows.routes.ts @@ -147,7 +147,8 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router { }); router.get('/runs/:runId', requireAuth(authService), (req, res) => { - const detail = workflowEngine.getRunDetail(String(req.params.runId ?? '')); + const includeLogs = req.query.includeLogs !== 'false' && req.query.includeLogs !== '0'; + const detail = workflowEngine.getRunDetail(String(req.params.runId ?? ''), { includeLogs }); if (!detail) { res.status(404).json({ error: 'RUN_NOT_FOUND' }); return; @@ -155,11 +156,20 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router { res.json(detail); }); + router.get('/runs/:runId/steps/:stepId/logs', requireAuth(authService), (req, res) => { + const runId = String(req.params.runId ?? ''); + const stepId = String(req.params.stepId ?? ''); + const offset = Number(req.query.offset) || 0; + const limit = Number(req.query.limit) || 50; + const result = workflowEngine.getStepLogs(runId, { stepId, offset, limit }); + res.json(result); + }); + + // Cancelling a running workflow must remain available under Safe Mode router.post( '/runs/:runId/cancel', requireAuth(authService), requireCsrf, - enforceSafeMode, (req, res) => { const runId = String(req.params.runId ?? ''); const cancelled = workflowEngine.cancelRun(runId, 'admin'); @@ -248,6 +258,7 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router { }), }) .safeParse(req.body ?? {}); + if (!parsed.success) { res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); return; @@ -269,6 +280,24 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router { }, ); + router.get('/broadcast/history', requireAuth(authService), (req, res) => { + const limit = Number(req.query.limit) || 50; + res.json({ jobs: broadcastService.listHistory(limit) }); + }); + + router.get('/broadcast/:jobId/export', requireAuth(authService), (req, res) => { + const jobId = String(req.params.jobId ?? ''); + const format = String(req.query.format ?? 'json') === 'csv' ? 'csv' : 'json'; + const exported = broadcastService.exportBroadcast(jobId, format); + if (!exported) { + res.status(404).json({ error: 'BROADCAST_NOT_FOUND' }); + return; + } + res.setHeader('Content-Type', exported.contentType); + res.setHeader('Content-Disposition', `attachment; filename="${exported.filename}"`); + res.send(exported.body); + }); + router.get('/broadcast/:jobId', requireAuth(authService), (req, res) => { const job = broadcastService.getBroadcastResult(String(req.params.jobId ?? '')); if (!job) { @@ -278,14 +307,22 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router { res.json({ job }); }); + // Cancelling a running broadcast must remain available under Safe Mode router.post( '/broadcast/:jobId/cancel', requireAuth(authService), requireCsrf, - enforceSafeMode, (req, res) => { const jobId = String(req.params.jobId ?? ''); - res.json({ cancelled: broadcastService.cancelBroadcast(jobId) }); + const cancelled = broadcastService.cancelBroadcast(jobId); + auditService.log({ + action: 'broadcast.cancel', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: jobId, + status: cancelled ? 'ok' : 'error', + }); + res.json({ cancelled }); }, ); diff --git a/src/server/app.ts b/src/server/app.ts index ea238e2..b35ebd0 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -206,7 +206,7 @@ export async function createGCoordinatorServer( probeRunner, getRuntimeLimits, ); - const transferEngine = new TransferEngine(sshPool, sftpService, configManager); + const transferEngine = new TransferEngine(sshPool, sftpService, configManager, knownHosts); const workflowEngine = new WorkflowEngine( db, configManager, @@ -217,6 +217,7 @@ export async function createGCoordinatorServer( transferEngine, wsHub, auditService, + getRuntimeLimits, ); const broadcastService = new BroadcastService( configManager, @@ -224,6 +225,8 @@ export async function createGCoordinatorServer( sshPool, wsHub, auditService, + db, + getRuntimeLimits, ); const alertEngine = new AlertEngine( db, diff --git a/src/server/automation/broadcast-service.ts b/src/server/automation/broadcast-service.ts index 4909164..69d9804 100644 --- a/src/server/automation/broadcast-service.ts +++ b/src/server/automation/broadcast-service.ts @@ -1,7 +1,9 @@ import crypto from 'node:crypto'; +import type Database from 'better-sqlite3'; import type { ServerWsFrame } from '../../shared/ws-protocol.js'; import type { WsHub } from '../api/ws-hub.js'; import type { ConfigManager } from '../config/config-manager.js'; +import type { RuntimeLimits } from '../config/runtime-limits.js'; import type { AuditService } from '../security/audit.js'; import type { VaultService } from '../security/vault.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; @@ -9,6 +11,8 @@ import { BufferedStreamEmitter } from './stream-buffer.js'; import { buildWorkflowEnv, interpolateShellCommandSafe, + maskSecretInputsForStorage, + redactWorkflowSecrets, resolveTargetServers, validateAndResolveInputs, } from './template.js'; @@ -38,10 +42,14 @@ export interface BroadcastJobSummary { interface ActiveBroadcastJob extends BroadcastJobSummary { emitter: BufferedStreamEmitter; abortController: AbortController; + secretValues: string[]; } -const MAX_RETAINED_BROADCASTS = 25; -const MAX_OUTPUT_PER_SERVER = 256 * 1024; +function csvSafeCell(val: unknown): string { + const s = val === null || val === undefined ? '' : String(val); + const safe = /^[=+\-@\t\r]/.test(s) ? `'${s}` : s; + return `"${safe.replace(/"/g, '""')}"`; +} async function runPool( items: T[], @@ -68,6 +76,8 @@ export class BroadcastService { private readonly sshPool: SSHPool, private readonly wsHub: WsHub, private readonly auditService: AuditService, + private readonly db?: Database.Database, + private readonly getRuntimeLimits?: () => RuntimeLimits, ) {} getStreamReplayFrames(jobId: string): ServerWsFrame[] { @@ -76,17 +86,178 @@ export class BroadcastService { getBroadcastResult(jobId: string): BroadcastJobSummary | undefined { const job = this.jobs.get(jobId); - if (!job) return undefined; + if (job) { + return { + jobId: job.jobId, + snippetId: job.snippetId, + command: job.command, + sudo: job.sudo, + createdAt: job.createdAt, + finishedAt: job.finishedAt, + cancelled: job.cancelled, + done: job.done, + targets: job.targets.map((t) => ({ ...t })), + }; + } + + if (!this.db) return undefined; + const row = this.db + .prepare( + `SELECT job_id AS jobId, command, snippet_id AS snippetId, status, + started_at AS startedAt, finished_at AS finishedAt, results_json AS resultsJson + FROM broadcast_jobs + WHERE job_id = ?`, + ) + .get(jobId) as + | { + jobId: string; + command: string; + snippetId: string | null; + status: string; + startedAt: number; + finishedAt: number | null; + resultsJson: string; + } + | undefined; + if (!row) return undefined; + + let targets: BroadcastTargetResult[] = []; + try { + targets = JSON.parse(row.resultsJson) as BroadcastTargetResult[]; + } catch { + targets = []; + } + return { - jobId: job.jobId, - snippetId: job.snippetId, - command: job.command, - sudo: job.sudo, - createdAt: job.createdAt, - finishedAt: job.finishedAt, - cancelled: job.cancelled, - done: job.done, - targets: job.targets.map((t) => ({ ...t })), + jobId: row.jobId, + snippetId: row.snippetId ?? undefined, + command: row.command, + sudo: false, + createdAt: row.startedAt, + finishedAt: row.finishedAt, + cancelled: row.status === 'cancelled', + done: row.finishedAt !== null || row.status !== 'running', + targets, + }; + } + + listHistory(limit = 50): Array<{ + jobId: string; + snippetId?: string; + command: string; + status: string; + startedAt: number; + finishedAt: number | null; + targetCount: number; + okCount: number; + }> { + if (!this.db) { + return [...this.jobs.values()] + .sort((a, b) => b.createdAt - a.createdAt) + .slice(0, limit) + .map((j) => ({ + jobId: j.jobId, + snippetId: j.snippetId, + command: j.command, + status: j.cancelled + ? 'cancelled' + : !j.done + ? 'running' + : j.targets.every((t) => t.status === 'ok') + ? 'ok' + : 'error', + startedAt: j.createdAt, + finishedAt: j.finishedAt, + targetCount: j.targets.length, + okCount: j.targets.filter((t) => t.status === 'ok').length, + })); + } + + const safeLimit = Math.max(1, Math.min(200, Math.floor(limit))); + const rows = this.db + .prepare( + `SELECT job_id AS jobId, command, snippet_id AS snippetId, status, + started_at AS startedAt, finished_at AS finishedAt, results_json AS resultsJson + FROM broadcast_jobs + ORDER BY started_at DESC + LIMIT ?`, + ) + .all(safeLimit) as Array<{ + jobId: string; + command: string; + snippetId: string | null; + status: string; + startedAt: number; + finishedAt: number | null; + resultsJson: string; + }>; + + return rows.map((r) => { + const live = this.jobs.get(r.jobId); + const targets = live + ? live.targets + : (() => { + try { + return JSON.parse(r.resultsJson) as BroadcastTargetResult[]; + } catch { + return []; + } + })(); + return { + jobId: r.jobId, + snippetId: r.snippetId ?? undefined, + command: r.command, + status: live + ? live.cancelled + ? 'cancelled' + : !live.done + ? 'running' + : live.targets.every((t) => t.status === 'ok') + ? 'ok' + : 'error' + : r.status, + startedAt: r.startedAt, + finishedAt: live ? live.finishedAt : r.finishedAt, + targetCount: targets.length, + okCount: targets.filter((t) => t.status === 'ok').length, + }; + }); + } + + exportBroadcast( + jobId: string, + format: 'json' | 'csv' = 'json', + ): { contentType: string; filename: string; body: string } | null { + const job = this.getBroadcastResult(jobId); + if (!job) return null; + + if (format === 'csv') { + const header = 'jobId,serverId,serverName,status,exitCode,durationMs,stdout,stderr'; + const rows = job.targets.map((t) => + [ + job.jobId, + t.serverId, + t.serverName, + t.status, + t.exitCode ?? '', + t.durationMs, + t.stdout, + t.stderr, + ] + .map(csvSafeCell) + .join(','), + ); + return { + contentType: 'text/csv; charset=utf-8', + filename: `${job.jobId}.csv`, + body: `${[header, ...rows].join('\n')}\n`, + }; + } + + return { + contentType: 'application/json; charset=utf-8', + filename: `${job.jobId}.json`, + body: JSON.stringify(job, null, 2), }; } @@ -125,6 +296,7 @@ export class BroadcastService { let rawCommand = opts.command?.trim() ?? ''; let sudo = Boolean(opts.sudo); let resolvedInputs: Record = {}; + let secretValues: string[] = []; if (opts.snippetId) { const snip = this.configManager @@ -134,6 +306,7 @@ export class BroadcastService { throw new Error(`Unknown command snippet "${opts.snippetId}"`); } resolvedInputs = validateAndResolveInputs(snip.inputs, opts.inputs ?? {}); + secretValues = maskSecretInputsForStorage(snip.inputs, resolvedInputs).secretValues; rawCommand = snip.command; sudo = opts.sudo ?? snip.sudo; } else { @@ -141,14 +314,14 @@ export class BroadcastService { throw new Error('Command or snippetId is required for Fleet Broadcast'); } if (opts.inputs) { - for (const [k, v] of Object.entries(opts.inputs)) { - if (v !== undefined && v !== null) resolvedInputs[k] = String(v); - } + resolvedInputs = validateAndResolveInputs([], opts.inputs); } } + const limits = this.getRuntimeLimits?.(); const baseCtx = { inputs: resolvedInputs }; const renderedCommand = interpolateShellCommandSafe(rawCommand, baseCtx); + const displayCommand = redactWorkflowSecrets(renderedCommand, secretValues); const allServers = this.configManager.listServers(); let matchedServers = resolveTargetServers(opts.target, allServers, baseCtx); @@ -168,7 +341,11 @@ export class BroadcastService { } const jobId = `bcast-${crypto.randomBytes(6).toString('hex')}`; - const emitter = new BufferedStreamEmitter(this.wsHub, jobId); + const emitter = new BufferedStreamEmitter( + this.wsHub, + jobId, + limits?.streamReplayBytes, + ); const abortController = new AbortController(); const targets: BroadcastTargetResult[] = matchedServers.map((s) => ({ @@ -184,7 +361,7 @@ export class BroadcastService { const job: ActiveBroadcastJob = { jobId, snippetId: opts.snippetId, - command: renderedCommand, + command: displayCommand, sudo, createdAt: Date.now(), finishedAt: null, @@ -193,9 +370,12 @@ export class BroadcastService { targets, emitter, abortController, + secretValues, }; this.jobs.set(jobId, job); + this.persistBroadcastRow(job, 'running'); + this.auditService.log({ action: 'broadcast.start', actorIp: opts.actorIp, @@ -211,12 +391,14 @@ export class BroadcastService { emitter.pushMeta({ event: 'start', jobId, - command: renderedCommand, + command: displayCommand, targets: targets.map((t) => ({ serverId: t.serverId, serverName: t.serverName })), }); + const maxStepLogBytes = limits?.maxStepLogBytes ?? 256 * 1024; const timeoutMs = (opts.timeoutSec ?? 120) * 1000; - const concurrency = Math.max(1, Math.min(opts.concurrency ?? 4, 32)); + const concurrencyCap = limits?.maxWorkflowStepTargets ?? 32; + const concurrency = Math.max(1, Math.min(opts.concurrency ?? 4, concurrencyCap)); void runPool(matchedServers, concurrency, async (srv) => { const targetEntry = job.targets.find((t) => t.serverId === srv.id)!; @@ -239,6 +421,7 @@ export class BroadcastService { const env = buildWorkflowEnv({ inputs: resolvedInputs, serverId: srv.id, + serverMeta: { id: srv.id, name: srv.name, host: srv.host, port: srv.port }, }); try { @@ -253,9 +436,9 @@ export class BroadcastService { let errBytes = 0; handle.channel.on('data', (chunk: Buffer) => { - const text = chunk.toString('utf8'); - if (outBytes < MAX_OUTPUT_PER_SERVER) { - const slice = chunk.subarray(0, MAX_OUTPUT_PER_SERVER - outBytes); + const text = redactWorkflowSecrets(chunk.toString('utf8'), secretValues); + if (outBytes < maxStepLogBytes) { + const slice = chunk.subarray(0, maxStepLogBytes - outBytes); outChunks.push(slice); outBytes += slice.length; } @@ -269,9 +452,9 @@ export class BroadcastService { }); handle.channel.stderr?.on('data', (chunk: Buffer) => { - const text = chunk.toString('utf8'); - if (errBytes < MAX_OUTPUT_PER_SERVER) { - const slice = chunk.subarray(0, MAX_OUTPUT_PER_SERVER - errBytes); + const text = redactWorkflowSecrets(chunk.toString('utf8'), secretValues); + if (errBytes < maxStepLogBytes) { + const slice = chunk.subarray(0, maxStepLogBytes - errBytes); errChunks.push(slice); errBytes += slice.length; } @@ -296,8 +479,14 @@ export class BroadcastService { try { const { exitCode } = await handle.done; - targetEntry.stdout = Buffer.concat(outChunks).toString('utf8'); - targetEntry.stderr = Buffer.concat(errChunks).toString('utf8'); + targetEntry.stdout = redactWorkflowSecrets( + Buffer.concat(outChunks).toString('utf8'), + secretValues, + ); + targetEntry.stderr = redactWorkflowSecrets( + Buffer.concat(errChunks).toString('utf8'), + secretValues, + ); targetEntry.durationMs = Date.now() - started; targetEntry.exitCode = exitCode; @@ -316,7 +505,10 @@ export class BroadcastService { } catch (err) { targetEntry.durationMs = Date.now() - started; targetEntry.status = abortController.signal.aborted ? 'cancelled' : 'error'; - const msg = err instanceof Error ? err.message : String(err); + const msg = redactWorkflowSecrets( + err instanceof Error ? err.message : String(err), + secretValues, + ); targetEntry.stderr = targetEntry.stderr ? `${targetEntry.stderr}\n${msg}` : msg; emitter.push('stderr', `[${srv.id}] ${msg}\n`); } @@ -332,6 +524,12 @@ export class BroadcastService { job.done = true; job.finishedAt = Date.now(); const okCount = job.targets.filter((t) => t.status === 'ok').length; + const finalStatus = job.cancelled + ? 'cancelled' + : okCount === job.targets.length + ? 'ok' + : 'error'; + this.persistBroadcastRow(job, finalStatus); emitter.pushMeta({ event: 'done', cancelled: job.cancelled, @@ -344,9 +542,33 @@ export class BroadcastService { return this.getBroadcastResult(jobId)!; } + private persistBroadcastRow(job: ActiveBroadcastJob, status: string): void { + if (!this.db) return; + this.db + .prepare( + `INSERT INTO broadcast_jobs (job_id, command, snippet_id, targets_json, status, started_at, finished_at, results_json) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(job_id) DO UPDATE SET + status = excluded.status, + finished_at = excluded.finished_at, + results_json = excluded.results_json`, + ) + .run( + job.jobId, + job.command, + job.snippetId ?? null, + JSON.stringify(job.targets.map((t) => t.serverId)), + status, + job.createdAt, + job.finishedAt, + JSON.stringify(job.targets), + ); + } + private pruneJobs(): void { + const maxRam = Math.max(1, this.getRuntimeLimits?.().maxRamBroadcastJobs ?? 5); const done = [...this.jobs.values()].filter((j) => j.done); - while (done.length > MAX_RETAINED_BROADCASTS) { + while (done.length > maxRam) { const oldest = done.shift()!; this.jobs.delete(oldest.jobId); } diff --git a/src/server/automation/template.ts b/src/server/automation/template.ts index a890e2f..4dd7b86 100644 --- a/src/server/automation/template.ts +++ b/src/server/automation/template.ts @@ -10,13 +10,17 @@ export interface StepOutputSummary { export interface TemplateContext { workflowId?: string; runId?: string; + triggerSource?: string; serverId?: string; + serverMeta?: { id: string; name: string; host: string; port: number }; inputs: Record; stepOutputs?: Map; captures?: Map; eventMeta?: Record; } +const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']); + export function toEnvIdent(raw: string): string { return raw.replace(/[^A-Za-z0-9]/g, '_').toUpperCase(); } @@ -27,8 +31,15 @@ export function validateAndResolveInputs( ): Record { const out: Record = {}; + for (const k of Object.keys(supplied)) { + if (FORBIDDEN_KEYS.has(k)) { + throw new Error(`Unsafe input parameter name "${k}"`); + } + } + for (const def of defs) { - const raw = supplied[def.name]; + if (FORBIDDEN_KEYS.has(def.name)) continue; + const raw = Object.hasOwn(supplied, def.name) ? supplied[def.name] : undefined; const hasSupplied = raw !== undefined && raw !== null && raw !== ''; const candidate = hasSupplied ? raw : def.default; @@ -61,6 +72,9 @@ export function validateAndResolveInputs( } const strVal = String(candidate); + if (/[\x00]/.test(strVal)) { + throw new Error(`Input "${def.name}" contains NUL bytes`); + } if (def.type === 'select' && def.options && def.options.length > 0) { if (!def.options.includes(strVal)) { throw new Error( @@ -72,14 +86,48 @@ export function validateAndResolveInputs( } for (const [k, v] of Object.entries(supplied)) { - if (!(k in out) && v !== undefined && v !== null) { - out[k] = String(v); + if (FORBIDDEN_KEYS.has(k)) continue; + if (!Object.hasOwn(out, k) && v !== undefined && v !== null) { + const s = String(v); + if (/[\x00]/.test(s)) { + throw new Error(`Input "${k}" contains NUL bytes`); + } + out[k] = s; } } return out; } +export function maskSecretInputsForStorage( + defs: InputDef[], + resolved: Record, +): { masked: Record; secretValues: string[] } { + const secretKeys = new Set(defs.filter((d) => d.type === 'secret').map((d) => d.name)); + const masked: Record = {}; + const secretValues: string[] = []; + for (const [k, v] of Object.entries(resolved)) { + if (secretKeys.has(k) && v.length > 0) { + masked[k] = '***REDACTED***'; + secretValues.push(v); + } else { + masked[k] = v; + } + } + return { masked, secretValues }; +} + +export function redactWorkflowSecrets(text: string, secretValues: string[]): string { + if (!text || secretValues.length === 0) return text; + let out = text; + for (const sec of secretValues) { + if (sec.length >= 2 && out.includes(sec)) { + out = out.split(sec).join('***REDACTED***'); + } + } + return out; +} + export function buildWorkflowEnv(ctx: TemplateContext): Record { const env: Record = {}; if (ctx.workflowId) env.GCOORD_WORKFLOW_ID = ctx.workflowId; @@ -87,6 +135,7 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record { if (ctx.serverId) env.GCOORD_SERVER_ID = ctx.serverId; for (const [k, v] of Object.entries(ctx.inputs)) { + if (FORBIDDEN_KEYS.has(k)) continue; env[`GCOORD_INPUT_${toEnvIdent(k)}`] = v; } @@ -106,6 +155,7 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record { if (ctx.eventMeta) { for (const [k, v] of Object.entries(ctx.eventMeta)) { + if (FORBIDDEN_KEYS.has(k)) continue; env[`GCOORD_EVENT_${toEnvIdent(k)}`] = v; } } @@ -113,45 +163,188 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record { return env; } -function resolveTemplateToken(rawExpr: string, ctx: TemplateContext): string { +/** + * Resolve ONLY recognized GCoordinator template namespaces so Go/Docker format + * templates like `{{.Names}}` or `{{json .}}` are left completely untouched. + */ +export function resolveTemplateToken( + rawExpr: string, + ctx: TemplateContext, +): { matched: boolean; value: string } { const expr = rawExpr.trim(); - if (expr.startsWith('inputs.')) { - const key = expr.slice('inputs.'.length); - return ctx.inputs[key] ?? ''; + if (!expr || expr.startsWith('.')) return { matched: false, value: '' }; + const parts = expr.split('.'); + if (parts.some((p) => FORBIDDEN_KEYS.has(p))) { + return { matched: false, value: '' }; } - if (expr.startsWith('steps.')) { - const rest = expr.slice('steps.'.length); + + if (expr.startsWith('inputs.') || expr.startsWith('input.')) { + const key = expr.slice(expr.indexOf('.') + 1); + if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(key)) return { matched: false, value: '' }; + return { + matched: true, + value: Object.hasOwn(ctx.inputs, key) ? ctx.inputs[key]! : '', + }; + } + + if (expr.startsWith('steps.') || expr.startsWith('step.')) { + const rest = expr.slice(expr.indexOf('.') + 1); const dot = rest.lastIndexOf('.'); if (dot > 0) { const stepId = rest.slice(0, dot); const field = rest.slice(dot + 1); const out = ctx.stepOutputs?.get(stepId); - if (!out) return ''; - if (field === 'stdout') return out.stdout.trim(); - if (field === 'exitCode') return out.exitCode === null ? '' : String(out.exitCode); + if (field === 'stdout') return { matched: true, value: out ? out.stdout.trim() : '' }; + if (field === 'exitCode') { + return { + matched: true, + value: out && out.exitCode !== null ? String(out.exitCode) : '', + }; + } } + return { matched: false, value: '' }; } - if (expr.startsWith('captures.')) { - const key = expr.slice('captures.'.length); - return (ctx.captures?.get(key) ?? '').trim(); + + if (expr.startsWith('captures.') || expr.startsWith('capture.')) { + const key = expr.slice(expr.indexOf('.') + 1); + return { matched: true, value: (ctx.captures?.get(key) ?? '').trim() }; } + if (expr.startsWith('event.')) { const key = expr.slice('event.'.length); - return ctx.eventMeta?.[key] ?? ''; + return { + matched: true, + value: ctx.eventMeta && Object.hasOwn(ctx.eventMeta, key) ? ctx.eventMeta[key]! : '', + }; } - return (ctx.captures?.get(expr) ?? ctx.inputs[expr] ?? '').trim(); + + if (expr.startsWith('server.')) { + const field = expr.slice('server.'.length); + if (field === 'id') return { matched: true, value: ctx.serverMeta?.id ?? ctx.serverId ?? '' }; + if (field === 'name') return { matched: true, value: ctx.serverMeta?.name ?? '' }; + if (field === 'host') return { matched: true, value: ctx.serverMeta?.host ?? '' }; + if (field === 'port') { + return { + matched: true, + value: ctx.serverMeta ? String(ctx.serverMeta.port) : '', + }; + } + return { matched: false, value: '' }; + } + + if (expr === 'run.id') return { matched: true, value: ctx.runId ?? '' }; + if (expr === 'run.workflowId') return { matched: true, value: ctx.workflowId ?? '' }; + if (expr === 'trigger.source') return { matched: true, value: ctx.triggerSource ?? '' }; + if (expr.startsWith('env.')) { + const key = expr.slice('env.'.length); + const env = buildWorkflowEnv(ctx); + return { matched: true, value: Object.hasOwn(env, key) ? env[key]! : '' }; + } + + if (/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(expr)) { + if (ctx.captures?.has(expr)) { + return { matched: true, value: (ctx.captures.get(expr) ?? '').trim() }; + } + if (Object.hasOwn(ctx.inputs, expr)) { + return { matched: true, value: ctx.inputs[expr]! }; + } + } + + return { matched: false, value: '' }; } export function interpolateValuePlain(template: string, ctx: TemplateContext): string { - return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) => - resolveTemplateToken(expr, ctx), - ); + return template.replace(/\{\{([^{}]+)\}\}/g, (full, expr: string) => { + const res = resolveTemplateToken(expr, ctx); + return res.matched ? res.value : full; + }); } +function escapeDoubleQuotedShell(val: string): string { + return val.replace(/([\\"$`])/g, '\\$1'); +} + +function escapeInsideSingleQuotedShell(val: string): string { + return val.replace(/'/g, "'\\''"); +} + +/** + * Quote-aware shell template substitution: + * - Unquoted `{{token}}`: wrapped in `posixSingleQuote(...)` + * - Inside `'...'`: safely single-quote escaped without outer quotes + * - Inside `"..."`: escaped for `$`, `"`, `\`, `` ` `` + * - Unrecognized `{{.Names}}` Go templates remain byte-for-byte untouched + */ export function interpolateShellCommandSafe(template: string, ctx: TemplateContext): string { - return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) => - posixSingleQuote(resolveTemplateToken(expr, ctx)), - ); + let out = ''; + let quote: 'none' | 'single' | 'double' = 'none'; + let i = 0; + + while (i < template.length) { + const ch = template[i]!; + if (quote === 'none') { + if (ch === '\\' && i + 1 < template.length) { + out += template.slice(i, i + 2); + i += 2; + continue; + } + if (ch === "'") { + quote = 'single'; + out += ch; + i += 1; + continue; + } + if (ch === '"') { + quote = 'double'; + out += ch; + i += 1; + continue; + } + } else if (quote === 'single') { + if (ch === "'") { + quote = 'none'; + out += ch; + i += 1; + continue; + } + } else if (quote === 'double') { + if (ch === '\\' && i + 1 < template.length) { + out += template.slice(i, i + 2); + i += 2; + continue; + } + if (ch === '"') { + quote = 'none'; + out += ch; + i += 1; + continue; + } + } + + if (ch === '{' && template[i + 1] === '{') { + const closeIdx = template.indexOf('}}', i + 2); + if (closeIdx > i + 1) { + const expr = template.slice(i + 2, closeIdx); + const resolved = resolveTemplateToken(expr, ctx); + if (!resolved.matched) { + out += template.slice(i, closeIdx + 2); + } else if (quote === 'single') { + out += escapeInsideSingleQuotedShell(resolved.value); + } else if (quote === 'double') { + out += escapeDoubleQuotedShell(resolved.value); + } else { + out += posixSingleQuote(resolved.value); + } + i = closeIdx + 2; + continue; + } + } + + out += ch; + i += 1; + } + + return out; } export function resolveTargetServers( diff --git a/src/server/automation/transfer-engine.ts b/src/server/automation/transfer-engine.ts index 88acdeb..a52b1b8 100644 --- a/src/server/automation/transfer-engine.ts +++ b/src/server/automation/transfer-engine.ts @@ -2,6 +2,7 @@ import crypto from 'node:crypto'; import path from 'node:path'; import type { FileEntryWithStats, SFTPWrapper, Stats } from 'ssh2'; import type { ConfigManager } from '../config/config-manager.js'; +import type { KnownHostsService } from '../ssh/known-hosts.js'; import type { SftpService } from '../ssh/sftp-service.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; import { posixSingleQuote } from '../ssh/sudo.js'; @@ -15,8 +16,42 @@ export interface TransferResult { durationMs: number; } +const FILE_TYPE_MASK = 0o170000; +const MODE_DIR = 0o040000; +const MODE_REG = 0o100000; + function isDirMode(mode: number): boolean { - return (mode & 0o170000) === 0o040000; + return (mode & FILE_TYPE_MASK) === MODE_DIR; +} + +function isRegularMode(mode: number): boolean { + return (mode & FILE_TYPE_MASK) === MODE_REG; +} + +function assertSafeRemotePath(rawPath: string, label: string): string { + const trimmed = rawPath.trim(); + if (!trimmed || /[\x00-\x1f\x7f]/.test(trimmed)) { + throw new Error(`Invalid ${label} path`); + } + const parts = trimmed.split('/'); + if (parts.some((seg) => seg === '..')) { + throw new Error(`${label} path cannot contain ".." traversal segments`); + } + return trimmed; +} + +function sanitizeRsyncExcludes(excludes?: string[]): string[] { + if (!excludes || excludes.length === 0) return []; + const out: string[] = []; + for (const raw of excludes) { + const clean = raw.trim(); + if (!clean) continue; + if (/[\x00-\x1f\x7f]/.test(clean) || clean.startsWith('-')) { + throw new Error(`Invalid rsync exclude pattern: "${clean}"`); + } + out.push(clean); + } + return out; } function promisifySftp( @@ -46,6 +81,7 @@ export class TransferEngine { private readonly sshPool: SSHPool, private readonly _sftpService: SftpService, private readonly configManager: ConfigManager, + private readonly knownHosts?: KnownHostsService, ) { void this._sftpService; } @@ -54,6 +90,8 @@ export class TransferEngine { mode: 'hub-relayed' | 'direct'; source: { serverId: string; path: string }; destination: { serverId: string; path: string }; + delete?: boolean; + exclude?: string[]; sudo?: boolean; timeoutMs?: number; signal?: AbortSignal; @@ -72,12 +110,29 @@ export class TransferEngine { throw new Error(`Destination server "${opts.destination.serverId}" not found or disabled`); } + const safeSrcPath = assertSafeRemotePath(opts.source.path, 'source'); + const safeDstPath = assertSafeRemotePath(opts.destination.path, 'destination'); const started = Date.now(); const timeoutMs = opts.timeoutMs ?? 600_000; if (opts.mode === 'direct') { - const sshOpt = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`; - const cmd = `rsync -az -e ${posixSingleQuote(sshOpt)} -- ${posixSingleQuote(opts.source.path)} ${posixSingleQuote(`${dstServer.username}@${dstServer.host}:${opts.destination.path}`)}`; + const safeExcludes = sanitizeRsyncExcludes(opts.exclude); + const excludeFlags = safeExcludes + .map((ex) => `--exclude=${posixSingleQuote(ex)} `) + .join(''); + const deleteFlag = opts.delete ? '--delete ' : ''; + const dstTarget = `${dstServer.username}@${dstServer.host}:${safeDstPath}`; + const khLine = this.knownHosts?.getOpenSshKnownHostLine(dstServer); + + let cmd: string; + if (khLine) { + const sshCmd = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$_kh`; + cmd = `_kh=$(mktemp /tmp/.gcoord_kh.XXXXXX) && chmod 600 "$_kh" && trap 'rm -f -- "$_kh"' EXIT && printf '%s\\n' ${posixSingleQuote(khLine)} > "$_kh" && rsync -az -s --stats -e "${sshCmd}" ${deleteFlag}${excludeFlags}-- ${posixSingleQuote(safeSrcPath)} ${posixSingleQuote(dstTarget)}`; + } else { + const sshOpt = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`; + cmd = `rsync -az -s --stats -e ${posixSingleQuote(sshOpt)} ${deleteFlag}${excludeFlags}-- ${posixSingleQuote(safeSrcPath)} ${posixSingleQuote(dstTarget)}`; + } + opts.onProgress?.(`Running direct rsync on ${srcServer.id}...`); const handle = await this.sshPool.execStream(srcServer.id, cmd, { @@ -157,8 +212,8 @@ export class TransferEngine { return { mode: 'direct', - sourcePath: opts.source.path, - destinationPath: opts.destination.path, + sourcePath: safeSrcPath, + destinationPath: safeDstPath, filesTransferred: 1, bytesTransferred: 0, durationMs: Date.now() - started, @@ -201,16 +256,21 @@ export class TransferEngine { opts.signal?.addEventListener('abort', onAbort, { once: true }); try { - const trimmedDest = opts.destination.path.trim(); + const trimmedDest = safeDstPath; const destEndsWithSlash = trimmedDest.length > 1 && trimmedDest.endsWith('/'); - const resolvedSrc = await this.resolveRemotePath(srcSftp, opts.source.path); - const resolvedDest = await this.resolveRemotePath(dstSftp, opts.destination.path); + const resolvedSrc = await this.resolveRemotePath(srcSftp, safeSrcPath); + const resolvedDest = await this.resolveRemotePath(dstSftp, safeDstPath); + + const srcStat = await promisifySftp((cb) => srcSftp.lstat(resolvedSrc, cb)); + const srcMode = srcStat.mode ?? 0; + if (!isDirMode(srcMode) && !isRegularMode(srcMode)) { + throw new Error(`Refusing SFTP transfer of non-regular/symlink source "${resolvedSrc}"`); + } - const srcStat = await promisifySftp((cb) => srcSftp.stat(resolvedSrc, cb)); let filesTransferred = 0; let bytesTransferred = 0; - if (isDirMode(srcStat.mode ?? 0)) { + if (isDirMode(srcMode)) { const dstStat = await promisifySftp((cb) => dstSftp!.stat(resolvedDest, cb)).catch( () => null, ); @@ -254,7 +314,7 @@ export class TransferEngine { dstSftp, resolvedSrc, targetFile, - srcStat.mode ?? 0o644, + srcMode || 0o644, activeStreams, () => timedOutOrAborted, opts.onProgress, @@ -341,10 +401,21 @@ export class TransferEngine { let files = 0; let bytes = 0; for (const entry of entries) { - if (entry.filename === '.' || entry.filename === '..') continue; + if ( + entry.filename === '.' || + entry.filename === '..' || + entry.filename.includes('/') || + entry.filename.includes('\0') + ) { + continue; + } const srcChild = path.posix.join(srcDir, entry.filename); const dstChild = path.posix.join(dstDir, entry.filename); - const mode = entry.attrs.mode ?? 0; + let mode = entry.attrs.mode ?? 0; + if (mode === 0) { + const ls = await promisifySftp((cb) => srcSftp.lstat(srcChild, cb)).catch(() => null); + mode = ls?.mode ?? 0; + } if (isDirMode(mode)) { const sub = await this.copyDirectoryRecursive( @@ -358,7 +429,7 @@ export class TransferEngine { ); files += sub.files; bytes += sub.bytes; - } else { + } else if (isRegularMode(mode)) { const copied = await this.copySingleFile( srcSftp, dstSftp, @@ -371,6 +442,8 @@ export class TransferEngine { ); files += 1; bytes += copied; + } else { + onProgress?.(`Skipping non-regular entry ${srcChild}`); } } return { files, bytes }; diff --git a/src/server/automation/workflow-engine.ts b/src/server/automation/workflow-engine.ts index d1de18a..7bd8312 100644 --- a/src/server/automation/workflow-engine.ts +++ b/src/server/automation/workflow-engine.ts @@ -1,17 +1,19 @@ import crypto from 'node:crypto'; import type Database from 'better-sqlite3'; import { Cron } from 'croner'; +import type { z } from 'zod'; import type { ServerConfig } from '../../shared/schemas/server.schema.js'; import type { StepDependencySchema, WorkflowConfig, WorkflowStep, } from '../../shared/schemas/workflow.schema.js'; -import type { z } from 'zod'; import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js'; import type { WsHub } from '../api/ws-hub.js'; import type { ConfigManager } from '../config/config-manager.js'; +import type { RuntimeLimits } from '../config/runtime-limits.js'; import type { AuditService } from '../security/audit.js'; +import { fetchWithEgressGuard } from '../security/egress-guard.js'; import type { VaultService } from '../security/vault.js'; import type { SftpService } from '../ssh/sftp-service.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; @@ -22,7 +24,10 @@ import { buildWorkflowEnv, interpolateShellCommandSafe, interpolateValuePlain, + maskSecretInputsForStorage, + redactWorkflowSecrets, resolveTargetServers, + resolveTemplateToken, validateAndResolveInputs, type StepOutputSummary, type TemplateContext, @@ -113,6 +118,8 @@ interface QueuedRunRequest { workflow: WorkflowConfig; triggerSource: string; inputs: Record; + maskedInputsJson: string; + secretValues: string[]; eventMeta?: Record; actorIp: string; sessionIdHash: string | null; @@ -124,9 +131,10 @@ export type FailureNotifierFn = ( channelId: string, message: string, workflowId: string, + meta?: { title?: string; severity?: 'warn' | 'critical' }, ) => Promise; -const MAX_OUTPUT_CHARS = 256 * 1024; +const MAX_HTTP_STEP_BYTES = 128 * 1024; const MAX_RETAINED_STREAM_RUNS = 30; function normalizeDep(dep: StepDependency): { @@ -137,6 +145,90 @@ function normalizeDep(dep: StepDependency): { return { stepId: dep.stepId, on: dep.on }; } +function unquoteLiteral(raw: string): string { + const s = raw.trim(); + if ( + (s.startsWith("'") && s.endsWith("'") && s.length >= 2) || + (s.startsWith('"') && s.endsWith('"') && s.length >= 2) + ) { + return s.slice(1, -1); + } + return s; +} + +function resolveWhenOperand(raw: string, ctx: TemplateContext): string { + const trimmed = raw.trim(); + if ( + (trimmed.startsWith("'") && trimmed.endsWith("'")) || + (trimmed.startsWith('"') && trimmed.endsWith('"')) + ) { + return unquoteLiteral(trimmed); + } + if (trimmed.startsWith('{{') && trimmed.endsWith('}}')) { + const inner = trimmed.slice(2, -2); + const tok = resolveTemplateToken(inner, ctx); + return tok.matched ? tok.value : ''; + } + const direct = resolveTemplateToken(trimmed, ctx); + if (direct.matched) return direct.value; + return trimmed; +} + +function evaluateStepWhen( + whenExpr: string | undefined, + deps: Array<{ stepId: string; on: 'success' | 'failure' | 'always' }>, + terminalState: Map, + ctx: TemplateContext, +): boolean { + if (!whenExpr) return true; + const expr = whenExpr.trim(); + if (!expr || expr === 'always' || expr === 'true') return true; + if (expr === 'false') return false; + if (expr === 'success') { + return deps.every((d) => terminalState.get(d.stepId) === 'succeeded'); + } + if (expr === 'failure') { + return deps.some((d) => terminalState.get(d.stepId) === 'failed'); + } + + const eqMatch = /^(.+?)\s*(==|!=)\s*(.+)$/.exec(expr); + if (eqMatch) { + const left = resolveWhenOperand(eqMatch[1]!, ctx); + const op = eqMatch[2]!; + const right = resolveWhenOperand(eqMatch[3]!, ctx); + return op === '==' ? left === right : left !== right; + } + + const negated = expr.startsWith('!'); + const inner = negated ? expr.slice(1).trim() : expr; + const val = resolveWhenOperand(inner, ctx).trim().toLowerCase(); + const truthy = val !== '' && val !== 'false' && val !== '0'; + return negated ? !truthy : truthy; +} + +async function readResponseCapped(res: Response, maxBytes = MAX_HTTP_STEP_BYTES): Promise { + if (!res.body) return ''; + const reader = res.body.getReader(); + const chunks: Buffer[] = []; + let total = 0; + try { + while (total < maxBytes) { + const { value, done } = await reader.read(); + if (done || !value) break; + const take = Math.min(value.byteLength, maxBytes - total); + chunks.push(Buffer.from(value.subarray(0, take))); + total += take; + if (total >= maxBytes) { + await reader.cancel().catch(() => undefined); + break; + } + } + } finally { + reader.releaseLock(); + } + return Buffer.concat(chunks).toString('utf8'); +} + async function runWithConcurrency( items: T[], concurrency: number, @@ -153,13 +245,33 @@ async function runWithConcurrency( await Promise.all(workers); } +async function sleepAbortable(ms: number, signal: AbortSignal): Promise { + if (ms <= 0) return; + if (signal.aborted) throw new Error('Cancelled'); + await new Promise((resolve, reject) => { + const onAbort = () => { + clearTimeout(t); + reject(new Error('Cancelled')); + }; + const t = setTimeout(() => { + signal.removeEventListener('abort', onAbort); + resolve(); + }, ms); + t.unref(); + signal.addEventListener('abort', onAbort, { once: true }); + }); +} + export class WorkflowEngine { private readonly cronJobs = new Map(); private readonly activeByWorkflow = new Map(); private readonly queueByWorkflow = new Map(); private readonly runsById = new Map(); + private readonly secretValuesByRun = new Map(); private failureNotifier: FailureNotifierFn | null = null; private closed = false; + private runningSlots = 0; + private readonly slotWaiters: Array<() => void> = []; constructor( private readonly db: Database.Database, @@ -171,6 +283,7 @@ export class WorkflowEngine { private readonly transferEngine: TransferEngine, private readonly wsHub: WsHub, private readonly auditService: AuditService, + private readonly getRuntimeLimits?: () => RuntimeLimits, ) {} setFailureNotifier(fn: FailureNotifierFn): void { @@ -180,7 +293,14 @@ export class WorkflowEngine { getStreamReplayFrames(jobId: string): ServerWsFrame[] { if (!jobId.startsWith('wf:')) return []; const runId = jobId.slice(3); - return this.runsById.get(runId)?.emitter.getReplayFrames() ?? []; + const control = this.runsById.get(runId); + if (!control) return []; + const secrets = this.secretValuesByRun.get(runId) ?? []; + return control.emitter.getReplayFrames().map((frame) => + frame.type === 'stream:chunk' + ? { ...frame, data: redactWorkflowSecrets(frame.data, secrets) } + : frame, + ); } start(): void { @@ -195,21 +315,31 @@ export class WorkflowEngine { for (const wf of this.configManager.listWorkflows()) { if (!wf.enabled || wf.trigger.type !== 'cron') continue; const wfId = wf.id; - const cron = new Cron( - wf.trigger.expression, - { - timezone: wf.trigger.timezone, - protect: true, - unref: true, - }, - () => { - if (this.closed || !this.vaultService.isRuntimeReady) return; - void this.triggerWorkflow(wfId, { - triggerSource: 'cron', - }).catch(() => undefined); - }, - ); - this.cronJobs.set(wfId, cron); + try { + const cron = new Cron( + wf.trigger.expression, + { + timezone: wf.trigger.timezone, + protect: true, + unref: true, + }, + () => { + if (this.closed || !this.vaultService.isRuntimeReady) return; + void this.triggerWorkflow(wfId, { + triggerSource: 'cron', + }).catch(() => undefined); + }, + ); + this.cronJobs.set(wfId, cron); + } catch (err) { + this.auditService.log({ + action: 'workflow.cron_error', + actorIp: 'scheduler', + target: wfId, + status: 'error', + details: { message: err instanceof Error ? err.message : String(err) }, + }); + } } } @@ -231,6 +361,9 @@ export class WorkflowEngine { for (const run of this.activeByWorkflow.values()) { this.cancelRun(run.runId, 'panic_lock'); } + while (this.slotWaiters.length > 0) { + this.slotWaiters.shift()?.(); + } } close(): void { @@ -329,7 +462,50 @@ export class WorkflowEngine { .all(capped) as WorkflowRunRecord[]; } - getRunDetail(runId: string): { + getStepLogs( + runId: string, + opts: { stepId?: string; offset?: number; limit?: number } = {}, + ): { logs: WorkflowStepLogRecord[]; total: number } { + const safeOffset = Math.max(0, Math.floor(opts.offset ?? 0)); + const safeLimit = Math.max(1, Math.min(200, Math.floor(opts.limit ?? 50))); + if (opts.stepId) { + const totalRow = this.db + .prepare('SELECT COUNT(*) AS cnt FROM workflow_step_logs WHERE run_id = ? AND step_id = ?') + .get(runId, opts.stepId) as { cnt: number }; + const logs = this.db + .prepare( + `SELECT id, run_id AS runId, step_id AS stepId, server_id AS serverId, + exit_code AS exitCode, duration_ms AS durationMs, stdout, stderr, + created_at AS createdAt + FROM workflow_step_logs + WHERE run_id = ? AND step_id = ? + ORDER BY id ASC + LIMIT ? OFFSET ?`, + ) + .all(runId, opts.stepId, safeLimit, safeOffset) as WorkflowStepLogRecord[]; + return { logs, total: totalRow.cnt }; + } + const totalRow = this.db + .prepare('SELECT COUNT(*) AS cnt FROM workflow_step_logs WHERE run_id = ?') + .get(runId) as { cnt: number }; + const logs = this.db + .prepare( + `SELECT id, run_id AS runId, step_id AS stepId, server_id AS serverId, + exit_code AS exitCode, duration_ms AS durationMs, stdout, stderr, + created_at AS createdAt + FROM workflow_step_logs + WHERE run_id = ? + ORDER BY id ASC + LIMIT ? OFFSET ?`, + ) + .all(runId, safeLimit, safeOffset) as WorkflowStepLogRecord[]; + return { logs, total: totalRow.cnt }; + } + + getRunDetail( + runId: string, + opts: { includeLogs?: boolean } = {}, + ): { run: WorkflowRunRecord; stepLogs: WorkflowStepLogRecord[]; workflow: WorkflowConfig | null; @@ -345,16 +521,19 @@ export class WorkflowEngine { .get(runId) as WorkflowRunRecord | undefined; if (!run) return null; - const stepLogs = this.db - .prepare( - `SELECT id, run_id AS runId, step_id AS stepId, server_id AS serverId, - exit_code AS exitCode, duration_ms AS durationMs, stdout, stderr, - created_at AS createdAt - FROM workflow_step_logs - WHERE run_id = ? - ORDER BY id ASC`, - ) - .all(runId) as WorkflowStepLogRecord[]; + const stepLogs = + opts.includeLogs === false + ? [] + : (this.db + .prepare( + `SELECT id, run_id AS runId, step_id AS stepId, server_id AS serverId, + exit_code AS exitCode, duration_ms AS durationMs, stdout, stderr, + created_at AS createdAt + FROM workflow_step_logs + WHERE run_id = ? + ORDER BY id ASC`, + ) + .all(runId) as WorkflowStepLogRecord[]); return { run, @@ -435,6 +614,8 @@ export class WorkflowEngine { } const inputs = validateAndResolveInputs(wf.inputs, opts.inputs ?? {}); + const { masked, secretValues } = maskSecretInputsForStorage(wf.inputs, inputs); + const maskedInputsJson = JSON.stringify(masked); const runId = `run-${crypto.randomBytes(6).toString('hex')}`; const now = Date.now(); const depth = opts.onFailureDepth ?? 0; @@ -449,7 +630,7 @@ export class WorkflowEngine { `INSERT INTO workflow_runs (run_id, workflow_id, trigger_source, status, started_at, finished_at, cancelled_by, inputs_json) VALUES (?, ?, ?, 'skipped', ?, ?, 'overlap:skip', ?)`, ) - .run(runId, wf.id, opts.triggerSource, now, now, JSON.stringify(inputs)); + .run(runId, wf.id, opts.triggerSource, now, now, maskedInputsJson); this.broadcastRunFrame({ runId, @@ -463,19 +644,26 @@ export class WorkflowEngine { } if (wf.overlapPolicy === 'queue') { + const q = this.queueByWorkflow.get(wf.id) ?? []; + const maxQueue = Math.max(1, this.getRuntimeLimits?.().maxWorkflowQueue ?? 10); + if (q.length >= maxQueue) { + throw new Error(`Workflow "${wf.id}" queue is full (${maxQueue} pending runs)`); + } + this.db .prepare( `INSERT INTO workflow_runs (run_id, workflow_id, trigger_source, status, started_at, finished_at, cancelled_by, inputs_json) VALUES (?, ?, ?, 'queued', ?, NULL, NULL, ?)`, ) - .run(runId, wf.id, opts.triggerSource, now, JSON.stringify(inputs)); + .run(runId, wf.id, opts.triggerSource, now, maskedInputsJson); - const q = this.queueByWorkflow.get(wf.id) ?? []; q.push({ runId, workflow: wf, triggerSource: opts.triggerSource, inputs, + maskedInputsJson, + secretValues, eventMeta: opts.eventMeta, actorIp, sessionIdHash, @@ -518,13 +706,15 @@ export class WorkflowEngine { `INSERT INTO workflow_runs (run_id, workflow_id, trigger_source, status, started_at, finished_at, cancelled_by, inputs_json) VALUES (?, ?, ?, 'running', ?, NULL, NULL, ?)`, ) - .run(runId, wf.id, opts.triggerSource, now, JSON.stringify(inputs)); + .run(runId, wf.id, opts.triggerSource, now, maskedInputsJson); this.startExecution({ runId, workflow: wf, triggerSource: opts.triggerSource, inputs, + maskedInputsJson, + secretValues, eventMeta: opts.eventMeta, actorIp, sessionIdHash, @@ -577,12 +767,12 @@ export class WorkflowEngine { throw new Error(`Unknown workflow "${String(workflowInput)}"`); } - const inputs = validateAndResolveInputs(wf.inputs, suppliedInputs); + const rawInputs = validateAndResolveInputs(wf.inputs, suppliedInputs); + const { masked: inputs } = maskSecretInputsForStorage(wf.inputs, rawInputs); const allServers = this.configManager.listServers(); const baseCtx: TemplateContext = { workflowId: wf.id, inputs }; const envKeys = Object.keys(buildWorkflowEnv(baseCtx)); - // Compute topological waves matching WorkflowConfigSchema DAG const waveMap = new Map(); const stepById = new Map(wf.steps.map((s) => [s.id, s])); const computeWave = (stepId: string): number => { @@ -694,8 +884,46 @@ export class WorkflowEngine { }; } + private async withGlobalWorkflowSlot( + signal: AbortSignal, + fn: () => Promise, + ): Promise { + const maxConcurrent = Math.max(1, this.getRuntimeLimits?.().maxConcurrentWorkflows ?? 2); + if (this.runningSlots >= maxConcurrent) { + await new Promise((resolve, reject) => { + if (signal.aborted) { + reject(new Error('Cancelled before acquiring workflow execution slot')); + return; + } + const wake = () => { + signal.removeEventListener('abort', onAbort); + resolve(); + }; + const onAbort = () => { + const idx = this.slotWaiters.indexOf(wake); + if (idx >= 0) this.slotWaiters.splice(idx, 1); + reject(new Error('Cancelled while waiting for workflow execution slot')); + }; + this.slotWaiters.push(wake); + signal.addEventListener('abort', onAbort, { once: true }); + }); + } + this.runningSlots += 1; + try { + return await fn(); + } finally { + this.runningSlots = Math.max(0, this.runningSlots - 1); + const next = this.slotWaiters.shift(); + if (next) next(); + } + } + private startExecution(req: QueuedRunRequest): void { - const emitter = new BufferedStreamEmitter(this.wsHub, `wf:${req.runId}`); + const emitter = new BufferedStreamEmitter( + this.wsHub, + `wf:${req.runId}`, + this.getRuntimeLimits?.().streamReplayBytes, + ); const abortController = new AbortController(); const control: ActiveRunControl = { runId: req.runId, @@ -708,6 +936,7 @@ export class WorkflowEngine { this.activeByWorkflow.set(req.workflow.id, control); this.runsById.set(req.runId, control); + this.secretValuesByRun.set(req.runId, req.secretValues); this.auditService.log({ action: 'workflow.start', @@ -733,7 +962,9 @@ export class WorkflowEngine { triggerSource: req.triggerSource, }); - void this.executeDag(req, control) + void this.withGlobalWorkflowSlot(abortController.signal, () => + this.executeDag(req, control), + ) .then((finalStatus) => { control.done = true; control.status = finalStatus; @@ -749,7 +980,10 @@ export class WorkflowEngine { }) .catch((err) => { control.done = true; - const msg = err instanceof Error ? err.message : String(err); + const msg = redactWorkflowSecrets( + err instanceof Error ? err.message : String(err), + req.secretValues, + ); emitter.push('stderr', `${msg}\n`); control.status = abortController.signal.aborted ? 'cancelled' : 'failed'; this.markRunFinished( @@ -847,6 +1081,21 @@ export class WorkflowEngine { } } + if (eligible && step.when) { + const whenCtx: TemplateContext = { + workflowId: wf.id, + runId: req.runId, + triggerSource: req.triggerSource, + inputs: req.inputs, + stepOutputs, + captures, + eventMeta: req.eventMeta, + }; + if (!evaluateStepWhen(step.when, deps, terminalState, whenCtx)) { + eligible = false; + } + } + if (!eligible) { terminalState.set(step.id, 'skipped'); madeProgress = true; @@ -855,7 +1104,7 @@ export class WorkflowEngine { madeProgress = true; const p = (async () => { - const ok = await this.runSingleStep( + const ok = await this.runStepWithRetries( wf, step, allServers, @@ -912,6 +1161,45 @@ export class WorkflowEngine { return hasFatalFailure ? 'failed' : 'succeeded'; } + private async runStepWithRetries( + wf: WorkflowConfig, + step: WorkflowStep, + allServers: ServerConfig[], + req: QueuedRunRequest, + control: ActiveRunControl, + stepOutputs: Map, + captures: Map, + ): Promise { + const maxRetries = Math.max(0, Math.min(5, step.retries ?? 0)); + const backoffMs = Math.max(500, Math.min(300_000, (step.retryBackoffSec ?? 5) * 1000)); + + for (let attempt = 0; attempt <= maxRetries; attempt++) { + const attemptOutcome = await this.runSingleStep( + wf, + step, + allServers, + req, + control, + stepOutputs, + captures, + ); + if (attemptOutcome.ok) return true; + if (attempt >= maxRetries || attemptOutcome.timedOut || control.abortController.signal.aborted) { + return false; + } + control.emitter.push( + 'stderr', + `[${step.id}] Attempt ${attempt + 1}/${maxRetries + 1} failed; retrying in ${Math.round(backoffMs / 1000)}s...\n`, + ); + try { + await sleepAbortable(backoffMs, control.abortController.signal); + } catch { + return false; + } + } + return false; + } + private async handleStepFailure( wf: WorkflowConfig, step: WorkflowStep, @@ -968,12 +1256,12 @@ export class WorkflowEngine { control: ActiveRunControl, stepOutputs: Map, captures: Map, - ): Promise { + ): Promise<{ ok: boolean; timedOut: boolean }> { const timeoutMs = (step.timeoutSec ?? 300) * 1000; const stepAbort = new AbortController(); const onParentAbort = () => stepAbort.abort(); if (control.abortController.signal.aborted) { - return false; + return { ok: false, timedOut: false }; } control.abortController.signal.addEventListener('abort', onParentAbort, { once: true }); @@ -984,16 +1272,27 @@ export class WorkflowEngine { }, timeoutMs); stepTimer.unref(); - const makeCtx = (serverId?: string): TemplateContext => ({ + const secrets = req.secretValues; + const safeEmit = (stream: 'stdout' | 'stderr', text: string) => { + control.emitter.push(stream, redactWorkflowSecrets(text, secrets)); + }; + + const makeCtx = (srv?: ServerConfig): TemplateContext => ({ workflowId: wf.id, runId: req.runId, - serverId, + triggerSource: req.triggerSource, + serverId: srv?.id, + serverMeta: srv + ? { id: srv.id, name: srv.name, host: srv.host, port: srv.port } + : undefined, inputs: req.inputs, stepOutputs, captures, eventMeta: req.eventMeta, }); + const maxTargetCap = Math.max(1, this.getRuntimeLimits?.().maxWorkflowStepTargets ?? 16); + control.emitter.pushMeta({ event: 'step-start', stepId: step.id, type: step.type }); try { @@ -1010,12 +1309,12 @@ export class WorkflowEngine { mode: step.mode, source: { serverId: srcServerId, path: srcPath }, destination: { serverId: dstServerId, path: dstPath }, + delete: step.delete, + exclude: step.exclude, sudo: step.sudo, timeoutMs, signal: stepAbort.signal, - onProgress: (msg) => { - control.emitter.push('stdout', `[${step.id}] ${msg}\n`); - }, + onProgress: (msg) => safeEmit('stdout', `[${step.id}] ${msg}\n`), }); const summaryJson = JSON.stringify(xfer); this.recordStepLog( @@ -1026,18 +1325,19 @@ export class WorkflowEngine { xfer.durationMs, summaryJson, '', + secrets, ); stepOutputs.set(step.id, { stdout: xfer.destinationPath, exitCode: 0 }); if (step.captureAs) captures.set(step.captureAs, xfer.destinationPath); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: true }); - return true; + return { ok: true, timedOut: false }; } catch (err) { const msg = timedOut ? `Step "${step.id}" timed out after ${timeoutMs}ms` : err instanceof Error ? err.message : String(err); - control.emitter.push('stderr', `[${step.id}] ${msg}\n`); + safeEmit('stderr', `[${step.id}] ${msg}\n`); this.recordStepLog( req.runId, step.id, @@ -1046,40 +1346,192 @@ export class WorkflowEngine { Date.now() - started, '', msg, + secrets, ); stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); - return false; + return { ok: false, timedOut }; } } - if (step.type === 'http' || step.type === 'notify') { - const msg = `Step type "${step.type}" handler not yet wired`; - control.emitter.push('stderr', `[${step.id}] ${msg}\n`); - this.recordStepLog(req.runId, step.id, 'hub', 1, 0, '', msg); - stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); - control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); - return false; + if (step.type === 'http') { + const started = Date.now(); + const ctx = makeCtx(); + const localSecrets = [...secrets]; + try { + const targetUrl = interpolateValuePlain(step.url, ctx).trim(); + let stepSecret: string | undefined; + if (step.secretRef) { + const cred = this.vaultService.getRuntimeSecret(step.secretRef); + if (!cred || (cred.type !== 'api-token' && cred.type !== 'webhook-secret')) { + throw new Error( + `HTTP step secretRef "${step.secretRef}" must be an api-token or webhook-secret`, + ); + } + stepSecret = cred.type === 'api-token' ? cred.token : cred.secret; + if (stepSecret) localSecrets.push(stepSecret); + } + + const headers: Record = {}; + let usedSecretInHeaders = false; + if (step.headers) { + for (const [k, v] of Object.entries(step.headers)) { + let renderedVal = interpolateValuePlain(v, ctx); + if (stepSecret && renderedVal.includes('{{secret}}')) { + renderedVal = renderedVal.split('{{secret}}').join(stepSecret); + usedSecretInHeaders = true; + } + headers[k] = renderedVal; + } + } + if (stepSecret && !usedSecretInHeaders && !Object.keys(headers).some((k) => k.toLowerCase() === 'authorization')) { + headers.Authorization = `Bearer ${stepSecret}`; + } + + let reqBody: string | undefined; + if (step.body !== undefined && step.method !== 'GET') { + reqBody = interpolateValuePlain(step.body, ctx); + if (stepSecret && reqBody.includes('{{secret}}')) { + reqBody = reqBody.split('{{secret}}').join(stepSecret); + } + if (!Object.keys(headers).some((k) => k.toLowerCase() === 'content-type')) { + headers['Content-Type'] = 'application/json'; + } + } + + const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; + const res = await fetchWithEgressGuard( + targetUrl, + { + method: step.method, + headers, + body: reqBody, + signal: stepAbort.signal, + }, + { allowedCidrs, timeoutMs }, + ); + const bodyText = redactWorkflowSecrets( + await readResponseCapped(res, MAX_HTTP_STEP_BYTES), + localSecrets, + ); + const ok = + step.expectedStatus !== undefined ? res.status === step.expectedStatus : res.ok; + + safeEmit(ok ? 'stdout' : 'stderr', `[${step.id}] HTTP ${res.status}\n${bodyText}\n`); + this.recordStepLog( + req.runId, + step.id, + 'http', + ok ? 0 : 1, + Date.now() - started, + bodyText, + ok ? '' : `HTTP status ${res.status}`, + localSecrets, + ); + stepOutputs.set(step.id, { stdout: bodyText, exitCode: ok ? 0 : 1 }); + if (step.captureAs && ok) captures.set(step.captureAs, bodyText.trim()); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok }); + return { ok, timedOut: false }; + } catch (err) { + const msg = redactWorkflowSecrets( + timedOut + ? `HTTP step timed out after ${timeoutMs}ms` + : err instanceof Error + ? err.message + : String(err), + localSecrets, + ); + safeEmit('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog( + req.runId, + step.id, + 'http', + 1, + Date.now() - started, + '', + msg, + localSecrets, + ); + stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); + return { ok: false, timedOut }; + } + } + + if (step.type === 'notify') { + const started = Date.now(); + const ctx = makeCtx(); + const title = redactWorkflowSecrets(interpolateValuePlain(step.title, ctx), secrets); + const message = redactWorkflowSecrets(interpolateValuePlain(step.message, ctx), secrets); + if (!this.failureNotifier) { + const msg = 'Alert notification handler is not wired'; + safeEmit('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, 'notify', 1, 0, '', msg, secrets); + stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); + return { ok: false, timedOut: false }; + } + try { + for (const channelId of step.channelIds) { + await this.failureNotifier(channelId, message, wf.id, { + title, + severity: step.severity, + }); + } + const summary = `Notified channels: ${step.channelIds.join(', ')}`; + safeEmit('stdout', `[${step.id}] ${summary}\n`); + this.recordStepLog( + req.runId, + step.id, + 'notify', + 0, + Date.now() - started, + summary, + '', + secrets, + ); + stepOutputs.set(step.id, { stdout: summary, exitCode: 0 }); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: true }); + return { ok: true, timedOut: false }; + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + safeEmit('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog( + req.runId, + step.id, + 'notify', + 1, + Date.now() - started, + '', + msg, + secrets, + ); + stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); + return { ok: false, timedOut: false }; + } } const targets = resolveTargetServers(step.target, allServers, makeCtx()); if (targets.length === 0) { const msg = `No enabled target servers matched step "${step.id}"`; - control.emitter.push('stderr', `[${step.id}] ${msg}\n`); - this.recordStepLog(req.runId, step.id, 'none', 1, 0, '', msg); + safeEmit('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, 'none', 1, 0, '', msg, secrets); stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); - return false; + return { ok: false, timedOut: false }; } if (step.type === 'exec') { let allOk = true; const stdouts: string[] = []; let lastExit: number | null = 0; + let lastNonZero: number | null = null; + const concurrency = Math.min(step.concurrency ?? wf.concurrency, maxTargetCap); - await runWithConcurrency(targets, step.concurrency ?? wf.concurrency, async (srv) => { + await runWithConcurrency(targets, concurrency, async (srv) => { const started = Date.now(); - const ctx = makeCtx(srv.id); + const ctx = makeCtx(srv); const env = buildWorkflowEnv(ctx); const cmd = interpolateShellCommandSafe(step.command, ctx); try { @@ -1087,8 +1539,8 @@ export class WorkflowEngine { env, sudo: step.sudo, signal: stepAbort.signal, - onStdout: (txt) => control.emitter.push('stdout', `[${step.id}@${srv.id}] ${txt}`), - onStderr: (txt) => control.emitter.push('stderr', `[${step.id}@${srv.id}] ${txt}`), + onStdout: (txt) => safeEmit('stdout', `[${step.id}@${srv.id}] ${txt}`), + onStderr: (txt) => safeEmit('stderr', `[${step.id}@${srv.id}] ${txt}`), }); this.recordStepLog( req.runId, @@ -1098,37 +1550,52 @@ export class WorkflowEngine { res.durationMs, res.stdout, res.stderr, + secrets, ); - stdouts.push(res.stdout); + stdouts.push(redactWorkflowSecrets(res.stdout, secrets)); lastExit = res.exitCode; - if (res.exitCode !== 0) allOk = false; + if (res.exitCode !== 0) { + allOk = false; + lastNonZero = res.exitCode; + } } catch (err) { allOk = false; lastExit = 1; + lastNonZero = 1; const msg = timedOut ? `Timed out after ${timeoutMs}ms` : err instanceof Error ? err.message : String(err); - control.emitter.push('stderr', `[${step.id}@${srv.id}] ${msg}\n`); - this.recordStepLog(req.runId, step.id, srv.id, 1, Date.now() - started, '', msg); + safeEmit('stderr', `[${step.id}@${srv.id}] ${msg}\n`); + this.recordStepLog( + req.runId, + step.id, + srv.id, + 1, + Date.now() - started, + '', + msg, + secrets, + ); } }); const joined = stdouts.join('\n'); - stepOutputs.set(step.id, { stdout: joined, exitCode: lastExit }); + stepOutputs.set(step.id, { stdout: joined, exitCode: lastNonZero ?? lastExit }); if (step.captureAs && allOk) captures.set(step.captureAs, joined.trim()); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: allOk }); - return allOk; + return { ok: allOk, timedOut }; } if (step.type === 'read-file') { let allOk = true; const contents: string[] = []; + const concurrency = Math.min(wf.concurrency, maxTargetCap); - await runWithConcurrency(targets, wf.concurrency, async (srv) => { + await runWithConcurrency(targets, concurrency, async (srv) => { const started = Date.now(); - const ctx = makeCtx(srv.id); + const ctx = makeCtx(srv); const remotePath = interpolateValuePlain(step.path, ctx); const tailRaw = typeof step.tailLines === 'number' @@ -1138,11 +1605,17 @@ export class WorkflowEngine { : undefined; try { + if (stepAbort.signal.aborted) { + throw new Error('Workflow step aborted'); + } let text = ''; try { const fileRes = await this.sftpService.readTextFile(srv.id, remotePath, { sudo: step.sudo, }); + if (stepAbort.signal.aborted) { + throw new Error('Workflow step aborted'); + } text = fileRes.content; if (tailRaw && Number.isFinite(tailRaw) && tailRaw > 0) { const lines = text.replace(/\n$/, '').split(/\r?\n/); @@ -1165,7 +1638,7 @@ export class WorkflowEngine { } } - control.emitter.push('stdout', `[${step.id}@${srv.id}] ${text}`); + safeEmit('stdout', `[${step.id}@${srv.id}] ${text}`); this.recordStepLog( req.runId, step.id, @@ -1174,13 +1647,23 @@ export class WorkflowEngine { Date.now() - started, text, '', + secrets, ); - contents.push(text); + contents.push(redactWorkflowSecrets(text, secrets)); } catch (err) { allOk = false; const msg = err instanceof Error ? err.message : String(err); - control.emitter.push('stderr', `[${step.id}@${srv.id}] ${msg}\n`); - this.recordStepLog(req.runId, step.id, srv.id, 1, Date.now() - started, '', msg); + safeEmit('stderr', `[${step.id}@${srv.id}] ${msg}\n`); + this.recordStepLog( + req.runId, + step.id, + srv.id, + 1, + Date.now() - started, + '', + msg, + secrets, + ); } }); @@ -1188,7 +1671,7 @@ export class WorkflowEngine { stepOutputs.set(step.id, { stdout: joined, exitCode: allOk ? 0 : 1 }); if (step.captureAs && allOk) captures.set(step.captureAs, joined.trim()); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: allOk }); - return allOk; + return { ok: allOk, timedOut }; } // system-action step @@ -1197,21 +1680,22 @@ export class WorkflowEngine { ); if (attachedTargets.length === 0) { const msg = `No matched server has system "${step.systemId}" attached`; - control.emitter.push('stderr', `[${step.id}] ${msg}\n`); - this.recordStepLog(req.runId, step.id, 'none', 1, 0, '', msg); + safeEmit('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, 'none', 1, 0, '', msg, secrets); stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); - return false; + return { ok: false, timedOut: false }; } const system = this.configManager.getSystem(step.systemId); const actionDef = system?.actions.find((a) => a.id === step.action); let allOk = true; const sysOutputs: string[] = []; + const concurrency = Math.min(step.concurrency ?? wf.concurrency, maxTargetCap); - await runWithConcurrency(attachedTargets, step.concurrency ?? wf.concurrency, async (srv) => { + await runWithConcurrency(attachedTargets, concurrency, async (srv) => { const started = Date.now(); - const ctx = makeCtx(srv.id); + const ctx = makeCtx(srv); const itemSpec = interpolateValuePlain(step.item, ctx); const subItemVal = step.subItem ? interpolateValuePlain(step.subItem, ctx) : undefined; @@ -1223,7 +1707,7 @@ export class WorkflowEngine { actionId: step.action, timeoutMs, signal: stepAbort.signal, - onChunk: (st, txt) => control.emitter.push(st, `[${step.id}@${srv.id}] ${txt}`), + onChunk: (st, txt) => safeEmit(st, `[${step.id}@${srv.id}] ${txt}`), }); this.recordStepLog( req.runId, @@ -1233,8 +1717,9 @@ export class WorkflowEngine { res.durationMs, res.stdout, res.stderr, + secrets, ); - sysOutputs.push(res.stdout); + sysOutputs.push(redactWorkflowSecrets(res.stdout, secrets)); if (res.exitCode !== 0) allOk = false; return; } @@ -1258,6 +1743,7 @@ export class WorkflowEngine { Date.now() - started, `No discovered items for ${step.systemId}`, '', + secrets, ); return; } @@ -1272,7 +1758,7 @@ export class WorkflowEngine { timeoutMs, signal: stepAbort.signal, onChunk: (st, txt) => - control.emitter.push(st, `[${step.id}@${srv.id}/${itemName}] ${txt}`), + safeEmit(st, `[${step.id}@${srv.id}/${itemName}] ${txt}`), }); this.recordStepLog( req.runId, @@ -1282,15 +1768,25 @@ export class WorkflowEngine { res.durationMs, res.stdout, res.stderr, + secrets, ); - sysOutputs.push(res.stdout); + sysOutputs.push(redactWorkflowSecrets(res.stdout, secrets)); if (res.exitCode !== 0) allOk = false; } } catch (err) { allOk = false; const msg = err instanceof Error ? err.message : String(err); - control.emitter.push('stderr', `[${step.id}@${srv.id}] ${msg}\n`); - this.recordStepLog(req.runId, step.id, srv.id, 1, Date.now() - started, '', msg); + safeEmit('stderr', `[${step.id}@${srv.id}] ${msg}\n`); + this.recordStepLog( + req.runId, + step.id, + srv.id, + 1, + Date.now() - started, + '', + msg, + secrets, + ); } }); @@ -1298,7 +1794,7 @@ export class WorkflowEngine { stepOutputs.set(step.id, { stdout: joined, exitCode: allOk ? 0 : 1 }); if (step.captureAs && allOk) captures.set(step.captureAs, joined.trim()); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: allOk }); - return allOk; + return { ok: allOk, timedOut }; } finally { clearTimeout(stepTimer); control.abortController.signal.removeEventListener('abort', onParentAbort); @@ -1320,6 +1816,7 @@ export class WorkflowEngine { throw new Error('Workflow step aborted'); } + const maxBytes = this.getRuntimeLimits?.().maxStepLogBytes ?? 256 * 1024; const started = Date.now(); const handle = await this.sshPool.execStream(serverId, command, { env: opts.env, @@ -1352,15 +1849,15 @@ export class WorkflowEngine { opts.signal.addEventListener('abort', onAbort, { once: true }); handle.channel.on('data', (chunk: Buffer) => { - if (outLen < MAX_OUTPUT_CHARS) { - outChunks.push(chunk.subarray(0, MAX_OUTPUT_CHARS - outLen)); + if (outLen < maxBytes) { + outChunks.push(chunk.subarray(0, maxBytes - outLen)); outLen += chunk.length; } opts.onStdout?.(chunk.toString('utf8')); }); handle.channel.stderr?.on('data', (chunk: Buffer) => { - if (errLen < MAX_OUTPUT_CHARS) { - errChunks.push(chunk.subarray(0, MAX_OUTPUT_CHARS - errLen)); + if (errLen < maxBytes) { + errChunks.push(chunk.subarray(0, maxBytes - errLen)); errLen += chunk.length; } opts.onStderr?.(chunk.toString('utf8')); @@ -1397,7 +1894,11 @@ export class WorkflowEngine { durationMs: number, stdout: string, stderr: string, + secrets: string[] = [], ): void { + const maxLog = this.getRuntimeLimits?.().maxStepLogBytes ?? 256 * 1024; + const cleanOut = redactWorkflowSecrets(stdout, secrets).slice(0, maxLog); + const cleanErr = redactWorkflowSecrets(stderr, secrets).slice(0, maxLog); this.db .prepare( `INSERT INTO workflow_step_logs (run_id, step_id, server_id, exit_code, duration_ms, stdout, stderr, created_at) @@ -1409,8 +1910,8 @@ export class WorkflowEngine { serverId, exitCode, Math.max(0, Math.round(durationMs)), - stdout.slice(0, MAX_OUTPUT_CHARS), - stderr.slice(0, MAX_OUTPUT_CHARS), + cleanOut, + cleanErr, Date.now(), ); } @@ -1461,6 +1962,7 @@ export class WorkflowEngine { while (doneRuns.length > MAX_RETAINED_STREAM_RUNS) { const oldest = doneRuns.shift()!; this.runsById.delete(oldest.runId); + this.secretValuesByRun.delete(oldest.runId); } } } diff --git a/src/server/ssh/known-hosts.ts b/src/server/ssh/known-hosts.ts index ab04201..6d2e6bf 100644 --- a/src/server/ssh/known-hosts.ts +++ b/src/server/ssh/known-hosts.ts @@ -49,6 +49,7 @@ export function parseHostKeyBuffer(keyBuf: Buffer): { export class KnownHostsService { private readonly pendingTofu = new Map(); private readonly pendingMismatches = new Map(); + private readonly verifiedOpenSshKeys = new Map(); private readonly listeners = new Set<() => void>(); private readonly mismatchListeners = new Set<(alert: HostKeyAlert) => void>(); @@ -96,6 +97,7 @@ export class KnownHostsService { if (exactRow.fingerprint === fingerprint) { const hadPending = this.pendingTofu.delete(server.id) || this.pendingMismatches.delete(server.id); + this.recordOpenSshKey(server, hostPortKey, algorithm, keyBuf); this.db .prepare('UPDATE known_hosts SET updated_at = ? WHERE host_port = ? AND algorithm = ?') .run(now, hostPortKey, algorithm); @@ -137,6 +139,7 @@ export class KnownHostsService { const expected = server.hostKeyFingerprint.trim(); if (expected === fingerprint) { this.upsertKnownHost(hostPortKey, algorithm, fingerprint, now); + this.recordOpenSshKey(server, hostPortKey, algorithm, keyBuf); this.pendingTofu.delete(server.id); this.pendingMismatches.delete(server.id); this.auditService?.log({ @@ -335,6 +338,22 @@ export class KnownHostsService { .run(hostPortKey, algorithm, fingerprint, now, now); } + private recordOpenSshKey( + server: Pick, + hostPortKey: string, + algorithm: string, + keyBuf: Buffer, + ): void { + const cleanHost = normalizeHostForKey(server.host); + const hostToken = server.port === 22 ? cleanHost : `${cleanHost.startsWith('[') ? cleanHost : `[${cleanHost}]`}:${server.port}`; + const line = `${hostToken} ${algorithm} ${keyBuf.toString('base64')}`; + this.verifiedOpenSshKeys.set(server.id, { hostPortKey, line }); + } + + getOpenSshKnownHostLine(server: Pick): string | undefined { + return this.verifiedOpenSshKeys.get(server.id)?.line; + } + private emitChange(): void { for (const listener of this.listeners) { try {