234 lines
8.3 KiB
TypeScript
234 lines
8.3 KiB
TypeScript
import fs from 'node:fs';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import { afterEach, describe, expect, it } from 'vitest';
|
|
import { ConfigManager } from '../src/server/config/config-manager.js';
|
|
import { openDatabase } from '../src/server/db/database.js';
|
|
import { AuditService } from '../src/server/security/audit.js';
|
|
import { VaultService } from '../src/server/security/vault.js';
|
|
import { KeyManager } from '../src/server/ssh/key-manager.js';
|
|
import { KnownHostsService } from '../src/server/ssh/known-hosts.js';
|
|
import { SSHPool } from '../src/server/ssh/ssh-pool.js';
|
|
import { MockSshServer } from './helpers/mock-ssh-server.js';
|
|
|
|
const cleanups: Array<() => Promise<void> | void> = [];
|
|
|
|
async function setupEnv() {
|
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-ssh-test-'));
|
|
const db = openDatabase(path.join(dir, 'gcoord.db'));
|
|
const audit = new AuditService(db);
|
|
const vault = new VaultService(path.join(dir, 'vault.enc'));
|
|
vault.initializeNewVault();
|
|
const cfg = new ConfigManager(path.join(dir, 'config'), db, vault);
|
|
await cfg.init({ watch: false });
|
|
const knownHosts = new KnownHostsService(db, audit);
|
|
const sshPool = new SSHPool(cfg, vault, knownHosts);
|
|
const keyManager = new KeyManager(sshPool, vault, cfg, audit);
|
|
|
|
cleanups.push(async () => {
|
|
sshPool.closeAll('shutdown');
|
|
await cfg.close();
|
|
db.close();
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
});
|
|
|
|
return { dir, db, audit, vault, cfg, knownHosts, sshPool, keyManager };
|
|
}
|
|
|
|
afterEach(async () => {
|
|
while (cleanups.length > 0) {
|
|
await cleanups.pop()!();
|
|
}
|
|
});
|
|
|
|
describe('SSHPool TOFU/MITM, ProxyJump, sudo, and Atomic Key Rotation', () => {
|
|
it('enforces strict TOFU, hard-blocks host key mismatch, and recovers via step-up reset', async () => {
|
|
const { vault, cfg, knownHosts, sshPool } = await setupEnv();
|
|
const cred = vault.generateEd25519Credential({ id: 'cred-main', name: 'Main' });
|
|
|
|
const mock = new MockSshServer({
|
|
username: 'ops',
|
|
authorizedKeys: [cred.publicKey!],
|
|
});
|
|
const port = await mock.start();
|
|
cleanups.push(() => mock.close());
|
|
|
|
cfg.saveConfigText(
|
|
'servers/app-01.json',
|
|
JSON.stringify({
|
|
id: 'app-01',
|
|
name: 'App 01',
|
|
host: '127.0.0.1',
|
|
port,
|
|
username: 'ops',
|
|
credentialId: 'cred-main',
|
|
}),
|
|
);
|
|
|
|
// 1. Initial connection must block awaiting TOFU approval
|
|
await expect(sshPool.exec('app-01', 'echo hello')).rejects.toThrow();
|
|
const state1 = sshPool.getState('app-01');
|
|
expect(state1?.status).toBe('tofu_pending');
|
|
expect(state1?.tofuPending?.fingerprint).toBe(mock.hostFingerprint);
|
|
|
|
// 2. Approve TOFU and connect cleanly
|
|
knownHosts.approveTofu('app-01', mock.hostFingerprint);
|
|
const res = await sshPool.exec('app-01', 'echo hello');
|
|
expect(res.exitCode).toBe(0);
|
|
expect(res.stdout.trim()).toBe('ok:echo hello');
|
|
expect(sshPool.getState('app-01')?.status).toBe('connected');
|
|
|
|
// 3. Simulate MITM host key swap
|
|
const newHostFp = await mock.swapHostKey();
|
|
sshPool.closeServer('app-01');
|
|
|
|
await expect(sshPool.exec('app-01', 'echo blocked')).rejects.toThrow();
|
|
const stateMismatch = sshPool.getState('app-01');
|
|
expect(stateMismatch?.status).toBe('host_key_mismatch');
|
|
expect(stateMismatch?.hostKeyMismatch?.actualFingerprint).toBe(newHostFp);
|
|
|
|
// 4. Reset mismatch and verify restored connection
|
|
knownHosts.resetMismatch('app-01', newHostFp);
|
|
const resAfter = await sshPool.exec('app-01', 'echo recovered');
|
|
expect(resAfter.stdout.trim()).toBe('ok:echo recovered');
|
|
});
|
|
|
|
it('chains multi-hop ProxyJump bastions and runs sudo -S via stdin without leaking secrets in command', async () => {
|
|
const { vault, cfg, knownHosts, sshPool } = await setupEnv();
|
|
const cred = vault.generateEd25519Credential({ id: 'cred-hop', name: 'Hop Key' });
|
|
vault.upsertCredential({
|
|
id: 'sudo-ops',
|
|
name: 'Sudo PW',
|
|
type: 'sudo-password',
|
|
password: 'vault-sudo-secret-pw',
|
|
});
|
|
|
|
const bastion = new MockSshServer({
|
|
username: 'bastion-user',
|
|
authorizedKeys: [cred.publicKey!],
|
|
allowTcpForward: true,
|
|
});
|
|
const bastionPort = await bastion.start();
|
|
cleanups.push(() => bastion.close());
|
|
|
|
const privateTarget = new MockSshServer({
|
|
username: 'ops',
|
|
authorizedKeys: [cred.publicKey!],
|
|
sudoPassword: 'vault-sudo-secret-pw',
|
|
});
|
|
const targetPort = await privateTarget.start();
|
|
cleanups.push(() => privateTarget.close());
|
|
|
|
cfg.saveConfigText(
|
|
'servers/bastion.json',
|
|
JSON.stringify({
|
|
id: 'bastion',
|
|
name: 'Bastion',
|
|
host: '127.0.0.1',
|
|
port: bastionPort,
|
|
username: 'bastion-user',
|
|
credentialId: 'cred-hop',
|
|
hostKeyFingerprint: bastion.hostFingerprint,
|
|
}),
|
|
);
|
|
|
|
cfg.saveConfigText(
|
|
'servers/priv-01.json',
|
|
JSON.stringify({
|
|
id: 'priv-01',
|
|
name: 'Private Target',
|
|
host: '127.0.0.1',
|
|
port: targetPort,
|
|
username: 'ops',
|
|
credentialId: 'cred-hop',
|
|
jumpHostId: 'bastion',
|
|
sudoCredentialId: 'sudo-ops',
|
|
hostKeyFingerprint: privateTarget.hostFingerprint,
|
|
}),
|
|
);
|
|
|
|
// First hop + second hop both use pre-seeded hostKeyFingerprint & forwardOut tunnel
|
|
const res = await sshPool.exec('priv-01', 'id -u', { sudo: true });
|
|
expect(res.exitCode).toBe(0);
|
|
expect(res.stdout.trim()).toBe('ok:id -u');
|
|
expect(privateTarget.lastSudoStdin).toBe('vault-sudo-secret-pw');
|
|
|
|
// Verify independent known_hosts key includes jumpHostId prefix
|
|
const kh = knownHosts.listKnownHosts().map((k) => k.hostPort);
|
|
expect(kh).toContain(`127.0.0.1:${bastionPort}`);
|
|
expect(kh).toContain(`bastion->127.0.0.1:${targetPort}`);
|
|
});
|
|
|
|
it('deploys/revokes authorized_keys and performs atomic zero-lockout rotation with rollback on failure', async () => {
|
|
const { vault, cfg, keyManager } = await setupEnv();
|
|
const initialCred = vault.generateEd25519Credential({
|
|
id: 'cred-initial',
|
|
name: 'Initial Key',
|
|
comment: 'initial@hub',
|
|
});
|
|
const extraCred = vault.generateEd25519Credential({
|
|
id: 'cred-extra',
|
|
name: 'Extra Key',
|
|
comment: 'extra@hub',
|
|
});
|
|
|
|
let failVerificationOnce = true;
|
|
const mock = new MockSshServer({
|
|
username: 'ops',
|
|
authorizedKeys: [initialCred.publicKey!],
|
|
onExec: (cmd) => {
|
|
if (cmd === 'echo gcoord-key-ok' && failVerificationOnce) {
|
|
failVerificationOnce = false;
|
|
return { stdout: '', stderr: 'simulated auth verify failure', exitCode: 1 };
|
|
}
|
|
return null;
|
|
},
|
|
});
|
|
const port = await mock.start();
|
|
cleanups.push(() => mock.close());
|
|
|
|
cfg.saveConfigText(
|
|
'servers/rot-01.json',
|
|
JSON.stringify({
|
|
id: 'rot-01',
|
|
name: 'Rot 01',
|
|
host: '127.0.0.1',
|
|
port,
|
|
username: 'ops',
|
|
credentialId: 'cred-initial',
|
|
hostKeyFingerprint: mock.hostFingerprint,
|
|
}),
|
|
);
|
|
|
|
// 1. Deploy extra key and refuse active key revocation without force
|
|
const dep = await keyManager.deployVaultKey('rot-01', 'cred-extra');
|
|
expect(dep.deployed).toBe(true);
|
|
await expect(
|
|
keyManager.revokeAuthorizedKey('rot-01', initialCred.fingerprint!),
|
|
).rejects.toThrow(/active/i);
|
|
|
|
const revExtra = await keyManager.revokeAuthorizedKey('rot-01', extraCred.fingerprint!);
|
|
expect(revExtra.removedCount).toBe(1);
|
|
|
|
// 2. Rotation failure must roll back authorized_keys and preserve cred-initial
|
|
const failedRot = await keyManager.rotateKeys({ serverIds: ['rot-01'] });
|
|
expect(failedRot[0]).toMatchObject({
|
|
serverId: 'rot-01',
|
|
ok: false,
|
|
rolledBack: true,
|
|
});
|
|
expect(cfg.getServer('rot-01')?.credentialId).toBe('cred-initial');
|
|
expect(mock.authorizedKeys).toEqual([initialCred.publicKey!]);
|
|
|
|
// 3. Successful rotation switches server JSON and removes old public key
|
|
const okRot = await keyManager.rotateKeys({ serverIds: ['rot-01'] });
|
|
expect(okRot[0]?.ok).toBe(true);
|
|
const newCredId = okRot[0]!.newCredentialId!;
|
|
expect(cfg.getServer('rot-01')?.credentialId).toBe(newCredId);
|
|
|
|
const afterKeys = await keyManager.inspectAuthorizedKeys('rot-01');
|
|
expect(afterKeys.entries).toHaveLength(1);
|
|
expect(afterKeys.entries[0]?.matchedVaultCredentialId).toBe(newCredId);
|
|
expect(afterKeys.entries[0]?.isCurrentServerKey).toBe(true);
|
|
});
|
|
});
|