diff --git a/src/server/api/routes/config.routes.ts b/src/server/api/routes/config.routes.ts index 7bcde14..ef1b955 100644 --- a/src/server/api/routes/config.routes.ts +++ b/src/server/api/routes/config.routes.ts @@ -1,4 +1,4 @@ -import { Router } from 'express'; +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'; @@ -7,17 +7,29 @@ import { enforceSafeMode, requireAuth, requireCsrf, + requireStepUp, } from '../../security/guards.js'; export interface ConfigRouterDeps { authService: AuthService; configManager: ConfigManager; auditService: AuditService; + stepUpGuard?: RequestHandler; +} + +function isStepUpSensitiveConfigPath(rawPath: string): boolean { + const norm = rawPath.replace(/\\/g, '/').replace(/^\/+/, ''); + return norm === 'settings.json' || norm === 'alerts.json' || norm.startsWith('servers/'); } export function createConfigRouter(deps: ConfigRouterDeps): Router { const router = Router(); - const { authService, configManager, auditService } = deps; + const { + authService, + configManager, + auditService, + stepUpGuard = requireStepUp, + } = deps; router.get('/overview', requireAuth(authService), (_req, res) => { res.json({ @@ -63,38 +75,46 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router { return; } - try { - const saved = configManager.saveConfigText( - parsed.data.path, - parsed.data.content, - 'ui', - parsed.data.summary, - ); - auditService.log({ - action: 'config.save', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: saved.filePath, - status: 'ok', - }); - res.json(saved); - } catch (err) { - if (err instanceof ZodError) { - res.status(400).json({ - error: 'CONFIG_SCHEMA_ERROR', - message: 'Schema validation failed', - issues: err.issues.map((i) => ({ - path: i.path.join('.') || '(root)', - message: i.message, - })), + const executeSave = () => { + try { + const saved = configManager.saveConfigText( + parsed.data.path, + parsed.data.content, + 'ui', + parsed.data.summary, + ); + auditService.log({ + action: 'config.save', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: saved.filePath, + status: 'ok', + }); + res.json(saved); + } catch (err) { + if (err instanceof ZodError) { + res.status(400).json({ + error: 'CONFIG_SCHEMA_ERROR', + message: 'Schema validation failed', + issues: err.issues.map((i) => ({ + path: i.path.join('.') || '(root)', + message: i.message, + })), + }); + return; + } + res.status(400).json({ + error: 'CONFIG_SAVE_ERROR', + message: err instanceof Error ? err.message : 'Unable to save config file', }); - return; } - res.status(400).json({ - error: 'CONFIG_SAVE_ERROR', - message: err instanceof Error ? err.message : 'Unable to save config file', - }); + }; + + if (isStepUpSensitiveConfigPath(parsed.data.path)) { + stepUpGuard(req, res, executeSave); + return; } + executeSave(); }); router.delete( @@ -108,26 +128,34 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router { res.status(400).json({ error: 'MISSING_PATH' }); return; } - try { - const deleted = configManager.deleteEntityFile(filePath); - if (!deleted) { - res.status(404).json({ error: 'CONFIG_NOT_FOUND' }); - return; + const executeDelete = () => { + try { + const deleted = configManager.deleteEntityFile(filePath); + if (!deleted) { + res.status(404).json({ error: 'CONFIG_NOT_FOUND' }); + return; + } + auditService.log({ + action: 'config.delete', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: filePath, + status: 'ok', + }); + res.json({ deleted: true }); + } catch (err) { + res.status(400).json({ + error: 'CONFIG_DELETE_ERROR', + message: err instanceof Error ? err.message : 'Unable to delete config file', + }); } - auditService.log({ - action: 'config.delete', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: filePath, - status: 'ok', - }); - res.json({ deleted: true }); - } catch (err) { - res.status(400).json({ - error: 'CONFIG_DELETE_ERROR', - message: err instanceof Error ? err.message : 'Unable to delete config file', - }); + }; + + if (isStepUpSensitiveConfigPath(filePath)) { + stepUpGuard(req, res, executeDelete); + return; } + executeDelete(); }, ); @@ -174,23 +202,38 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router { res.status(400).json({ error: 'INVALID_REVISION_ID' }); return; } - try { - const result = configManager.rollbackRevision(id); - auditService.log({ - action: 'config.rollback', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: result.filePath, - status: 'ok', - details: { revisionId: id }, - }); - res.json(result); - } catch (err) { + const rev = configManager.getRevision(id); + if (!rev) { res.status(400).json({ error: 'ROLLBACK_FAILED', - message: err instanceof Error ? err.message : 'Rollback failed', + message: `Revision #${id} not found`, }); + return; } + const executeRollback = () => { + try { + const result = configManager.rollbackRevision(id); + auditService.log({ + action: 'config.rollback', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: result.filePath, + status: 'ok', + details: { revisionId: id }, + }); + res.json(result); + } catch (err) { + res.status(400).json({ + error: 'ROLLBACK_FAILED', + message: err instanceof Error ? err.message : 'Rollback failed', + }); + } + }; + if (isStepUpSensitiveConfigPath(rev.filePath)) { + stepUpGuard(req, res, executeRollback); + return; + } + executeRollback(); }, ); diff --git a/src/server/api/routes/vault.routes.ts b/src/server/api/routes/vault.routes.ts index 504f861..8cf4836 100644 --- a/src/server/api/routes/vault.routes.ts +++ b/src/server/api/routes/vault.routes.ts @@ -15,6 +15,7 @@ import { import { computeOpenSshFingerprint, generateMasterKeyBuffer, + validatePrivateKey, type VaultCredentialInput, type VaultService, } from '../../security/vault.js'; @@ -114,6 +115,7 @@ export function createVaultRouter(deps: VaultRouterDeps): { type: 'vault:state', vaultState: vaultService.state, vaultRuntimeReady: vaultService.isRuntimeReady, + vaultSealState: vaultService.sealState, isPanicLocked: vaultService.isPanicLocked, }); }; @@ -122,43 +124,52 @@ export function createVaultRouter(deps: VaultRouterDeps): { res.json({ state: vaultService.state, runtimeReady: vaultService.isRuntimeReady, + sealState: vaultService.sealState, isPanicLocked: vaultService.isPanicLocked, }); }); - vaultRouter.post('/init', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { - const ip = req.clientIp ?? 'unknown'; - const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {}); - if (!parsed.success) { - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - try { - const result = vaultService.initializeNewVault(parsed.data.masterKey); - notifyConfigReeval(); - onVaultUnlocked?.(); - onVaultChanged?.('vault-init'); - broadcastVaultState(); - auditService.log({ - action: 'vault.init', - actorIp: ip, - sessionIdHash: req.authSession!.idHash, - status: 'ok', - }); - res.status(201).json({ - state: vaultService.state, - runtimeReady: vaultService.isRuntimeReady, - generatedKeyHex: result.generatedKeyHex, - }); - } catch (err) { - res.status(400).json({ - error: 'VAULT_INIT_FAILED', - message: err instanceof Error ? err.message : 'Vault initialization failed', - }); - } - }); + vaultRouter.post( + '/init', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + (req, res) => { + const ip = req.clientIp ?? 'unknown'; + const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {}); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + try { + const result = vaultService.initializeNewVault(parsed.data.masterKey); + notifyConfigReeval(); + onVaultUnlocked?.(); + onVaultChanged?.('vault-init'); + broadcastVaultState(); + auditService.log({ + action: 'vault.init', + actorIp: ip, + sessionIdHash: req.authSession!.idHash, + status: 'ok', + }); + res.status(201).json({ + state: vaultService.state, + runtimeReady: vaultService.isRuntimeReady, + sealState: vaultService.sealState, + generatedKeyHex: result.generatedKeyHex, + }); + } catch (err) { + res.status(400).json({ + error: 'VAULT_INIT_FAILED', + message: err instanceof Error ? err.message : 'Vault initialization failed', + }); + } + }, + ); - vaultRouter.post('/unlock', requireAuth(authService), requireCsrf, (req, res) => { + vaultRouter.post('/unlock', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { const ip = req.clientIp ?? 'unknown'; const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {}); if (!parsed.success) { @@ -191,6 +202,7 @@ export function createVaultRouter(deps: VaultRouterDeps): { res.json({ state: vaultService.state, runtimeReady: vaultService.isRuntimeReady, + sealState: vaultService.sealState, isPanicLocked: vaultService.isPanicLocked, }); } catch (err) { @@ -231,6 +243,7 @@ export function createVaultRouter(deps: VaultRouterDeps): { res.json({ state: vaultService.state, runtimeReady: vaultService.isRuntimeReady, + sealState: vaultService.sealState, isPanicLocked: vaultService.isPanicLocked, }); } catch (err) { @@ -254,10 +267,35 @@ export function createVaultRouter(deps: VaultRouterDeps): { res.json({ state: vaultService.state, runtimeReady: vaultService.isRuntimeReady, + sealState: vaultService.sealState, isPanicLocked: vaultService.isPanicLocked, }); }); + vaultRouter.post( + '/seal', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + (req, res) => { + vaultService.seal(); + broadcastVaultState(); + auditService.log({ + action: 'vault.seal', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + status: 'ok', + }); + res.json({ + state: vaultService.state, + runtimeReady: vaultService.isRuntimeReady, + sealState: vaultService.sealState, + isPanicLocked: vaultService.isPanicLocked, + }); + }, + ); + // Panic Lock is ALWAYS reachable when authenticated + CSRF verified (even under Safe Mode!) panicLockHandler.post('/panic-lock', requireAuth(authService), requireCsrf, (req, res) => { const session = req.authSession!; @@ -299,6 +337,13 @@ export function createVaultRouter(deps: VaultRouterDeps): { requireAuth(authService), stepUpGuard, (req, res) => { + if (req.authSession?.safeMode || req.headers['x-gcoord-safe-mode'] === '1') { + res.status(423).json({ + error: 'SAFE_MODE_ACTIVE', + message: 'Disable Safe / Read-Only Mode before revealing secrets.', + }); + return; + } if (vaultService.state !== 'unlocked') { res.status(423).json({ error: 'VAULT_LOCKED' }); return; @@ -337,15 +382,27 @@ export function createVaultRouter(deps: VaultRouterDeps): { return; } const credInput: VaultCredentialInput = { ...parsed.data }; - if ( - credInput.type === 'ssh-key' && - credInput.publicKey && - !credInput.fingerprint - ) { + if (credInput.type === 'ssh-key') { try { - credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey); - } catch { - // Leave fingerprint omitted if user imported an unusual public key format + validatePrivateKey(credInput.privateKey, credInput.passphrase); + } catch (err) { + res.status(400).json({ + error: 'INVALID_SSH_KEY', + message: err instanceof Error ? err.message : 'Invalid SSH private key', + }); + return; + } + if (credInput.publicKey) { + try { + credInput.publicKey = credInput.publicKey.trim(); + credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey); + } catch (err) { + res.status(400).json({ + error: 'INVALID_SSH_PUBLIC_KEY', + message: err instanceof Error ? err.message : 'Invalid SSH public key', + }); + return; + } } } const meta = vaultService.upsertCredential(credInput); @@ -381,15 +438,27 @@ export function createVaultRouter(deps: VaultRouterDeps): { return; } const credInput: VaultCredentialInput = { ...parsed.data }; - if ( - credInput.type === 'ssh-key' && - credInput.publicKey && - !credInput.fingerprint - ) { + if (credInput.type === 'ssh-key') { try { - credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey); - } catch { - // Ignore non-standard public key strings + validatePrivateKey(credInput.privateKey, credInput.passphrase); + } catch (err) { + res.status(400).json({ + error: 'INVALID_SSH_KEY', + message: err instanceof Error ? err.message : 'Invalid SSH private key', + }); + return; + } + if (credInput.publicKey) { + try { + credInput.publicKey = credInput.publicKey.trim(); + credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey); + } catch (err) { + res.status(400).json({ + error: 'INVALID_SSH_PUBLIC_KEY', + message: err instanceof Error ? err.message : 'Invalid SSH public key', + }); + return; + } } } const meta = vaultService.upsertCredential(credInput); @@ -495,6 +564,12 @@ export function createVaultRouter(deps: VaultRouterDeps): { sessionIdHash: req.authSession!.idHash, expiresAt, }; + auditService.log({ + action: 'vault.rotate_key.prepare', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + status: 'ok', + }); res.json({ candidateKeyHex, confirmToken, expiresAt }); }, ); @@ -510,10 +585,17 @@ export function createVaultRouter(deps: VaultRouterDeps): { res.status(423).json({ error: 'VAULT_LOCKED' }); return; } + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('vault-rotate-commit', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; + } const parsed = z .object({ confirmToken: z.string().min(1), - confirmedKeyHex: z.string().min(1).optional(), + confirmedKeyHex: z.string().min(64).max(64), }) .safeParse(req.body); if (!parsed.success) { @@ -521,32 +603,57 @@ export function createVaultRouter(deps: VaultRouterDeps): { return; } + const timingEq = (a: string, b: string) => { + const ba = Buffer.from(a, 'utf8'); + const bb = Buffer.from(b, 'utf8'); + return ba.length === bb.length && crypto.timingSafeEqual(ba, bb); + }; + if ( !pendingRotation || pendingRotation.expiresAt <= Date.now() || pendingRotation.sessionIdHash !== req.authSession!.idHash || - pendingRotation.confirmToken !== parsed.data.confirmToken + !timingEq(pendingRotation.confirmToken, parsed.data.confirmToken) ) { + pendingRotation = null; + rateLimiter.recordFailure('vault-rotate-commit', ip); + auditService.log({ + action: 'vault.rotate_key.commit', + actorIp: ip, + sessionIdHash: req.authSession!.idHash, + status: 'denied', + }); res.status(400).json({ error: 'ROTATION_TOKEN_INVALID_OR_EXPIRED' }); return; } if ( - parsed.data.confirmedKeyHex && - parsed.data.confirmedKeyHex.trim().toLowerCase() !== - pendingRotation.candidateKeyHex.toLowerCase() + !timingEq( + parsed.data.confirmedKeyHex.trim().toLowerCase(), + pendingRotation.candidateKeyHex.toLowerCase(), + ) ) { + pendingRotation = null; + rateLimiter.recordFailure('vault-rotate-commit', ip); + auditService.log({ + action: 'vault.rotate_key.commit', + actorIp: ip, + sessionIdHash: req.authSession!.idHash, + status: 'denied', + details: { reason: 'key_confirmation_mismatch' }, + }); res.status(400).json({ error: 'KEY_CONFIRMATION_MISMATCH' }); return; } + rateLimiter.recordSuccess('vault-rotate-commit', ip); const nextHex = pendingRotation.candidateKeyHex; pendingRotation = null; vaultService.rotateMasterKey(nextHex); onVaultChanged?.('master-key-rotation'); auditService.log({ action: 'vault.rotate_key', - actorIp: req.clientIp ?? 'unknown', + actorIp: ip, sessionIdHash: req.authSession!.idHash, status: 'ok', }); diff --git a/src/server/app.ts b/src/server/app.ts index a4f433b..c0cdded 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -118,6 +118,7 @@ export async function createGCoordinatorServer( const auditService = new AuditService(db); const vaultService = new VaultService(vaultPath, { keyFilePath: path.join(dataDir, 'vault.key'), + allowLocalKeyFile: options.autoKeyFile ?? true, }); const recoveryStore = new EmergencyRecoveryService(dataDir); const rateLimiter = new RateLimiter({ db }); @@ -349,6 +350,19 @@ export async function createGCoordinatorServer( workflowEngine.start(); alertEngine.start(); + vaultService.onSeal(() => { + aiService.cancelAll(); + alertEngine.handlePanicLock(); + workflowEngine.handlePanicLock(); + broadcastService.cancelAll(); + monitoringService.stopAll(); + customSystemsEngine.stopBackgroundChecks(); + customSystemsEngine.cancelAllStreams(); + tunnelManager.stopAll(); + ptyManager.closeAll(true); + sshPool.closeAll('vault_sealed'); + }); + vaultService.onPanicLock(() => { aiService.cancelAll(); alertEngine.handlePanicLock(); @@ -391,7 +405,11 @@ export async function createGCoordinatorServer( } if (event.entityType === 'settings') { applyDatabaseThrottlePragmas(db, getRuntimeLimits()); - authService.syncRecovery(); + if (!configManager.getSettings().security.enableEmergencySecretsBackup) { + recoveryStore.wipeAll(); + } else { + authService.syncRecovery(); + } } monitoringService.syncServers(); customSystemsEngine.syncBackgroundChecks(); @@ -528,7 +546,7 @@ export async function createGCoordinatorServer( ); app.use( '/api/config', - createConfigRouter({ authService, configManager, auditService }), + createConfigRouter({ authService, configManager, auditService, stepUpGuard }), ); app.use('/api/audit', createAuditRouter(authService, auditService)); diff --git a/src/server/config/config-manager.ts b/src/server/config/config-manager.ts index f86cc2a..c23a4ba 100644 --- a/src/server/config/config-manager.ts +++ b/src/server/config/config-manager.ts @@ -368,6 +368,21 @@ export class ConfigManager { } } + for (const ch of this.alerts.channels) { + if ( + ch.url && + /(discord\.com\/api\/webhooks\/|api\.telegram\.org\/bot|[?&](token|key|secret|password)=)/i.test( + ch.url, + ) + ) { + next.push({ + filePath: 'alerts.json', + code: 'ALERT_INLINE_SECRET', + message: `Alert channel "${ch.id}" URL appears to contain an inline token/secret; store secrets in Vault via secretRef instead.`, + }); + } + } + for (const rule of this.alerts.rules) { for (const cid of rule.channelIds) { if (!channelIds.has(cid)) { @@ -604,6 +619,7 @@ export class ConfigManager { ignoreInitial: true, persistent: true, depth: 2, + followSymlinks: false, }); const scheduleReload = (absPath: string, kind: 'upsert' | 'unlink') => { @@ -813,11 +829,39 @@ export class ConfigManager { } private resolveSafeAbsPath(relPath: string): string { - const resolved = path.resolve(this.configDir, relPath); const root = path.resolve(this.configDir); + const resolved = path.resolve(root, relPath); if (!resolved.startsWith(`${root}${path.sep}`)) { throw new Error(`Path escapes config directory: ${relPath}`); } + + // Verify no symlinked directory/file components inside configDir + let cur = root; + const parts = path.relative(root, resolved).split(path.sep).filter(Boolean); + for (const part of parts) { + cur = path.join(cur, part); + if (fs.existsSync(cur)) { + const lstat = fs.lstatSync(cur); + if (lstat.isSymbolicLink()) { + throw new Error(`Symlinks are not allowed inside config directory: ${relPath}`); + } + } + } + + if (fs.existsSync(root)) { + const realRoot = fs.realpathSync(root); + let checkPath = resolved; + while (!fs.existsSync(checkPath) && checkPath !== root) { + checkPath = path.dirname(checkPath); + } + if (fs.existsSync(checkPath)) { + const realTarget = fs.realpathSync(checkPath); + if (realTarget !== realRoot && !realTarget.startsWith(`${realRoot}${path.sep}`)) { + throw new Error(`Realpath escapes config directory: ${relPath}`); + } + } + } + return resolved; } @@ -898,8 +942,8 @@ export class ConfigManager { } private writeAtomicFile(absPath: string, content: string): void { - fs.mkdirSync(path.dirname(absPath), { recursive: true }); - const tmpPath = `${absPath}.tmp.${process.pid}.${Date.now()}`; + fs.mkdirSync(path.dirname(absPath), { recursive: true, mode: 0o700 }); + const tmpPath = `${absPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { fs.writeFileSync(fd, content, 'utf8'); diff --git a/src/server/config/presets.ts b/src/server/config/presets.ts index da391d8..b603c41 100644 --- a/src/server/config/presets.ts +++ b/src/server/config/presets.ts @@ -322,7 +322,10 @@ export function seedDefaultConfigs(configDir: string): string[] { for (const [relPath, obj] of defaults) { const absPath = path.join(configDir, relPath); if (!fs.existsSync(absPath)) { - fs.writeFileSync(absPath, `${JSON.stringify(obj, null, 2)}\n`, 'utf8'); + fs.writeFileSync(absPath, `${JSON.stringify(obj, null, 2)}\n`, { + encoding: 'utf8', + mode: 0o600, + }); created.push(relPath); } } diff --git a/src/server/security/auth.ts b/src/server/security/auth.ts index 6d9480e..fb1500d 100644 --- a/src/server/security/auth.ts +++ b/src/server/security/auth.ts @@ -374,12 +374,6 @@ export class AuthService { this.pendingBootstrap = null; this.syncRecovery({ - passwordPlaintextUpdate: { - id: 'pw-primary', - label: 'Primary Password', - password: params.password, - createdAt: nowMs, - }, newRecoveryCodes: recoveryCodes, snapshotReason: 'bootstrap', }); @@ -942,12 +936,6 @@ export class AuthService { .run(id, cleanLabel, hash, createdAt); this.syncRecovery({ - passwordPlaintextUpdate: { - id, - label: cleanLabel, - password, - createdAt, - }, snapshotReason: 'password-added', }); @@ -1090,12 +1078,6 @@ export class AuthService { syncRecovery( overrides: { - passwordPlaintextUpdate?: { - id: string; - label: string; - password: string; - createdAt?: number; - }; removedPasswordId?: string; newRecoveryCodes?: string[]; snapshotReason?: string; diff --git a/src/server/security/recovery-store.ts b/src/server/security/recovery-store.ts index d77c752..e0c5312 100644 --- a/src/server/security/recovery-store.ts +++ b/src/server/security/recovery-store.ts @@ -1,3 +1,4 @@ +import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import type { VaultCredential } from '../../shared/schemas/vault.schema.js'; @@ -6,7 +7,6 @@ import type { VaultService } from './vault.js'; export interface SavedPasswordEntry { id: string; label: string; - plaintextPassword?: string; createdAt: string; } @@ -48,7 +48,6 @@ export interface SyncRecoveryOptions { username?: string | null; totps?: SavedTotpEntry[]; passwordMetaList?: Array<{ id: string; label: string; createdAt: number }>; - passwordPlaintextUpdate?: { id: string; label: string; password: string; createdAt?: number }; removedPasswordId?: string; newRecoveryCodes?: string[]; snapshotReason?: string; @@ -74,6 +73,8 @@ export class EmergencyRecoveryService { readBundle(): EmergencySecretsBundle | null { if (!fs.existsSync(this.bundlePath)) return null; try { + const stat = fs.lstatSync(this.bundlePath); + if (!stat.isFile() || stat.isSymbolicLink()) return null; const raw = JSON.parse(fs.readFileSync(this.bundlePath, 'utf8')); if (!raw || typeof raw !== 'object' || raw.version !== 1) return null; return raw as EmergencySecretsBundle; @@ -105,43 +106,30 @@ export class EmergencyRecoveryService { ? opts.vault.exportAllCredentials() : existing?.vaultCredentials ?? {}; - // Merge saved plaintext passwords safely across updates const prevPwById = new Map(); for (const p of existing?.admin.passwords ?? []) { - prevPwById.set(p.id, p); + prevPwById.set(p.id, { + id: p.id, + label: p.label, + createdAt: p.createdAt, + }); } if (opts.removedPasswordId) { prevPwById.delete(opts.removedPasswordId); } - if (opts.passwordPlaintextUpdate) { - const u = opts.passwordPlaintextUpdate; - prevPwById.set(u.id, { - id: u.id, - label: u.label, - plaintextPassword: u.password, - createdAt: new Date(u.createdAt ?? Date.now()).toISOString(), - }); - } - let finalPasswords: SavedPasswordEntry[]; - if (opts.passwordMetaList) { - finalPasswords = opts.passwordMetaList.map((meta) => { - const prev = prevPwById.get(meta.id); - return { + const finalPasswords: SavedPasswordEntry[] = opts.passwordMetaList + ? opts.passwordMetaList.map((meta) => ({ id: meta.id, label: meta.label, - plaintextPassword: prev?.plaintextPassword, createdAt: new Date(meta.createdAt).toISOString(), - }; - }); - } else { - finalPasswords = [...prevPwById.values()]; - } + })) + : [...prevPwById.values()]; const bundle: EmergencySecretsBundle = { version: 1, updatedAt: nowIso, - note: 'Local emergency plaintext backup managed by GCoordinator. Keep this file private (chmod 0600).', + note: 'Local emergency recovery bundle managed by GCoordinator (passwords excluded). Keep this file private (chmod 0600).', vaultMasterKeyHex: masterKeyHex, admin: { username: opts.username !== undefined ? opts.username : existing?.admin.username ?? null, @@ -185,10 +173,22 @@ export class EmergencyRecoveryService { wipeAll(): void { const shred = (filePath: string) => { - if (!fs.existsSync(filePath)) return; + let stat: fs.Stats; try { - const stat = fs.statSync(filePath); - if (stat.isFile() && stat.size > 0) { + stat = fs.lstatSync(filePath); + } catch { + return; + } + if (stat.isSymbolicLink()) { + fs.unlinkSync(filePath); + return; + } + if (stat.isDirectory()) { + fs.rmSync(filePath, { recursive: true, force: true }); + return; + } + if (stat.isFile() && stat.size > 0) { + try { const fd = fs.openSync(filePath, 'r+'); try { fs.writeSync(fd, Buffer.alloc(stat.size, 0), 0, stat.size, 0); @@ -196,9 +196,9 @@ export class EmergencyRecoveryService { } finally { fs.closeSync(fd); } + } catch { + // Best-effort overwrite before unlink } - } catch { - // Best-effort overwrite before unlink } fs.unlinkSync(filePath); }; @@ -208,7 +208,11 @@ export class EmergencyRecoveryService { for (const f of fs.readdirSync(this.snapshotsDir)) { shred(path.join(this.snapshotsDir, f)); } - fs.rmdirSync(this.snapshotsDir); + try { + fs.rmdirSync(this.snapshotsDir); + } catch { + // Ignore unexpected remaining files + } } if (fs.existsSync(this.recoveryDir)) { try { @@ -227,7 +231,7 @@ export class EmergencyRecoveryService { } private writeAtomicSecure(targetPath: string, content: string): void { - const tmpPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`; + const tmpPath = `${targetPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { fs.writeFileSync(fd, content, 'utf8'); @@ -247,8 +251,19 @@ export class EmergencyRecoveryService { .sort(); while (files.length > MAX_SNAPSHOTS) { const oldest = files.shift()!; + const p = path.join(this.snapshotsDir, oldest); try { - fs.unlinkSync(path.join(this.snapshotsDir, oldest)); + const stat = fs.lstatSync(p); + if (stat.isFile() && !stat.isSymbolicLink() && stat.size > 0) { + const fd = fs.openSync(p, 'r+'); + try { + fs.writeSync(fd, Buffer.alloc(stat.size, 0), 0, stat.size, 0); + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } + } + fs.unlinkSync(p); } catch { // Ignore cleanup failure } diff --git a/src/server/security/vault.ts b/src/server/security/vault.ts index 26811a3..5207c67 100644 --- a/src/server/security/vault.ts +++ b/src/server/security/vault.ts @@ -10,11 +10,14 @@ import { type VaultCredentialMeta, type VaultPayload, } from '../../shared/schemas/vault.schema.js'; -import type { VaultState } from '../../shared/ws-protocol.js'; +import type { VaultSealState, VaultState } from '../../shared/ws-protocol.js'; + +const VAULT_AAD = Buffer.from('gcoord-vault-v1', 'utf8'); export const VaultEnvelopeSchema = z.object({ version: z.literal(1), alg: z.literal('aes-256-gcm'), + aad: z.boolean().optional(), iv: z.string().min(1), tag: z.string().min(1), ciphertext: z.string().min(1), @@ -42,6 +45,7 @@ export function generateMasterKeyBuffer(): Buffer { function encryptPayload(payload: VaultPayload, key: Buffer): VaultEnvelope { const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); + cipher.setAAD(VAULT_AAD); const plaintext = Buffer.from(JSON.stringify(payload), 'utf8'); const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]); const tag = cipher.getAuthTag(); @@ -50,6 +54,7 @@ function encryptPayload(payload: VaultPayload, key: Buffer): VaultEnvelope { return { version: 1, alg: 'aes-256-gcm', + aad: true, iv: iv.toString('base64'), tag: tag.toString('base64'), ciphertext: ciphertext.toString('base64'), @@ -67,6 +72,9 @@ function decryptEnvelope(envelope: VaultEnvelope, key: Buffer): VaultPayload { } const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); + if (envelope.aad) { + decipher.setAAD(VAULT_AAD); + } decipher.setAuthTag(tag); const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]); try { @@ -109,7 +117,11 @@ export function verifyVaultEnvelopeText( } export function computeOpenSshFingerprint(publicKeyLine: string): string { - const parsed = ssh2.utils.parseKey(publicKeyLine.trim()); + const trimmed = publicKeyLine.trim(); + if (/[\r\n\0]/.test(trimmed)) { + throw new Error('Public key must be a single line'); + } + const parsed = ssh2.utils.parseKey(trimmed); if (parsed instanceof Error) { throw parsed; } @@ -122,6 +134,13 @@ export function computeOpenSshFingerprint(publicKeyLine: string): string { return `SHA256:${hash}`; } +export function validatePrivateKey(privateKey: string, passphrase?: string): void { + const parsed = ssh2.utils.parseKey(privateKey, passphrase); + if (parsed instanceof Error) { + throw new Error(`Invalid SSH private key or passphrase: ${parsed.message}`); + } +} + /** * Generates an OpenSSH Ed25519 keypair, retrying around ssh2's BitString * leading-zero stripping bug when a generated public key starts with 0x00. @@ -165,22 +184,29 @@ export type VaultCredentialInput = DistributiveOmit< export interface VaultServiceOptions { keyFilePath?: string; + allowLocalKeyFile?: boolean; } +type KeySource = 'secret-file' | 'env' | 'key-file' | 'backup' | 'generated' | 'manual'; + export class VaultService { private masterKey: Buffer | null = null; private credentials = new Map(); private writeUnlocked = false; private autoInitializedEmpty = false; private wasPanicLocked = false; + private keySource: KeySource | null = null; private readonly keyFilePath: string | null; + private readonly allowLocalKeyFile: boolean; private readonly panicListeners = new Set<() => void>(); + private readonly sealListeners = new Set<() => void>(); constructor( private readonly vaultFilePath: string, options: VaultServiceOptions = {}, ) { this.keyFilePath = options.keyFilePath ? path.resolve(options.keyFilePath) : null; + this.allowLocalKeyFile = options.allowLocalKeyFile ?? true; this.wasPanicLocked = fs.existsSync(this.panicLockMarkerPath()); } @@ -212,6 +238,12 @@ export class VaultService { return fs.existsSync(this.vaultFilePath) ? 'locked' : 'uninitialized'; } + get sealState(): VaultSealState { + if (!fs.existsSync(this.vaultFilePath)) return 'uninitialized'; + if (this.masterKey === null) return 'sealed'; + return this.writeUnlocked ? 'unlocked' : 'write-locked'; + } + get isPanicLocked(): boolean { return this.wasPanicLocked || fs.existsSync(this.panicLockMarkerPath()); } @@ -223,6 +255,13 @@ export class VaultService { }; } + onSeal(listener: () => void): () => void { + this.sealListeners.add(listener); + return () => { + this.sealListeners.delete(listener); + }; + } + initRuntime(options: { secretFilePath?: string; envKey?: string; @@ -234,20 +273,20 @@ export class VaultService { return { runtimeReady: false, reason: 'panic_locked' }; } - const candidates: string[] = []; + const candidates: Array<{ value: string; source: KeySource }> = []; if (options.secretFilePath && fs.existsSync(options.secretFilePath)) { const val = fs.readFileSync(options.secretFilePath, 'utf8').trim(); - if (val) candidates.push(val); + if (val) candidates.push({ value: val, source: 'secret-file' }); } if (options.envKey && options.envKey.trim().length > 0) { - candidates.push(options.envKey.trim()); + candidates.push({ value: options.envKey.trim(), source: 'env' }); } if (this.keyFilePath && fs.existsSync(this.keyFilePath)) { const val = fs.readFileSync(this.keyFilePath, 'utf8').trim(); - if (val) candidates.push(val); + if (val) candidates.push({ value: val, source: 'key-file' }); } if (options.backupKey && options.backupKey.trim().length > 0) { - candidates.push(options.backupKey.trim()); + candidates.push({ value: options.backupKey.trim(), source: 'backup' }); } if (fs.existsSync(this.vaultFilePath)) { @@ -268,15 +307,19 @@ export class VaultService { for (const candidate of candidates) { let keyBuf: Buffer | null = null; try { - keyBuf = parseMasterKey(candidate); + keyBuf = parseMasterKey(candidate.value); const payload = decryptEnvelope(envelope, keyBuf); this.zeroizeMasterKey(); this.masterKey = keyBuf; + this.keySource = candidate.source; this.credentials = new Map(Object.entries(payload.credentials)); this.writeUnlocked = false; this.autoInitializedEmpty = false; this.setPanicLockMarker(false); - this.persistKeyFileIfConfigured(keyBuf); + // Security invariant: NEVER mirror Docker Secret or env master keys to disk vault.key + if (candidate.source === 'key-file') { + this.persistKeyFileIfConfigured(keyBuf); + } return { runtimeReady: true }; } catch { keyBuf?.fill(0); @@ -291,17 +334,28 @@ export class VaultService { let keyBuf: Buffer | null = null; try { - keyBuf = candidates[0] ? parseMasterKey(candidates[0]) : generateMasterKeyBuffer(); + const chosen = candidates[0]; + const source: KeySource = chosen ? chosen.source : 'generated'; + keyBuf = chosen ? parseMasterKey(chosen.value) : generateMasterKeyBuffer(); const emptyPayload: VaultPayload = { version: 1, credentials: {} }; this.writeVerifiedVaultAtomic(emptyPayload, keyBuf); this.zeroizeMasterKey(); this.masterKey = keyBuf; + this.keySource = source; this.credentials.clear(); this.writeUnlocked = false; this.autoInitializedEmpty = true; this.setPanicLockMarker(false); - this.persistKeyFileIfConfigured(keyBuf); + // Only write local keyfile when generated locally (or already using key-file) and allowed + if ( + this.allowLocalKeyFile && + source !== 'secret-file' && + source !== 'env' && + source !== 'backup' + ) { + this.persistKeyFileIfConfigured(keyBuf); + } return { runtimeReady: true, initialized: true }; } catch (err) { keyBuf?.fill(0); @@ -362,11 +416,14 @@ export class VaultService { this.zeroizeMasterKey(); this.masterKey = keyBuf; + this.keySource = 'manual'; this.credentials.clear(); this.writeUnlocked = true; this.autoInitializedEmpty = false; this.setPanicLockMarker(false); - this.persistKeyFileIfConfigured(keyBuf); + if (this.allowLocalKeyFile && this.keyFilePath && fs.existsSync(this.keyFilePath)) { + this.persistKeyFileIfConfigured(keyBuf); + } return masterKeyInput ? {} : { generatedKeyHex: keyBuf.toString('hex') }; } @@ -384,17 +441,36 @@ export class VaultService { this.zeroizeMasterKey(); this.masterKey = keyBuf; + this.keySource = 'manual'; this.credentials = new Map(Object.entries(payload.credentials)); this.writeUnlocked = true; this.autoInitializedEmpty = false; this.setPanicLockMarker(false); - this.persistKeyFileIfConfigured(keyBuf); + if (this.allowLocalKeyFile && this.keyFilePath && fs.existsSync(this.keyFilePath)) { + this.persistKeyFileIfConfigured(keyBuf); + } } catch (err) { keyBuf.fill(0); throw err; } } + seal(): void { + this.zeroizeMasterKey(); + this.keySource = null; + this.credentials.clear(); + this.writeUnlocked = false; + this.autoInitializedEmpty = false; + + for (const listener of this.sealListeners) { + try { + listener(); + } catch { + // Seal cleanup must continue across all listeners + } + } + } + unlockForModifications(): void { if (this.masterKey === null || this.isPanicLocked) { throw new Error('Master key is required to unseal vault'); @@ -472,7 +548,15 @@ export class VaultService { this.zeroizeMasterKey(); this.masterKey = nextKey; this.writeUnlocked = true; - this.persistKeyFileIfConfigured(nextKey); + if ( + this.allowLocalKeyFile && + this.keySource !== 'secret-file' && + this.keySource !== 'env' && + this.keyFilePath && + fs.existsSync(this.keyFilePath) + ) { + this.persistKeyFileIfConfigured(nextKey); + } return newMasterKeyInput ? {} : { generatedKeyHex: nextKey.toString('hex') }; } catch (err) { nextKey.fill(0); @@ -613,8 +697,8 @@ export class VaultService { this.keyFilePath ?? (fs.existsSync(siblingKeyFile) ? siblingKeyFile : null); if (!targetPath) return; - fs.mkdirSync(path.dirname(targetPath), { recursive: true }); - const tmpPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`; + fs.mkdirSync(path.dirname(targetPath), { recursive: true, mode: 0o700 }); + const tmpPath = `${targetPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { fs.writeFileSync(fd, `${key.toString('hex')}\n`, 'utf8'); @@ -635,11 +719,11 @@ export class VaultService { private writeVerifiedVaultAtomic(payload: VaultPayload, key: Buffer): void { const dir = path.dirname(this.vaultFilePath); - fs.mkdirSync(dir, { recursive: true }); + fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); const envelope = encryptPayload(payload, key); const serialized = JSON.stringify(envelope, null, 2); - const tmpPath = `${this.vaultFilePath}.tmp.${process.pid}.${Date.now()}`; + const tmpPath = `${this.vaultFilePath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { diff --git a/src/server/ssh/ssh-pool.ts b/src/server/ssh/ssh-pool.ts index e27920f..58e4969 100644 --- a/src/server/ssh/ssh-pool.ts +++ b/src/server/ssh/ssh-pool.ts @@ -574,7 +574,7 @@ export class SSHPool { } } - closeAll(reason: 'panic_lock' | 'shutdown'): void { + closeAll(reason: 'panic_lock' | 'shutdown' | 'vault_sealed'): void { if (reason === 'shutdown') { this.closed = true; } @@ -588,12 +588,13 @@ export class SSHPool { this.closeServer(id); } - if (reason === 'panic_lock') { + if (reason === 'panic_lock' || reason === 'vault_sealed') { + const msg = reason === 'panic_lock' ? 'Panic Lock engaged' : 'Vault sealed'; for (const server of this.configManager.listServers()) { this.states.set(server.id, { serverId: server.id, status: server.enabled ? 'vault_locked' : 'disabled', - lastError: server.enabled ? 'Panic Lock engaged' : undefined, + lastError: server.enabled ? msg : undefined, }); } this.emitStates(); diff --git a/tests/api-ws-smoke.test.ts b/tests/api-ws-smoke.test.ts index d697842..1e603de 100644 --- a/tests/api-ws-smoke.test.ts +++ b/tests/api-ws-smoke.test.ts @@ -202,20 +202,13 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => { ).toBe(200); // 6. Vault Init + Step-Up guard + Drop Elevation + Generate Ed25519 key - const vInit = await api('/api/vault/init', { method: 'POST', body: {} }); - expect(vInit.status).toBe(201); - const generatedMasterKey = String(vInit.data.generatedKeyHex); - - // v1.1 defaults elevateOnLogin=false; step up first, then verify drop-elevation clears it + // v1.1 defaults elevateOnLogin=false; verify non-elevated session cannot init vault const statusInitial = await api('/api/auth/status'); expect(statusInitial.data.elevatedUntil).toBeNull(); - const noStepUp = await api('/api/vault/generate-ed25519', { - method: 'POST', - body: { id: 'prod-key', name: 'Prod Key' }, - }); - expect(noStepUp.status).toBe(403); - expect(noStepUp.data.error).toBe('STEP_UP_REQUIRED'); + const vInitDenied = await api('/api/vault/init', { method: 'POST', body: {} }); + expect(vInitDenied.status).toBe(403); + expect(vInitDenied.data.error).toBe('STEP_UP_REQUIRED'); const stepUpRes = await api('/api/auth/step-up', { method: 'POST', @@ -223,6 +216,10 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => { }); expect(stepUpRes.status).toBe(200); + const vInit = await api('/api/vault/init', { method: 'POST', body: {} }); + expect(vInit.status).toBe(201); + const generatedMasterKey = String(vInit.data.generatedKeyHex); + const statusBeforeDrop = await api('/api/auth/status'); expect(typeof statusBeforeDrop.data.elevatedUntil).toBe('number'); const dropped = await api('/api/auth/drop-elevation', { method: 'POST' }); diff --git a/tests/multi-auth-and-recovery.test.ts b/tests/multi-auth-and-recovery.test.ts index 7e61fe3..921ce26 100644 --- a/tests/multi-auth-and-recovery.test.ts +++ b/tests/multi-auth-and-recovery.test.ts @@ -250,6 +250,9 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret expect(anyLogin.status).toBe(200); // Switch settings.json to strict multi-factor 'all' + 'every-action' + password step-up + expect( + (await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp1.generate() } })).status, + ).toBe(200); const rawSettings = await api.call('/api/config/file?path=settings.json'); expect(rawSettings.status).toBe(200); const parsedSettings = JSON.parse(String(rawSettings.data.rawContent)) as Record< @@ -431,7 +434,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret const bundle = JSON.parse(fs.readFileSync(bundlePath, 'utf8')) as EmergencySecretsBundle; expect(bundle.vaultMasterKeyHex).toBe(masterKeyHex); expect(bundle.admin.username).toBe('admin'); - expect(bundle.admin.passwords.some((p) => p.plaintextPassword === password)).toBe(true); + expect(bundle.admin.passwords.some((p) => p.label === 'Primary Password' && !('plaintextPassword' in p))).toBe(true); expect(bundle.admin.totps.some((t) => t.secretBase32 === secretBase32)).toBe(true); expect(bundle.admin.recoveryCodes).toEqual(recoveryCodes); expect(bundle.vaultCredentials['backup-key']).toBeDefined(); diff --git a/tests/servers-api-e2e.test.ts b/tests/servers-api-e2e.test.ts index 583252b..26e9060 100644 --- a/tests/servers-api-e2e.test.ts +++ b/tests/servers-api-e2e.test.ts @@ -121,10 +121,10 @@ describe('Phase 2 E2E: /api/servers, TOFU, Live Metrics WS, Key Rotation & Panic }); ws.send(JSON.stringify({ type: 'sub', channels: ['metrics', 'alerts', 'config'] })); - expect((await api('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201); expect( (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, ).toBe(200); + expect((await api('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201); const keyRes = await api('/api/vault/generate-ed25519', { method: 'POST',