diff --git a/src/server/api/routes/config.routes.ts b/src/server/api/routes/config.routes.ts index ef1b955..b9c6eef 100644 --- a/src/server/api/routes/config.routes.ts +++ b/src/server/api/routes/config.routes.ts @@ -1,8 +1,9 @@ +import crypto from 'node:crypto'; import { Router, type RequestHandler } from 'express'; import { ZodError, z } from 'zod'; import type { ConfigManager } from '../../config/config-manager.js'; import type { AuditService } from '../../security/audit.js'; -import type { AuthService } from '../../security/auth.js'; +import { sha256Hex, type AuthService } from '../../security/auth.js'; import { enforceSafeMode, requireAuth, @@ -237,5 +238,50 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router { }, ); + router.post( + '/prometheus-token', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + (req, res) => { + const parsed = z + .object({ enable: z.boolean().optional() }) + .safeParse(req.body ?? {}); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + const token = crypto.randomBytes(32).toString('base64url'); + const tokenHash = sha256Hex(token); + const next = structuredClone(configManager.getSettings()); + next.metrics.prometheusTokenHash = tokenHash; + if (parsed.data.enable !== undefined) { + next.metrics.prometheusEnabled = parsed.data.enable; + } else { + next.metrics.prometheusEnabled = true; + } + configManager.saveConfigText( + 'settings.json', + JSON.stringify(next, null, 2), + 'ui', + 'Rotate Prometheus metrics Bearer token', + ); + auditService.log({ + action: 'metrics.prometheus_token_rotate', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: 'settings.json', + status: 'ok', + details: { prometheusEnabled: next.metrics.prometheusEnabled }, + }); + res.json({ + token, + tokenHash, + prometheusEnabled: next.metrics.prometheusEnabled, + }); + }, + ); + return router; } diff --git a/src/server/api/routes/servers.routes.ts b/src/server/api/routes/servers.routes.ts index d91ba04..b177717 100644 --- a/src/server/api/routes/servers.routes.ts +++ b/src/server/api/routes/servers.routes.ts @@ -548,23 +548,140 @@ export function createServersRouter(deps: ServersRouterDeps): Router { }); }); - router.get('/:id/inspect', requireAuth(authService), async (req, res) => { + router.get('/:id/inspect', requireAuth(authService), (req, res) => { const id = String(req.params.id ?? ''); if (!configManager.getServer(id)) { res.status(404).json({ error: 'SERVER_NOT_FOUND' }); return; } - try { - const result = await serverInspector.inspect(id); - res.json(result); - } catch (err) { - res.status(502).json({ - error: 'INSPECT_FAILED', - message: err instanceof Error ? err.message : 'Server inspection failed', + const sort = String(req.query.sort ?? 'cpu') === 'mem' ? 'mem' : 'cpu'; + const useSudo = req.query.sudo === 'true' || req.query.sudo === '1'; + + const executeInspect = async () => { + try { + const result = await serverInspector.inspect(id, { sort, useSudo }); + res.json(result); + } catch (err) { + res.status(502).json({ + error: 'INSPECT_FAILED', + message: err instanceof Error ? err.message : 'Server inspection failed', + }); + } + }; + + if (useSudo) { + stepUpGuard(req, res, () => { + void executeInspect(); }); + return; } + void executeInspect(); }); + router.post( + '/:id/processes/:pid/signal', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + async (req, res) => { + const id = String(req.params.id ?? ''); + if (!configManager.getServer(id)) { + res.status(404).json({ error: 'SERVER_NOT_FOUND' }); + return; + } + const rawPid = String(req.params.pid ?? ''); + if (!/^[1-9][0-9]{0,7}$/.test(rawPid)) { + res.status(400).json({ error: 'INVALID_PID' }); + return; + } + const parsed = z + .object({ + signal: z.enum(['SIGTERM', 'SIGKILL']).default('SIGTERM'), + sudo: z.boolean().optional(), + }) + .safeParse(req.body ?? {}); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + const pid = Number(rawPid); + try { + const result = await serverInspector.signalProcess(id, pid, parsed.data.signal, { + useSudo: parsed.data.sudo, + }); + auditService.log({ + action: 'server.process_signal', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: `${id}:${pid}`, + status: result.ok ? 'ok' : 'error', + details: { signal: parsed.data.signal, sudo: Boolean(parsed.data.sudo) }, + }); + res.json(result); + } catch (err) { + res.status(400).json({ + error: 'SIGNAL_FAILED', + message: err instanceof Error ? err.message : 'Unable to send process signal', + }); + } + }, + ); + + router.get('/:id/probes/history', requireAuth(authService), (req, res) => { + const id = String(req.params.id ?? ''); + if (!configManager.getServer(id)) { + res.status(404).json({ error: 'SERVER_NOT_FOUND' }); + return; + } + const rawRange = String(req.query.range ?? '24h') as MetricRange; + const hoursMap: Record = { + '1h': 1, + '6h': 6, + '24h': 24, + '7d': 168, + '30d': 720, + }; + const hours = hoursMap[rawRange] ?? 24; + const limit = Math.max(1, Math.min(1000, Number(req.query.limit) || 200)); + const samples = monitoringService.queryProbeHistory( + id, + Date.now() - hours * 3600_000, + limit, + ); + res.json({ serverId: id, samples }); + }); + + router.post( + '/:id/probes/:probeId/run', + requireAuth(authService), + requireCsrf, + async (req, res) => { + const id = String(req.params.id ?? ''); + const probeId = String(req.params.probeId ?? ''); + if (!configManager.getServer(id)) { + res.status(404).json({ error: 'SERVER_NOT_FOUND' }); + return; + } + try { + const sample = await monitoringService.runProbeNow(id, probeId); + auditService.log({ + action: 'server.probe_run', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: `${id}:${probeId}`, + status: sample.ok ? 'ok' : 'error', + }); + res.json({ serverId: id, sample }); + } catch (err) { + res.status(404).json({ + error: 'PROBE_RUN_FAILED', + message: err instanceof Error ? err.message : 'Unable to run probe', + }); + } + }, + ); + router.get('/:id/keys', requireAuth(authService), async (req, res) => { const id = String(req.params.id ?? ''); if (!configManager.getServer(id)) { diff --git a/src/server/app.ts b/src/server/app.ts index fb19dc9..b51d6b0 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -15,6 +15,7 @@ import { applyDatabaseThrottlePragmas, openDatabase } from './db/database.js'; import { ServerInspector } from './monitoring/inspector.js'; import { MonitoringService } from './monitoring/monitoring-service.js'; import { ProbeRunner } from './monitoring/probes.js'; +import { createPrometheusHandler } from './monitoring/prometheus.js'; import { AuditService } from './security/audit.js'; import { AuthService } from './security/auth.js'; import { BackupScheduler } from './security/backup-scheduler.js'; @@ -195,13 +196,14 @@ export async function createGCoordinatorServer( wsHub, ); const serverInspector = new ServerInspector(sshPool, configManager); - const probeRunner = new ProbeRunner(sshPool); + const probeRunner = new ProbeRunner(sshPool, configManager); const monitoringService = new MonitoringService( db, configManager, vaultService, sshPool, probeRunner, + getRuntimeLimits, ); const transferEngine = new TransferEngine(sshPool, sftpService, configManager); const workflowEngine = new WorkflowEngine( @@ -612,6 +614,17 @@ export async function createGCoordinatorServer( createConfigRouter({ authService, configManager, auditService, stepUpGuard }), ); app.use('/api/audit', createAuditRouter(authService, auditService)); + app.get( + '/metrics', + createPrometheusHandler({ + configManager, + vaultService, + sshPool, + monitoringService, + tunnelManager, + alertEngine, + }), + ); app.use('/api', (_req, res) => { res.status(404).json({ error: 'API_ROUTE_NOT_FOUND' }); diff --git a/src/server/monitoring/collectors.ts b/src/server/monitoring/collectors.ts index b1a7220..5faee22 100644 --- a/src/server/monitoring/collectors.ts +++ b/src/server/monitoring/collectors.ts @@ -56,20 +56,67 @@ export const LINUX_METRIC_CMD = [ ].join('; '); export const BSD_METRIC_CMD = [ - 'printf "===SYSCTL===\\n"; sysctl -n hw.physmem hw.pagesize vm.loadavg kern.boottime kern.cp_time 2>/dev/null', + 'printf "===SYSCTL===\\n"; sysctl hw.physmem hw.pagesize vm.loadavg kern.boottime kern.cp_time 2>/dev/null || true', 'printf "===VMSTAT===\\n"; vmstat -H 2>/dev/null || vmstat', 'printf "===NET===\\n"; netstat -ibn 2>/dev/null', 'printf "===DF===\\n"; df -kT 2>/dev/null || df -kP', ].join('; '); export const MACOS_METRIC_CMD = [ - 'printf "===SYSCTL===\\n"; sysctl -n hw.memsize hw.pagesize vm.loadavg kern.boottime', + 'printf "===SYSCTL===\\n"; sysctl hw.memsize hw.pagesize vm.loadavg kern.boottime 2>/dev/null || true', 'printf "===VMSTAT===\\n"; vm_stat', 'printf "===TOP===\\n"; top -l 1 -n 0 2>/dev/null | grep -i "CPU usage" || true', 'printf "===NET===\\n"; netstat -ibn 2>/dev/null || netstat -ib', 'printf "===DF===\\n"; df -kP', ].join('; '); +const VIRTUAL_NIC_PREFIXES = [ + 'lo', + 'veth', + 'docker', + 'br-', + 'tun', + 'tap', + 'wg', + 'virbr', + 'dummy', + 'cilium', + 'flannel', + 'cni', + 'vxlan', + 'ifb', +]; + +function isVirtualNic(iface: string): boolean { + const clean = iface.trim().replace(/:$/, '').toLowerCase(); + return VIRTUAL_NIC_PREFIXES.some( + (p) => clean === p || (p.endsWith('-') ? clean.startsWith(p) : clean.startsWith(p)), + ); +} + +/** + * Parse `sysctl` sections supporting both `key: val` / `key=val` (resilient to + * missing keys across BSD/macOS versions) and legacy unlabeled positional lines. + */ +function parseSysctlMap(rawText: string, positionalKeys: string[]): Map { + const out = new Map(); + const lines = rawText + .split(/\r?\n/) + .map((l) => l.trim()) + .filter(Boolean); + let posIdx = 0; + for (const line of lines) { + const kv = /^([a-zA-Z][a-zA-Z0-9_.]*)\s*[:=]\s*(.+)$/.exec(line); + if (kv) { + out.set(kv[1]!, kv[2]!.trim()); + } else if (posIdx < positionalKeys.length) { + out.set(positionalKeys[posIdx]!, line); + posIdx += 1; + } + } + return out; +} + function splitSections(stdout: string): Record { const sections: Record = {}; let current = ''; @@ -137,6 +184,7 @@ function parseDfLines( if ( fsName === 'devfs' || fsName === 'map' || + fsName.startsWith('/dev/loop') || !Number.isFinite(totalKb) || totalKb <= 0 ) { @@ -205,9 +253,12 @@ export function parseLinuxOutput( Math.floor(Number((sec.UPTIME ?? '0').trim().split(/\s+/)[0]) || 0), ); - // Network RX/TX across non-loopback interfaces - let netRxBytes = 0; - let netTxBytes = 0; + // Network RX/TX prioritizing physical NICs and excluding loopback/virtual bridges + let physRxBytes = 0; + let physTxBytes = 0; + let hasPhys = false; + let fallbackRxBytes = 0; + let fallbackTxBytes = 0; for (const line of (sec.NET ?? '').split(/\r?\n/)) { const colon = line.indexOf(':'); if (colon <= 0) continue; @@ -215,10 +266,19 @@ export function parseLinuxOutput( if (iface === 'lo' || iface.startsWith('lo:')) continue; const cols = line.slice(colon + 1).trim().split(/\s+/); if (cols.length >= 9) { - netRxBytes += Number(cols[0]) || 0; - netTxBytes += Number(cols[8]) || 0; + const rx = Number(cols[0]) || 0; + const tx = Number(cols[8]) || 0; + fallbackRxBytes += rx; + fallbackTxBytes += tx; + if (!isVirtualNic(iface)) { + hasPhys = true; + physRxBytes += rx; + physTxBytes += tx; + } } } + const netRxBytes = hasPhys ? physRxBytes : fallbackRxBytes; + const netTxBytes = hasPhys ? physTxBytes : fallbackTxBytes; let netRxBps = 0; let netTxBps = 0; @@ -267,25 +327,28 @@ export function parseBsdOutput( nowMs = Date.now(), ): CollectOutput { const sec = splitSections(stdout); - const sysctlLines = (sec.SYSCTL ?? '') - .split(/\r?\n/) - .map((l) => l.trim()) - .filter(Boolean); + const sysctl = parseSysctlMap(sec.SYSCTL ?? '', [ + 'hw.physmem', + 'hw.pagesize', + 'vm.loadavg', + 'kern.boottime', + 'kern.cp_time', + ]); - const physMemBytes = Number(sysctlLines[0]) || 0; - const pageSize = Number(sysctlLines[1]) || 4096; - const loadMatch = /([\d.]+)/.exec(sysctlLines[2] ?? '0'); + const physMemBytes = Number(sysctl.get('hw.physmem')) || 0; + const pageSize = Number(sysctl.get('hw.pagesize')) || 4096; + const loadMatch = /([\d.]+)/.exec(sysctl.get('vm.loadavg') ?? '0'); const load1m = round2(Number(loadMatch?.[1] ?? 0)); let uptimeSec = 0; - const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctlLines[3] ?? ''); + const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctl.get('kern.boottime') ?? ''); if (bootSecMatch) { uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!)); } let cpuTotal = 0; let cpuIdle = 0; - const cpNums = (sysctlLines[4] ?? '') + const cpNums = (sysctl.get('kern.cp_time') ?? '') .split(/\s+/) .map((n) => Number(n) || 0); if (cpNums.length >= 5) { @@ -369,18 +432,20 @@ export function parseMacOsOutput( nowMs = Date.now(), ): CollectOutput { const sec = splitSections(stdout); - const sysctlLines = (sec.SYSCTL ?? '') - .split(/\r?\n/) - .map((l) => l.trim()) - .filter(Boolean); + const sysctl = parseSysctlMap(sec.SYSCTL ?? '', [ + 'hw.memsize', + 'hw.pagesize', + 'vm.loadavg', + 'kern.boottime', + ]); - const memBytes = Number(sysctlLines[0]) || 0; - const pageSize = Number(sysctlLines[1]) || 4096; - const loadMatch = /([\d.]+)/.exec(sysctlLines[2] ?? '0'); + const memBytes = Number(sysctl.get('hw.memsize')) || 0; + const pageSize = Number(sysctl.get('hw.pagesize')) || 4096; + const loadMatch = /([\d.]+)/.exec(sysctl.get('vm.loadavg') ?? '0'); const load1m = round2(Number(loadMatch?.[1] ?? 0)); let uptimeSec = 0; - const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctlLines[3] ?? ''); + const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctl.get('kern.boottime') ?? ''); if (bootSecMatch) { uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!)); } diff --git a/src/server/monitoring/inspector.ts b/src/server/monitoring/inspector.ts index 518de1a..3246dcc 100644 --- a/src/server/monitoring/inspector.ts +++ b/src/server/monitoring/inspector.ts @@ -26,25 +26,30 @@ export interface ServerInspectionResult { serverId: string; os: OsType; collectedAt: number; + sort: 'cpu' | 'mem'; processes: ProcessEntry[]; ports: PortEntry[]; thermals: ThermalEntry[]; } -const LINUX_INSPECT_CMD = [ - 'printf "===PROCS===\\n"; ps -eo pid,user:24,%cpu,%mem,rss,args --sort=-%cpu 2>/dev/null | head -n 26 || ps -Ao pid,user,pcpu,pmem,rss,args | head -n 26', - 'printf "===PORTS===\\n"; ss -tulnp 2>/dev/null || netstat -tulnp 2>/dev/null || true', - 'printf "===THERMAL===\\n"; for z in /sys/class/thermal/thermal_zone*; do [ -r "$z/temp" ] && printf "%s:%s\\n" "$(cat "$z/type" 2>/dev/null || basename "$z")" "$(cat "$z/temp")"; done 2>/dev/null || true', -].join('; '); +function buildLinuxInspectCmd(sort: 'cpu' | 'mem'): string { + const linuxSort = sort === 'mem' ? '-rss' : '-%cpu'; + const bsdFlag = sort === 'mem' ? '-m' : '-r'; + return [ + `printf "===PROCS===\\n"; ps -eo pid,user:24,%cpu,%mem,rss,args --sort=${linuxSort} 2>/dev/null | head -n 41 || ps -Ao pid,user,pcpu,pmem,rss,args ${bsdFlag} 2>/dev/null | head -n 41 || ps -Ao pid,user,pcpu,pmem,rss,args | head -n 41`, + 'printf "===PORTS===\\n"; ss -tulnp 2>/dev/null || netstat -tulnp 2>/dev/null || true', + 'printf "===THERMAL===\\n"; for z in /sys/class/thermal/thermal_zone*; do [ -r "$z/temp" ] && printf "%s:%s\\n" "$(cat "$z/type" 2>/dev/null || basename "$z")" "$(cat "$z/temp")"; done 2>/dev/null || true', + ].join('; '); +} const BSD_INSPECT_CMD = [ - 'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command 2>/dev/null | head -n 26', + 'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command 2>/dev/null | head -n 41', 'printf "===PORTS===\\n"; sockstat -l 2>/dev/null || netstat -an 2>/dev/null || true', 'printf "===THERMAL===\\n"; sysctl dev.cpu 2>/dev/null | grep temperature || true', ].join('; '); const MACOS_INSPECT_CMD = [ - 'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command | head -n 26', + 'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command | head -n 41', 'printf "===PORTS===\\n"; lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null || netstat -an 2>/dev/null || true', 'printf "===THERMAL===\\n"; true', ].join('; '); @@ -54,6 +59,7 @@ export function parseInspectorOutput( os: OsType, stdout: string, collectedAt = Date.now(), + sort: 'cpu' | 'mem' = 'cpu', ): ServerInspectionResult { const sections: Record = {}; let current = ''; @@ -85,6 +91,12 @@ export function parseInspectorOutput( }); } + processes.sort((a, b) => + sort === 'mem' + ? b.memPct - a.memPct || b.rssMb - a.rssMb || b.cpuPct - a.cpuPct + : b.cpuPct - a.cpuPct || b.memPct - a.memPct, + ); + // Ports const ports: PortEntry[] = []; const portLines = sections.PORTS ?? []; @@ -98,7 +110,6 @@ export function parseInspectorOutput( } const cols = trimmed.split(/\s+/); if (/^(tcp|udp|tcp4|tcp6|udp4|udp6)/i.test(cols[0] ?? '')) { - // ss -tulnp format: Netid State Recv-Q Send-Q Local Peer Process if (cols.length >= 6 && (cols[1] === 'LISTEN' || cols[1] === 'UNCONN')) { ports.push({ proto: cols[0]!, @@ -113,14 +124,12 @@ export function parseInspectorOutput( }); } } else if (cols.length >= 9 && cols[cols.length - 1] === '(LISTEN)') { - // lsof format ports.push({ proto: cols[7] ?? 'TCP', localAddress: cols[8] ?? '', process: `${cols[0]}(${cols[1]})`, }); } else if (cols.length >= 6 && /^\d+$/.test(cols[2] ?? '')) { - // sockstat -l: USER COMMAND PID FD PROTO LOCAL FOREIGN ports.push({ proto: cols[4] ?? 'tcp', localAddress: cols[5] ?? '', @@ -144,7 +153,7 @@ export function parseInspectorOutput( thermals.push({ zone, tempC }); } - return { serverId, os, collectedAt, processes, ports, thermals }; + return { serverId, os, collectedAt, sort, processes, ports, thermals }; } export class ServerInspector { @@ -153,11 +162,15 @@ export class ServerInspector { private readonly configManager: ConfigManager, ) {} - async inspect(serverId: string): Promise { + async inspect( + serverId: string, + opts: { sort?: 'cpu' | 'mem'; useSudo?: boolean } = {}, + ): Promise { const server = this.configManager.getServer(serverId); if (!server) { throw new Error(`Unknown server "${serverId}"`); } + const sort = opts.sort === 'mem' ? 'mem' : 'cpu'; const runtime = this.sshPool.getState(serverId); const os = await detectServerOs(this.sshPool, server, runtime?.osDetected); const cmd = @@ -165,9 +178,39 @@ export class ServerInspector { ? MACOS_INSPECT_CMD : os === 'bsd' ? BSD_INSPECT_CMD - : LINUX_INSPECT_CMD; + : buildLinuxInspectCmd(sort); - const res = await this.sshPool.exec(serverId, cmd, { timeoutMs: 15_000 }); - return parseInspectorOutput(serverId, os, res.stdout); + const res = await this.sshPool.exec(serverId, cmd, { + timeoutMs: 15_000, + sudo: opts.useSudo, + }); + return parseInspectorOutput(serverId, os, res.stdout, Date.now(), sort); + } + + async signalProcess( + serverId: string, + pid: number, + signal: 'SIGTERM' | 'SIGKILL', + opts: { useSudo?: boolean } = {}, + ): Promise<{ ok: boolean; pid: number; signal: string; stderr: string }> { + const server = this.configManager.getServer(serverId); + if (!server) { + throw new Error(`Unknown server "${serverId}"`); + } + if (!Number.isInteger(pid) || pid < 1 || pid > 99_999_999) { + throw new Error('Invalid PID'); + } + const sigName = signal === 'SIGKILL' ? 'KILL' : 'TERM'; + const res = await this.sshPool.exec( + serverId, + `kill -s ${sigName} ${pid}`, + { timeoutMs: 10_000, sudo: opts.useSudo }, + ); + return { + ok: res.exitCode === 0, + pid, + signal, + stderr: res.stderr.trim(), + }; } } diff --git a/src/server/monitoring/monitoring-service.ts b/src/server/monitoring/monitoring-service.ts index 1a69daa..29a02b1 100644 --- a/src/server/monitoring/monitoring-service.ts +++ b/src/server/monitoring/monitoring-service.ts @@ -6,6 +6,7 @@ import type { ProbeSample, } from '../../shared/ws-protocol.js'; import type { ConfigManager } from '../config/config-manager.js'; +import type { RuntimeLimits } from '../config/runtime-limits.js'; import type { VaultService } from '../security/vault.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; import { @@ -37,6 +38,7 @@ export interface MonitoringTickEvent { interface ServerTimers { metricTimer: NodeJS.Timeout | null; warmupTimer: NodeJS.Timeout | null; + staggerTimer: NodeJS.Timeout | null; probeTimers: Map; pollingMetrics: boolean; } @@ -54,6 +56,8 @@ export class MonitoringService { >(); private maintenanceTimer: NodeJS.Timeout | null = null; private stopped = false; + private inFlightPolls = 0; + private readonly pollQueue: Array<() => void> = []; constructor( private readonly db: Database.Database, @@ -61,6 +65,7 @@ export class MonitoringService { private readonly vaultService: VaultService, private readonly sshPool: SSHPool, private readonly probeRunner: ProbeRunner, + private readonly getRuntimeLimits?: () => RuntimeLimits, ) {} onTick(listener: (event: MonitoringTickEvent) => void): () => void { @@ -96,6 +101,7 @@ export class MonitoringService { for (const timers of this.serverTimers.values()) { if (timers.metricTimer) clearInterval(timers.metricTimer); if (timers.warmupTimer) clearTimeout(timers.warmupTimer); + if (timers.staggerTimer) clearTimeout(timers.staggerTimer); for (const pt of timers.probeTimers.values()) clearInterval(pt); } this.serverTimers.clear(); @@ -104,6 +110,9 @@ export class MonitoringService { close(): void { this.stopped = true; this.stopAll(); + while (this.pollQueue.length > 0) { + this.pollQueue.shift()?.(); + } if (this.maintenanceTimer) { clearInterval(this.maintenanceTimer); this.maintenanceTimer = null; @@ -119,10 +128,10 @@ export class MonitoringService { return; } - for (const server of this.configManager.listServers()) { - if (!server.enabled) continue; - this.scheduleServer(server); - } + const enabledServers = this.configManager.listServers().filter((s) => s.enabled); + enabledServers.forEach((server, idx) => { + this.scheduleServer(server, idx); + }); } getLatest(serverId: string): LatestServerTelemetry | undefined { @@ -138,45 +147,105 @@ export class MonitoringService { return this.executeMetricPoll(server); } + async runProbeNow(serverId: string, probeId: string): Promise { + const server = this.configManager.getServer(serverId); + if (!server) { + throw new Error(`Unknown server "${serverId}"`); + } + const probe = server.probes.find((p) => p.id === probeId); + if (!probe) { + throw new Error(`Unknown probe "${probeId}" on server "${serverId}"`); + } + return this.runAndPersistProbe(server, probe); + } + runMaintenance(nowMs = Date.now()): void { const settings = this.configManager.getSettings(); const rawCutoff = nowMs - settings.rawRetentionHours * 3600_000; const rollupCutoff = nowMs - settings.rollupRetentionDays * 86_400_000; + const auditCutoff = nowMs - settings.auditRetentionDays * 86_400_000; + const workflowCutoff = nowMs - settings.workflowRunRetentionDays * 86_400_000; + const alertCutoff = nowMs - settings.alertEventRetentionDays * 86_400_000; const tx = this.db.transaction(() => { - // Aggregate hourly rollups from raw metrics + // Stage 1: Aggregate 1h rollups preserving any partial bucket spanning rawCutoff this.db .prepare( - `INSERT OR REPLACE INTO metrics_rollup (bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, mem_avg_pct, load_max) + `INSERT INTO metrics_rollup ( + bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, + mem_avg_pct, load_max, net_rx_avg_bps, net_tx_avg_bps, disk_max_pct + ) SELECT - (ts / 3600000) * 3600000 AS bucket_ts, + (r.ts / 3600000) * 3600000 AS bucket_ts, '1h' AS granularity, - server_id, - MIN(cpu_pct), - AVG(cpu_pct), - MAX(cpu_pct), - COALESCE(AVG(CASE WHEN mem_total_mb > 0 THEN (mem_used_mb * 100.0 / mem_total_mb) ELSE 0 END), 0), - MAX(load_1m) - FROM metrics_raw - GROUP BY server_id, (ts / 3600000) * 3600000`, + r.server_id, + MIN(r.cpu_pct), + AVG(r.cpu_pct), + MAX(r.cpu_pct), + COALESCE(AVG(CASE WHEN r.mem_total_mb > 0 THEN (r.mem_used_mb * 100.0 / r.mem_total_mb) ELSE 0 END), 0), + MAX(r.load_1m), + AVG(r.net_rx_bps), + AVG(r.net_tx_bps), + COALESCE(MAX(d.max_disk_pct), 0) + FROM metrics_raw r + LEFT JOIN ( + SELECT server_id, ts, MAX(used_pct) AS max_disk_pct + FROM metrics_disks + GROUP BY server_id, ts + ) d ON d.server_id = r.server_id AND d.ts = r.ts + GROUP BY r.server_id, (r.ts / 3600000) * 3600000 + ON CONFLICT(server_id, granularity, bucket_ts) DO UPDATE SET + cpu_min = CASE WHEN excluded.bucket_ts >= ? THEN excluded.cpu_min ELSE MIN(metrics_rollup.cpu_min, excluded.cpu_min) END, + cpu_max = CASE WHEN excluded.bucket_ts >= ? THEN excluded.cpu_max ELSE MAX(metrics_rollup.cpu_max, excluded.cpu_max) END, + load_max = CASE WHEN excluded.bucket_ts >= ? THEN excluded.load_max ELSE MAX(metrics_rollup.load_max, excluded.load_max) END, + disk_max_pct = CASE WHEN excluded.bucket_ts >= ? THEN excluded.disk_max_pct ELSE MAX(metrics_rollup.disk_max_pct, excluded.disk_max_pct) END, + cpu_avg = CASE WHEN excluded.bucket_ts >= ? THEN excluded.cpu_avg ELSE metrics_rollup.cpu_avg END, + mem_avg_pct = CASE WHEN excluded.bucket_ts >= ? THEN excluded.mem_avg_pct ELSE metrics_rollup.mem_avg_pct END, + net_rx_avg_bps = CASE WHEN excluded.bucket_ts >= ? THEN excluded.net_rx_avg_bps ELSE metrics_rollup.net_rx_avg_bps END, + net_tx_avg_bps = CASE WHEN excluded.bucket_ts >= ? THEN excluded.net_tx_avg_bps ELSE metrics_rollup.net_tx_avg_bps END`, ) - .run(); + .run( + rawCutoff, + rawCutoff, + rawCutoff, + rawCutoff, + rawCutoff, + rawCutoff, + rawCutoff, + rawCutoff, + ); - // Aggregate daily rollups + // Stage 2: Aggregate 1d rollups from complete 1h buckets so raw pruning never truncates a day this.db .prepare( - `INSERT OR REPLACE INTO metrics_rollup (bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, mem_avg_pct, load_max) + `INSERT INTO metrics_rollup ( + bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, + mem_avg_pct, load_max, net_rx_avg_bps, net_tx_avg_bps, disk_max_pct + ) SELECT - (ts / 86400000) * 86400000 AS bucket_ts, + (bucket_ts / 86400000) * 86400000 AS day_ts, '1d' AS granularity, server_id, - MIN(cpu_pct), - AVG(cpu_pct), - MAX(cpu_pct), - COALESCE(AVG(CASE WHEN mem_total_mb > 0 THEN (mem_used_mb * 100.0 / mem_total_mb) ELSE 0 END), 0), - MAX(load_1m) - FROM metrics_raw - GROUP BY server_id, (ts / 86400000) * 86400000`, + MIN(cpu_min), + AVG(cpu_avg), + MAX(cpu_max), + AVG(mem_avg_pct), + MAX(load_max), + AVG(net_rx_avg_bps), + AVG(net_tx_avg_bps), + MAX(disk_max_pct) + FROM metrics_rollup + WHERE granularity = '1h' + GROUP BY server_id, (bucket_ts / 86400000) * 86400000 + ON CONFLICT(server_id, granularity, bucket_ts) DO UPDATE SET + cpu_min = MIN(metrics_rollup.cpu_min, excluded.cpu_min), + cpu_max = MAX(metrics_rollup.cpu_max, excluded.cpu_max), + load_max = MAX(metrics_rollup.load_max, excluded.load_max), + disk_max_pct = MAX(metrics_rollup.disk_max_pct, excluded.disk_max_pct), + cpu_avg = excluded.cpu_avg, + mem_avg_pct = excluded.mem_avg_pct, + net_rx_avg_bps = excluded.net_rx_avg_bps, + net_tx_avg_bps = excluded.net_tx_avg_bps`, ) .run(); @@ -184,16 +253,65 @@ export class MonitoringService { this.db.prepare('DELETE FROM metrics_disks WHERE ts < ?').run(rawCutoff); this.db.prepare('DELETE FROM probe_results WHERE ts < ?').run(rawCutoff); this.db.prepare('DELETE FROM metrics_rollup WHERE bucket_ts < ?').run(rollupCutoff); + this.db.prepare('DELETE FROM audit_log WHERE ts < ?').run(auditCutoff); + this.db + .prepare('DELETE FROM workflow_runs WHERE finished_at IS NOT NULL AND started_at < ?') + .run(workflowCutoff); + this.db + .prepare( + "DELETE FROM alert_events WHERE state = 'resolved' AND COALESCE(resolved_at, triggered_at) < ?", + ) + .run(alertCutoff); + this.db.prepare('DELETE FROM alert_silences WHERE expires_at < ?').run(nowMs); + this.db + .prepare('DELETE FROM broadcast_jobs WHERE finished_at IS NOT NULL AND started_at < ?') + .run(workflowCutoff); }); tx(); } + queryProbeHistory( + serverId: string, + sinceMs = Date.now() - 24 * 3600_000, + limit = 200, + ): Array { + const safeLimit = Math.max(1, Math.min(1000, Math.floor(limit))); + const rows = this.db + .prepare( + `SELECT ts, probe_id AS probeId, ok AS okInt, status_code AS statusCode, + latency_ms AS latencyMs, error + FROM probe_results + WHERE server_id = ? AND ts >= ? + ORDER BY ts DESC + LIMIT ?`, + ) + .all(serverId, sinceMs, safeLimit) as Array<{ + ts: number; + probeId: string; + okInt: number; + statusCode: number | null; + latencyMs: number; + error: string | null; + }>; + + return rows.reverse().map((r) => ({ + ts: r.ts, + probeId: r.probeId, + ok: r.okInt === 1, + statusCode: r.statusCode ?? undefined, + latencyMs: r.latencyMs, + error: r.error ?? undefined, + })); + } + queryHistory(serverId: string, range: MetricRange = '1h'): { range: MetricRange; granularity: 'raw' | '1h' | '1d'; points: Array>; latestDisks: DiskSample[]; latestProbes: Array; + probeHistory: Array; + diskHistory: Array<{ ts: number; mountPoint: string; usedPct: number; usedMb: number; totalMb: number }>; } { const now = Date.now(); const rangeMs: Record = { @@ -223,7 +341,9 @@ export class MonitoringService { points = this.db .prepare( `SELECT bucket_ts AS ts, cpu_min AS cpuMin, cpu_avg AS cpuAvg, cpu_max AS cpuMax, - mem_avg_pct AS memAvgPct, load_max AS loadMax + mem_avg_pct AS memAvgPct, load_max AS loadMax, + net_rx_avg_bps AS netRxAvgBps, net_tx_avg_bps AS netTxAvgBps, + disk_max_pct AS diskMaxPct FROM metrics_rollup WHERE server_id = ? AND granularity = ? AND bucket_ts >= ? ORDER BY bucket_ts ASC`, @@ -240,6 +360,22 @@ export class MonitoringService { ) .all(serverId, serverId) as DiskSample[]; + const diskHistory = this.db + .prepare( + `SELECT ts, mount_point AS mountPoint, used_pct AS usedPct, used_mb AS usedMb, total_mb AS totalMb + FROM metrics_disks + WHERE server_id = ? AND ts >= ? + ORDER BY ts ASC + LIMIT 500`, + ) + .all(serverId, since) as Array<{ + ts: number; + mountPoint: string; + usedPct: number; + usedMb: number; + totalMb: number; + }>; + const latestProbes = this.db .prepare( `SELECT p.probe_id AS probeId, p.ok AS okInt, p.status_code AS statusCode, @@ -262,6 +398,8 @@ export class MonitoringService { ts: number; }>; + const probeHistory = this.queryProbeHistory(serverId, since, 200); + return { range, granularity, @@ -275,50 +413,88 @@ export class MonitoringService { error: r.error ?? undefined, ts: r.ts, })), + probeHistory, + diskHistory, }; } - private scheduleServer(server: ServerConfig): void { + private async withPollSlot(fn: () => Promise): Promise { + const limit = Math.max(1, this.getRuntimeLimits?.().maxConcurrentMetricPolls ?? 4); + if (this.inFlightPolls >= limit) { + await new Promise((resolve) => { + this.pollQueue.push(resolve); + }); + } + this.inFlightPolls += 1; + try { + return await fn(); + } finally { + this.inFlightPolls = Math.max(0, this.inFlightPolls - 1); + const next = this.pollQueue.shift(); + if (next) next(); + } + } + + private scheduleServer(server: ServerConfig, index: number): void { const timers: ServerTimers = { metricTimer: null, warmupTimer: null, + staggerTimer: null, probeTimers: new Map(), pollingMetrics: false, }; this.serverTimers.set(server.id, timers); - // Kick initial poll asynchronously without delaying syncServers() - const hadDelta = this.deltaStates.has(server.id); - void this.executeMetricPoll(server).then((ev) => { - if ( - ev && - !hadDelta && - !this.stopped && - this.serverTimers.get(server.id) === timers && - server.pollIntervalSec >= 3 - ) { - const wt = setTimeout(() => { - timers.warmupTimer = null; - void this.executeMetricPoll(server); - }, 1000); - wt.unref(); - timers.warmupTimer = wt; - } - }); + const limits = this.getRuntimeLimits?.(); + const staggerMs = + limits?.staggerPolls && index > 0 ? Math.min(index * 120, 2_500) : 0; - timers.metricTimer = setInterval(() => { - void this.executeMetricPoll(server); - }, server.pollIntervalSec * 1000); - timers.metricTimer.unref(); + const kickInitialAndStartTimer = () => { + if (this.stopped || this.serverTimers.get(server.id) !== timers) return; - for (const probe of server.probes) { - if (!probe.enabled) continue; - void this.executeProbe(server, probe.id); - const pt = setInterval(() => { + const hadDelta = this.deltaStates.has(server.id); + void this.executeMetricPoll(server).then((ev) => { + if ( + ev && + !hadDelta && + !this.stopped && + this.serverTimers.get(server.id) === timers && + server.pollIntervalSec >= 3 + ) { + const wt = setTimeout(() => { + timers.warmupTimer = null; + void this.executeMetricPoll(server); + }, 1000); + wt.unref(); + timers.warmupTimer = wt; + } + }); + + timers.metricTimer = setInterval(() => { + void this.executeMetricPoll(server); + }, server.pollIntervalSec * 1000); + timers.metricTimer.unref(); + + for (const probe of server.probes) { + if (!probe.enabled) continue; void this.executeProbe(server, probe.id); - }, probe.intervalSec * 1000); - pt.unref(); - timers.probeTimers.set(probe.id, pt); + const pt = setInterval(() => { + void this.executeProbe(server, probe.id); + }, probe.intervalSec * 1000); + pt.unref(); + timers.probeTimers.set(probe.id, pt); + } + }; + + if (staggerMs > 0) { + const st = setTimeout(() => { + timers.staggerTimer = null; + kickInitialAndStartTimer(); + }, staggerMs); + st.unref(); + timers.staggerTimer = st; + } else { + kickInitialAndStartTimer(); } } @@ -332,51 +508,55 @@ export class MonitoringService { if (timerState) timerState.pollingMetrics = true; try { - const os = await detectServerOs( - this.sshPool, - server, - this.osCache.get(server.id), - ); - this.osCache.set(server.id, os); + return await this.withPollSlot(async () => { + if (this.stopped || !this.vaultService.isRuntimeReady) return null; - const collected = await collectServerMetrics( - this.sshPool, - server, - os, - this.deltaStates.get(server.id), - ); - this.deltaStates.set(server.id, collected.nextState); + const os = await detectServerOs( + this.sshPool, + server, + this.osCache.get(server.id), + ); + this.osCache.set(server.id, os); - this.persistMetricSample(server.id, collected.sample, collected.disks); + const collected = await collectServerMetrics( + this.sshPool, + server, + os, + this.deltaStates.get(server.id), + ); + this.deltaStates.set(server.id, collected.nextState); - const prevLatest = this.latest.get(server.id) ?? { - serverId: server.id, - disks: [], - probes: {}, - }; - this.latest.set(server.id, { - ...prevLatest, - os, - sample: collected.sample, - disks: collected.disks, - lastError: undefined, - }); + this.persistMetricSample(server.id, collected.sample, collected.disks); - const probes = Object.values(this.latest.get(server.id)!.probes); - const event: MonitoringTickEvent = { - serverId: server.id, - sample: collected.sample, - disks: collected.disks, - probes, - }; - for (const listener of this.tickListeners) { - try { - listener(event); - } catch { - // Isolate listener errors + const prevLatest = this.latest.get(server.id) ?? { + serverId: server.id, + disks: [], + probes: {}, + }; + this.latest.set(server.id, { + ...prevLatest, + os, + sample: collected.sample, + disks: collected.disks, + lastError: undefined, + }); + + const probes = Object.values(this.latest.get(server.id)!.probes); + const event: MonitoringTickEvent = { + serverId: server.id, + sample: collected.sample, + disks: collected.disks, + probes, + }; + for (const listener of this.tickListeners) { + try { + listener(event); + } catch { + // Isolate listener errors + } } - } - return event; + return event; + }); } catch (err) { const prevLatest = this.latest.get(server.id) ?? { serverId: server.id, @@ -397,8 +577,16 @@ export class MonitoringService { if (this.stopped || !this.vaultService.isRuntimeReady) return; const probe = server.probes.find((p) => p.id === probeId); if (!probe || !probe.enabled) return; + await this.runAndPersistProbe(server, probe); + } - const sample = await this.probeRunner.runProbe(server.id, probe); + private async runAndPersistProbe( + server: ServerConfig, + probe: ServerConfig['probes'][number], + ): Promise { + const sample = await this.withPollSlot(() => + this.probeRunner.runProbe(server.id, probe), + ); const ts = Date.now(); this.db .prepare( @@ -430,6 +618,7 @@ export class MonitoringService { // Isolate probe listener errors } } + return sample; } private hydrateLatestFromDb(): void { diff --git a/src/server/monitoring/probes.ts b/src/server/monitoring/probes.ts index 02d5bed..b09f3aa 100644 --- a/src/server/monitoring/probes.ts +++ b/src/server/monitoring/probes.ts @@ -3,36 +3,93 @@ import tls from 'node:tls'; import type { Duplex } from 'node:stream'; import type { ServerProbe } from '../../shared/schemas/server.schema.js'; import type { ProbeSample } from '../../shared/ws-protocol.js'; +import type { ConfigManager } from '../config/config-manager.js'; +import { + fetchWithEgressGuard, + resolveAllowedEgressIps, +} from '../security/egress-guard.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; +const MAX_PROBE_BODY_BYTES = 128 * 1024; + +function decodeChunkedIfNeeded(head: string, body: string): string { + if (!/^transfer-encoding:\s*chunked\b/im.test(head)) return body; + let idx = 0; + let out = ''; + while (idx < body.length) { + const lineEnd = body.indexOf('\r\n', idx); + if (lineEnd < 0) break; + const sizeHex = body.slice(idx, lineEnd).split(';')[0]!.trim(); + const size = Number.parseInt(sizeHex, 16); + if (!Number.isFinite(size) || size <= 0) break; + idx = lineEnd + 2; + out += body.slice(idx, idx + size); + idx += size + 2; + } + return out || body; +} + +async function readResponseTextCapped( + res: Response, + maxBytes = MAX_PROBE_BODY_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'); +} + function readHttpFromStream( stream: Duplex, url: URL, timeoutMs: number, -): Promise<{ statusCode: number; body: string }> { + tlsOpts: { rejectUnauthorized?: boolean } = {}, +): Promise<{ statusCode: number; body: string; certExpiryDays?: number }> { return new Promise((resolve, reject) => { let settled = false; + let certExpiryDays: number | undefined; const timer = setTimeout(() => { if (settled) return; settled = true; stream.destroy(); - reject(new Error(`Target HTTP probe timed out after ${timeoutMs}ms`)); + reject(new Error(`HTTP probe timed out after ${timeoutMs}ms`)); }, timeoutMs); + const servername = net.isIP(url.hostname) ? undefined : url.hostname; const transport: Duplex = url.protocol === 'https:' - ? tls.connect({ socket: stream, servername: url.hostname }) + ? tls.connect({ + socket: stream, + servername, + rejectUnauthorized: tlsOpts.rejectUnauthorized ?? true, + }) : stream; const chunks: Buffer[] = []; let total = 0; - const maxBytes = 256 * 1024; const done = (err?: Error) => { if (settled) return; settled = true; clearTimeout(timer); transport.destroy(); + stream.destroy(); if (err) { reject(err); return; @@ -40,36 +97,53 @@ function readHttpFromStream( const raw = Buffer.concat(chunks).toString('utf8'); const headerEnd = raw.indexOf('\r\n\r\n'); const head = headerEnd >= 0 ? raw.slice(0, headerEnd) : raw; - const body = headerEnd >= 0 ? raw.slice(headerEnd + 4) : ''; + const rawBody = headerEnd >= 0 ? raw.slice(headerEnd + 4) : ''; const statusLine = head.split('\r\n')[0] ?? ''; const m = /^HTTP\/\d(?:\.\d)?\s+(\d{3})/.exec(statusLine); if (!m) { reject(new Error(`Invalid HTTP response line: ${statusLine}`)); return; } - resolve({ statusCode: Number(m[1]), body }); + resolve({ + statusCode: Number(m[1]), + body: decodeChunkedIfNeeded(head, rawBody), + certExpiryDays, + }); }; transport.on('data', (chunk: Buffer) => { - if (total < maxBytes) { - chunks.push(chunk.subarray(0, maxBytes - total)); + if (total < MAX_PROBE_BODY_BYTES) { + chunks.push(chunk.subarray(0, MAX_PROBE_BODY_BYTES - total)); total += chunk.length; + } else { + transport.destroy(); } }); transport.once('end', () => done()); transport.once('close', () => done()); transport.once('error', (err) => done(err)); + if (transport !== stream) { + stream.once('error', (err) => done(err)); + } const pathAndQuery = `${url.pathname || '/'}${url.search || ''}`; const hostHeader = url.port ? `${url.hostname}:${url.port}` : url.hostname; const reqText = `GET ${pathAndQuery} HTTP/1.1\r\n` + `Host: ${hostHeader}\r\n` + - `User-Agent: GCoordinator-Probe/1.0\r\n` + + `User-Agent: GCoordinator-Probe/1.1\r\n` + + `Accept-Encoding: identity\r\n` + `Connection: close\r\n\r\n`; if (url.protocol === 'https:') { (transport as tls.TLSSocket).once('secureConnect', () => { + const cert = (transport as tls.TLSSocket).getPeerCertificate(false); + if (cert && typeof cert.valid_to === 'string') { + const expMs = Date.parse(cert.valid_to); + if (Number.isFinite(expMs)) { + certExpiryDays = Math.floor((expMs - Date.now()) / 86_400_000); + } + } transport.write(reqText); }); } else { @@ -79,16 +153,26 @@ function readHttpFromStream( } export class ProbeRunner { - constructor(private readonly sshPool: SSHPool) {} + constructor( + private readonly sshPool: SSHPool, + private readonly configManager?: ConfigManager, + ) {} + + runSingleProbe(serverId: string, probe: ServerProbe): Promise { + return this.runProbe(serverId, probe); + } async runProbe(serverId: string, probe: ServerProbe): Promise { const started = Date.now(); + const allowedCidrs = this.configManager?.getSettings().security.egressAllowedCidrs ?? []; + try { if (probe.type === 'tcp') { if (probe.from === 'hub') { + const ips = await resolveAllowedEgressIps(probe.host, allowedCidrs); await new Promise((resolve, reject) => { const sock = net.createConnection({ - host: probe.host, + host: ips[0]!, port: probe.port, }); const timer = setTimeout(() => { @@ -125,19 +209,35 @@ export class ProbeRunner { } // HTTP(S) probe + const parsedUrl = new URL(probe.url); let statusCode: number; let body: string; + let certExpiryDays: number | undefined; if (probe.from === 'hub') { - const res = await fetch(probe.url, { - method: 'GET', - redirect: 'manual', - signal: AbortSignal.timeout(probe.timeoutMs), - }); - statusCode = res.status; - body = await res.text(); + if ( + parsedUrl.protocol === 'https:' && + (probe.tlsRejectUnauthorized === false || probe.tlsCheckExpiryDays !== undefined) + ) { + const ips = await resolveAllowedEgressIps(parsedUrl.hostname, allowedCidrs); + const port = parsedUrl.port ? Number(parsedUrl.port) : 443; + const sock = net.createConnection({ host: ips[0]!, port }); + const resp = await readHttpFromStream(sock, parsedUrl, probe.timeoutMs, { + rejectUnauthorized: probe.tlsRejectUnauthorized, + }); + statusCode = resp.statusCode; + body = resp.body; + certExpiryDays = resp.certExpiryDays; + } else { + const res = await fetchWithEgressGuard( + probe.url, + { method: 'GET', redirect: 'manual' }, + { allowedCidrs, timeoutMs: probe.timeoutMs }, + ); + statusCode = res.status; + body = await readResponseTextCapped(res, MAX_PROBE_BODY_BYTES); + } } else { - const parsedUrl = new URL(probe.url); const port = parsedUrl.port ? Number(parsedUrl.port) : parsedUrl.protocol === 'https:' @@ -149,24 +249,40 @@ export class ProbeRunner { port, probe.timeoutMs, ); - const resp = await readHttpFromStream(stream, parsedUrl, probe.timeoutMs); + const resp = await readHttpFromStream(stream, parsedUrl, probe.timeoutMs, { + rejectUnauthorized: probe.tlsRejectUnauthorized, + }); statusCode = resp.statusCode; body = resp.body; + certExpiryDays = resp.certExpiryDays; } const statusOk = statusCode === probe.expectedStatus; const bodyOk = probe.bodyIncludes ? body.includes(probe.bodyIncludes) : true; - const ok = statusOk && bodyOk; + const certOk = + probe.tlsCheckExpiryDays !== undefined && certExpiryDays !== undefined + ? certExpiryDays >= probe.tlsCheckExpiryDays + : true; + const ok = statusOk && bodyOk && certOk; + + let error: string | undefined; + if (!ok) { + if (!statusOk) { + error = `Expected HTTP ${probe.expectedStatus}, got ${statusCode}`; + } else if (!bodyOk) { + error = `Response body missing substring "${probe.bodyIncludes}"`; + } else { + error = `TLS certificate expires in ${certExpiryDays}d (threshold ${probe.tlsCheckExpiryDays}d)`; + } + } + return { probeId: probe.id, ok, statusCode, latencyMs: Date.now() - started, - error: ok - ? undefined - : !statusOk - ? `Expected HTTP ${probe.expectedStatus}, got ${statusCode}` - : `Response body missing substring "${probe.bodyIncludes}"`, + certExpiryDays, + error, }; } catch (err) { return { diff --git a/src/server/monitoring/prometheus.ts b/src/server/monitoring/prometheus.ts new file mode 100644 index 0000000..a69692c --- /dev/null +++ b/src/server/monitoring/prometheus.ts @@ -0,0 +1,180 @@ +import crypto from 'node:crypto'; +import type { Request, Response } from 'express'; +import type { AlertEngine } from '../alerts/alert-engine.js'; +import type { ConfigManager } from '../config/config-manager.js'; +import { sha256Hex } from '../security/auth.js'; +import type { VaultService } from '../security/vault.js'; +import type { SSHPool } from '../ssh/ssh-pool.js'; +import type { TunnelManager } from '../ssh/tunnel-manager.js'; +import type { MonitoringService } from './monitoring-service.js'; + +export interface PrometheusHandlerDeps { + configManager: ConfigManager; + vaultService: VaultService; + sshPool: SSHPool; + monitoringService: MonitoringService; + tunnelManager: TunnelManager; + alertEngine: AlertEngine; +} + +function escapePromLabel(val: string): string { + return val.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n'); +} + +function labels(pairs: Record): string { + const parts = Object.entries(pairs).map( + ([k, v]) => `${k}="${escapePromLabel(v)}"`, + ); + return parts.length > 0 ? `{${parts.join(',')}}` : ''; +} + +function constantTimeTokenMatch(provided: string, expectedSha256Hex: string): boolean { + if (!/^[a-f0-9]{64}$/i.test(expectedSha256Hex)) return false; + const providedDigest = Buffer.from(sha256Hex(provided), 'hex'); + const expectedDigest = Buffer.from(expectedSha256Hex.toLowerCase(), 'hex'); + if (providedDigest.length !== expectedDigest.length) return false; + return crypto.timingSafeEqual(providedDigest, expectedDigest); +} + +export function createPrometheusHandler(deps: PrometheusHandlerDeps) { + const { + configManager, + vaultService, + sshPool, + monitoringService, + tunnelManager, + alertEngine, + } = deps; + + return (req: Request, res: Response): void => { + const settings = configManager.getSettings(); + if (!settings.metrics.prometheusEnabled) { + res.status(404).json({ error: 'METRICS_DISABLED' }); + return; + } + + const authHeader = typeof req.headers.authorization === 'string' ? req.headers.authorization : ''; + const bearerMatch = /^Bearer\s+(.+)$/i.exec(authHeader.trim()); + const providedToken = bearerMatch?.[1]?.trim() ?? ''; + + let authorized = false; + if (providedToken) { + if (settings.metrics.prometheusSecretRef && vaultService.isRuntimeReady) { + const cred = vaultService.getRuntimeSecret(settings.metrics.prometheusSecretRef); + const rawSecret = + cred?.type === 'api-token' + ? cred.token + : cred?.type === 'webhook-secret' + ? cred.secret + : undefined; + if (rawSecret) { + authorized = constantTimeTokenMatch(providedToken, sha256Hex(rawSecret)); + } + } + if (!authorized && settings.metrics.prometheusTokenHash) { + authorized = constantTimeTokenMatch(providedToken, settings.metrics.prometheusTokenHash); + } + } + + if (!authorized) { + res.setHeader('WWW-Authenticate', 'Bearer realm="GCoordinator"'); + res.status(401).json({ error: 'METRICS_UNAUTHORIZED' }); + return; + } + + const lines: string[] = []; + const metric = (name: string, help: string, type: 'gauge' | 'counter', rows: string[]) => { + lines.push(`# HELP ${name} ${help}`); + lines.push(`# TYPE ${name} ${type}`); + lines.push(...rows); + }; + + const states = new Map(sshPool.getStates().map((s) => [s.serverId, s])); + const servers = configManager.listServers(); + + const upRows: string[] = []; + const cpuRows: string[] = []; + const memUsedRows: string[] = []; + const memTotalRows: string[] = []; + const load1Rows: string[] = []; + const uptimeRows: string[] = []; + const netRxRows: string[] = []; + const netTxRows: string[] = []; + const diskRows: string[] = []; + const probeUpRows: string[] = []; + const probeLatencyRows: string[] = []; + const probeTlsExpiryRows: string[] = []; + + for (const srv of servers) { + const state = states.get(srv.id); + const isUp = state?.status === 'connected' ? 1 : 0; + const baseLabels = labels({ server_id: srv.id, name: srv.name }); + upRows.push(`gcoordinator_server_up${baseLabels} ${isUp}`); + + const latest = monitoringService.getLatest(srv.id); + if (latest?.sample) { + const s = latest.sample; + cpuRows.push(`gcoordinator_server_cpu_percent${baseLabels} ${s.cpuPct}`); + memUsedRows.push( + `gcoordinator_server_memory_used_bytes${baseLabels} ${Math.round(s.memUsedMb * 1024 * 1024)}`, + ); + memTotalRows.push( + `gcoordinator_server_memory_total_bytes${baseLabels} ${Math.round(s.memTotalMb * 1024 * 1024)}`, + ); + load1Rows.push(`gcoordinator_server_load1${baseLabels} ${s.load1m}`); + uptimeRows.push(`gcoordinator_server_uptime_seconds${baseLabels} ${s.uptimeSec}`); + netRxRows.push(`gcoordinator_server_net_rx_bytes_per_sec${baseLabels} ${s.netRxBps}`); + netTxRows.push(`gcoordinator_server_net_tx_bytes_per_sec${baseLabels} ${s.netTxBps}`); + } + if (latest?.disks) { + for (const d of latest.disks) { + const dl = labels({ server_id: srv.id, mount: d.mountPoint }); + diskRows.push(`gcoordinator_server_disk_used_percent${dl} ${d.usedPct}`); + } + } + if (latest?.probes) { + for (const p of Object.values(latest.probes)) { + const pl = labels({ server_id: srv.id, probe_id: p.probeId }); + probeUpRows.push(`gcoordinator_probe_up${pl} ${p.ok ? 1 : 0}`); + probeLatencyRows.push(`gcoordinator_probe_latency_ms${pl} ${p.latencyMs}`); + if (typeof p.certExpiryDays === 'number') { + probeTlsExpiryRows.push(`gcoordinator_probe_tls_expiry_days${pl} ${p.certExpiryDays}`); + } + } + } + } + + metric('gcoordinator_server_up', 'Server SSH reachability (1=connected, 0=disconnected)', 'gauge', upRows); + metric('gcoordinator_server_cpu_percent', 'Latest sampled CPU utilization percentage', 'gauge', cpuRows); + metric('gcoordinator_server_memory_used_bytes', 'Latest sampled memory used in bytes', 'gauge', memUsedRows); + metric('gcoordinator_server_memory_total_bytes', 'Total RAM in bytes', 'gauge', memTotalRows); + metric('gcoordinator_server_load1', 'Latest 1-minute load average', 'gauge', load1Rows); + metric('gcoordinator_server_uptime_seconds', 'Server uptime in seconds', 'gauge', uptimeRows); + metric('gcoordinator_server_net_rx_bytes_per_sec', 'Network receive throughput B/s', 'gauge', netRxRows); + metric('gcoordinator_server_net_tx_bytes_per_sec', 'Network transmit throughput B/s', 'gauge', netTxRows); + metric('gcoordinator_server_disk_used_percent', 'Disk filesystem usage percentage', 'gauge', diskRows); + metric('gcoordinator_probe_up', 'Latest health probe result (1=ok, 0=fail)', 'gauge', probeUpRows); + metric('gcoordinator_probe_latency_ms', 'Latest health probe latency in ms', 'gauge', probeLatencyRows); + if (probeTlsExpiryRows.length > 0) { + metric('gcoordinator_probe_tls_expiry_days', 'Days remaining until TLS certificate expiry', 'gauge', probeTlsExpiryRows); + } + + const activeTunnels = tunnelManager.listTunnels().filter((t) => t.active).length; + metric('gcoordinator_tunnels_active', 'Number of currently active SSH tunnels', 'gauge', [ + `gcoordinator_tunnels_active ${activeTunnels}`, + ]); + metric('gcoordinator_alerts_active', 'Number of active unresolved alert incidents', 'gauge', [ + `gcoordinator_alerts_active ${alertEngine.getActiveCount()}`, + ]); + metric('gcoordinator_process_resident_memory_bytes', 'Hub Node.js resident set size bytes', 'gauge', [ + `gcoordinator_process_resident_memory_bytes ${process.memoryUsage().rss}`, + ]); + metric('gcoordinator_process_uptime_seconds', 'Hub Node.js process uptime in seconds', 'gauge', [ + `gcoordinator_process_uptime_seconds ${Math.round(process.uptime())}`, + ]); + + res.setHeader('Content-Type', 'text/plain; version=0.0.4; charset=utf-8'); + res.setHeader('Cache-Control', 'no-store'); + res.send(`${lines.join('\n')}\n`); + }; +} diff --git a/src/shared/schemas/settings.schema.ts b/src/shared/schemas/settings.schema.ts index 811b3e9..003e01c 100644 --- a/src/shared/schemas/settings.schema.ts +++ b/src/shared/schemas/settings.schema.ts @@ -86,6 +86,7 @@ export const SettingsSchema = z.object({ .object({ prometheusEnabled: z.boolean().default(false), prometheusSecretRef: EntityIdSchema.optional(), + prometheusTokenHash: z.string().regex(/^[a-f0-9]{64}$/).optional(), }) .default({ prometheusEnabled: false }), security: SecuritySettingsSchema.default({}), diff --git a/src/shared/ws-protocol.ts b/src/shared/ws-protocol.ts index 0dc686c..6a8092a 100644 --- a/src/shared/ws-protocol.ts +++ b/src/shared/ws-protocol.ts @@ -49,6 +49,7 @@ export interface ProbeSample { ok: boolean; statusCode?: number; latencyMs: number; + certExpiryDays?: number; error?: string; } diff --git a/tests/monitoring-and-probes.test.ts b/tests/monitoring-and-probes.test.ts index 46d8097..c15573e 100644 --- a/tests/monitoring-and-probes.test.ts +++ b/tests/monitoring-and-probes.test.ts @@ -170,7 +170,7 @@ describe('OS Collectors, ServerInspector, Health Probes & MonitoringService', () await cfg.init({ watch: false }); const knownHosts = new KnownHostsService(db, audit); const sshPool = new SSHPool(cfg, vault, knownHosts); - const probeRunner = new ProbeRunner(sshPool); + const probeRunner = new ProbeRunner(sshPool, cfg); const inspector = new ServerInspector(sshPool, cfg); const monitoring = new MonitoringService(db, cfg, vault, sshPool, probeRunner); @@ -222,6 +222,15 @@ describe('OS Collectors, ServerInspector, Health Probes & MonitoringService', () ); const serverCfg = cfg.getServer('linux-01')!; + // Hub loopback HTTP probe is blocked by default Zero-Trust egress policy until explicitly allowlisted + const hubProbe = serverCfg.probes.find((p) => p.id === 'hub-http')!; + const deniedSample = await probeRunner.runProbe('linux-01', hubProbe); + expect(deniedSample.ok).toBe(false); + + const nextSettings = cfg.getSettings(); + nextSettings.security.egressAllowedCidrs = ['127.0.0.1/32']; + cfg.saveConfigText('settings.json', JSON.stringify(nextSettings, null, 2)); + for (const p of serverCfg.probes) { const sample = await probeRunner.runProbe('linux-01', p); expect(sample.ok).toBe(true);