203 lines
6.6 KiB
TypeScript
203 lines
6.6 KiB
TypeScript
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' });
|
|
});
|
|
});
|