diff --git a/src/server/ai/ai-service.ts b/src/server/ai/ai-service.ts index fd9c629..61af7b6 100644 --- a/src/server/ai/ai-service.ts +++ b/src/server/ai/ai-service.ts @@ -13,7 +13,9 @@ import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js'; import type { WsHub } from '../api/ws-hub.js'; import type { ConfigManager } from '../config/config-manager.js'; import { computeLineDiff, type DiffLine } from '../config/diff.js'; +import type { RuntimeLimits } from '../config/runtime-limits.js'; import type { AuditService } from '../security/audit.js'; +import { fetchWithEgressGuard } from '../security/egress-guard.js'; import type { VaultService } from '../security/vault.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; import { @@ -31,6 +33,14 @@ export class AiDisabledError extends Error { } } +export class AiOverloadError extends Error { + readonly code = 'AI_CONCURRENCY_LIMIT'; + readonly status = 503; + constructor(limit: number) { + super(`Too many concurrent AI streams (limit: ${limit}). Retry shortly.`); + } +} + export interface ChatMessageInput { role: 'user' | 'assistant'; content: string; @@ -64,6 +74,7 @@ export class AiService { private readonly sshPool: SSHPool, private readonly wsHub: WsHub, private readonly auditService: AuditService, + private readonly getRuntimeLimits?: () => RuntimeLimits, ) {} getReplayFrames(chatId: string): ServerWsFrame[] { @@ -93,11 +104,8 @@ export class AiService { private resolveBearerToken(secretRef?: string): string | undefined { if (!secretRef || !this.vaultService.isRuntimeReady) return undefined; const cred = this.vaultService.getRuntimeSecret(secretRef); - if (!cred) return undefined; - if (cred.type === 'api-token') return cred.token; - if (cred.type === 'webhook-secret') return cred.secret; - if (cred.type === 'ssh-password' || cred.type === 'sudo-password') return cred.password; - return undefined; + if (!cred || cred.type !== 'api-token') return undefined; + return cred.token; } previewContext(opts: { @@ -168,6 +176,12 @@ export class AiService { throw new AiDisabledError(); } + const activeStreams = [...this.chats.values()].filter((c) => !c.done).length; + const maxStreams = Math.max(1, this.getRuntimeLimits?.().maxConcurrentAiStreams ?? 2); + if (activeStreams >= maxStreams) { + throw new AiOverloadError(maxStreams); + } + const knownSecrets = collectVaultSecretStrings(this.vaultService); const guide = buildSurfaceGuideAndInventory( opts.surface, @@ -289,19 +303,26 @@ export class AiService { headers.Authorization = `Bearer ${bearerToken}`; } - const res = await fetch(endpointUrl, { - method: 'POST', - headers, - body: JSON.stringify({ model, stream: true, messages }), - signal: chat.abortController.signal, - }); + const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; + const aiCfg = this.configManager.getSettings().ai; + const res = await fetchWithEgressGuard( + endpointUrl, + { + method: 'POST', + headers, + body: JSON.stringify({ model, stream: true, messages, max_tokens: aiCfg.maxTokens }), + signal: chat.abortController.signal, + }, + { allowedCidrs, timeoutMs: (aiCfg.timeoutSec ?? 90) * 1000 }, + ); if (!res.ok) { const errBody = await res.text().catch(() => ''); + const cleanErr = bearerToken ? errBody.split(bearerToken).join('[REDACTED]') : errBody; this.emitDelta(chat, { chunk: '', done: true, - error: `LLM endpoint HTTP ${res.status}${errBody ? `: ${errBody.slice(0, 240)}` : ''}`, + error: `LLM endpoint HTTP ${res.status}${cleanErr ? `: ${cleanErr.slice(0, 240)}` : ''}`, }); return; } @@ -323,12 +344,22 @@ export class AiService { const reader = res.body.getReader(); const decoder = new TextDecoder(); let buf = ''; + const MAX_SSE_LINE_BUF = 256 * 1024; let doneSent = false; while (true) { const { value, done } = await reader.read(); if (done) break; buf += decoder.decode(value, { stream: true }); + if (buf.length > MAX_SSE_LINE_BUF) { + await reader.cancel().catch(() => undefined); + this.emitDelta(chat, { + chunk: '', + done: true, + error: 'AI SSE line buffer exceeded 256 KiB limit', + }); + return; + } let nlIdx: number; while ((nlIdx = buf.indexOf('\n')) >= 0) { @@ -371,11 +402,11 @@ export class AiService { this.emitDelta(chat, { chunk: '', done: true }); } } catch (err) { + const rawErr = err instanceof Error ? err.message : String(err); + const safeErr = bearerToken ? rawErr.split(bearerToken).join('[REDACTED]') : rawErr; const msg = chat.abortController.signal.aborted ? 'Generation cancelled' - : err instanceof Error - ? err.message - : String(err); + : safeErr; this.emitDelta(chat, { chunk: '', done: true, @@ -413,24 +444,29 @@ export class AiService { const headers: Record = { 'Content-Type': 'application/json' }; if (bearer) headers.Authorization = `Bearer ${bearer}`; - const res = await fetch(url, { - method: 'POST', - headers, - body: JSON.stringify({ - model, - stream: false, - max_tokens: 16, - messages: [{ role: 'user', content: 'Reply with OK' }], - }), - signal: AbortSignal.timeout(10_000), - }); + const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; + const res = await fetchWithEgressGuard( + url, + { + method: 'POST', + headers, + body: JSON.stringify({ + model, + stream: false, + max_tokens: 16, + messages: [{ role: 'user', content: 'Reply with OK' }], + }), + }, + { allowedCidrs, timeoutMs: 10_000 }, + ); const latencyMs = Date.now() - started; if (!res.ok) { const text = await res.text().catch(() => ''); + const cleanText = bearer ? text.split(bearer).join('[REDACTED]') : text; return { ok: false, latencyMs, - error: `HTTP ${res.status}${text ? `: ${text.slice(0, 180)}` : ''}`, + error: `HTTP ${res.status}${cleanText ? `: ${cleanText.slice(0, 180)}` : ''}`, }; } const data = (await res.json().catch(() => ({}))) as { @@ -440,10 +476,11 @@ export class AiService { data.choices?.[0]?.message?.content ?? data.choices?.[0]?.text ?? 'Connected'; return { ok: true, latencyMs, replyPreview: String(preview).trim().slice(0, 120) }; } catch (err) { + const rawErr = err instanceof Error ? err.message : String(err); return { ok: false, latencyMs: Date.now() - started, - error: err instanceof Error ? err.message : String(err), + error: bearer ? rawErr.split(bearer).join('[REDACTED]') : rawErr, }; } } @@ -486,9 +523,29 @@ export class AiService { }; } + if ( + opts.targetId && + rawObj && + typeof rawObj === 'object' && + !Array.isArray(rawObj) + ) { + const suppliedId = (rawObj as Record).id; + if (suppliedId !== undefined && suppliedId !== opts.targetId) { + return { + valid: false, + issues: [ + { + path: 'id', + message: `Draft id "${String(suppliedId)}" does not match locked targetId "${opts.targetId}"`, + }, + ], + }; + } + } + const withOptionalId = (obj: unknown) => opts.targetId && obj && typeof obj === 'object' && !Array.isArray(obj) - ? { ...(obj as Record), id: (obj as Record).id ?? opts.targetId } + ? { ...(obj as Record), id: opts.targetId } : obj; let targetPath: string; diff --git a/src/server/ai/guides.ts b/src/server/ai/guides.ts index 5d3b16f..4906066 100644 --- a/src/server/ai/guides.ts +++ b/src/server/ai/guides.ts @@ -26,7 +26,8 @@ export function buildSurfaceGuideAndInventory( targetPath?: string; } = {}, ): SurfaceGuideResult { - const { configManager, vaultService, sshPool } = deps; + const { configManager, sshPool } = deps; + void deps.vaultService; const servers = configManager.listServers(); const systems = configManager.listSystems(); const snippets = configManager.getSnippets().snippets; @@ -51,10 +52,6 @@ export function buildSurfaceGuideAndInventory( actions: sys.actions.map((a) => ({ id: a.id, scope: a.scope, mode: a.mode })), })); - const credMeta = vaultService.isRuntimeReady - ? vaultService.listMetadata().map((c) => ({ id: c.id, name: c.name, type: c.type })) - : []; - const targetSrv = opts.serverId ? configManager.getServer(opts.serverId) : undefined; const targetSrvOs = opts.serverId ? sshPool.getState(opts.serverId)?.osDetected ?? targetSrv?.osHint ?? 'unknown' @@ -67,7 +64,6 @@ export function buildSurfaceGuideAndInventory( existingWorkflowIds: workflows.map((w) => w.id), existingSnippetIds: snippets.map((s) => s.id), alertChannelIds: alerts.channels.map((c) => c.id), - vaultCredentialRefs: credMeta, ...(opts.serverId ? { focusedServer: { id: opts.serverId, os: targetSrvOs } } : {}), ...(opts.targetPath ? { focusedConfigPath: opts.targetPath } : {}), }, diff --git a/src/server/ai/redactor.ts b/src/server/ai/redactor.ts index 43a4fe8..dc4b5bb 100644 --- a/src/server/ai/redactor.ts +++ b/src/server/ai/redactor.ts @@ -6,9 +6,7 @@ export interface RedactionResult { truncated: boolean; } -function escapeRegExp(literal: string): string { - return literal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); -} +const MIN_VAULT_SECRET_LEN = 4; export function collectVaultSecretStrings(vaultService: VaultService): string[] { if (!vaultService.isRuntimeReady) return []; @@ -18,21 +16,21 @@ export function collectVaultSecretStrings(vaultService: VaultService): string[] const creds = vaultService.exportAllCredentials(); for (const cred of Object.values(creds)) { if (cred.type === 'ssh-password' || cred.type === 'sudo-password') { - if (cred.password.length >= 6) collected.add(cred.password); + if (cred.password.length >= MIN_VAULT_SECRET_LEN) collected.add(cred.password); } else if (cred.type === 'webhook-secret') { - if (cred.secret.length >= 6) collected.add(cred.secret); + if (cred.secret.length >= MIN_VAULT_SECRET_LEN) collected.add(cred.secret); } else if (cred.type === 'api-token') { - if (cred.token.length >= 6) collected.add(cred.token); + if (cred.token.length >= MIN_VAULT_SECRET_LEN) collected.add(cred.token); } else if (cred.type === 'ssh-key') { const trimmed = cred.privateKey.trim(); - if (trimmed.length >= 6) collected.add(trimmed); + if (trimmed.length >= MIN_VAULT_SECRET_LEN) collected.add(trimmed); for (const line of trimmed.split(/\r?\n/)) { const l = line.trim(); if (l.length >= 12 && !l.startsWith('-----')) { collected.add(l); } } - if (cred.passphrase && cred.passphrase.length >= 6) { + if (cred.passphrase && cred.passphrase.length >= MIN_VAULT_SECRET_LEN) { collected.add(cred.passphrase); } } @@ -44,6 +42,119 @@ export function collectVaultSecretStrings(vaultService: VaultService): string[] return [...collected].sort((a, b) => b.length - a.length); } +function replaceLiteralLinear( + text: string, + needle: string, + replacement: string, +): { text: string; hits: number } { + if (!needle) return { text, hits: 0 }; + let idx = text.indexOf(needle); + if (idx < 0) return { text, hits: 0 }; + let out = ''; + let last = 0; + let hits = 0; + while (idx >= 0) { + out += text.slice(last, idx) + replacement; + last = idx + needle.length; + hits += 1; + idx = text.indexOf(needle, last); + } + out += text.slice(last); + return { text: out, hits }; +} + +/** + * Linear-time PEM private key block scanner (catches both complete blocks and + * truncated logs containing only `-----BEGIN ... PRIVATE KEY-----` headers). + */ +function stripPemPrivateKeys(input: string): { text: string; hits: number } { + const beginMarker = '-----BEGIN '; + let idx = input.indexOf(beginMarker); + if (idx < 0) return { text: input, hits: 0 }; + + let out = ''; + let last = 0; + let hits = 0; + + while (idx >= 0) { + const headerEnd = input.indexOf('-----', idx + beginMarker.length); + if (headerEnd < 0 || headerEnd - idx > 80) break; + const headerSlice = input.slice(idx + beginMarker.length, headerEnd); + if (!/PRIVATE KEY$/i.test(headerSlice)) { + idx = input.indexOf(beginMarker, headerEnd + 5); + continue; + } + + const endHeader = `-----END ${headerSlice}-----`; + const footerPos = input.indexOf(endHeader, headerEnd + 5); + let blockEnd: number; + if (footerPos >= 0) { + blockEnd = footerPos + endHeader.length; + } else { + // Truncated PEM: strip from BEGIN header up to a blank line or 8 KiB + const blank = input.indexOf('\n\n', headerEnd + 5); + blockEnd = + blank >= 0 + ? blank + : Math.min(input.length, headerEnd + 5 + 8192); + } + + out += input.slice(last, idx) + '[REDACTED_PRIVATE_KEY]'; + hits += 1; + last = blockEnd; + idx = input.indexOf(beginMarker, last); + } + + out += input.slice(last); + return { text: out, hits }; +} + +/** + * Linear-time O(n) JSON `"secretKey": "secretVal"` scrubber without ReDoS-prone + * nested escape quantifiers. + */ +function stripJsonSecretValues(input: string): { text: string; hits: number } { + const keyRe = + /"[A-Za-z0-9_-]{0,40}(?:password|passwd|secret|token|apiKey|api_key|privateKey|private_key|passphrase|accessKey|secretKey|client_secret|refresh_token)[A-Za-z0-9_-]{0,40}"\s*:\s*"/gi; + let out = ''; + let last = 0; + let hits = 0; + let m: RegExpExecArray | null; + + while ((m = keyRe.exec(input)) !== null) { + const valStart = m.index + m[0].length; + if (valStart < last) continue; + + // Scan forward strictly once in O(k) checking backslash escapes + let pos = valStart; + let closed = false; + while (pos < input.length) { + const ch = input.charCodeAt(pos); + if (ch === 92 /* '\\' */) { + pos += 2; + continue; + } + if (ch === 34 /* '"' */) { + closed = true; + break; + } + if (ch === 10 || ch === 13) break; + pos += 1; + } + + const valSlice = input.slice(valStart, pos); + if (valSlice.includes('[REDACTED')) continue; + + out += input.slice(last, valStart) + '[REDACTED_SECRET]' + (closed ? '"' : ''); + hits += 1; + last = closed ? pos + 1 : pos; + keyRe.lastIndex = last; + } + + out += input.slice(last); + return { text: out, hits }; +} + export function redactSecrets( input: string, knownSecrets: string[] = [], @@ -52,27 +163,22 @@ export function redactSecrets( let redactedCount = 0; let text = input ?? ''; - // 1. Strip PEM / OpenSSH private key blocks - const keyBlockRe = - /-----BEGIN [A-Z0-9 -]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 -]*PRIVATE KEY-----/g; - text = text.replace(keyBlockRe, () => { - redactedCount += 1; - return '[REDACTED_PRIVATE_KEY]'; - }); + // 1. Complete & truncated PEM / OpenSSH private keys in O(n) + const pem = stripPemPrivateKeys(text); + text = pem.text; + redactedCount += pem.hits; - // 2. Strip known secrets currently held in Vault + // 2. Vault secrets >= 4 chars in O(n * m) for (const secret of knownSecrets) { - if (secret.length < 6) continue; - const re = new RegExp(escapeRegExp(secret), 'g'); - text = text.replace(re, () => { - redactedCount += 1; - return '[REDACTED_VAULT_SECRET]'; - }); + if (secret.length < MIN_VAULT_SECRET_LEN) continue; + const res = replaceLiteralLinear(text, secret, '[REDACTED_VAULT_SECRET]'); + text = res.text; + redactedCount += res.hits; } - // 3. Strip HTTP Authorization / Bearer / custom secret headers + // 3. HTTP Authorization / Cookie / Proxy / custom secret headers text = text.replace( - /\b(Authorization\s*:\s*(?:Bearer|Basic)\s+)([^\r\n]+)/gi, + /\b((?:Proxy-)?Authorization\s*:\s*(?:Bearer|Basic|Token)\s+)([^\r\n]{1,1024})/gi, (_m, prefix: string, val: string) => { if (val.includes('[REDACTED')) return _m; redactedCount += 1; @@ -80,25 +186,45 @@ export function redactSecrets( }, ); text = text.replace( - /\bBearer\s+([A-Za-z0-9._~+/=-]{12,})/g, - (_m, val: string) => { + /\b(Cookie|Set-Cookie|X-API-Key|X-Auth-Token|X-Telegram-Bot-Token|X-Access-Token)\s*:\s*([^\r\n]{1,1024})/gi, + (_m, key: string, val: string) => { if (val.includes('[REDACTED')) return _m; redactedCount += 1; - return 'Bearer [REDACTED_TOKEN]'; + return `${key}: [REDACTED_TOKEN]`; }, ); text = text.replace( - /\b(X-(?:API-Key|Telegram-Bot-Token|Auth-Token)\s*:\s*)([^\s\r\n]+)/gi, - (_m, prefix: string, val: string) => { - if (val.includes('[REDACTED')) return _m; + /\b(?:Bearer|Basic)\s+([A-Za-z0-9._~+/=-]{8,1024})/g, + (full, val: string) => { + if (val.includes('[REDACTED')) return full; redactedCount += 1; - return `${prefix}[REDACTED_TOKEN]`; + return full.startsWith('Basic') ? 'Basic [REDACTED_TOKEN]' : 'Bearer [REDACTED_TOKEN]'; }, ); - // 4. Strip .env / shell KEY=value secret assignments + // 4. URL embedded credentials (user:pass@host) text = text.replace( - /(^|[\s;|&])([A-Za-z0-9_]*(?:PASSWORD|PASSWD|SECRET|TOKEN|API_KEY|APIKEY|PRIVATE_KEY|PASSPHRASE)[A-Za-z0-9_]*)=("[^"\n]*"|'[^'\n]*'|[^\s\r\n]+)/gim, + /([a-zA-Z][a-zA-Z0-9+.-]{1,15}:\/\/[^:/\s@]{1,64}:)([^/\s@]{1,256})@/g, + (_m, prefix: string, pw: string) => { + if (pw.includes('[REDACTED')) return _m; + redactedCount += 1; + return `${prefix}[REDACTED_SECRET]@`; + }, + ); + + // 5. Known API/cloud token formats + text = text.replace( + /\b(?:sk-[A-Za-z0-9_-]{12,256}|gh[pou]_[A-Za-z0-9]{12,256}|github_pat_[A-Za-z0-9_]{16,256}|AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{10,256}|AIza[0-9A-Za-z_-]{20,64}|glpat-[A-Za-z0-9_-]{12,256})/g, + (tok) => { + if (tok.includes('[REDACTED')) return tok; + redactedCount += 1; + return '[REDACTED_TOKEN]'; + }, + ); + + // 6. .env / shell KEY=value secret assignments (linear bounded match) + text = text.replace( + /(^|[\s;|&])([A-Za-z0-9_]{0,48}(?:PASSWORD|PASSWD|SECRET|TOKEN|API_KEY|APIKEY|PRIVATE_KEY|PASSPHRASE|ACCESS_KEY|CREDENTIAL)[A-Za-z0-9_]{0,48})=([^\s\r\n]{1,512}|"[^"\r\n]{0,512}"|'[^'\r\n]{0,512}')/gim, (_m, lead: string, key: string, rawVal: string) => { if (rawVal.includes('[REDACTED')) return _m; redactedCount += 1; @@ -106,15 +232,10 @@ export function redactSecrets( }, ); - // 5. Strip JSON "key": "secret" string properties - text = text.replace( - /("(?:[A-Za-z0-9_-]*(?:password|passwd|secret|token|apiKey|api_key|privateKey|private_key|passphrase)[A-Za-z0-9_-]*)"\s*:\s*)"([^"\\]*(?:\\.[^"\\]*)*)"/gi, - (_m, keyPrefix: string, val: string) => { - if (val.includes('[REDACTED')) return _m; - redactedCount += 1; - return `${keyPrefix}"[REDACTED_SECRET]"`; - }, - ); + // 7. JSON "key": "secret" string properties in O(n) + const jsonRes = stripJsonSecretValues(text); + text = jsonRes.text; + redactedCount += jsonRes.hits; const cap = Math.max(256, maxChars); let truncated = false; diff --git a/src/server/alerts/alert-engine.ts b/src/server/alerts/alert-engine.ts index ba8189f..765e58f 100644 --- a/src/server/alerts/alert-engine.ts +++ b/src/server/alerts/alert-engine.ts @@ -5,6 +5,7 @@ import type { AlertChannel, AlertRule, AlertRuleTargetSchema, + SecurityEventKind, } from '../../shared/schemas/alerts.schema.js'; import type { ServerConfig } from '../../shared/schemas/server.schema.js'; import type { z } from 'zod'; @@ -17,6 +18,7 @@ import type { MonitoringTickEvent, } from '../monitoring/monitoring-service.js'; import type { AuditService } from '../security/audit.js'; +import { fetchWithEgressGuard } from '../security/egress-guard.js'; import type { VaultService } from '../security/vault.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; import type { @@ -63,6 +65,7 @@ export class AlertEngine { private readonly emittedOffline = new Set(); private readonly prevProbeOk = new Map(); private readonly prevSystemDown = new Set(); + private readonly channelCircuit = new Map(); private readonly unsubs: Array<() => void> = []; private sweepTimer: NodeJS.Timeout | null = null; private stopped = false; @@ -298,16 +301,20 @@ export class AlertEngine { throw new Error(`Unknown alert channel "${channelId}"`); } - const res = await this.dispatchToChannel(ch, { - id: `test-${crypto.randomBytes(4).toString('hex')}`, - ruleId: 'test-alert', - serverId: 'hub', - severity: 'warn', - title: '[TEST] GCoordinator Alert Channel Verification', - message: `Test notification dispatched to "${ch.name}" (${ch.type}) at ${new Date().toISOString()}.`, - state: 'firing', - ts: Date.now(), - }); + const res = await this.dispatchToChannel( + ch, + { + id: `test-${crypto.randomBytes(4).toString('hex')}`, + ruleId: 'test-alert', + serverId: 'hub', + severity: 'warn', + title: '[TEST] GCoordinator Alert Channel Verification', + message: `Test notification dispatched to "${ch.name}" (${ch.type}) at ${new Date().toISOString()}.`, + state: 'firing', + ts: Date.now(), + }, + { bypassCircuitBreaker: true }, + ); this.auditService.log({ action: 'alert.test_channel', @@ -355,10 +362,6 @@ export class AlertEngine { } } } - - for (const probe of event.probes) { - await this.evaluateProbe(server.id, probe, nowMs); - } } async evaluateProbe( @@ -688,7 +691,151 @@ export class AlertEngine { } } + syncWithConfig(): void { + const alerts = this.configManager.getAlerts(); + const activeRuleIds = new Set(alerts.rules.filter((r) => r.enabled).map((r) => r.id)); + const activeServerIds = new Set( + this.configManager.listServers().filter((s) => s.enabled).map((s) => s.id), + ); + const now = Date.now(); + let changed = false; + + for (const [key, state] of this.incidents.entries()) { + const parts = key.split('::'); + const ruleId = parts[0] ?? ''; + const serverId = parts[1] ?? ''; + if (!activeRuleIds.has(ruleId) || (serverId !== 'hub' && !activeServerIds.has(serverId))) { + if (state.firingEventId) { + this.db + .prepare(`UPDATE alert_events SET state = 'resolved', resolved_at = ? WHERE id = ? AND state = 'firing'`) + .run(now, state.firingEventId); + changed = true; + } + this.incidents.delete(key); + } + } + + if (changed) { + this.wsHub.broadcastChannel(WS_CHANNELS.ALERTS, { + type: 'alerts:update', + activeCount: this.getActiveCount(), + }); + } + } + + async emitSecurityEvent( + eventType: SecurityEventKind | string, + payload: { + serverId?: string; + ip?: string; + message?: string; + details?: Record; + } = {}, + nowMs = Date.now(), + ): Promise { + if (this.stopped) return; + + const aliasMap: Record = { + 'auth.lockout': ['auth.lockout', 'login_burst'], + login_burst: ['login_burst', 'auth.lockout'], + 'auth.totp_replay': ['auth.totp_replay', 'login_burst'], + 'auth.recovery_code_used': ['auth.recovery_code_used', 'new_ip_login'], + 'auth.session_idle_expired': ['auth.session_idle_expired'], + 'ssh.host_key_mismatch': ['ssh.host_key_mismatch'], + 'vault.panic_lock': ['vault.panic_lock', 'panic_lock'], + panic_lock: ['panic_lock', 'vault.panic_lock'], + }; + const matchSet = new Set(aliasMap[eventType] ?? [eventType]); + + const rules = this.configManager + .getAlerts() + .rules.filter( + (r) => + r.enabled && + r.kind === 'security-event' && + r.events.some((ev) => matchSet.has(ev)), + ); + + if (rules.length === 0) return; + + const server = payload.serverId ? this.configManager.getServer(payload.serverId) : undefined; + const msgSuffix = + payload.message ?? + (payload.ip ? `source IP ${payload.ip}` : 'hub security boundary'); + const summaryMsg = `SECURITY [${eventType}]: ${msgSuffix}`; + + for (const rule of rules) { + if (rule.kind !== 'security-event') continue; + if (server && !this.matchesTarget(rule.target, server)) continue; + + const incKey = `${rule.id}::${server?.id ?? 'hub'}::sec::${eventType}`; + const state = this.incidents.get(incKey) ?? { consecutiveFailures: 0 }; + const inCooldown = + state.lastNotifiedAt !== undefined && + nowMs - state.lastNotifiedAt < rule.cooldownSec * 1000; + const silences = this.listSilences(nowMs); + const silenced = silences.some( + (s) => + s.scopeType === 'all' || + (s.scopeType === 'rule' && s.targetId === rule.id) || + (server && s.scopeType === 'server' && s.targetId === server.id), + ); + + const eventId = `evt-${crypto.randomBytes(6).toString('hex')}`; + const initialStatus = silenced ? 'suppressed' : inCooldown ? 'cooldown' : 'pending'; + + this.db + .prepare( + `INSERT INTO alert_events (id, rule_id, server_id, state, severity, message, webhook_status, triggered_at, resolved_at, incident_key) + VALUES (?, ?, ?, 'firing', ?, ?, ?, ?, NULL, ?)`, + ) + .run( + eventId, + rule.id, + server?.id ?? null, + rule.severity, + summaryMsg, + initialStatus, + nowMs, + incKey, + ); + + this.wsHub.broadcastChannel(WS_CHANNELS.ALERTS, { + type: 'alerts:update', + activeCount: this.getActiveCount(), + event: { + id: eventId, + ruleId: rule.id, + serverId: server?.id, + severity: rule.severity, + message: summaryMsg, + ts: nowMs, + }, + }); + + if (!silenced && !inCooldown && rule.channelIds.length > 0) { + state.lastNotifiedAt = nowMs; + this.incidents.set(incKey, state); + const statusText = await this.dispatchRuleChannels(rule.channelIds, { + id: eventId, + ruleId: rule.id, + serverId: server?.id ?? 'hub', + severity: rule.severity, + title: `[SECURITY ${rule.severity.toUpperCase()}] ${rule.name}`, + message: summaryMsg, + state: 'firing', + ts: nowMs, + }); + this.db + .prepare('UPDATE alert_events SET webhook_status = ? WHERE id = ?') + .run(statusText, eventId); + } + } + } + private matchesTarget(target: AlertRuleTarget, server: ServerConfig): boolean { + if (target.all) return true; + if (!target.serverId && (!target.tags || target.tags.length === 0)) return false; if (target.serverId && target.serverId !== server.id) return false; if (target.tags && target.tags.length > 0) { if (!server.tags.some((t) => target.tags!.includes(t))) return false; @@ -751,11 +898,8 @@ export class AlertEngine { private readChannelSecret(secretRef: string): string | null { if (!this.vaultService.isRuntimeReady) return null; const cred = this.vaultService.getRuntimeSecret(secretRef); - if (!cred) return null; - if (cred.type === 'webhook-secret') return cred.secret; - if (cred.type === 'api-token') return cred.token; - if (cred.type === 'ssh-password' || cred.type === 'sudo-password') return cred.password; - return null; + if (!cred || cred.type !== 'webhook-secret') return null; + return cred.secret; } private async dispatchToChannel( @@ -770,15 +914,30 @@ export class AlertEngine { state: 'firing' | 'resolved'; ts: number; }, + opts: { bypassCircuitBreaker?: boolean } = {}, ): Promise<{ ok: boolean; statusCode?: number; error?: string }> { - const secret = channel.secretRef ? this.readChannelSecret(channel.secretRef) : null; - if (!secret && !channel.url) { - return { ok: false, error: `Missing vault secret "${channel.secretRef ?? ''}"` }; + const cb = this.channelCircuit.get(channel.id); + if (!opts.bypassCircuitBreaker && cb && cb.openUntil > Date.now()) { + return { ok: false, error: 'Channel circuit breaker temporarily open after repeated failures' }; } + const secret = channel.secretRef ? this.readChannelSecret(channel.secretRef) : null; + if (channel.secretRef && !secret) { + return { + ok: false, + error: `Missing or incompatible webhook-secret "${channel.secretRef}" in Vault`, + }; + } + if (!secret && !channel.url) { + return { ok: false, error: 'Missing alert channel URL and webhook-secret' }; + } + + const redactErr = (raw: string): string => + secret && secret.length > 0 ? raw.split(secret).join('[REDACTED]') : raw; + try { let targetUrl = channel.url ?? ''; - let method = 'POST'; + const method = 'POST'; const headers: Record = {}; let body: string; @@ -831,24 +990,42 @@ export class AlertEngine { body = JSON.stringify(payload); } - const res = await fetch(targetUrl, { - method, - headers, - body, - signal: AbortSignal.timeout(10_000), - }); + const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; + const res = await fetchWithEgressGuard( + targetUrl, + { method, headers, body }, + { allowedCidrs, timeoutMs: 10_000 }, + ); + + if (res.ok) { + this.channelCircuit.delete(channel.id); + } else { + this.recordChannelFailure(channel.id); + } + return { ok: res.ok, statusCode: res.status, error: res.ok ? undefined : `HTTP ${res.status}`, }; } catch (err) { + this.recordChannelFailure(channel.id); return { ok: false, - error: err instanceof Error ? err.message : String(err), + error: redactErr(err instanceof Error ? err.message : String(err)), }; } } + + private recordChannelFailure(channelId: string): void { + const cur = this.channelCircuit.get(channelId) ?? { failures: 0, openUntil: 0 }; + cur.failures += 1; + if (cur.failures >= 5) { + cur.openUntil = Date.now() + 60_000; + cur.failures = 0; + } + this.channelCircuit.set(channelId, cur); + } } function compareOp( diff --git a/src/server/api/routes/ai.routes.ts b/src/server/api/routes/ai.routes.ts index 6f45cec..0fdb554 100644 --- a/src/server/api/routes/ai.routes.ts +++ b/src/server/api/routes/ai.routes.ts @@ -1,23 +1,30 @@ -import { Router } from 'express'; +import { Router, type RequestHandler } from 'express'; import { z } from 'zod'; import { EntityIdSchema } from '../../../shared/schemas/common.js'; -import { AiDisabledError, AiDraftKindSchema, type AiService } from '../../ai/ai-service.js'; +import { + AiDisabledError, + AiDraftKindSchema, + AiOverloadError, + type AiService, +} from '../../ai/ai-service.js'; import { AiSurfaceSchema } from '../../ai/guides.js'; import type { AuthService } from '../../security/auth.js'; import { enforceSafeMode, requireAuth, requireCsrf, + requireStepUp, } from '../../security/guards.js'; export interface AiRouterDeps { authService: AuthService; aiService: AiService; + stepUpGuard?: RequestHandler; } export function createAiRouter(deps: AiRouterDeps): Router { const router = Router(); - const { authService, aiService } = deps; + const { authService, aiService, stepUpGuard = requireStepUp } = deps; // Read-only context redaction & preview (Safe-Mode exempt) router.post('/context-preview', requireAuth(authService), requireCsrf, (req, res) => { @@ -56,8 +63,8 @@ export function createAiRouter(deps: AiRouterDeps): Router { res.json(aiService.validateDraft(parsed.data)); }); - // Strictly read-only draft streaming: never auto-executes commands (Safe-Mode exempt) - router.post('/chat', requireAuth(authService), requireCsrf, (req, res) => { + // Read-only draft streaming: Safe-Mode exempt, stepUpGuard protects Vault API token egress + router.post('/chat', requireAuth(authService), requireCsrf, stepUpGuard, (req, res) => { const parsed = z .object({ chatId: z.string().min(1).max(64).optional(), @@ -90,8 +97,8 @@ export function createAiRouter(deps: AiRouterDeps): Router { }); res.status(202).json(started); } catch (err) { - if (err instanceof AiDisabledError) { - res.status(403).json({ error: err.code, message: err.message }); + if (err instanceof AiDisabledError || err instanceof AiOverloadError) { + res.status(err.status).json({ error: err.code, message: err.message }); return; } res.status(400).json({ @@ -106,22 +113,29 @@ export function createAiRouter(deps: AiRouterDeps): Router { res.json({ cancelled: aiService.cancelChat(chatId) }); }); - router.post('/test', requireAuth(authService), requireCsrf, enforceSafeMode, async (req, res) => { - const parsed = z - .object({ - baseUrl: z.string().url().optional(), - model: z.string().min(1).optional(), - secretRef: z.string().max(64).optional(), - }) - .safeParse(req.body ?? {}); + router.post( + '/test', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + async (req, res) => { + const parsed = z + .object({ + baseUrl: z.string().url().optional(), + model: z.string().min(1).optional(), + secretRef: z.string().max(64).optional(), + }) + .safeParse(req.body ?? {}); - if (!parsed.success) { - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } - res.json(await aiService.testEndpoint(parsed.data)); - }); + res.json(await aiService.testEndpoint(parsed.data)); + }, + ); return router; } diff --git a/src/server/api/routes/alerts.routes.ts b/src/server/api/routes/alerts.routes.ts index bfb82f7..0b2c345 100644 --- a/src/server/api/routes/alerts.routes.ts +++ b/src/server/api/routes/alerts.routes.ts @@ -1,4 +1,4 @@ -import { Router } from 'express'; +import { Router, type RequestHandler } from 'express'; import { ZodError, z } from 'zod'; import { AlertsFileSchema } from '../../../shared/schemas/alerts.schema.js'; import type { AlertEngine } from '../../alerts/alert-engine.js'; @@ -9,6 +9,7 @@ import { enforceSafeMode, requireAuth, requireCsrf, + requireStepUp, } from '../../security/guards.js'; export interface AlertsRouterDeps { @@ -16,11 +17,13 @@ export interface AlertsRouterDeps { configManager: ConfigManager; auditService: AuditService; alertEngine: AlertEngine; + stepUpGuard?: RequestHandler; } export function createAlertsRouter(deps: AlertsRouterDeps): Router { const router = Router(); - const { authService, configManager, auditService, alertEngine } = deps; + const { authService, configManager, auditService, alertEngine, stepUpGuard = requireStepUp } = + deps; router.get('/', requireAuth(authService), (req, res) => { const limit = typeof req.query.limit === 'string' ? Number(req.query.limit) : 50; @@ -30,41 +33,48 @@ export function createAlertsRouter(deps: AlertsRouterDeps): Router { }); }); - router.put('/config', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { - try { - const parsed = AlertsFileSchema.parse({ version: 1, ...(req.body ?? {}) }); - const saved = configManager.saveConfigText( - 'alerts.json', - JSON.stringify(parsed, null, 2), - 'ui', - 'Updated alerts configuration via UI', - ); - auditService.log({ - action: 'alerts.config_update', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: 'alerts.json', - status: 'ok', - }); - res.json({ alertsConfig: saved.config, warnings: saved.warnings }); - } catch (err) { - if (err instanceof ZodError) { - res.status(400).json({ - error: 'VALIDATION_ERROR', - message: 'Invalid alerts configuration', - issues: err.issues.map((i) => ({ - path: i.path.join('.') || '(root)', - message: i.message, - })), + router.put( + '/config', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + (req, res) => { + try { + const parsed = AlertsFileSchema.parse({ version: 1, ...(req.body ?? {}) }); + const saved = configManager.saveConfigText( + 'alerts.json', + JSON.stringify(parsed, null, 2), + 'ui', + 'Updated alerts configuration via UI', + ); + auditService.log({ + action: 'alerts.config_update', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: 'alerts.json', + status: 'ok', + }); + res.json({ alertsConfig: saved.config, warnings: saved.warnings }); + } catch (err) { + if (err instanceof ZodError) { + res.status(400).json({ + error: 'VALIDATION_ERROR', + message: 'Invalid alerts configuration', + issues: err.issues.map((i) => ({ + path: i.path.join('.') || '(root)', + message: i.message, + })), + }); + return; + } + res.status(400).json({ + error: 'ALERTS_SAVE_ERROR', + message: err instanceof Error ? err.message : 'Unable to save alerts configuration', }); - return; } - res.status(400).json({ - error: 'ALERTS_SAVE_ERROR', - message: err instanceof Error ? err.message : 'Unable to save alerts configuration', - }); - } - }); + }, + ); router.post( '/silences', @@ -122,6 +132,7 @@ export function createAlertsRouter(deps: AlertsRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, + stepUpGuard, async (req, res) => { const id = String(req.params.id ?? ''); try { diff --git a/src/server/app.ts b/src/server/app.ts index b35ebd0..5e525b2 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -245,6 +245,7 @@ export async function createGCoordinatorServer( sshPool, wsHub, auditService, + getRuntimeLimits, ); const backupScheduler = new BackupScheduler( dataDir, @@ -396,6 +397,21 @@ export async function createGCoordinatorServer( }); }); + authService.setSecurityEventListener((ev) => { + void alertEngine.emitSecurityEvent(ev.type, { + ip: ev.ip, + details: ev.details, + message: `${ev.type}${ev.ip ? ` from ${ev.ip}` : ''}`, + }); + }); + + knownHosts.onHostKeyMismatch((alert) => { + void alertEngine.emitSecurityEvent('ssh.host_key_mismatch', { + serverId: alert.serverId, + message: `Host key mismatch on ${alert.hostPortKey} (${alert.algorithm})`, + }); + }); + monitoringService.start(); void tunnelManager.syncAutoStart(); customSystemsEngine.syncBackgroundChecks(); @@ -419,6 +435,9 @@ export async function createGCoordinatorServer( }); vaultService.onPanicLock(() => { + void alertEngine.emitSecurityEvent('vault.panic_lock', { + message: 'Emergency Panic Lock activated', + }); aiService.cancelAll(); backupScheduler.stop(); alertEngine.handlePanicLock(); @@ -442,6 +461,9 @@ export async function createGCoordinatorServer( warnings: event.warnings, errors: event.errors, }); + if (event.entityType === 'alerts' || event.entityType === 'server' || event.entityType === 'all') { + alertEngine.syncWithConfig(); + } if ( event.entityType === 'server' || event.entityType === 'system' || @@ -456,22 +478,32 @@ export async function createGCoordinatorServer( customSystemsEngine.invalidateCache(event.id); } else if (event.entityType === 'system' && event.id) { customSystemsEngine.invalidateCache(undefined, event.id); - } else { + } else if (event.entityType === 'all') { customSystemsEngine.invalidateCache(); } - if (event.entityType === 'settings') { + if (event.entityType === 'settings' || event.entityType === 'all') { applyDatabaseThrottlePragmas(db, getRuntimeLimits()); if (!configManager.getSettings().security.enableEmergencySecretsBackup) { recoveryStore.wipeAll(); } else { authService.syncRecovery(); } + backupScheduler.sync(); + } + if (event.entityType === 'server' || event.entityType === 'all') { + monitoringService.syncServers(); + void tunnelManager.syncAutoStart(); + } + if ( + event.entityType === 'server' || + event.entityType === 'system' || + event.entityType === 'all' + ) { + customSystemsEngine.syncBackgroundChecks(); + } + if (event.entityType === 'workflow' || event.entityType === 'all') { + workflowEngine.syncCronJobs(); } - monitoringService.syncServers(); - customSystemsEngine.syncBackgroundChecks(); - workflowEngine.syncCronJobs(); - backupScheduler.sync(); - void tunnelManager.syncAutoStart(); } }); @@ -593,9 +625,9 @@ export async function createGCoordinatorServer( ); app.use( '/api/alerts', - createAlertsRouter({ authService, configManager, auditService, alertEngine }), + createAlertsRouter({ authService, configManager, auditService, alertEngine, stepUpGuard }), ); - app.use('/api/ai', createAiRouter({ authService, aiService })); + app.use('/api/ai', createAiRouter({ authService, aiService, stepUpGuard })); app.use( '/api/servers/:id/sftp', createSftpRouter({ authService, configManager, auditService, sftpService, stepUpGuard }), diff --git a/src/shared/schemas/alerts.schema.ts b/src/shared/schemas/alerts.schema.ts index 1c0959f..26f751b 100644 --- a/src/shared/schemas/alerts.schema.ts +++ b/src/shared/schemas/alerts.schema.ts @@ -58,6 +58,12 @@ export const SecurityEventKindSchema = z.enum([ 'panic_lock', 'key_rotation', 'backup_restore', + 'auth.lockout', + 'auth.totp_replay', + 'auth.recovery_code_used', + 'auth.session_idle_expired', + 'ssh.host_key_mismatch', + 'vault.panic_lock', ]); export const AlertRuleSchema = z.discriminatedUnion('kind', [ diff --git a/tests/ai-assistant.test.ts b/tests/ai-assistant.test.ts index 48d5181..66f40b7 100644 --- a/tests/ai-assistant.test.ts +++ b/tests/ai-assistant.test.ts @@ -287,6 +287,19 @@ describe('Phase 5: Optional BYO-API AI Assistant, Secret Redactor, Surface Guide // Write-lock Vault -> AI runtime secret still works via VaultService.getRuntimeSecret expect((await api('/api/vault/lock', { method: 'POST' })).data.state).toBe('locked'); + // Default Zero-Trust egress policy blocks outbound calls to loopback until allowlisted + const blockedEp = await api('/api/ai/test', { method: 'POST', body: {} }); + expect(blockedEp.data.ok).toBe(false); + + expect( + ( + await api('/api/auth/security-policy', { + method: 'PUT', + body: { egressAllowedCidrs: ['127.0.0.1/32'] }, + }) + ).status, + ).toBe(200); + const testEp = await api('/api/ai/test', { method: 'POST', body: {} }); expect(testEp.status).toBe(200); expect(testEp.data.ok).toBe(true); diff --git a/tests/alerts-engine.test.ts b/tests/alerts-engine.test.ts index 59f6380..c1caaca 100644 --- a/tests/alerts-engine.test.ts +++ b/tests/alerts-engine.test.ts @@ -415,6 +415,19 @@ describe('Phase 4: AlertEngine, Webhooks, Silences & Maintenance Windows', () => expect(lockRes.data.state).toBe('locked'); expect(lockRes.data.runtimeReady).toBe(true); + // Default Zero-Trust egress policy blocks webhook dispatch to 127.0.0.1 until allowlisted + const deniedWebhook = await api('/api/alerts/channels/ch-discord/test', { method: 'POST' }); + expect(deniedWebhook.data.ok).toBe(false); + + expect( + ( + await api('/api/auth/security-policy', { + method: 'PUT', + body: { egressAllowedCidrs: ['127.0.0.1/32'] }, + }) + ).status, + ).toBe(200); + // --- 1. Send Test Alert for all 4 channel types while Vault is write-locked --- for (const chId of ['ch-discord', 'ch-tg', 'ch-ntfy', 'ch-generic']) { const tRes = await api(`/api/alerts/channels/${chId}/test`, { method: 'POST' }); diff --git a/tests/workflows-and-transfer.test.ts b/tests/workflows-and-transfer.test.ts index ec1e5f2..70b63be 100644 --- a/tests/workflows-and-transfer.test.ts +++ b/tests/workflows-and-transfer.test.ts @@ -607,7 +607,7 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers expect(dagStart.status).toBe(202); const dagRunId = String(dagStart.data.runId); const dagDetail = await waitForWorkflowRun(server, dagRunId, 10_000); - expect(dagDetail.run.status).toBe('succeeded'); + expect(dagDetail.run.status, JSON.stringify(dagDetail.stepLogs)).toBe('succeeded'); const logByStep = new Map(dagDetail.stepLogs.map((l) => [l.stepId, l])); expect(logByStep.get('gen-token')?.stdout).toBe('tok-v42');