diff --git a/tests/multi-auth-and-recovery.test.ts b/tests/multi-auth-and-recovery.test.ts index 1d19acc..f2431b2 100644 --- a/tests/multi-auth-and-recovery.test.ts +++ b/tests/multi-auth-and-recovery.test.ts @@ -431,11 +431,13 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret }, }); expect(relogin.status).toBe(200); - expect(relogin.data.vaultState).toBe('unlocked'); + expect(relogin.data.vaultState).toBe('locked'); + expect(relogin.data.vaultRuntimeReady).toBe(true); const vStatus = await api.call('/api/vault/status'); expect(vStatus.status).toBe(200); - expect(vStatus.data.state).toBe('unlocked'); + expect(vStatus.data.state).toBe('locked'); + expect(vStatus.data.runtimeReady).toBe(true); // Trigger Panic Lock -> locks vault while keeping backup file intact; restart must stay locked expect((await api.call('/api/security/panic-lock', { method: 'POST' })).status).toBe(200); @@ -464,6 +466,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret }); expect(loginAfterPanic.status).toBe(200); expect(loginAfterPanic.data.vaultState).toBe('locked'); + expect(loginAfterPanic.data.vaultRuntimeReady).toBe(false); // Unlock manually, then wipe and disable recovery backup expect( diff --git a/tests/vault-runtime-and-collectors.test.ts b/tests/vault-runtime-and-collectors.test.ts new file mode 100644 index 0000000..373a588 --- /dev/null +++ b/tests/vault-runtime-and-collectors.test.ts @@ -0,0 +1,302 @@ +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 } from 'vitest'; +import { createGCoordinatorServer, type GCoordinatorInstance } from '../src/server/app.js'; +import { MockSshServer } from './helpers/mock-ssh-server.js'; + +const cleanups: Array<() => Promise | void> = []; + +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('; '); + } +} + +function createApiClient(server: GCoordinatorInstance) { + const baseUrl = `http://127.0.0.1:${server.port}`; + const jar = new CookieJar(); + let csrfToken = ''; + + const call = async ( + pathname: string, + opts: { method?: string; body?: unknown; csrf?: string | null } = {}, + ) => { + const headers: Record = {}; + if (jar.header()) headers.Cookie = jar.header(); + if (opts.body !== undefined) headers['Content-Type'] = 'application/json'; + const token = opts.csrf === undefined ? csrfToken : opts.csrf; + if (token) headers['X-CSRF-Token'] = token; + + 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(() => ({}))) as Record; + if (typeof data.csrfToken === 'string' && data.csrfToken) { + csrfToken = data.csrfToken; + } + return { status: res.status, data }; + }; + + return { + call, + clearCsrf: () => { + csrfToken = ''; + }, + }; +} + +async function waitFor(fn: () => T | undefined | null | false, timeoutMs = 4000): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const val = fn(); + if (val) return val; + await new Promise((r) => setTimeout(r, 40)); + } + throw new Error('Timed out waiting for condition'); +} + +afterEach(async () => { + while (cleanups.length > 0) { + await cleanups.pop()!(); + } +}); + +describe('Always-on background collectors & write-only Vault lock', () => { + it('collects metrics before login across restarts while keeping Vault locked against modifications and reveals', async () => { + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-runtime-vault-test-')); + cleanups.push(() => { + fs.rmSync(dataDir, { recursive: true, force: true }); + }); + + let activeServer: GCoordinatorInstance | null = await createGCoordinatorServer({ + dataDir, + port: 0, + host: '127.0.0.1', + publicDir: path.resolve('dist/public'), + watchConfig: false, + }); + cleanups.push(async () => { + if (activeServer) { + await activeServer.close(); + activeServer = null; + } + }); + + let api = createApiClient(activeServer); + const bootInfo = await api.call('/api/auth/bootstrap'); + const secretBase32 = String(bootInfo.data.secretBase32); + const totp = new OTPAuth.TOTP({ + issuer: 'GCoordinator', + label: 'admin', + algorithm: 'SHA1', + digits: 6, + period: 30, + secret: OTPAuth.Secret.fromBase32(secretBase32), + }); + const password = 'always-on-collectors-pw-1'; + + const bootRes = await api.call('/api/auth/bootstrap', { + method: 'POST', + body: { + username: 'admin', + password, + totpCode: totp.generate(), + secretBase32, + }, + }); + expect(bootRes.status).toBe(201); + const recoveryCodes = bootRes.data.recoveryCodes as string[]; + expect(recoveryCodes.length).toBeGreaterThan(0); + + // Explicitly initialize & add SSH key, register server, then lock Vault + expect((await api.call('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201); + const keyRes = await api.call('/api/vault/generate-ed25519', { + method: 'POST', + body: { id: 'srv-key', name: 'Server Key' }, + }); + expect(keyRes.status).toBe(201); + const pubKey = String((keyRes.data.credential as { publicKey: string }).publicKey); + + const mock = new MockSshServer({ + username: 'ops', + os: 'Linux', + authorizedKeys: [pubKey], + }); + const sshPort = await mock.start(); + cleanups.push(() => mock.close()); + + const reg = await api.call('/api/servers', { + method: 'POST', + body: { + id: 'srv-1', + name: 'Always-On Node', + host: '127.0.0.1', + port: sshPort, + username: 'ops', + credentialId: 'srv-key', + hostKeyFingerprint: mock.hostFingerprint, + pollIntervalSec: 5, + }, + }); + expect(reg.status).toBe(201); + + const lockRes = await api.call('/api/vault/lock', { method: 'POST' }); + expect(lockRes.status).toBe(200); + expect(lockRes.data.state).toBe('locked'); + expect(lockRes.data.runtimeReady).toBe(true); + + // Restart server cleanly + await activeServer.close(); + activeServer = null; + + activeServer = await createGCoordinatorServer({ + dataDir, + port: 0, + host: '127.0.0.1', + publicDir: path.resolve('dist/public'), + watchConfig: false, + }); + api = createApiClient(activeServer); + + // Before ANY user logs in, status is unauthenticated + write-locked, yet runtime collectors run immediately + const preLoginStatus = await api.call('/api/auth/status'); + expect(preLoginStatus.status).toBe(200); + expect(preLoginStatus.data.authenticated).toBe(false); + expect(preLoginStatus.data.vaultState).toBe('locked'); + expect(preLoginStatus.data.vaultRuntimeReady).toBe(true); + + const latestBeforeLogin = await waitFor( + () => activeServer!.monitoringService.getLatest('srv-1')?.sample, + ); + expect(latestBeforeLogin.ts).toBeGreaterThan(0); + expect(mock.activeConnectionCount).toBeGreaterThanOrEqual(1); + + // Log in without unlocking the Vault: dashboard metrics, inspect, SFTP, and metadata listing all work + const login = await api.call('/api/auth/login', { + method: 'POST', + body: { + username: 'admin', + password, + code: recoveryCodes[0]!, + }, + csrf: null, + }); + expect(login.status).toBe(200); + expect(login.data.vaultState).toBe('locked'); + expect(login.data.vaultRuntimeReady).toBe(true); + + const serversRes = await api.call('/api/servers'); + expect(serversRes.status).toBe(200); + const srvEntry = ( + serversRes.data.servers as Array<{ + runtime: { status: string }; + telemetry: { sample?: { ts: number }; disks: unknown[] } | null; + }> + )[0]!; + expect(srvEntry.runtime.status).toBe('connected'); + expect(srvEntry.telemetry?.sample?.ts).toBeGreaterThan(0); + expect(srvEntry.telemetry?.disks.length).toBeGreaterThan(0); + + const credsMeta = await api.call('/api/vault/credentials'); + expect(credsMeta.status).toBe(200); + expect(credsMeta.data.state).toBe('locked'); + expect(credsMeta.data.runtimeReady).toBe(true); + expect((credsMeta.data.credentials as Array<{ id: string }>).map((c) => c.id)).toContain( + 'srv-key', + ); + + expect((await api.call('/api/servers/srv-1/inspect')).status).toBe(200); + expect((await api.call('/api/servers/srv-1/sftp/list?path=/')).status).toBe(200); + + // Modifications and secret reveals must still be blocked with 423 VAULT_LOCKED while locked + const addBlocked = await api.call('/api/vault/credentials', { + method: 'POST', + body: { id: 'tok-1', name: 'Token', type: 'api-token', token: 'abc' }, + }); + expect(addBlocked.status).toBe(423); + expect(addBlocked.data.error).toBe('VAULT_LOCKED'); + + const genBlocked = await api.call('/api/vault/generate-ed25519', { + method: 'POST', + body: { id: 'k2', name: 'Key 2' }, + }); + expect(genBlocked.status).toBe(423); + expect(genBlocked.data.error).toBe('VAULT_LOCKED'); + + const delBlocked = await api.call('/api/vault/credentials/srv-key', { + method: 'DELETE', + }); + expect(delBlocked.status).toBe(423); + expect(delBlocked.data.error).toBe('VAULT_LOCKED'); + + const revealBlocked = await api.call('/api/vault/credentials/srv-key/reveal'); + expect(revealBlocked.status).toBe(423); + expect(revealBlocked.data.error).toBe('VAULT_LOCKED'); + + const rotateBlocked = await api.call('/api/servers/rotate-keys', { + method: 'POST', + body: { serverIds: ['srv-1'] }, + }); + expect(rotateBlocked.status).toBe(423); + expect(rotateBlocked.data.error).toBe('VAULT_LOCKED'); + + // Unlock for modifications using session unlock ({}, no raw 64-hex master key required) + const unlockSession = await api.call('/api/vault/unlock', { + method: 'POST', + body: {}, + }); + expect(unlockSession.status).toBe(200); + expect(unlockSession.data.state).toBe('unlocked'); + expect(unlockSession.data.runtimeReady).toBe(true); + + expect( + ( + await api.call('/api/vault/credentials', { + method: 'POST', + body: { id: 'tok-1', name: 'Token', type: 'api-token', token: 'abc' }, + }) + ).status, + ).toBe(201); + expect((await api.call('/api/vault/credentials/srv-key/reveal')).status).toBe(200); + + const rotOk = await api.call('/api/servers/rotate-keys', { + method: 'POST', + body: { serverIds: ['srv-1'] }, + }); + expect(rotOk.status).toBe(200); + expect((rotOk.data.results as Array<{ ok: boolean }>)[0]?.ok).toBe(true); + + // Re-lock against modifications without disconnecting runtime SSH + const relock = await api.call('/api/vault/lock', { method: 'POST' }); + expect(relock.status).toBe(200); + expect(relock.data.state).toBe('locked'); + expect(relock.data.runtimeReady).toBe(true); + + const serversAfterRelock = await api.call('/api/servers'); + expect( + (serversAfterRelock.data.servers as Array<{ runtime: { status: string } }>)[0]?.runtime.status, + ).toBe('connected'); + }); +}); diff --git a/tests/vault.test.ts b/tests/vault.test.ts index da0b23d..36365df 100644 --- a/tests/vault.test.ts +++ b/tests/vault.test.ts @@ -200,4 +200,64 @@ describe('VaultService & CLI key rotation', () => { checkCli.unlock(rotatedKey2); expect(checkCli.getSecret('api-1')).toMatchObject({ token: 'tok-xyz' }); }); + + it('supports runtime-ready write-locked mode via initRuntime and keyFilePath without blocking established secret reads', () => { + const dir = makeTempDir(); + const vaultPath = path.join(dir, 'vault.enc'); + const keyFilePath = path.join(dir, 'vault.key'); + + const v1 = new VaultService(vaultPath, { keyFilePath }); + const initRes = v1.initRuntime({ autoCreateIfMissing: true }); + expect(initRes.runtimeReady).toBe(true); + expect(initRes.initialized).toBe(true); + expect(v1.isRuntimeReady).toBe(true); + expect(v1.state).toBe('locked'); + expect(fs.existsSync(keyFilePath)).toBe(true); + expect(fs.statSync(keyFilePath).mode & 0o777).toBe(0o600); + + // Explicitly initialize / unlock for modifications and save an established credential + v1.unlockForModifications(); + expect(v1.state).toBe('unlocked'); + v1.upsertCredential({ + id: 'runtime-cred', + name: 'Runtime SSH Key', + type: 'ssh-password', + password: 'established-runtime-secret', + }); + v1.lockForModifications(); + expect(v1.state).toBe('locked'); + expect(v1.isRuntimeReady).toBe(true); + + // Reload across restart with initRuntime() -> active for runtime use, locked for mutations/reveals + const v2 = new VaultService(vaultPath, { keyFilePath }); + const bootRes = v2.initRuntime({ autoCreateIfMissing: true }); + expect(bootRes.runtimeReady).toBe(true); + expect(v2.isRuntimeReady).toBe(true); + expect(v2.state).toBe('locked'); + + expect(v2.hasCredential('runtime-cred')).toBe(true); + expect(v2.listMetadata().map((m) => m.id)).toEqual(['runtime-cred']); + expect(v2.getRuntimeSecret('runtime-cred')).toMatchObject({ + password: 'established-runtime-secret', + }); + + expect(() => v2.getSecret('runtime-cred')).toThrow(/locked/i); + expect(() => + v2.upsertCredential({ + id: 'new-cred', + name: 'Blocked While Locked', + type: 'api-token', + token: 'nope', + }), + ).toThrow(/locked/i); + + v2.unlockForModifications(); + expect(v2.state).toBe('unlocked'); + expect(v2.getSecret('runtime-cred')).toMatchObject({ + password: 'established-runtime-secret', + }); + v2.lockForModifications(); + expect(v2.state).toBe('locked'); + expect(v2.isRuntimeReady).toBe(true); + }); });