diff --git a/src/server/config/config-manager.ts b/src/server/config/config-manager.ts index 3648dc3..1b5ea8a 100644 --- a/src/server/config/config-manager.ts +++ b/src/server/config/config-manager.ts @@ -117,7 +117,7 @@ export class ConfigManager { this.recomputeWarnings(); if (options.watch !== false) { - this.startWatcher(); + await this.startWatcher(); } } @@ -547,7 +547,7 @@ export class ConfigManager { ); } - private startWatcher(): void { + private startWatcher(): Promise { this.watcher = chokidar.watch(this.configDir, { ignoreInitial: true, persistent: true, @@ -577,6 +577,10 @@ export class ConfigManager { this.watcher.on('add', (p) => scheduleReload(p, 'upsert')); this.watcher.on('change', (p) => scheduleReload(p, 'upsert')); this.watcher.on('unlink', (p) => scheduleReload(p, 'unlink')); + + return new Promise((resolve) => { + this.watcher!.once('ready', () => resolve()); + }); } private handleExternalUpsert(relPath: string): void { diff --git a/tests/api-ws-smoke.test.ts b/tests/api-ws-smoke.test.ts new file mode 100644 index 0000000..f47752a --- /dev/null +++ b/tests/api-ws-smoke.test.ts @@ -0,0 +1,296 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import * as OTPAuth from 'otpauth'; +import { afterEach, describe, expect, it } from 'vitest'; +import WebSocket from 'ws'; +import { createGCoordinatorServer } from '../src/server/app.js'; + +const tempDirs: string[] = []; + +function makeTempDir(): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-smoke-test-')); + tempDirs.push(dir); + return dir; +} + +class CookieJar { + private cookies = new Map(); + + updateFrom(res: Response): void { + const getSetCookie = (res.headers as unknown as { getSetCookie?: () => string[] }).getSetCookie; + const rawList = typeof getSetCookie === 'function' ? getSetCookie.call(res.headers) : []; + for (const line of rawList) { + const first = line.split(';')[0] ?? ''; + const eq = first.indexOf('='); + if (eq > 0) { + const name = first.slice(0, eq).trim(); + const val = first.slice(eq + 1).trim(); + if (val === '') this.cookies.delete(name); + else this.cookies.set(name, val); + } + } + } + + header(): string { + return [...this.cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; '); + } +} + +async function openWs( + url: string, + headers: Record, +): Promise<{ ws: WebSocket; frames: Array> }> { + return new Promise((resolve, reject) => { + const frames: Array> = []; + const ws = new WebSocket(url, { headers }); + ws.on('message', (raw) => { + frames.push(JSON.parse(raw.toString())); + }); + ws.once('open', () => resolve({ ws, frames })); + ws.once('unexpected-response', (_req, res) => { + reject(new Error(`WS_HTTP_${res.statusCode}`)); + }); + ws.once('error', reject); + }); +} + +afterEach(() => { + while (tempDirs.length > 0) { + fs.rmSync(tempDirs.pop()!, { recursive: true, force: true }); + } +}); + +describe('Bundle size budget & full-stack Express + WS lifecycle', () => { + it('keeps built core frontend bundle under 50KB gzipped', () => { + const pubDir = path.resolve('dist/public'); + const coreFiles = ['index.html', 'themes.css', 'base.css', 'main.js']; + let gzipBytes = 0; + for (const f of coreFiles) { + const buf = fs.readFileSync(path.join(pubDir, f)); + gzipBytes += zlib.gzipSync(buf, { level: 9 }).length; + } + expect(gzipBytes).toBeLessThan(50 * 1024); + }); + + it('enforces auth, CSRF, Safe Mode, Step-Up, hot-reload WS push, Panic Lock, and recovery unlock', async () => { + const dataDir = makeTempDir(); + const server = await createGCoordinatorServer({ + dataDir, + port: 0, + host: '127.0.0.1', + publicDir: path.resolve('dist/public'), + }); + + const baseUrl = `http://127.0.0.1:${server.port}`; + const wsUrl = `ws://127.0.0.1:${server.port}/ws`; + const jar = new CookieJar(); + let csrfToken = ''; + + const api = async ( + pathname: string, + opts: { method?: string; body?: unknown; csrf?: string | null; safeHeader?: boolean } = {}, + ) => { + const headers: Record = {}; + if (jar.header()) headers.Cookie = jar.header(); + if (opts.body !== undefined) headers['Content-Type'] = 'application/json'; + const tokenToSend = opts.csrf === undefined ? csrfToken : opts.csrf; + if (tokenToSend) headers['X-CSRF-Token'] = tokenToSend; + if (opts.safeHeader) headers['X-GCoord-Safe-Mode'] = '1'; + + const res = await fetch(`${baseUrl}${pathname}`, { + method: opts.method ?? 'GET', + headers, + body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, + }); + jar.updateFrom(res); + const data = await res.json().catch(() => ({})); + return { status: res.status, data: data as Record }; + }; + + try { + // 1. Health check & unauthenticated WS blocked + const health = await api('/api/healthz'); + expect(health.status).toBe(200); + await expect(openWs(wsUrl, {})).rejects.toThrow('WS_HTTP_401'); + + // 2. Bootstrap Admin + TOTP + const bootInfo = await api('/api/auth/bootstrap'); + expect(bootInfo.status).toBe(200); + const secretBase32 = String(bootInfo.data.secretBase32); + const totpGen = new OTPAuth.TOTP({ + issuer: 'GCoordinator', + label: 'admin', + algorithm: 'SHA1', + digits: 6, + period: 30, + secret: OTPAuth.Secret.fromBase32(secretBase32), + }); + + const bootDone = await api('/api/auth/bootstrap', { + method: 'POST', + body: { + username: 'admin', + password: 'integration-password-123', + totpCode: totpGen.generate(), + secretBase32, + initialSafeMode: false, + }, + }); + expect(bootDone.status).toBe(201); + csrfToken = String(bootDone.data.csrfToken); + const recoveryCodes = bootDone.data.recoveryCodes as string[]; + expect(recoveryCodes).toHaveLength(8); + + // 3. Cross-origin WS rejected with 403; same-origin WS receives hello + await expect( + openWs(wsUrl, { + Cookie: jar.header(), + Host: `127.0.0.1:${server.port}`, + Origin: 'https://evil.example', + }), + ).rejects.toThrow('WS_HTTP_403'); + + const { ws, frames } = await openWs(wsUrl, { + Cookie: jar.header(), + Host: `127.0.0.1:${server.port}`, + Origin: baseUrl, + }); + + await new Promise((r) => setTimeout(r, 80)); + expect(frames[0]?.type).toBe('hello'); + + // 4. CSRF check + const badCsrf = await api('/api/vault/init', { + method: 'POST', + body: {}, + csrf: null, + }); + expect(badCsrf.status).toBe(403); + + // 5. Safe Mode blocks mutating REST & WS pty:input + expect( + (await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: true } })).status, + ).toBe(200); + + const safeBlocked = await api('/api/config/file', { + method: 'PUT', + body: { + path: 'servers/prod-01.json', + content: JSON.stringify({ + id: 'prod-01', + name: 'Prod 01', + host: '10.0.0.99', + username: 'ops', + credentialId: 'prod-key', + }), + }, + }); + expect(safeBlocked.status).toBe(423); + + ws.send(JSON.stringify({ type: 'pty:input', sessionId: 's1', data: 'ls\n' })); + await new Promise((r) => setTimeout(r, 80)); + expect(frames.some((f) => f.type === 'error' && f.code === 'SAFE_MODE_ACTIVE')).toBe(true); + + // Disable Safe Mode + expect( + (await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: false } })).status, + ).toBe(200); + + // 6. Vault Init + Step-Up guard + Generate Ed25519 key + const vInit = await api('/api/vault/init', { method: 'POST', body: {} }); + expect(vInit.status).toBe(201); + const generatedMasterKey = String(vInit.data.generatedKeyHex); + + 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 stepUpRes = await api('/api/auth/step-up', { + method: 'POST', + body: { code: totpGen.generate() }, + }); + expect(stepUpRes.status).toBe(200); + + const genRes = await api('/api/vault/generate-ed25519', { + method: 'POST', + body: { id: 'prod-key', name: 'Prod Key' }, + }); + expect(genRes.status).toBe(201); + + // 7. Save server JSON and confirm WS receives config:updated + const saveServer = await api('/api/config/file', { + method: 'PUT', + body: { + path: 'servers/prod-01.json', + content: JSON.stringify({ + id: 'prod-01', + name: 'Prod 01', + host: '10.0.0.99', + username: 'ops', + credentialId: 'prod-key', + }), + }, + }); + expect(saveServer.status).toBe(200); + await new Promise((r) => setTimeout(r, 80)); + expect( + frames.some((f) => f.type === 'config:updated' && f.id === 'prod-01'), + ).toBe(true); + + // 8. Re-enable Safe Mode and verify Panic Lock STILL executes immediately + await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: true } }); + + let wsCloseCode = 0; + const wsClosed = new Promise((resolve) => { + ws.once('close', (code) => { + wsCloseCode = code; + resolve(); + }); + }); + + const panicRes = await api('/api/security/panic-lock', { method: 'POST' }); + expect(panicRes.status).toBe(200); + await wsClosed; + expect(wsCloseCode).toBe(4001); + expect(frames.some((f) => f.type === 'security:panic-lock')).toBe(true); + + // Old session must now be revoked (401) + const afterPanic = await api('/api/vault/status'); + expect(afterPanic.status).toBe(401); + + // 9. Re-login using a single-use recovery code and unlock vault manually + const relogin = await api('/api/auth/login', { + method: 'POST', + body: { + username: 'admin', + password: 'integration-password-123', + code: recoveryCodes[0]!, + }, + csrf: null, + }); + expect(relogin.status).toBe(200); + csrfToken = String(relogin.data.csrfToken); + expect(relogin.data.vaultState).toBe('locked'); + + const unlockRes = await api('/api/vault/unlock', { + method: 'POST', + body: { masterKey: generatedMasterKey }, + }); + expect(unlockRes.status).toBe(200); + expect(unlockRes.data.state).toBe('unlocked'); + + const credsAfter = await api('/api/vault/credentials'); + expect(credsAfter.status).toBe(200); + expect( + (credsAfter.data.credentials as Array<{ id: string }>).map((c) => c.id), + ).toContain('prod-key'); + } finally { + await server.close(); + } + }); +}); diff --git a/tests/auth-and-guards.test.ts b/tests/auth-and-guards.test.ts new file mode 100644 index 0000000..d051adf --- /dev/null +++ b/tests/auth-and-guards.test.ts @@ -0,0 +1,183 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import * as OTPAuth from 'otpauth'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { openDatabase } from '../src/server/db/database.js'; +import { AuthService } from '../src/server/security/auth.js'; +import { RateLimiter, resolveClientIp } from '../src/server/security/guards.js'; + +const tempDirs: string[] = []; + +function makeTempDb() { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-auth-test-')); + tempDirs.push(dir); + return openDatabase(path.join(dir, 'gcoord.db')); +} + +function generateTotp(secretBase32: string, timestampMs = Date.now()): string { + return new OTPAuth.TOTP({ + issuer: 'GCoordinator', + label: 'admin', + algorithm: 'SHA1', + digits: 6, + period: 30, + secret: OTPAuth.Secret.fromBase32(secretBase32), + }).generate({ timestamp: timestampMs }); +} + +afterEach(() => { + vi.useRealTimers(); + while (tempDirs.length > 0) { + fs.rmSync(tempDirs.pop()!, { recursive: true, force: true }); + } +}); + +describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => { + it('completes Argon2id + TOTP bootstrap, issues single-use recovery codes, and blocks TOTP replay', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + const t0 = 1_700_000_010_000; + vi.setSystemTime(t0); + + const db = makeTempDb(); + const auth = new AuthService(db); + expect(auth.isBootstrapped()).toBe(false); + + const enroll = await auth.beginBootstrap('admin'); + expect(enroll.qrSvg).toContain(' { + vi.useFakeTimers({ toFake: ['Date'] }); + const t0 = 1_700_000_010_000; + vi.setSystemTime(t0); + + const db = makeTempDb(); + const auth = new AuthService(db); + const enroll = await auth.beginBootstrap('admin'); + const code0 = generateTotp(enroll.secretBase32, t0); + const boot = await auth.completeBootstrap({ + username: 'admin', + password: 'strong-admin-password-123', + totpCode: code0, + ip: '127.0.0.1', + userAgent: 'vitest', + }); + + // Step-up tracks replay independently from login step + const stepUp1 = auth.stepUp(boot.session.idHash, code0); + expect(stepUp1).toEqual({ + ok: true, + elevatedUntil: t0 + 5 * 60 * 1000, + }); + + // Replaying exact same step-up code is denied + const stepUpReplay = auth.stepUp(boot.session.idHash, code0); + expect(stepUpReplay).toEqual({ ok: false, reason: 'totp_replayed' }); + + // Enabling Safe Mode clears elevatedUntil immediately + const safeSession = auth.setSafeMode(boot.session.idHash, true); + expect(safeSession?.safeMode).toBe(true); + expect(safeSession?.elevatedUntil).toBeNull(); + + // Step-up is blocked while Safe Mode is ON + vi.setSystemTime(t0 + 31_000); + const code1 = generateTotp(enroll.secretBase32, t0 + 31_000); + const whileSafe = auth.stepUp(boot.session.idHash, code1); + expect(whileSafe).toEqual({ ok: false, reason: 'safe_mode_active' }); + + // Turning Safe Mode OFF allows step-up again + auth.setSafeMode(boot.session.idHash, false); + const stepUp2 = auth.stepUp(boot.session.idHash, code1); + expect(stepUp2.ok).toBe(true); + + // Elevation expires automatically after 5 minutes + vi.setSystemTime(t0 + 31_000 + 5 * 60 * 1000 + 1000); + const expiredSession = auth.getSessionByToken(boot.sessionToken); + expect(expiredSession?.elevatedUntil).toBeNull(); + + db.close(); + }); + + it('applies exponential rate-limit backoff and honors CF-Connecting-IP only when trusted', () => { + const limiter = new RateLimiter(); + for (let i = 0; i < 4; i++) { + limiter.recordFailure('login', '198.51.100.10'); + expect(limiter.check('login', '198.51.100.10').allowed).toBe(true); + } + + limiter.recordFailure('login', '198.51.100.10'); + const blocked = limiter.check('login', '198.51.100.10'); + expect(blocked.allowed).toBe(false); + expect(blocked.retryAfterSec).toBeGreaterThanOrEqual(1); + + limiter.recordSuccess('login', '198.51.100.10'); + expect(limiter.check('login', '198.51.100.10').allowed).toBe(true); + + const fakeReq = { + headers: { 'cf-connecting-ip': '203.0.113.55' }, + ip: '127.0.0.1', + socket: { remoteAddress: '127.0.0.1' }, + } as never; + + expect(resolveClientIp(fakeReq, false)).toBe('127.0.0.1'); + expect(resolveClientIp(fakeReq, true)).toBe('203.0.113.55'); + }); +}); diff --git a/tests/config-manager.test.ts b/tests/config-manager.test.ts new file mode 100644 index 0000000..ae05ca3 --- /dev/null +++ b/tests/config-manager.test.ts @@ -0,0 +1,234 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { WorkflowConfigSchema } from '../src/shared/schemas/workflow.schema.js'; +import { ConfigManager } from '../src/server/config/config-manager.js'; +import { openDatabase } from '../src/server/db/database.js'; +import { VaultService } from '../src/server/security/vault.js'; + +const tempDirs: string[] = []; + +function makeEnv() { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-cfg-test-')); + tempDirs.push(dir); + const db = openDatabase(path.join(dir, 'gcoord.db')); + const vault = new VaultService(path.join(dir, 'vault.enc')); + const configDir = path.join(dir, 'config'); + const mgr = new ConfigManager(configDir, db, vault); + return { dir, configDir, db, vault, mgr }; +} + +async function waitFor(predicate: () => boolean, timeoutMs = 4000): Promise { + const start = Date.now(); + while (Date.now() - start < timeoutMs) { + if (predicate()) return; + await new Promise((r) => setTimeout(r, 50)); + } + throw new Error(`Timed out after ${timeoutMs}ms waiting for condition`); +} + +afterEach(async () => { + while (tempDirs.length > 0) { + fs.rmSync(tempDirs.pop()!, { recursive: true, force: true }); + } +}); + +describe('ConfigManager, Presets, Hot-Reload, DAG & Revisions', () => { + it('seeds presets on first boot, records revisions, computes diff, and performs 1-click rollback', async () => { + const { configDir, db, mgr } = makeEnv(); + await mgr.init({ watch: false }); + + try { + expect(fs.existsSync(path.join(configDir, 'settings.json'))).toBe(true); + expect(fs.existsSync(path.join(configDir, 'alerts.json'))).toBe(true); + expect(fs.existsSync(path.join(configDir, 'snippets.json'))).toBe(true); + expect(mgr.listSystems().map((s) => s.id).sort()).toEqual([ + 'docker-compose', + 'os-packages', + 'systemd', + ]); + + const v1 = mgr.getSettings(); + expect(v1.theme).toBe('phosphor-green'); + + mgr.saveConfigText( + 'settings.json', + JSON.stringify({ ...v1, theme: 'amber-term' }, null, 2), + 'ui', + 'Switch to amber-term', + ); + expect(mgr.getSettings().theme).toBe('amber-term'); + + const revs = mgr.listRevisions('settings.json'); + expect(revs).toHaveLength(2); + const seedRev = revs[1]!; + const diffRes = mgr.diffRevision(seedRev.id); + expect(diffRes.diff.unified).toContain('- "theme": "phosphor-green"'); + expect(diffRes.diff.unified).toContain('+ "theme": "amber-term"'); + + mgr.rollbackRevision(seedRev.id); + expect(mgr.getSettings().theme).toBe('phosphor-green'); + expect(mgr.listRevisions('settings.json')).toHaveLength(3); + } finally { + await mgr.close(); + db.close(); + } + }); + + it('hot-reloads external edits and preserves isolated valid state when one file breaks', async () => { + const { configDir, db, mgr } = makeEnv(); + await mgr.init({ watch: true }); + + try { + mgr.saveConfigText( + 'servers/web-01.json', + JSON.stringify({ + id: 'web-01', + name: 'Web 01', + host: '10.0.0.10', + username: 'ops', + credentialId: 'cred-1', + }), + ); + mgr.saveConfigText( + 'servers/db-01.json', + JSON.stringify({ + id: 'db-01', + name: 'DB 01', + host: '10.0.0.11', + username: 'ops', + credentialId: 'cred-1', + }), + ); + + // External creation of new server JSON picked up via chokidar + fs.writeFileSync( + path.join(configDir, 'servers', 'edge-01.json'), + JSON.stringify({ + id: 'edge-01', + name: 'Edge 01', + host: '10.0.0.12', + username: 'ops', + credentialId: 'cred-1', + }), + ); + await waitFor(() => Boolean(mgr.getServer('edge-01'))); + expect(mgr.getServer('edge-01')?.name).toBe('Edge 01'); + + // Corrupt ONLY web-01.json externally on disk + fs.writeFileSync(path.join(configDir, 'servers', 'web-01.json'), '{ invalid json'); + await waitFor(() => + mgr.getDiagnostics().errors.some((e) => e.filePath === 'servers/web-01.json'), + ); + + // Isolated fallback: prior valid web-01 remains in memory; db-01 & edge-01 unaffected + expect(mgr.getServer('web-01')?.host).toBe('10.0.0.10'); + expect(mgr.getServer('db-01')?.host).toBe('10.0.0.11'); + expect(mgr.getServer('edge-01')?.host).toBe('10.0.0.12'); + } finally { + await mgr.close(); + db.close(); + } + }); + + it('validates Full-DAG workflows, rejects cycles, and emits non-blocking cross-ref warnings', async () => { + const { db, vault, mgr } = makeEnv(); + vault.initializeNewVault(); + await mgr.init({ watch: false }); + + try { + // Valid parallel diamond DAG + const validDag = WorkflowConfigSchema.safeParse({ + id: 'deploy-dag', + name: 'Parallel Deploy DAG', + trigger: { + type: 'event', + event: 'system.unhealthy', + filter: { systemId: 'docker-compose' }, + }, + steps: [ + { + id: 'build', + type: 'exec', + target: { serverId: 'app-01' }, + dependsOn: [], + command: 'echo build', + }, + { + id: 'backup', + type: 'exec', + target: { serverId: 'db-01' }, + dependsOn: ['build'], + command: 'echo backup', + }, + { + id: 'sync', + type: 'transfer', + mode: 'hub-relayed', + dependsOn: [{ stepId: 'build', on: 'success' }], + source: { serverId: 'app-01', path: '/tmp/a' }, + destination: { serverId: 'edge-01', path: '/tmp/a' }, + }, + { + id: 'finalize', + type: 'exec', + target: { all: true }, + dependsOn: ['backup', 'sync'], + command: 'echo done', + }, + ], + }); + expect(validDag.success).toBe(true); + + // Cyclic DAG must fail Zod validation + const cyclicDag = WorkflowConfigSchema.safeParse({ + id: 'bad-cycle', + name: 'Cyclic DAG', + trigger: { type: 'manual' }, + steps: [ + { id: 'step-a', type: 'exec', target: { all: true }, dependsOn: ['step-c'], command: 'true' }, + { id: 'step-b', type: 'exec', target: { all: true }, dependsOn: ['step-a'], command: 'true' }, + { id: 'step-c', type: 'exec', target: { all: true }, dependsOn: ['step-b'], command: 'true' }, + ], + }); + expect(cyclicDag.success).toBe(false); + if (!cyclicDag.success) { + expect(JSON.stringify(cyclicDag.error.issues)).toContain('cycle'); + } + + // Non-blocking cross-ref warnings (missing credential, jumpHost cycle, missing system) + mgr.saveConfigText( + 'servers/hop-a.json', + JSON.stringify({ + id: 'hop-a', + name: 'Hop A', + host: '10.0.0.1', + username: 'ops', + credentialId: 'missing-cred', + jumpHostId: 'hop-b', + systems: [{ systemId: 'nonexistent-system', params: {} }], + }), + ); + mgr.saveConfigText( + 'servers/hop-b.json', + JSON.stringify({ + id: 'hop-b', + name: 'Hop B', + host: '10.0.0.2', + username: 'ops', + credentialId: 'missing-cred', + jumpHostId: 'hop-a', + }), + ); + + const codes = mgr.getDiagnostics().warnings.map((w) => w.code); + expect(codes).toContain('MISSING_CREDENTIAL'); + expect(codes).toContain('JUMP_HOST_CYCLE'); + expect(codes).toContain('MISSING_SYSTEM'); + } finally { + await mgr.close(); + db.close(); + } + }); +}); diff --git a/tests/vault.test.ts b/tests/vault.test.ts new file mode 100644 index 0000000..da0b23d --- /dev/null +++ b/tests/vault.test.ts @@ -0,0 +1,203 @@ +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import ssh2 from 'ssh2'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + generateMasterKeyBuffer, + VaultService, +} from '../src/server/security/vault.js'; + +const tempDirs: string[] = []; + +function makeTempDir(): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-vault-test-')); + tempDirs.push(dir); + return dir; +} + +afterEach(() => { + while (tempDirs.length > 0) { + fs.rmSync(tempDirs.pop()!, { recursive: true, force: true }); + } +}); + +describe('VaultService & CLI key rotation', () => { + it('encrypts/decrypts with AES-256-GCM and rejects tampered ciphertext or auth tags', () => { + const dir = makeTempDir(); + const vaultPath = path.join(dir, 'vault.enc'); + const vault = new VaultService(vaultPath); + expect(vault.state).toBe('uninitialized'); + + const { generatedKeyHex } = vault.initializeNewVault(); + expect(generatedKeyHex).toMatch(/^[0-9a-f]{64}$/); + expect(vault.state).toBe('unlocked'); + + vault.upsertCredential({ + id: 'db-pass', + name: 'DB Password', + type: 'sudo-password', + password: 'super-secret-password', + }); + + // Reload from disk with a fresh instance + const v2 = new VaultService(vaultPath); + expect(v2.state).toBe('locked'); + expect(() => v2.unlock('00'.repeat(32))).toThrow(); + v2.unlock(generatedKeyHex!); + expect(v2.getSecret('db-pass')).toMatchObject({ + id: 'db-pass', + password: 'super-secret-password', + }); + + // Tamper with GCM tag + const envelope = JSON.parse(fs.readFileSync(vaultPath, 'utf8')); + const tagBuf = Buffer.from(envelope.tag, 'base64'); + tagBuf[0] = tagBuf[0]! ^ 0xff; + envelope.tag = tagBuf.toString('base64'); + fs.writeFileSync(vaultPath, JSON.stringify(envelope, null, 2)); + + const v3 = new VaultService(vaultPath); + expect(() => v3.unlock(generatedKeyHex!)).toThrow(); + }); + + it('auto-unlocks from secret file or envKey and enforces Panic Lock', () => { + const dir = makeTempDir(); + const vaultPath = path.join(dir, 'vault.enc'); + const secretFile = path.join(dir, 'master.txt'); + const keyHex = generateMasterKeyBuffer().toString('hex'); + fs.writeFileSync(secretFile, `${keyHex}\n`, { mode: 0o600 }); + + const vault = new VaultService(vaultPath); + const res1 = vault.tryAutoUnlockFromEnvOrSecret({ secretFilePath: secretFile }); + expect(res1.unlocked).toBe(true); + expect(res1.initialized).toBe(true); + + vault.upsertCredential({ + id: 'hook-1', + name: 'Discord Hook', + type: 'webhook-secret', + secret: 'https://discord.example/hook/123', + }); + + const onPanic = vi.fn(); + vault.onPanicLock(onPanic); + vault.panicLock(); + + expect(onPanic).toHaveBeenCalledTimes(1); + expect(vault.state).toBe('locked'); + expect(vault.isPanicLocked).toBe(true); + expect(() => vault.getSecret('hook-1')).toThrow(/locked/i); + + // Must refuse unattended secret re-read after Panic Lock + const resAfterPanic = vault.tryAutoUnlockFromEnvOrSecret({ + secretFilePath: secretFile, + envKey: keyHex, + }); + expect(resAfterPanic.unlocked).toBe(false); + expect(resAfterPanic.reason).toBe('panic_locked'); + + // Explicit manual unlock restores access and clears panic lock flag + vault.unlock(keyHex); + expect(vault.isPanicLocked).toBe(false); + expect(vault.getSecret('hook-1')).toMatchObject({ + id: 'hook-1', + secret: 'https://discord.example/hook/123', + }); + }); + + it('generates ssh2-compatible OpenSSH Ed25519 keypairs with SHA-256 fingerprints', () => { + const dir = makeTempDir(); + const vault = new VaultService(path.join(dir, 'vault.enc')); + vault.initializeNewVault(); + + const m1 = vault.generateEd25519Credential({ + id: 'ssh-plain', + name: 'Plain Ed25519', + comment: 'ops@hub', + }); + const m2 = vault.generateEd25519Credential({ + id: 'ssh-enc', + name: 'Passphrase Ed25519', + passphrase: 'key-passphrase-123', + }); + + expect(m1.publicKey).toMatch(/^ssh-ed25519 AAAA/); + expect(m1.fingerprint).toMatch(/^SHA256:[A-Za-z0-9+/]+$/); + expect(m2.hasPassphrase).toBe(true); + + const s1 = vault.getSecret('ssh-plain'); + const s2 = vault.getSecret('ssh-enc'); + if (s1?.type !== 'ssh-key' || s2?.type !== 'ssh-key') { + throw new Error('Expected ssh-key'); + } + + const p1 = ssh2.utils.parseKey(s1.privateKey); + expect(p1).not.toBeInstanceOf(Error); + if (!Array.isArray(p1) && !(p1 instanceof Error)) { + expect(p1.type).toBe('ssh-ed25519'); + } + + const p2Fail = ssh2.utils.parseKey(s2.privateKey); + expect(p2Fail).toBeInstanceOf(Error); + const p2Ok = ssh2.utils.parseKey(s2.privateKey, 'key-passphrase-123'); + expect(p2Ok).not.toBeInstanceOf(Error); + if (!Array.isArray(p2Ok) && !(p2Ok instanceof Error)) { + expect(p2Ok.type).toBe('ssh-ed25519'); + } + }); + + it('rotates master key atomically via VaultService and gcoord CLI', () => { + const dir = makeTempDir(); + const vaultPath = path.join(dir, 'vault.enc'); + const oldKeyPath = path.join(dir, 'old.key'); + const newKeyPath = path.join(dir, 'new.key'); + + const vault = new VaultService(vaultPath); + const { generatedKeyHex: initialKey } = vault.initializeNewVault(); + vault.upsertCredential({ + id: 'api-1', + name: 'Local AI Key', + type: 'api-token', + token: 'tok-xyz', + }); + + // In-process rotation + const { generatedKeyHex: rotatedKey1 } = vault.rotateMasterKey(); + expect(rotatedKey1).toMatch(/^[0-9a-f]{64}$/); + expect(rotatedKey1).not.toBe(initialKey); + + const checkOld = new VaultService(vaultPath); + expect(() => checkOld.unlock(initialKey!)).toThrow(); + checkOld.unlock(rotatedKey1!); + expect(checkOld.getSecret('api-1')).toMatchObject({ token: 'tok-xyz' }); + + // CLI rotation via built dist/cli/gcoord.js + const cliPath = path.resolve('dist/cli/gcoord.js'); + fs.writeFileSync(oldKeyPath, `${rotatedKey1}\n`, { mode: 0o600 }); + execFileSync( + process.execPath, + [ + cliPath, + 'rotate-key', + '--data-dir', + dir, + '--current-key-file', + oldKeyPath, + '--new-key-out', + newKeyPath, + ], + { encoding: 'utf8' }, + ); + + const rotatedKey2 = fs.readFileSync(newKeyPath, 'utf8').trim(); + expect(rotatedKey2).toMatch(/^[0-9a-f]{64}$/); + expect(rotatedKey2).not.toBe(rotatedKey1); + + const checkCli = new VaultService(vaultPath); + expect(() => checkCli.unlock(rotatedKey1!)).toThrow(); + checkCli.unlock(rotatedKey2); + expect(checkCli.getSecret('api-1')).toMatchObject({ token: 'tok-xyz' }); + }); +});