security(vault,recovery,config): harden Vault keyfile/seal, strip recovery passwords, guard config & symlinks

This commit is contained in:
tyuXX 2026-11-27 22:22:59 +00:00
parent 005c82e6bf
commit e3f716d24f
12 changed files with 504 additions and 207 deletions

View file

@ -1,4 +1,4 @@
import { Router } from 'express'; import { Router, type RequestHandler } from 'express';
import { ZodError, z } from 'zod'; import { ZodError, z } from 'zod';
import type { ConfigManager } from '../../config/config-manager.js'; import type { ConfigManager } from '../../config/config-manager.js';
import type { AuditService } from '../../security/audit.js'; import type { AuditService } from '../../security/audit.js';
@ -7,17 +7,29 @@ import {
enforceSafeMode, enforceSafeMode,
requireAuth, requireAuth,
requireCsrf, requireCsrf,
requireStepUp,
} from '../../security/guards.js'; } from '../../security/guards.js';
export interface ConfigRouterDeps { export interface ConfigRouterDeps {
authService: AuthService; authService: AuthService;
configManager: ConfigManager; configManager: ConfigManager;
auditService: AuditService; 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 { export function createConfigRouter(deps: ConfigRouterDeps): Router {
const router = Router(); const router = Router();
const { authService, configManager, auditService } = deps; const {
authService,
configManager,
auditService,
stepUpGuard = requireStepUp,
} = deps;
router.get('/overview', requireAuth(authService), (_req, res) => { router.get('/overview', requireAuth(authService), (_req, res) => {
res.json({ res.json({
@ -63,38 +75,46 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router {
return; return;
} }
try { const executeSave = () => {
const saved = configManager.saveConfigText( try {
parsed.data.path, const saved = configManager.saveConfigText(
parsed.data.content, parsed.data.path,
'ui', parsed.data.content,
parsed.data.summary, 'ui',
); parsed.data.summary,
auditService.log({ );
action: 'config.save', auditService.log({
actorIp: req.clientIp ?? 'unknown', action: 'config.save',
sessionIdHash: req.authSession!.idHash, actorIp: req.clientIp ?? 'unknown',
target: saved.filePath, sessionIdHash: req.authSession!.idHash,
status: 'ok', target: saved.filePath,
}); status: 'ok',
res.json(saved); });
} catch (err) { res.json(saved);
if (err instanceof ZodError) { } catch (err) {
res.status(400).json({ if (err instanceof ZodError) {
error: 'CONFIG_SCHEMA_ERROR', res.status(400).json({
message: 'Schema validation failed', error: 'CONFIG_SCHEMA_ERROR',
issues: err.issues.map((i) => ({ message: 'Schema validation failed',
path: i.path.join('.') || '(root)', issues: err.issues.map((i) => ({
message: i.message, 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( router.delete(
@ -108,26 +128,34 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router {
res.status(400).json({ error: 'MISSING_PATH' }); res.status(400).json({ error: 'MISSING_PATH' });
return; return;
} }
try { const executeDelete = () => {
const deleted = configManager.deleteEntityFile(filePath); try {
if (!deleted) { const deleted = configManager.deleteEntityFile(filePath);
res.status(404).json({ error: 'CONFIG_NOT_FOUND' }); if (!deleted) {
return; 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', if (isStepUpSensitiveConfigPath(filePath)) {
sessionIdHash: req.authSession!.idHash, stepUpGuard(req, res, executeDelete);
target: filePath, return;
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',
});
} }
executeDelete();
}, },
); );
@ -174,23 +202,38 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router {
res.status(400).json({ error: 'INVALID_REVISION_ID' }); res.status(400).json({ error: 'INVALID_REVISION_ID' });
return; return;
} }
try { const rev = configManager.getRevision(id);
const result = configManager.rollbackRevision(id); if (!rev) {
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({ res.status(400).json({
error: 'ROLLBACK_FAILED', 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();
}, },
); );

View file

@ -15,6 +15,7 @@ import {
import { import {
computeOpenSshFingerprint, computeOpenSshFingerprint,
generateMasterKeyBuffer, generateMasterKeyBuffer,
validatePrivateKey,
type VaultCredentialInput, type VaultCredentialInput,
type VaultService, type VaultService,
} from '../../security/vault.js'; } from '../../security/vault.js';
@ -114,6 +115,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
type: 'vault:state', type: 'vault:state',
vaultState: vaultService.state, vaultState: vaultService.state,
vaultRuntimeReady: vaultService.isRuntimeReady, vaultRuntimeReady: vaultService.isRuntimeReady,
vaultSealState: vaultService.sealState,
isPanicLocked: vaultService.isPanicLocked, isPanicLocked: vaultService.isPanicLocked,
}); });
}; };
@ -122,43 +124,52 @@ export function createVaultRouter(deps: VaultRouterDeps): {
res.json({ res.json({
state: vaultService.state, state: vaultService.state,
runtimeReady: vaultService.isRuntimeReady, runtimeReady: vaultService.isRuntimeReady,
sealState: vaultService.sealState,
isPanicLocked: vaultService.isPanicLocked, isPanicLocked: vaultService.isPanicLocked,
}); });
}); });
vaultRouter.post('/init', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { vaultRouter.post(
const ip = req.clientIp ?? 'unknown'; '/init',
const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {}); requireAuth(authService),
if (!parsed.success) { requireCsrf,
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); enforceSafeMode,
return; stepUpGuard,
} (req, res) => {
try { const ip = req.clientIp ?? 'unknown';
const result = vaultService.initializeNewVault(parsed.data.masterKey); const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {});
notifyConfigReeval(); if (!parsed.success) {
onVaultUnlocked?.(); res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
onVaultChanged?.('vault-init'); return;
broadcastVaultState(); }
auditService.log({ try {
action: 'vault.init', const result = vaultService.initializeNewVault(parsed.data.masterKey);
actorIp: ip, notifyConfigReeval();
sessionIdHash: req.authSession!.idHash, onVaultUnlocked?.();
status: 'ok', onVaultChanged?.('vault-init');
}); broadcastVaultState();
res.status(201).json({ auditService.log({
state: vaultService.state, action: 'vault.init',
runtimeReady: vaultService.isRuntimeReady, actorIp: ip,
generatedKeyHex: result.generatedKeyHex, sessionIdHash: req.authSession!.idHash,
}); status: 'ok',
} catch (err) { });
res.status(400).json({ res.status(201).json({
error: 'VAULT_INIT_FAILED', state: vaultService.state,
message: err instanceof Error ? err.message : 'Vault initialization failed', 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 ip = req.clientIp ?? 'unknown';
const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {}); const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {});
if (!parsed.success) { if (!parsed.success) {
@ -191,6 +202,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
res.json({ res.json({
state: vaultService.state, state: vaultService.state,
runtimeReady: vaultService.isRuntimeReady, runtimeReady: vaultService.isRuntimeReady,
sealState: vaultService.sealState,
isPanicLocked: vaultService.isPanicLocked, isPanicLocked: vaultService.isPanicLocked,
}); });
} catch (err) { } catch (err) {
@ -231,6 +243,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
res.json({ res.json({
state: vaultService.state, state: vaultService.state,
runtimeReady: vaultService.isRuntimeReady, runtimeReady: vaultService.isRuntimeReady,
sealState: vaultService.sealState,
isPanicLocked: vaultService.isPanicLocked, isPanicLocked: vaultService.isPanicLocked,
}); });
} catch (err) { } catch (err) {
@ -254,10 +267,35 @@ export function createVaultRouter(deps: VaultRouterDeps): {
res.json({ res.json({
state: vaultService.state, state: vaultService.state,
runtimeReady: vaultService.isRuntimeReady, runtimeReady: vaultService.isRuntimeReady,
sealState: vaultService.sealState,
isPanicLocked: vaultService.isPanicLocked, 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!) // Panic Lock is ALWAYS reachable when authenticated + CSRF verified (even under Safe Mode!)
panicLockHandler.post('/panic-lock', requireAuth(authService), requireCsrf, (req, res) => { panicLockHandler.post('/panic-lock', requireAuth(authService), requireCsrf, (req, res) => {
const session = req.authSession!; const session = req.authSession!;
@ -299,6 +337,13 @@ export function createVaultRouter(deps: VaultRouterDeps): {
requireAuth(authService), requireAuth(authService),
stepUpGuard, stepUpGuard,
(req, res) => { (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') { if (vaultService.state !== 'unlocked') {
res.status(423).json({ error: 'VAULT_LOCKED' }); res.status(423).json({ error: 'VAULT_LOCKED' });
return; return;
@ -337,15 +382,27 @@ export function createVaultRouter(deps: VaultRouterDeps): {
return; return;
} }
const credInput: VaultCredentialInput = { ...parsed.data }; const credInput: VaultCredentialInput = { ...parsed.data };
if ( if (credInput.type === 'ssh-key') {
credInput.type === 'ssh-key' &&
credInput.publicKey &&
!credInput.fingerprint
) {
try { try {
credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey); validatePrivateKey(credInput.privateKey, credInput.passphrase);
} catch { } catch (err) {
// Leave fingerprint omitted if user imported an unusual public key format 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); const meta = vaultService.upsertCredential(credInput);
@ -381,15 +438,27 @@ export function createVaultRouter(deps: VaultRouterDeps): {
return; return;
} }
const credInput: VaultCredentialInput = { ...parsed.data }; const credInput: VaultCredentialInput = { ...parsed.data };
if ( if (credInput.type === 'ssh-key') {
credInput.type === 'ssh-key' &&
credInput.publicKey &&
!credInput.fingerprint
) {
try { try {
credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey); validatePrivateKey(credInput.privateKey, credInput.passphrase);
} catch { } catch (err) {
// Ignore non-standard public key strings 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); const meta = vaultService.upsertCredential(credInput);
@ -495,6 +564,12 @@ export function createVaultRouter(deps: VaultRouterDeps): {
sessionIdHash: req.authSession!.idHash, sessionIdHash: req.authSession!.idHash,
expiresAt, expiresAt,
}; };
auditService.log({
action: 'vault.rotate_key.prepare',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
status: 'ok',
});
res.json({ candidateKeyHex, confirmToken, expiresAt }); res.json({ candidateKeyHex, confirmToken, expiresAt });
}, },
); );
@ -510,10 +585,17 @@ export function createVaultRouter(deps: VaultRouterDeps): {
res.status(423).json({ error: 'VAULT_LOCKED' }); res.status(423).json({ error: 'VAULT_LOCKED' });
return; 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 const parsed = z
.object({ .object({
confirmToken: z.string().min(1), confirmToken: z.string().min(1),
confirmedKeyHex: z.string().min(1).optional(), confirmedKeyHex: z.string().min(64).max(64),
}) })
.safeParse(req.body); .safeParse(req.body);
if (!parsed.success) { if (!parsed.success) {
@ -521,32 +603,57 @@ export function createVaultRouter(deps: VaultRouterDeps): {
return; 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 ( if (
!pendingRotation || !pendingRotation ||
pendingRotation.expiresAt <= Date.now() || pendingRotation.expiresAt <= Date.now() ||
pendingRotation.sessionIdHash !== req.authSession!.idHash || 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' }); res.status(400).json({ error: 'ROTATION_TOKEN_INVALID_OR_EXPIRED' });
return; return;
} }
if ( if (
parsed.data.confirmedKeyHex && !timingEq(
parsed.data.confirmedKeyHex.trim().toLowerCase() !== parsed.data.confirmedKeyHex.trim().toLowerCase(),
pendingRotation.candidateKeyHex.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' }); res.status(400).json({ error: 'KEY_CONFIRMATION_MISMATCH' });
return; return;
} }
rateLimiter.recordSuccess('vault-rotate-commit', ip);
const nextHex = pendingRotation.candidateKeyHex; const nextHex = pendingRotation.candidateKeyHex;
pendingRotation = null; pendingRotation = null;
vaultService.rotateMasterKey(nextHex); vaultService.rotateMasterKey(nextHex);
onVaultChanged?.('master-key-rotation'); onVaultChanged?.('master-key-rotation');
auditService.log({ auditService.log({
action: 'vault.rotate_key', action: 'vault.rotate_key',
actorIp: req.clientIp ?? 'unknown', actorIp: ip,
sessionIdHash: req.authSession!.idHash, sessionIdHash: req.authSession!.idHash,
status: 'ok', status: 'ok',
}); });

View file

@ -118,6 +118,7 @@ export async function createGCoordinatorServer(
const auditService = new AuditService(db); const auditService = new AuditService(db);
const vaultService = new VaultService(vaultPath, { const vaultService = new VaultService(vaultPath, {
keyFilePath: path.join(dataDir, 'vault.key'), keyFilePath: path.join(dataDir, 'vault.key'),
allowLocalKeyFile: options.autoKeyFile ?? true,
}); });
const recoveryStore = new EmergencyRecoveryService(dataDir); const recoveryStore = new EmergencyRecoveryService(dataDir);
const rateLimiter = new RateLimiter({ db }); const rateLimiter = new RateLimiter({ db });
@ -349,6 +350,19 @@ export async function createGCoordinatorServer(
workflowEngine.start(); workflowEngine.start();
alertEngine.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(() => { vaultService.onPanicLock(() => {
aiService.cancelAll(); aiService.cancelAll();
alertEngine.handlePanicLock(); alertEngine.handlePanicLock();
@ -391,7 +405,11 @@ export async function createGCoordinatorServer(
} }
if (event.entityType === 'settings') { if (event.entityType === 'settings') {
applyDatabaseThrottlePragmas(db, getRuntimeLimits()); applyDatabaseThrottlePragmas(db, getRuntimeLimits());
authService.syncRecovery(); if (!configManager.getSettings().security.enableEmergencySecretsBackup) {
recoveryStore.wipeAll();
} else {
authService.syncRecovery();
}
} }
monitoringService.syncServers(); monitoringService.syncServers();
customSystemsEngine.syncBackgroundChecks(); customSystemsEngine.syncBackgroundChecks();
@ -528,7 +546,7 @@ export async function createGCoordinatorServer(
); );
app.use( app.use(
'/api/config', '/api/config',
createConfigRouter({ authService, configManager, auditService }), createConfigRouter({ authService, configManager, auditService, stepUpGuard }),
); );
app.use('/api/audit', createAuditRouter(authService, auditService)); app.use('/api/audit', createAuditRouter(authService, auditService));

View file

@ -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 rule of this.alerts.rules) {
for (const cid of rule.channelIds) { for (const cid of rule.channelIds) {
if (!channelIds.has(cid)) { if (!channelIds.has(cid)) {
@ -604,6 +619,7 @@ export class ConfigManager {
ignoreInitial: true, ignoreInitial: true,
persistent: true, persistent: true,
depth: 2, depth: 2,
followSymlinks: false,
}); });
const scheduleReload = (absPath: string, kind: 'upsert' | 'unlink') => { const scheduleReload = (absPath: string, kind: 'upsert' | 'unlink') => {
@ -813,11 +829,39 @@ export class ConfigManager {
} }
private resolveSafeAbsPath(relPath: string): string { private resolveSafeAbsPath(relPath: string): string {
const resolved = path.resolve(this.configDir, relPath);
const root = path.resolve(this.configDir); const root = path.resolve(this.configDir);
const resolved = path.resolve(root, relPath);
if (!resolved.startsWith(`${root}${path.sep}`)) { if (!resolved.startsWith(`${root}${path.sep}`)) {
throw new Error(`Path escapes config directory: ${relPath}`); 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; return resolved;
} }
@ -898,8 +942,8 @@ export class ConfigManager {
} }
private writeAtomicFile(absPath: string, content: string): void { private writeAtomicFile(absPath: string, content: string): void {
fs.mkdirSync(path.dirname(absPath), { recursive: true }); fs.mkdirSync(path.dirname(absPath), { recursive: true, mode: 0o700 });
const tmpPath = `${absPath}.tmp.${process.pid}.${Date.now()}`; const tmpPath = `${absPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`;
const fd = fs.openSync(tmpPath, 'w', 0o600); const fd = fs.openSync(tmpPath, 'w', 0o600);
try { try {
fs.writeFileSync(fd, content, 'utf8'); fs.writeFileSync(fd, content, 'utf8');

View file

@ -322,7 +322,10 @@ export function seedDefaultConfigs(configDir: string): string[] {
for (const [relPath, obj] of defaults) { for (const [relPath, obj] of defaults) {
const absPath = path.join(configDir, relPath); const absPath = path.join(configDir, relPath);
if (!fs.existsSync(absPath)) { 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); created.push(relPath);
} }
} }

View file

@ -374,12 +374,6 @@ export class AuthService {
this.pendingBootstrap = null; this.pendingBootstrap = null;
this.syncRecovery({ this.syncRecovery({
passwordPlaintextUpdate: {
id: 'pw-primary',
label: 'Primary Password',
password: params.password,
createdAt: nowMs,
},
newRecoveryCodes: recoveryCodes, newRecoveryCodes: recoveryCodes,
snapshotReason: 'bootstrap', snapshotReason: 'bootstrap',
}); });
@ -942,12 +936,6 @@ export class AuthService {
.run(id, cleanLabel, hash, createdAt); .run(id, cleanLabel, hash, createdAt);
this.syncRecovery({ this.syncRecovery({
passwordPlaintextUpdate: {
id,
label: cleanLabel,
password,
createdAt,
},
snapshotReason: 'password-added', snapshotReason: 'password-added',
}); });
@ -1090,12 +1078,6 @@ export class AuthService {
syncRecovery( syncRecovery(
overrides: { overrides: {
passwordPlaintextUpdate?: {
id: string;
label: string;
password: string;
createdAt?: number;
};
removedPasswordId?: string; removedPasswordId?: string;
newRecoveryCodes?: string[]; newRecoveryCodes?: string[];
snapshotReason?: string; snapshotReason?: string;

View file

@ -1,3 +1,4 @@
import crypto from 'node:crypto';
import fs from 'node:fs'; import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import type { VaultCredential } from '../../shared/schemas/vault.schema.js'; import type { VaultCredential } from '../../shared/schemas/vault.schema.js';
@ -6,7 +7,6 @@ import type { VaultService } from './vault.js';
export interface SavedPasswordEntry { export interface SavedPasswordEntry {
id: string; id: string;
label: string; label: string;
plaintextPassword?: string;
createdAt: string; createdAt: string;
} }
@ -48,7 +48,6 @@ export interface SyncRecoveryOptions {
username?: string | null; username?: string | null;
totps?: SavedTotpEntry[]; totps?: SavedTotpEntry[];
passwordMetaList?: Array<{ id: string; label: string; createdAt: number }>; passwordMetaList?: Array<{ id: string; label: string; createdAt: number }>;
passwordPlaintextUpdate?: { id: string; label: string; password: string; createdAt?: number };
removedPasswordId?: string; removedPasswordId?: string;
newRecoveryCodes?: string[]; newRecoveryCodes?: string[];
snapshotReason?: string; snapshotReason?: string;
@ -74,6 +73,8 @@ export class EmergencyRecoveryService {
readBundle(): EmergencySecretsBundle | null { readBundle(): EmergencySecretsBundle | null {
if (!fs.existsSync(this.bundlePath)) return null; if (!fs.existsSync(this.bundlePath)) return null;
try { try {
const stat = fs.lstatSync(this.bundlePath);
if (!stat.isFile() || stat.isSymbolicLink()) return null;
const raw = JSON.parse(fs.readFileSync(this.bundlePath, 'utf8')); const raw = JSON.parse(fs.readFileSync(this.bundlePath, 'utf8'));
if (!raw || typeof raw !== 'object' || raw.version !== 1) return null; if (!raw || typeof raw !== 'object' || raw.version !== 1) return null;
return raw as EmergencySecretsBundle; return raw as EmergencySecretsBundle;
@ -105,43 +106,30 @@ export class EmergencyRecoveryService {
? opts.vault.exportAllCredentials() ? opts.vault.exportAllCredentials()
: existing?.vaultCredentials ?? {}; : existing?.vaultCredentials ?? {};
// Merge saved plaintext passwords safely across updates
const prevPwById = new Map<string, SavedPasswordEntry>(); const prevPwById = new Map<string, SavedPasswordEntry>();
for (const p of existing?.admin.passwords ?? []) { 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) { if (opts.removedPasswordId) {
prevPwById.delete(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[]; const finalPasswords: SavedPasswordEntry[] = opts.passwordMetaList
if (opts.passwordMetaList) { ? opts.passwordMetaList.map((meta) => ({
finalPasswords = opts.passwordMetaList.map((meta) => {
const prev = prevPwById.get(meta.id);
return {
id: meta.id, id: meta.id,
label: meta.label, label: meta.label,
plaintextPassword: prev?.plaintextPassword,
createdAt: new Date(meta.createdAt).toISOString(), createdAt: new Date(meta.createdAt).toISOString(),
}; }))
}); : [...prevPwById.values()];
} else {
finalPasswords = [...prevPwById.values()];
}
const bundle: EmergencySecretsBundle = { const bundle: EmergencySecretsBundle = {
version: 1, version: 1,
updatedAt: nowIso, 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, vaultMasterKeyHex: masterKeyHex,
admin: { admin: {
username: opts.username !== undefined ? opts.username : existing?.admin.username ?? null, username: opts.username !== undefined ? opts.username : existing?.admin.username ?? null,
@ -185,10 +173,22 @@ export class EmergencyRecoveryService {
wipeAll(): void { wipeAll(): void {
const shred = (filePath: string) => { const shred = (filePath: string) => {
if (!fs.existsSync(filePath)) return; let stat: fs.Stats;
try { try {
const stat = fs.statSync(filePath); stat = fs.lstatSync(filePath);
if (stat.isFile() && stat.size > 0) { } 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+'); const fd = fs.openSync(filePath, 'r+');
try { try {
fs.writeSync(fd, Buffer.alloc(stat.size, 0), 0, stat.size, 0); fs.writeSync(fd, Buffer.alloc(stat.size, 0), 0, stat.size, 0);
@ -196,9 +196,9 @@ export class EmergencyRecoveryService {
} finally { } finally {
fs.closeSync(fd); fs.closeSync(fd);
} }
} catch {
// Best-effort overwrite before unlink
} }
} catch {
// Best-effort overwrite before unlink
} }
fs.unlinkSync(filePath); fs.unlinkSync(filePath);
}; };
@ -208,7 +208,11 @@ export class EmergencyRecoveryService {
for (const f of fs.readdirSync(this.snapshotsDir)) { for (const f of fs.readdirSync(this.snapshotsDir)) {
shred(path.join(this.snapshotsDir, f)); 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)) { if (fs.existsSync(this.recoveryDir)) {
try { try {
@ -227,7 +231,7 @@ export class EmergencyRecoveryService {
} }
private writeAtomicSecure(targetPath: string, content: string): void { 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); const fd = fs.openSync(tmpPath, 'w', 0o600);
try { try {
fs.writeFileSync(fd, content, 'utf8'); fs.writeFileSync(fd, content, 'utf8');
@ -247,8 +251,19 @@ export class EmergencyRecoveryService {
.sort(); .sort();
while (files.length > MAX_SNAPSHOTS) { while (files.length > MAX_SNAPSHOTS) {
const oldest = files.shift()!; const oldest = files.shift()!;
const p = path.join(this.snapshotsDir, oldest);
try { 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 { } catch {
// Ignore cleanup failure // Ignore cleanup failure
} }

View file

@ -10,11 +10,14 @@ import {
type VaultCredentialMeta, type VaultCredentialMeta,
type VaultPayload, type VaultPayload,
} from '../../shared/schemas/vault.schema.js'; } 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({ export const VaultEnvelopeSchema = z.object({
version: z.literal(1), version: z.literal(1),
alg: z.literal('aes-256-gcm'), alg: z.literal('aes-256-gcm'),
aad: z.boolean().optional(),
iv: z.string().min(1), iv: z.string().min(1),
tag: z.string().min(1), tag: z.string().min(1),
ciphertext: z.string().min(1), ciphertext: z.string().min(1),
@ -42,6 +45,7 @@ export function generateMasterKeyBuffer(): Buffer {
function encryptPayload(payload: VaultPayload, key: Buffer): VaultEnvelope { function encryptPayload(payload: VaultPayload, key: Buffer): VaultEnvelope {
const iv = crypto.randomBytes(12); const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
cipher.setAAD(VAULT_AAD);
const plaintext = Buffer.from(JSON.stringify(payload), 'utf8'); const plaintext = Buffer.from(JSON.stringify(payload), 'utf8');
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]); const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
const tag = cipher.getAuthTag(); const tag = cipher.getAuthTag();
@ -50,6 +54,7 @@ function encryptPayload(payload: VaultPayload, key: Buffer): VaultEnvelope {
return { return {
version: 1, version: 1,
alg: 'aes-256-gcm', alg: 'aes-256-gcm',
aad: true,
iv: iv.toString('base64'), iv: iv.toString('base64'),
tag: tag.toString('base64'), tag: tag.toString('base64'),
ciphertext: ciphertext.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); const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
if (envelope.aad) {
decipher.setAAD(VAULT_AAD);
}
decipher.setAuthTag(tag); decipher.setAuthTag(tag);
const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]); const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
try { try {
@ -109,7 +117,11 @@ export function verifyVaultEnvelopeText(
} }
export function computeOpenSshFingerprint(publicKeyLine: string): string { 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) { if (parsed instanceof Error) {
throw parsed; throw parsed;
} }
@ -122,6 +134,13 @@ export function computeOpenSshFingerprint(publicKeyLine: string): string {
return `SHA256:${hash}`; 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 * Generates an OpenSSH Ed25519 keypair, retrying around ssh2's BitString
* leading-zero stripping bug when a generated public key starts with 0x00. * leading-zero stripping bug when a generated public key starts with 0x00.
@ -165,22 +184,29 @@ export type VaultCredentialInput = DistributiveOmit<
export interface VaultServiceOptions { export interface VaultServiceOptions {
keyFilePath?: string; keyFilePath?: string;
allowLocalKeyFile?: boolean;
} }
type KeySource = 'secret-file' | 'env' | 'key-file' | 'backup' | 'generated' | 'manual';
export class VaultService { export class VaultService {
private masterKey: Buffer | null = null; private masterKey: Buffer | null = null;
private credentials = new Map<string, VaultCredential>(); private credentials = new Map<string, VaultCredential>();
private writeUnlocked = false; private writeUnlocked = false;
private autoInitializedEmpty = false; private autoInitializedEmpty = false;
private wasPanicLocked = false; private wasPanicLocked = false;
private keySource: KeySource | null = null;
private readonly keyFilePath: string | null; private readonly keyFilePath: string | null;
private readonly allowLocalKeyFile: boolean;
private readonly panicListeners = new Set<() => void>(); private readonly panicListeners = new Set<() => void>();
private readonly sealListeners = new Set<() => void>();
constructor( constructor(
private readonly vaultFilePath: string, private readonly vaultFilePath: string,
options: VaultServiceOptions = {}, options: VaultServiceOptions = {},
) { ) {
this.keyFilePath = options.keyFilePath ? path.resolve(options.keyFilePath) : null; this.keyFilePath = options.keyFilePath ? path.resolve(options.keyFilePath) : null;
this.allowLocalKeyFile = options.allowLocalKeyFile ?? true;
this.wasPanicLocked = fs.existsSync(this.panicLockMarkerPath()); this.wasPanicLocked = fs.existsSync(this.panicLockMarkerPath());
} }
@ -212,6 +238,12 @@ export class VaultService {
return fs.existsSync(this.vaultFilePath) ? 'locked' : 'uninitialized'; 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 { get isPanicLocked(): boolean {
return this.wasPanicLocked || fs.existsSync(this.panicLockMarkerPath()); 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: { initRuntime(options: {
secretFilePath?: string; secretFilePath?: string;
envKey?: string; envKey?: string;
@ -234,20 +273,20 @@ export class VaultService {
return { runtimeReady: false, reason: 'panic_locked' }; return { runtimeReady: false, reason: 'panic_locked' };
} }
const candidates: string[] = []; const candidates: Array<{ value: string; source: KeySource }> = [];
if (options.secretFilePath && fs.existsSync(options.secretFilePath)) { if (options.secretFilePath && fs.existsSync(options.secretFilePath)) {
const val = fs.readFileSync(options.secretFilePath, 'utf8').trim(); 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) { 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)) { if (this.keyFilePath && fs.existsSync(this.keyFilePath)) {
const val = fs.readFileSync(this.keyFilePath, 'utf8').trim(); 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) { 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)) { if (fs.existsSync(this.vaultFilePath)) {
@ -268,15 +307,19 @@ export class VaultService {
for (const candidate of candidates) { for (const candidate of candidates) {
let keyBuf: Buffer | null = null; let keyBuf: Buffer | null = null;
try { try {
keyBuf = parseMasterKey(candidate); keyBuf = parseMasterKey(candidate.value);
const payload = decryptEnvelope(envelope, keyBuf); const payload = decryptEnvelope(envelope, keyBuf);
this.zeroizeMasterKey(); this.zeroizeMasterKey();
this.masterKey = keyBuf; this.masterKey = keyBuf;
this.keySource = candidate.source;
this.credentials = new Map(Object.entries(payload.credentials)); this.credentials = new Map(Object.entries(payload.credentials));
this.writeUnlocked = false; this.writeUnlocked = false;
this.autoInitializedEmpty = false; this.autoInitializedEmpty = false;
this.setPanicLockMarker(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 }; return { runtimeReady: true };
} catch { } catch {
keyBuf?.fill(0); keyBuf?.fill(0);
@ -291,17 +334,28 @@ export class VaultService {
let keyBuf: Buffer | null = null; let keyBuf: Buffer | null = null;
try { 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: {} }; const emptyPayload: VaultPayload = { version: 1, credentials: {} };
this.writeVerifiedVaultAtomic(emptyPayload, keyBuf); this.writeVerifiedVaultAtomic(emptyPayload, keyBuf);
this.zeroizeMasterKey(); this.zeroizeMasterKey();
this.masterKey = keyBuf; this.masterKey = keyBuf;
this.keySource = source;
this.credentials.clear(); this.credentials.clear();
this.writeUnlocked = false; this.writeUnlocked = false;
this.autoInitializedEmpty = true; this.autoInitializedEmpty = true;
this.setPanicLockMarker(false); 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 }; return { runtimeReady: true, initialized: true };
} catch (err) { } catch (err) {
keyBuf?.fill(0); keyBuf?.fill(0);
@ -362,11 +416,14 @@ export class VaultService {
this.zeroizeMasterKey(); this.zeroizeMasterKey();
this.masterKey = keyBuf; this.masterKey = keyBuf;
this.keySource = 'manual';
this.credentials.clear(); this.credentials.clear();
this.writeUnlocked = true; this.writeUnlocked = true;
this.autoInitializedEmpty = false; this.autoInitializedEmpty = false;
this.setPanicLockMarker(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') }; return masterKeyInput ? {} : { generatedKeyHex: keyBuf.toString('hex') };
} }
@ -384,17 +441,36 @@ export class VaultService {
this.zeroizeMasterKey(); this.zeroizeMasterKey();
this.masterKey = keyBuf; this.masterKey = keyBuf;
this.keySource = 'manual';
this.credentials = new Map(Object.entries(payload.credentials)); this.credentials = new Map(Object.entries(payload.credentials));
this.writeUnlocked = true; this.writeUnlocked = true;
this.autoInitializedEmpty = false; this.autoInitializedEmpty = false;
this.setPanicLockMarker(false); this.setPanicLockMarker(false);
this.persistKeyFileIfConfigured(keyBuf); if (this.allowLocalKeyFile && this.keyFilePath && fs.existsSync(this.keyFilePath)) {
this.persistKeyFileIfConfigured(keyBuf);
}
} catch (err) { } catch (err) {
keyBuf.fill(0); keyBuf.fill(0);
throw err; 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 { unlockForModifications(): void {
if (this.masterKey === null || this.isPanicLocked) { if (this.masterKey === null || this.isPanicLocked) {
throw new Error('Master key is required to unseal vault'); throw new Error('Master key is required to unseal vault');
@ -472,7 +548,15 @@ export class VaultService {
this.zeroizeMasterKey(); this.zeroizeMasterKey();
this.masterKey = nextKey; this.masterKey = nextKey;
this.writeUnlocked = true; 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') }; return newMasterKeyInput ? {} : { generatedKeyHex: nextKey.toString('hex') };
} catch (err) { } catch (err) {
nextKey.fill(0); nextKey.fill(0);
@ -613,8 +697,8 @@ export class VaultService {
this.keyFilePath ?? (fs.existsSync(siblingKeyFile) ? siblingKeyFile : null); this.keyFilePath ?? (fs.existsSync(siblingKeyFile) ? siblingKeyFile : null);
if (!targetPath) return; if (!targetPath) return;
fs.mkdirSync(path.dirname(targetPath), { recursive: true }); fs.mkdirSync(path.dirname(targetPath), { recursive: true, mode: 0o700 });
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); const fd = fs.openSync(tmpPath, 'w', 0o600);
try { try {
fs.writeFileSync(fd, `${key.toString('hex')}\n`, 'utf8'); fs.writeFileSync(fd, `${key.toString('hex')}\n`, 'utf8');
@ -635,11 +719,11 @@ export class VaultService {
private writeVerifiedVaultAtomic(payload: VaultPayload, key: Buffer): void { private writeVerifiedVaultAtomic(payload: VaultPayload, key: Buffer): void {
const dir = path.dirname(this.vaultFilePath); const dir = path.dirname(this.vaultFilePath);
fs.mkdirSync(dir, { recursive: true }); fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
const envelope = encryptPayload(payload, key); const envelope = encryptPayload(payload, key);
const serialized = JSON.stringify(envelope, null, 2); 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); const fd = fs.openSync(tmpPath, 'w', 0o600);
try { try {

View file

@ -574,7 +574,7 @@ export class SSHPool {
} }
} }
closeAll(reason: 'panic_lock' | 'shutdown'): void { closeAll(reason: 'panic_lock' | 'shutdown' | 'vault_sealed'): void {
if (reason === 'shutdown') { if (reason === 'shutdown') {
this.closed = true; this.closed = true;
} }
@ -588,12 +588,13 @@ export class SSHPool {
this.closeServer(id); 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()) { for (const server of this.configManager.listServers()) {
this.states.set(server.id, { this.states.set(server.id, {
serverId: server.id, serverId: server.id,
status: server.enabled ? 'vault_locked' : 'disabled', status: server.enabled ? 'vault_locked' : 'disabled',
lastError: server.enabled ? 'Panic Lock engaged' : undefined, lastError: server.enabled ? msg : undefined,
}); });
} }
this.emitStates(); this.emitStates();

View file

@ -202,20 +202,13 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => {
).toBe(200); ).toBe(200);
// 6. Vault Init + Step-Up guard + Drop Elevation + Generate Ed25519 key // 6. Vault Init + Step-Up guard + Drop Elevation + Generate Ed25519 key
const vInit = await api('/api/vault/init', { method: 'POST', body: {} }); // v1.1 defaults elevateOnLogin=false; verify non-elevated session cannot init vault
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
const statusInitial = await api('/api/auth/status'); const statusInitial = await api('/api/auth/status');
expect(statusInitial.data.elevatedUntil).toBeNull(); expect(statusInitial.data.elevatedUntil).toBeNull();
const noStepUp = await api('/api/vault/generate-ed25519', { const vInitDenied = await api('/api/vault/init', { method: 'POST', body: {} });
method: 'POST', expect(vInitDenied.status).toBe(403);
body: { id: 'prod-key', name: 'Prod Key' }, expect(vInitDenied.data.error).toBe('STEP_UP_REQUIRED');
});
expect(noStepUp.status).toBe(403);
expect(noStepUp.data.error).toBe('STEP_UP_REQUIRED');
const stepUpRes = await api('/api/auth/step-up', { const stepUpRes = await api('/api/auth/step-up', {
method: 'POST', method: 'POST',
@ -223,6 +216,10 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => {
}); });
expect(stepUpRes.status).toBe(200); 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'); const statusBeforeDrop = await api('/api/auth/status');
expect(typeof statusBeforeDrop.data.elevatedUntil).toBe('number'); expect(typeof statusBeforeDrop.data.elevatedUntil).toBe('number');
const dropped = await api('/api/auth/drop-elevation', { method: 'POST' }); const dropped = await api('/api/auth/drop-elevation', { method: 'POST' });

View file

@ -250,6 +250,9 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
expect(anyLogin.status).toBe(200); expect(anyLogin.status).toBe(200);
// Switch settings.json to strict multi-factor 'all' + 'every-action' + password step-up // 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'); const rawSettings = await api.call('/api/config/file?path=settings.json');
expect(rawSettings.status).toBe(200); expect(rawSettings.status).toBe(200);
const parsedSettings = JSON.parse(String(rawSettings.data.rawContent)) as Record< 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; const bundle = JSON.parse(fs.readFileSync(bundlePath, 'utf8')) as EmergencySecretsBundle;
expect(bundle.vaultMasterKeyHex).toBe(masterKeyHex); expect(bundle.vaultMasterKeyHex).toBe(masterKeyHex);
expect(bundle.admin.username).toBe('admin'); 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.totps.some((t) => t.secretBase32 === secretBase32)).toBe(true);
expect(bundle.admin.recoveryCodes).toEqual(recoveryCodes); expect(bundle.admin.recoveryCodes).toEqual(recoveryCodes);
expect(bundle.vaultCredentials['backup-key']).toBeDefined(); expect(bundle.vaultCredentials['backup-key']).toBeDefined();

View file

@ -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'] })); ws.send(JSON.stringify({ type: 'sub', channels: ['metrics', 'alerts', 'config'] }));
expect((await api('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201);
expect( expect(
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200); ).toBe(200);
expect((await api('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201);
const keyRes = await api('/api/vault/generate-ed25519', { const keyRes = await api('/api/vault/generate-ed25519', {
method: 'POST', method: 'POST',