feat(workflows,transfers,broadcast): harden templates/rsync/SFTP-transfer, add http/notify steps, retries, secret inputs & broadcast history
This commit is contained in:
parent
d5822c9eca
commit
2b878c1d99
8 changed files with 1217 additions and 168 deletions
|
|
@ -83,10 +83,10 @@ export class AlertEngine {
|
||||||
this.stopped = false;
|
this.stopped = false;
|
||||||
this.hydrateOpenIncidents();
|
this.hydrateOpenIncidents();
|
||||||
|
|
||||||
this.workflowEngine.setFailureNotifier(async (channelId, message, _workflowId) => {
|
this.workflowEngine.setFailureNotifier(async (channelId, message, _workflowId, meta) => {
|
||||||
await this.sendDirectChannelMessage(channelId, {
|
await this.sendDirectChannelMessage(channelId, {
|
||||||
severity: 'critical',
|
severity: meta?.severity ?? 'critical',
|
||||||
title: 'Workflow Execution Failure',
|
title: meta?.title ?? 'Workflow Execution Failure',
|
||||||
message,
|
message,
|
||||||
state: 'firing',
|
state: 'firing',
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -147,7 +147,8 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router {
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/runs/:runId', requireAuth(authService), (req, res) => {
|
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) {
|
if (!detail) {
|
||||||
res.status(404).json({ error: 'RUN_NOT_FOUND' });
|
res.status(404).json({ error: 'RUN_NOT_FOUND' });
|
||||||
return;
|
return;
|
||||||
|
|
@ -155,11 +156,20 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router {
|
||||||
res.json(detail);
|
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(
|
router.post(
|
||||||
'/runs/:runId/cancel',
|
'/runs/:runId/cancel',
|
||||||
requireAuth(authService),
|
requireAuth(authService),
|
||||||
requireCsrf,
|
requireCsrf,
|
||||||
enforceSafeMode,
|
|
||||||
(req, res) => {
|
(req, res) => {
|
||||||
const runId = String(req.params.runId ?? '');
|
const runId = String(req.params.runId ?? '');
|
||||||
const cancelled = workflowEngine.cancelRun(runId, 'admin');
|
const cancelled = workflowEngine.cancelRun(runId, 'admin');
|
||||||
|
|
@ -248,6 +258,7 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router {
|
||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
.safeParse(req.body ?? {});
|
.safeParse(req.body ?? {});
|
||||||
|
|
||||||
if (!parsed.success) {
|
if (!parsed.success) {
|
||||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||||
return;
|
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) => {
|
router.get('/broadcast/:jobId', requireAuth(authService), (req, res) => {
|
||||||
const job = broadcastService.getBroadcastResult(String(req.params.jobId ?? ''));
|
const job = broadcastService.getBroadcastResult(String(req.params.jobId ?? ''));
|
||||||
if (!job) {
|
if (!job) {
|
||||||
|
|
@ -278,14 +307,22 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router {
|
||||||
res.json({ job });
|
res.json({ job });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Cancelling a running broadcast must remain available under Safe Mode
|
||||||
router.post(
|
router.post(
|
||||||
'/broadcast/:jobId/cancel',
|
'/broadcast/:jobId/cancel',
|
||||||
requireAuth(authService),
|
requireAuth(authService),
|
||||||
requireCsrf,
|
requireCsrf,
|
||||||
enforceSafeMode,
|
|
||||||
(req, res) => {
|
(req, res) => {
|
||||||
const jobId = String(req.params.jobId ?? '');
|
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 });
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -206,7 +206,7 @@ export async function createGCoordinatorServer(
|
||||||
probeRunner,
|
probeRunner,
|
||||||
getRuntimeLimits,
|
getRuntimeLimits,
|
||||||
);
|
);
|
||||||
const transferEngine = new TransferEngine(sshPool, sftpService, configManager);
|
const transferEngine = new TransferEngine(sshPool, sftpService, configManager, knownHosts);
|
||||||
const workflowEngine = new WorkflowEngine(
|
const workflowEngine = new WorkflowEngine(
|
||||||
db,
|
db,
|
||||||
configManager,
|
configManager,
|
||||||
|
|
@ -217,6 +217,7 @@ export async function createGCoordinatorServer(
|
||||||
transferEngine,
|
transferEngine,
|
||||||
wsHub,
|
wsHub,
|
||||||
auditService,
|
auditService,
|
||||||
|
getRuntimeLimits,
|
||||||
);
|
);
|
||||||
const broadcastService = new BroadcastService(
|
const broadcastService = new BroadcastService(
|
||||||
configManager,
|
configManager,
|
||||||
|
|
@ -224,6 +225,8 @@ export async function createGCoordinatorServer(
|
||||||
sshPool,
|
sshPool,
|
||||||
wsHub,
|
wsHub,
|
||||||
auditService,
|
auditService,
|
||||||
|
db,
|
||||||
|
getRuntimeLimits,
|
||||||
);
|
);
|
||||||
const alertEngine = new AlertEngine(
|
const alertEngine = new AlertEngine(
|
||||||
db,
|
db,
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
import crypto from 'node:crypto';
|
import crypto from 'node:crypto';
|
||||||
|
import type Database from 'better-sqlite3';
|
||||||
import type { ServerWsFrame } from '../../shared/ws-protocol.js';
|
import type { ServerWsFrame } from '../../shared/ws-protocol.js';
|
||||||
import type { WsHub } from '../api/ws-hub.js';
|
import type { WsHub } from '../api/ws-hub.js';
|
||||||
import type { ConfigManager } from '../config/config-manager.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 { AuditService } from '../security/audit.js';
|
||||||
import type { VaultService } from '../security/vault.js';
|
import type { VaultService } from '../security/vault.js';
|
||||||
import type { SSHPool } from '../ssh/ssh-pool.js';
|
import type { SSHPool } from '../ssh/ssh-pool.js';
|
||||||
|
|
@ -9,6 +11,8 @@ import { BufferedStreamEmitter } from './stream-buffer.js';
|
||||||
import {
|
import {
|
||||||
buildWorkflowEnv,
|
buildWorkflowEnv,
|
||||||
interpolateShellCommandSafe,
|
interpolateShellCommandSafe,
|
||||||
|
maskSecretInputsForStorage,
|
||||||
|
redactWorkflowSecrets,
|
||||||
resolveTargetServers,
|
resolveTargetServers,
|
||||||
validateAndResolveInputs,
|
validateAndResolveInputs,
|
||||||
} from './template.js';
|
} from './template.js';
|
||||||
|
|
@ -38,10 +42,14 @@ export interface BroadcastJobSummary {
|
||||||
interface ActiveBroadcastJob extends BroadcastJobSummary {
|
interface ActiveBroadcastJob extends BroadcastJobSummary {
|
||||||
emitter: BufferedStreamEmitter;
|
emitter: BufferedStreamEmitter;
|
||||||
abortController: AbortController;
|
abortController: AbortController;
|
||||||
|
secretValues: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
const MAX_RETAINED_BROADCASTS = 25;
|
function csvSafeCell(val: unknown): string {
|
||||||
const MAX_OUTPUT_PER_SERVER = 256 * 1024;
|
const s = val === null || val === undefined ? '' : String(val);
|
||||||
|
const safe = /^[=+\-@\t\r]/.test(s) ? `'${s}` : s;
|
||||||
|
return `"${safe.replace(/"/g, '""')}"`;
|
||||||
|
}
|
||||||
|
|
||||||
async function runPool<T>(
|
async function runPool<T>(
|
||||||
items: T[],
|
items: T[],
|
||||||
|
|
@ -68,6 +76,8 @@ export class BroadcastService {
|
||||||
private readonly sshPool: SSHPool,
|
private readonly sshPool: SSHPool,
|
||||||
private readonly wsHub: WsHub,
|
private readonly wsHub: WsHub,
|
||||||
private readonly auditService: AuditService,
|
private readonly auditService: AuditService,
|
||||||
|
private readonly db?: Database.Database,
|
||||||
|
private readonly getRuntimeLimits?: () => RuntimeLimits,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
getStreamReplayFrames(jobId: string): ServerWsFrame[] {
|
getStreamReplayFrames(jobId: string): ServerWsFrame[] {
|
||||||
|
|
@ -76,7 +86,7 @@ export class BroadcastService {
|
||||||
|
|
||||||
getBroadcastResult(jobId: string): BroadcastJobSummary | undefined {
|
getBroadcastResult(jobId: string): BroadcastJobSummary | undefined {
|
||||||
const job = this.jobs.get(jobId);
|
const job = this.jobs.get(jobId);
|
||||||
if (!job) return undefined;
|
if (job) {
|
||||||
return {
|
return {
|
||||||
jobId: job.jobId,
|
jobId: job.jobId,
|
||||||
snippetId: job.snippetId,
|
snippetId: job.snippetId,
|
||||||
|
|
@ -90,6 +100,167 @@ export class BroadcastService {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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: 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),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
cancelBroadcast(jobId: string): boolean {
|
cancelBroadcast(jobId: string): boolean {
|
||||||
const job = this.jobs.get(jobId);
|
const job = this.jobs.get(jobId);
|
||||||
if (!job || job.done) return false;
|
if (!job || job.done) return false;
|
||||||
|
|
@ -125,6 +296,7 @@ export class BroadcastService {
|
||||||
let rawCommand = opts.command?.trim() ?? '';
|
let rawCommand = opts.command?.trim() ?? '';
|
||||||
let sudo = Boolean(opts.sudo);
|
let sudo = Boolean(opts.sudo);
|
||||||
let resolvedInputs: Record<string, string> = {};
|
let resolvedInputs: Record<string, string> = {};
|
||||||
|
let secretValues: string[] = [];
|
||||||
|
|
||||||
if (opts.snippetId) {
|
if (opts.snippetId) {
|
||||||
const snip = this.configManager
|
const snip = this.configManager
|
||||||
|
|
@ -134,6 +306,7 @@ export class BroadcastService {
|
||||||
throw new Error(`Unknown command snippet "${opts.snippetId}"`);
|
throw new Error(`Unknown command snippet "${opts.snippetId}"`);
|
||||||
}
|
}
|
||||||
resolvedInputs = validateAndResolveInputs(snip.inputs, opts.inputs ?? {});
|
resolvedInputs = validateAndResolveInputs(snip.inputs, opts.inputs ?? {});
|
||||||
|
secretValues = maskSecretInputsForStorage(snip.inputs, resolvedInputs).secretValues;
|
||||||
rawCommand = snip.command;
|
rawCommand = snip.command;
|
||||||
sudo = opts.sudo ?? snip.sudo;
|
sudo = opts.sudo ?? snip.sudo;
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -141,14 +314,14 @@ export class BroadcastService {
|
||||||
throw new Error('Command or snippetId is required for Fleet Broadcast');
|
throw new Error('Command or snippetId is required for Fleet Broadcast');
|
||||||
}
|
}
|
||||||
if (opts.inputs) {
|
if (opts.inputs) {
|
||||||
for (const [k, v] of Object.entries(opts.inputs)) {
|
resolvedInputs = validateAndResolveInputs([], opts.inputs);
|
||||||
if (v !== undefined && v !== null) resolvedInputs[k] = String(v);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const limits = this.getRuntimeLimits?.();
|
||||||
const baseCtx = { inputs: resolvedInputs };
|
const baseCtx = { inputs: resolvedInputs };
|
||||||
const renderedCommand = interpolateShellCommandSafe(rawCommand, baseCtx);
|
const renderedCommand = interpolateShellCommandSafe(rawCommand, baseCtx);
|
||||||
|
const displayCommand = redactWorkflowSecrets(renderedCommand, secretValues);
|
||||||
const allServers = this.configManager.listServers();
|
const allServers = this.configManager.listServers();
|
||||||
|
|
||||||
let matchedServers = resolveTargetServers(opts.target, allServers, baseCtx);
|
let matchedServers = resolveTargetServers(opts.target, allServers, baseCtx);
|
||||||
|
|
@ -168,7 +341,11 @@ export class BroadcastService {
|
||||||
}
|
}
|
||||||
|
|
||||||
const jobId = `bcast-${crypto.randomBytes(6).toString('hex')}`;
|
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 abortController = new AbortController();
|
||||||
|
|
||||||
const targets: BroadcastTargetResult[] = matchedServers.map((s) => ({
|
const targets: BroadcastTargetResult[] = matchedServers.map((s) => ({
|
||||||
|
|
@ -184,7 +361,7 @@ export class BroadcastService {
|
||||||
const job: ActiveBroadcastJob = {
|
const job: ActiveBroadcastJob = {
|
||||||
jobId,
|
jobId,
|
||||||
snippetId: opts.snippetId,
|
snippetId: opts.snippetId,
|
||||||
command: renderedCommand,
|
command: displayCommand,
|
||||||
sudo,
|
sudo,
|
||||||
createdAt: Date.now(),
|
createdAt: Date.now(),
|
||||||
finishedAt: null,
|
finishedAt: null,
|
||||||
|
|
@ -193,9 +370,12 @@ export class BroadcastService {
|
||||||
targets,
|
targets,
|
||||||
emitter,
|
emitter,
|
||||||
abortController,
|
abortController,
|
||||||
|
secretValues,
|
||||||
};
|
};
|
||||||
this.jobs.set(jobId, job);
|
this.jobs.set(jobId, job);
|
||||||
|
|
||||||
|
this.persistBroadcastRow(job, 'running');
|
||||||
|
|
||||||
this.auditService.log({
|
this.auditService.log({
|
||||||
action: 'broadcast.start',
|
action: 'broadcast.start',
|
||||||
actorIp: opts.actorIp,
|
actorIp: opts.actorIp,
|
||||||
|
|
@ -211,12 +391,14 @@ export class BroadcastService {
|
||||||
emitter.pushMeta({
|
emitter.pushMeta({
|
||||||
event: 'start',
|
event: 'start',
|
||||||
jobId,
|
jobId,
|
||||||
command: renderedCommand,
|
command: displayCommand,
|
||||||
targets: targets.map((t) => ({ serverId: t.serverId, serverName: t.serverName })),
|
targets: targets.map((t) => ({ serverId: t.serverId, serverName: t.serverName })),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const maxStepLogBytes = limits?.maxStepLogBytes ?? 256 * 1024;
|
||||||
const timeoutMs = (opts.timeoutSec ?? 120) * 1000;
|
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) => {
|
void runPool(matchedServers, concurrency, async (srv) => {
|
||||||
const targetEntry = job.targets.find((t) => t.serverId === srv.id)!;
|
const targetEntry = job.targets.find((t) => t.serverId === srv.id)!;
|
||||||
|
|
@ -239,6 +421,7 @@ export class BroadcastService {
|
||||||
const env = buildWorkflowEnv({
|
const env = buildWorkflowEnv({
|
||||||
inputs: resolvedInputs,
|
inputs: resolvedInputs,
|
||||||
serverId: srv.id,
|
serverId: srv.id,
|
||||||
|
serverMeta: { id: srv.id, name: srv.name, host: srv.host, port: srv.port },
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
@ -253,9 +436,9 @@ export class BroadcastService {
|
||||||
let errBytes = 0;
|
let errBytes = 0;
|
||||||
|
|
||||||
handle.channel.on('data', (chunk: Buffer) => {
|
handle.channel.on('data', (chunk: Buffer) => {
|
||||||
const text = chunk.toString('utf8');
|
const text = redactWorkflowSecrets(chunk.toString('utf8'), secretValues);
|
||||||
if (outBytes < MAX_OUTPUT_PER_SERVER) {
|
if (outBytes < maxStepLogBytes) {
|
||||||
const slice = chunk.subarray(0, MAX_OUTPUT_PER_SERVER - outBytes);
|
const slice = chunk.subarray(0, maxStepLogBytes - outBytes);
|
||||||
outChunks.push(slice);
|
outChunks.push(slice);
|
||||||
outBytes += slice.length;
|
outBytes += slice.length;
|
||||||
}
|
}
|
||||||
|
|
@ -269,9 +452,9 @@ export class BroadcastService {
|
||||||
});
|
});
|
||||||
|
|
||||||
handle.channel.stderr?.on('data', (chunk: Buffer) => {
|
handle.channel.stderr?.on('data', (chunk: Buffer) => {
|
||||||
const text = chunk.toString('utf8');
|
const text = redactWorkflowSecrets(chunk.toString('utf8'), secretValues);
|
||||||
if (errBytes < MAX_OUTPUT_PER_SERVER) {
|
if (errBytes < maxStepLogBytes) {
|
||||||
const slice = chunk.subarray(0, MAX_OUTPUT_PER_SERVER - errBytes);
|
const slice = chunk.subarray(0, maxStepLogBytes - errBytes);
|
||||||
errChunks.push(slice);
|
errChunks.push(slice);
|
||||||
errBytes += slice.length;
|
errBytes += slice.length;
|
||||||
}
|
}
|
||||||
|
|
@ -296,8 +479,14 @@ export class BroadcastService {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { exitCode } = await handle.done;
|
const { exitCode } = await handle.done;
|
||||||
targetEntry.stdout = Buffer.concat(outChunks).toString('utf8');
|
targetEntry.stdout = redactWorkflowSecrets(
|
||||||
targetEntry.stderr = Buffer.concat(errChunks).toString('utf8');
|
Buffer.concat(outChunks).toString('utf8'),
|
||||||
|
secretValues,
|
||||||
|
);
|
||||||
|
targetEntry.stderr = redactWorkflowSecrets(
|
||||||
|
Buffer.concat(errChunks).toString('utf8'),
|
||||||
|
secretValues,
|
||||||
|
);
|
||||||
targetEntry.durationMs = Date.now() - started;
|
targetEntry.durationMs = Date.now() - started;
|
||||||
targetEntry.exitCode = exitCode;
|
targetEntry.exitCode = exitCode;
|
||||||
|
|
||||||
|
|
@ -316,7 +505,10 @@ export class BroadcastService {
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
targetEntry.durationMs = Date.now() - started;
|
targetEntry.durationMs = Date.now() - started;
|
||||||
targetEntry.status = abortController.signal.aborted ? 'cancelled' : 'error';
|
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;
|
targetEntry.stderr = targetEntry.stderr ? `${targetEntry.stderr}\n${msg}` : msg;
|
||||||
emitter.push('stderr', `[${srv.id}] ${msg}\n`);
|
emitter.push('stderr', `[${srv.id}] ${msg}\n`);
|
||||||
}
|
}
|
||||||
|
|
@ -332,6 +524,12 @@ export class BroadcastService {
|
||||||
job.done = true;
|
job.done = true;
|
||||||
job.finishedAt = Date.now();
|
job.finishedAt = Date.now();
|
||||||
const okCount = job.targets.filter((t) => t.status === 'ok').length;
|
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({
|
emitter.pushMeta({
|
||||||
event: 'done',
|
event: 'done',
|
||||||
cancelled: job.cancelled,
|
cancelled: job.cancelled,
|
||||||
|
|
@ -344,9 +542,33 @@ export class BroadcastService {
|
||||||
return this.getBroadcastResult(jobId)!;
|
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 {
|
private pruneJobs(): void {
|
||||||
|
const maxRam = Math.max(1, this.getRuntimeLimits?.().maxRamBroadcastJobs ?? 5);
|
||||||
const done = [...this.jobs.values()].filter((j) => j.done);
|
const done = [...this.jobs.values()].filter((j) => j.done);
|
||||||
while (done.length > MAX_RETAINED_BROADCASTS) {
|
while (done.length > maxRam) {
|
||||||
const oldest = done.shift()!;
|
const oldest = done.shift()!;
|
||||||
this.jobs.delete(oldest.jobId);
|
this.jobs.delete(oldest.jobId);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -10,13 +10,17 @@ export interface StepOutputSummary {
|
||||||
export interface TemplateContext {
|
export interface TemplateContext {
|
||||||
workflowId?: string;
|
workflowId?: string;
|
||||||
runId?: string;
|
runId?: string;
|
||||||
|
triggerSource?: string;
|
||||||
serverId?: string;
|
serverId?: string;
|
||||||
|
serverMeta?: { id: string; name: string; host: string; port: number };
|
||||||
inputs: Record<string, string>;
|
inputs: Record<string, string>;
|
||||||
stepOutputs?: Map<string, StepOutputSummary>;
|
stepOutputs?: Map<string, StepOutputSummary>;
|
||||||
captures?: Map<string, string>;
|
captures?: Map<string, string>;
|
||||||
eventMeta?: Record<string, string>;
|
eventMeta?: Record<string, string>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
||||||
|
|
||||||
export function toEnvIdent(raw: string): string {
|
export function toEnvIdent(raw: string): string {
|
||||||
return raw.replace(/[^A-Za-z0-9]/g, '_').toUpperCase();
|
return raw.replace(/[^A-Za-z0-9]/g, '_').toUpperCase();
|
||||||
}
|
}
|
||||||
|
|
@ -27,8 +31,15 @@ export function validateAndResolveInputs(
|
||||||
): Record<string, string> {
|
): Record<string, string> {
|
||||||
const out: Record<string, string> = {};
|
const out: Record<string, string> = {};
|
||||||
|
|
||||||
|
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) {
|
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 hasSupplied = raw !== undefined && raw !== null && raw !== '';
|
||||||
const candidate = hasSupplied ? raw : def.default;
|
const candidate = hasSupplied ? raw : def.default;
|
||||||
|
|
||||||
|
|
@ -61,6 +72,9 @@ export function validateAndResolveInputs(
|
||||||
}
|
}
|
||||||
|
|
||||||
const strVal = String(candidate);
|
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.type === 'select' && def.options && def.options.length > 0) {
|
||||||
if (!def.options.includes(strVal)) {
|
if (!def.options.includes(strVal)) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
|
|
@ -72,14 +86,48 @@ export function validateAndResolveInputs(
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const [k, v] of Object.entries(supplied)) {
|
for (const [k, v] of Object.entries(supplied)) {
|
||||||
if (!(k in out) && v !== undefined && v !== null) {
|
if (FORBIDDEN_KEYS.has(k)) continue;
|
||||||
out[k] = String(v);
|
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;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function maskSecretInputsForStorage(
|
||||||
|
defs: InputDef[],
|
||||||
|
resolved: Record<string, string>,
|
||||||
|
): { masked: Record<string, string>; secretValues: string[] } {
|
||||||
|
const secretKeys = new Set(defs.filter((d) => d.type === 'secret').map((d) => d.name));
|
||||||
|
const masked: Record<string, string> = {};
|
||||||
|
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<string, string> {
|
export function buildWorkflowEnv(ctx: TemplateContext): Record<string, string> {
|
||||||
const env: Record<string, string> = {};
|
const env: Record<string, string> = {};
|
||||||
if (ctx.workflowId) env.GCOORD_WORKFLOW_ID = ctx.workflowId;
|
if (ctx.workflowId) env.GCOORD_WORKFLOW_ID = ctx.workflowId;
|
||||||
|
|
@ -87,6 +135,7 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record<string, string> {
|
||||||
if (ctx.serverId) env.GCOORD_SERVER_ID = ctx.serverId;
|
if (ctx.serverId) env.GCOORD_SERVER_ID = ctx.serverId;
|
||||||
|
|
||||||
for (const [k, v] of Object.entries(ctx.inputs)) {
|
for (const [k, v] of Object.entries(ctx.inputs)) {
|
||||||
|
if (FORBIDDEN_KEYS.has(k)) continue;
|
||||||
env[`GCOORD_INPUT_${toEnvIdent(k)}`] = v;
|
env[`GCOORD_INPUT_${toEnvIdent(k)}`] = v;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -106,6 +155,7 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record<string, string> {
|
||||||
|
|
||||||
if (ctx.eventMeta) {
|
if (ctx.eventMeta) {
|
||||||
for (const [k, v] of Object.entries(ctx.eventMeta)) {
|
for (const [k, v] of Object.entries(ctx.eventMeta)) {
|
||||||
|
if (FORBIDDEN_KEYS.has(k)) continue;
|
||||||
env[`GCOORD_EVENT_${toEnvIdent(k)}`] = v;
|
env[`GCOORD_EVENT_${toEnvIdent(k)}`] = v;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -113,45 +163,188 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record<string, string> {
|
||||||
return env;
|
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();
|
const expr = rawExpr.trim();
|
||||||
if (expr.startsWith('inputs.')) {
|
if (!expr || expr.startsWith('.')) return { matched: false, value: '' };
|
||||||
const key = expr.slice('inputs.'.length);
|
const parts = expr.split('.');
|
||||||
return ctx.inputs[key] ?? '';
|
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('.');
|
const dot = rest.lastIndexOf('.');
|
||||||
if (dot > 0) {
|
if (dot > 0) {
|
||||||
const stepId = rest.slice(0, dot);
|
const stepId = rest.slice(0, dot);
|
||||||
const field = rest.slice(dot + 1);
|
const field = rest.slice(dot + 1);
|
||||||
const out = ctx.stepOutputs?.get(stepId);
|
const out = ctx.stepOutputs?.get(stepId);
|
||||||
if (!out) return '';
|
if (field === 'stdout') return { matched: true, value: out ? out.stdout.trim() : '' };
|
||||||
if (field === 'stdout') return out.stdout.trim();
|
if (field === 'exitCode') {
|
||||||
if (field === 'exitCode') return out.exitCode === null ? '' : String(out.exitCode);
|
return {
|
||||||
|
matched: true,
|
||||||
|
value: out && out.exitCode !== null ? String(out.exitCode) : '',
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (expr.startsWith('captures.')) {
|
return { matched: false, value: '' };
|
||||||
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.')) {
|
if (expr.startsWith('event.')) {
|
||||||
const key = expr.slice('event.'.length);
|
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 {
|
export function interpolateValuePlain(template: string, ctx: TemplateContext): string {
|
||||||
return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) =>
|
return template.replace(/\{\{([^{}]+)\}\}/g, (full, expr: string) => {
|
||||||
resolveTemplateToken(expr, ctx),
|
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 {
|
export function interpolateShellCommandSafe(template: string, ctx: TemplateContext): string {
|
||||||
return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) =>
|
let out = '';
|
||||||
posixSingleQuote(resolveTemplateToken(expr, ctx)),
|
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(
|
export function resolveTargetServers(
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ import crypto from 'node:crypto';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import type { FileEntryWithStats, SFTPWrapper, Stats } from 'ssh2';
|
import type { FileEntryWithStats, SFTPWrapper, Stats } from 'ssh2';
|
||||||
import type { ConfigManager } from '../config/config-manager.js';
|
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 { SftpService } from '../ssh/sftp-service.js';
|
||||||
import type { SSHPool } from '../ssh/ssh-pool.js';
|
import type { SSHPool } from '../ssh/ssh-pool.js';
|
||||||
import { posixSingleQuote } from '../ssh/sudo.js';
|
import { posixSingleQuote } from '../ssh/sudo.js';
|
||||||
|
|
@ -15,8 +16,42 @@ export interface TransferResult {
|
||||||
durationMs: number;
|
durationMs: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const FILE_TYPE_MASK = 0o170000;
|
||||||
|
const MODE_DIR = 0o040000;
|
||||||
|
const MODE_REG = 0o100000;
|
||||||
|
|
||||||
function isDirMode(mode: number): boolean {
|
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<T>(
|
function promisifySftp<T>(
|
||||||
|
|
@ -46,6 +81,7 @@ export class TransferEngine {
|
||||||
private readonly sshPool: SSHPool,
|
private readonly sshPool: SSHPool,
|
||||||
private readonly _sftpService: SftpService,
|
private readonly _sftpService: SftpService,
|
||||||
private readonly configManager: ConfigManager,
|
private readonly configManager: ConfigManager,
|
||||||
|
private readonly knownHosts?: KnownHostsService,
|
||||||
) {
|
) {
|
||||||
void this._sftpService;
|
void this._sftpService;
|
||||||
}
|
}
|
||||||
|
|
@ -54,6 +90,8 @@ export class TransferEngine {
|
||||||
mode: 'hub-relayed' | 'direct';
|
mode: 'hub-relayed' | 'direct';
|
||||||
source: { serverId: string; path: string };
|
source: { serverId: string; path: string };
|
||||||
destination: { serverId: string; path: string };
|
destination: { serverId: string; path: string };
|
||||||
|
delete?: boolean;
|
||||||
|
exclude?: string[];
|
||||||
sudo?: boolean;
|
sudo?: boolean;
|
||||||
timeoutMs?: number;
|
timeoutMs?: number;
|
||||||
signal?: AbortSignal;
|
signal?: AbortSignal;
|
||||||
|
|
@ -72,12 +110,29 @@ export class TransferEngine {
|
||||||
throw new Error(`Destination server "${opts.destination.serverId}" not found or disabled`);
|
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 started = Date.now();
|
||||||
const timeoutMs = opts.timeoutMs ?? 600_000;
|
const timeoutMs = opts.timeoutMs ?? 600_000;
|
||||||
|
|
||||||
if (opts.mode === 'direct') {
|
if (opts.mode === 'direct') {
|
||||||
|
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`;
|
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}`)}`;
|
cmd = `rsync -az -s --stats -e ${posixSingleQuote(sshOpt)} ${deleteFlag}${excludeFlags}-- ${posixSingleQuote(safeSrcPath)} ${posixSingleQuote(dstTarget)}`;
|
||||||
|
}
|
||||||
|
|
||||||
opts.onProgress?.(`Running direct rsync on ${srcServer.id}...`);
|
opts.onProgress?.(`Running direct rsync on ${srcServer.id}...`);
|
||||||
|
|
||||||
const handle = await this.sshPool.execStream(srcServer.id, cmd, {
|
const handle = await this.sshPool.execStream(srcServer.id, cmd, {
|
||||||
|
|
@ -157,8 +212,8 @@ export class TransferEngine {
|
||||||
|
|
||||||
return {
|
return {
|
||||||
mode: 'direct',
|
mode: 'direct',
|
||||||
sourcePath: opts.source.path,
|
sourcePath: safeSrcPath,
|
||||||
destinationPath: opts.destination.path,
|
destinationPath: safeDstPath,
|
||||||
filesTransferred: 1,
|
filesTransferred: 1,
|
||||||
bytesTransferred: 0,
|
bytesTransferred: 0,
|
||||||
durationMs: Date.now() - started,
|
durationMs: Date.now() - started,
|
||||||
|
|
@ -201,16 +256,21 @@ export class TransferEngine {
|
||||||
opts.signal?.addEventListener('abort', onAbort, { once: true });
|
opts.signal?.addEventListener('abort', onAbort, { once: true });
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const trimmedDest = opts.destination.path.trim();
|
const trimmedDest = safeDstPath;
|
||||||
const destEndsWithSlash = trimmedDest.length > 1 && trimmedDest.endsWith('/');
|
const destEndsWithSlash = trimmedDest.length > 1 && trimmedDest.endsWith('/');
|
||||||
const resolvedSrc = await this.resolveRemotePath(srcSftp, opts.source.path);
|
const resolvedSrc = await this.resolveRemotePath(srcSftp, safeSrcPath);
|
||||||
const resolvedDest = await this.resolveRemotePath(dstSftp, opts.destination.path);
|
const resolvedDest = await this.resolveRemotePath(dstSftp, safeDstPath);
|
||||||
|
|
||||||
|
const srcStat = await promisifySftp<Stats>((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<Stats>((cb) => srcSftp.stat(resolvedSrc, cb));
|
|
||||||
let filesTransferred = 0;
|
let filesTransferred = 0;
|
||||||
let bytesTransferred = 0;
|
let bytesTransferred = 0;
|
||||||
|
|
||||||
if (isDirMode(srcStat.mode ?? 0)) {
|
if (isDirMode(srcMode)) {
|
||||||
const dstStat = await promisifySftp<Stats>((cb) => dstSftp!.stat(resolvedDest, cb)).catch(
|
const dstStat = await promisifySftp<Stats>((cb) => dstSftp!.stat(resolvedDest, cb)).catch(
|
||||||
() => null,
|
() => null,
|
||||||
);
|
);
|
||||||
|
|
@ -254,7 +314,7 @@ export class TransferEngine {
|
||||||
dstSftp,
|
dstSftp,
|
||||||
resolvedSrc,
|
resolvedSrc,
|
||||||
targetFile,
|
targetFile,
|
||||||
srcStat.mode ?? 0o644,
|
srcMode || 0o644,
|
||||||
activeStreams,
|
activeStreams,
|
||||||
() => timedOutOrAborted,
|
() => timedOutOrAborted,
|
||||||
opts.onProgress,
|
opts.onProgress,
|
||||||
|
|
@ -341,10 +401,21 @@ export class TransferEngine {
|
||||||
let files = 0;
|
let files = 0;
|
||||||
let bytes = 0;
|
let bytes = 0;
|
||||||
for (const entry of entries) {
|
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 srcChild = path.posix.join(srcDir, entry.filename);
|
||||||
const dstChild = path.posix.join(dstDir, 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<Stats>((cb) => srcSftp.lstat(srcChild, cb)).catch(() => null);
|
||||||
|
mode = ls?.mode ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
if (isDirMode(mode)) {
|
if (isDirMode(mode)) {
|
||||||
const sub = await this.copyDirectoryRecursive(
|
const sub = await this.copyDirectoryRecursive(
|
||||||
|
|
@ -358,7 +429,7 @@ export class TransferEngine {
|
||||||
);
|
);
|
||||||
files += sub.files;
|
files += sub.files;
|
||||||
bytes += sub.bytes;
|
bytes += sub.bytes;
|
||||||
} else {
|
} else if (isRegularMode(mode)) {
|
||||||
const copied = await this.copySingleFile(
|
const copied = await this.copySingleFile(
|
||||||
srcSftp,
|
srcSftp,
|
||||||
dstSftp,
|
dstSftp,
|
||||||
|
|
@ -371,6 +442,8 @@ export class TransferEngine {
|
||||||
);
|
);
|
||||||
files += 1;
|
files += 1;
|
||||||
bytes += copied;
|
bytes += copied;
|
||||||
|
} else {
|
||||||
|
onProgress?.(`Skipping non-regular entry ${srcChild}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { files, bytes };
|
return { files, bytes };
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -49,6 +49,7 @@ export function parseHostKeyBuffer(keyBuf: Buffer): {
|
||||||
export class KnownHostsService {
|
export class KnownHostsService {
|
||||||
private readonly pendingTofu = new Map<string, PendingTofuInfo>();
|
private readonly pendingTofu = new Map<string, PendingTofuInfo>();
|
||||||
private readonly pendingMismatches = new Map<string, HostKeyAlert>();
|
private readonly pendingMismatches = new Map<string, HostKeyAlert>();
|
||||||
|
private readonly verifiedOpenSshKeys = new Map<string, { hostPortKey: string; line: string }>();
|
||||||
private readonly listeners = new Set<() => void>();
|
private readonly listeners = new Set<() => void>();
|
||||||
private readonly mismatchListeners = new Set<(alert: HostKeyAlert) => void>();
|
private readonly mismatchListeners = new Set<(alert: HostKeyAlert) => void>();
|
||||||
|
|
||||||
|
|
@ -96,6 +97,7 @@ export class KnownHostsService {
|
||||||
if (exactRow.fingerprint === fingerprint) {
|
if (exactRow.fingerprint === fingerprint) {
|
||||||
const hadPending =
|
const hadPending =
|
||||||
this.pendingTofu.delete(server.id) || this.pendingMismatches.delete(server.id);
|
this.pendingTofu.delete(server.id) || this.pendingMismatches.delete(server.id);
|
||||||
|
this.recordOpenSshKey(server, hostPortKey, algorithm, keyBuf);
|
||||||
this.db
|
this.db
|
||||||
.prepare('UPDATE known_hosts SET updated_at = ? WHERE host_port = ? AND algorithm = ?')
|
.prepare('UPDATE known_hosts SET updated_at = ? WHERE host_port = ? AND algorithm = ?')
|
||||||
.run(now, hostPortKey, algorithm);
|
.run(now, hostPortKey, algorithm);
|
||||||
|
|
@ -137,6 +139,7 @@ export class KnownHostsService {
|
||||||
const expected = server.hostKeyFingerprint.trim();
|
const expected = server.hostKeyFingerprint.trim();
|
||||||
if (expected === fingerprint) {
|
if (expected === fingerprint) {
|
||||||
this.upsertKnownHost(hostPortKey, algorithm, fingerprint, now);
|
this.upsertKnownHost(hostPortKey, algorithm, fingerprint, now);
|
||||||
|
this.recordOpenSshKey(server, hostPortKey, algorithm, keyBuf);
|
||||||
this.pendingTofu.delete(server.id);
|
this.pendingTofu.delete(server.id);
|
||||||
this.pendingMismatches.delete(server.id);
|
this.pendingMismatches.delete(server.id);
|
||||||
this.auditService?.log({
|
this.auditService?.log({
|
||||||
|
|
@ -335,6 +338,22 @@ export class KnownHostsService {
|
||||||
.run(hostPortKey, algorithm, fingerprint, now, now);
|
.run(hostPortKey, algorithm, fingerprint, now, now);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private recordOpenSshKey(
|
||||||
|
server: Pick<ServerConfig, 'id' | 'host' | 'port'>,
|
||||||
|
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<ServerConfig, 'id'>): string | undefined {
|
||||||
|
return this.verifiedOpenSshKeys.get(server.id)?.line;
|
||||||
|
}
|
||||||
|
|
||||||
private emitChange(): void {
|
private emitChange(): void {
|
||||||
for (const listener of this.listeners) {
|
for (const listener of this.listeners) {
|
||||||
try {
|
try {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue