test: add comprehensive v1.1 security, proxy/SFTP, automation/CLI & bundle tests
This commit is contained in:
parent
f45d128c4f
commit
a5a937850e
4 changed files with 1228 additions and 3 deletions
361
tests/v11-ssh-proxy-sftp.test.ts
Normal file
361
tests/v11-ssh-proxy-sftp.test.ts
Normal file
|
|
@ -0,0 +1,361 @@
|
|||
import fs from 'node:fs';
|
||||
import net from 'node:net';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { createGCoordinatorServer } from '../src/server/app.js';
|
||||
import { formatRemoteCd } from '../src/server/ssh/pty-manager.js';
|
||||
import { parseOpenSshConfig } from '../src/server/ssh/ssh-config-import.js';
|
||||
import { MockSshServer } from './helpers/mock-ssh-server.js';
|
||||
|
||||
const cleanups: Array<() => Promise<void> | void> = [];
|
||||
|
||||
class CookieJar {
|
||||
private cookies = new Map<string, string>();
|
||||
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('; ');
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
while (cleanups.length > 0) {
|
||||
await cleanups.pop()!();
|
||||
}
|
||||
});
|
||||
|
||||
describe('v1.1 SSH Import, Multi-Algo known_hosts, PTY Security/.cast, SFTP v1.1 & Isolated Proxy / SOCKS5', () => {
|
||||
it('parses & imports OpenSSH config, manages multi-algo known_hosts, enforces PTY/SFTP v1.1 ops, and validates proxy/SOCKS5/TTL', async () => {
|
||||
const seenExecs: string[] = [];
|
||||
const mock = new MockSshServer({
|
||||
username: 'ops',
|
||||
os: 'Linux',
|
||||
allowTcpForward: true,
|
||||
onExec: (cmd) => {
|
||||
seenExecs.push(cmd);
|
||||
if (cmd.startsWith('chown ')) {
|
||||
return { stdout: '', exitCode: 0 };
|
||||
}
|
||||
if (cmd.startsWith('find ') && cmd.includes('needle')) {
|
||||
return { stdout: '/sub/needle.conf\n', exitCode: 0 };
|
||||
}
|
||||
return null;
|
||||
},
|
||||
});
|
||||
await mock.start();
|
||||
cleanups.push(() => mock.close());
|
||||
|
||||
// Populate mock sftp root files
|
||||
fs.writeFileSync(path.join(mock.sftpRootDir, 'alpha.log'), 'hello-alpha\n');
|
||||
fs.mkdirSync(path.join(mock.sftpRootDir, 'sub'), { recursive: true });
|
||||
fs.writeFileSync(path.join(mock.sftpRootDir, 'sub', 'needle.conf'), 'port=8080\n');
|
||||
const outsideSecret = path.join(os.tmpdir(), `outside-secret-${Date.now()}.txt`);
|
||||
fs.writeFileSync(outsideSecret, 'TOP_SECRET');
|
||||
cleanups.push(() => fs.rmSync(outsideSecret, { force: true }));
|
||||
fs.symlinkSync(outsideSecret, path.join(mock.sftpRootDir, 'escape-link'));
|
||||
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-ssh-'));
|
||||
// First start WITHOUT proxyPort to test strict PROXY_ORIGIN_ISOLATION_REQUIRED enforcement
|
||||
const serverNoIso = await createGCoordinatorServer({
|
||||
dataDir,
|
||||
port: 0,
|
||||
host: '127.0.0.1',
|
||||
publicDir: path.resolve('dist/public'),
|
||||
watchConfig: false,
|
||||
});
|
||||
|
||||
const baseUrl = `http://127.0.0.1:${serverNoIso.port}`;
|
||||
const jar = new CookieJar();
|
||||
let csrfToken = '';
|
||||
const api = async (
|
||||
pathname: string,
|
||||
opts: { method?: string; body?: unknown; raw?: boolean } = {},
|
||||
) => {
|
||||
const headers: Record<string, string> = {};
|
||||
if (jar.header()) headers.Cookie = jar.header();
|
||||
if (opts.body !== undefined) headers['Content-Type'] = 'application/json';
|
||||
if (csrfToken) headers['X-CSRF-Token'] = csrfToken;
|
||||
const res = await fetch(`${baseUrl}${pathname}`, {
|
||||
method: opts.method ?? 'GET',
|
||||
headers,
|
||||
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
||||
});
|
||||
jar.updateFrom(res);
|
||||
if (opts.raw) {
|
||||
return { status: res.status, text: await res.text(), data: {} as Record<string, unknown> };
|
||||
}
|
||||
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
return { status: res.status, data, text: '' };
|
||||
};
|
||||
|
||||
try {
|
||||
const bootInfo = await api('/api/auth/bootstrap');
|
||||
const totp = new OTPAuth.TOTP({
|
||||
issuer: 'GCoordinator',
|
||||
label: 'admin',
|
||||
algorithm: 'SHA1',
|
||||
digits: 6,
|
||||
period: 30,
|
||||
secret: OTPAuth.Secret.fromBase32(String(bootInfo.data.secretBase32)),
|
||||
});
|
||||
const bootRes = await api('/api/auth/bootstrap', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
username: 'admin',
|
||||
password: 'ssh-proxy-v11-password!',
|
||||
totpCode: totp.generate(),
|
||||
securityPreset: 'relaxed',
|
||||
},
|
||||
});
|
||||
expect(bootRes.status).toBe(201);
|
||||
csrfToken = String(bootRes.data.csrfToken);
|
||||
|
||||
await api('/api/vault/init', { method: 'POST', body: {} });
|
||||
const genKey = await api('/api/vault/generate-ed25519', {
|
||||
method: 'POST',
|
||||
body: { id: 'ssh-main', name: 'Main Key' },
|
||||
});
|
||||
mock.authorizedKeys.push(
|
||||
String((genKey.data.credential as { publicKey: string }).publicKey),
|
||||
);
|
||||
|
||||
// OpenSSH parser + /api/servers/import-ssh-config preview & apply
|
||||
const sshConfigText = [
|
||||
'Host *',
|
||||
' User ignored',
|
||||
'Host bastion',
|
||||
' HostName 127.0.0.1',
|
||||
` Port ${mock.port}`,
|
||||
' User ops',
|
||||
'Host app-behind-bastion',
|
||||
' HostName 127.0.0.1',
|
||||
` Port ${mock.port}`,
|
||||
' User ops',
|
||||
' ProxyJump bastion',
|
||||
].join('\n');
|
||||
const parsed = parseOpenSshConfig(sshConfigText);
|
||||
expect(parsed.entries.map((e) => e.alias)).toEqual(['bastion', 'app-behind-bastion']);
|
||||
|
||||
const prevRes = await api('/api/servers/import-ssh-config', {
|
||||
method: 'POST',
|
||||
body: { configText: sshConfigText, apply: false },
|
||||
});
|
||||
expect(prevRes.status).toBe(200);
|
||||
expect((prevRes.data.createdIds as string[]).length).toBe(0);
|
||||
|
||||
const applyRes = await api('/api/servers/import-ssh-config', {
|
||||
method: 'POST',
|
||||
body: { configText: sshConfigText, defaultCredentialId: 'ssh-main', apply: true },
|
||||
});
|
||||
expect(applyRes.status).toBe(201);
|
||||
expect(applyRes.data.createdIds).toEqual(['bastion', 'app-behind-bastion']);
|
||||
|
||||
// Reconnect + approve TOFU on bastion
|
||||
await api('/api/servers/bastion/reconnect', { method: 'POST' });
|
||||
const approve = await api('/api/servers/bastion/tofu/approve', {
|
||||
method: 'POST',
|
||||
body: { fingerprint: mock.hostFingerprint },
|
||||
});
|
||||
expect(approve.status).toBe(200);
|
||||
|
||||
// Multi-algorithm known_hosts CRUD
|
||||
const curKnown = serverNoIso.knownHosts.listKnownHosts();
|
||||
serverNoIso.knownHosts.replaceAllKnownHosts([
|
||||
...curKnown,
|
||||
{
|
||||
hostPort: `127.0.0.1:${mock.port}`,
|
||||
algorithm: 'ssh-rsa',
|
||||
fingerprint: 'SHA256:fakeRsaFp',
|
||||
},
|
||||
]);
|
||||
const khList = await api('/api/servers/known-hosts');
|
||||
expect(khList.status).toBe(200);
|
||||
const matching = (khList.data.knownHosts as Array<{ hostPort: string; algorithm: string }>).filter(
|
||||
(x) => x.hostPort === `127.0.0.1:${mock.port}`,
|
||||
);
|
||||
expect(matching.length).toBeGreaterThanOrEqual(2);
|
||||
|
||||
const delRsa = await api(
|
||||
`/api/servers/known-hosts?hostPort=${encodeURIComponent(`127.0.0.1:${mock.port}`)}&algorithm=ssh-rsa`,
|
||||
{ method: 'DELETE' },
|
||||
);
|
||||
expect(delRsa.status).toBe(200);
|
||||
|
||||
// PTY cwd injection defense (control chars blocked 400 + single-quoted shell cwd) + .cast export + reconnect
|
||||
expect(formatRemoteCd("/tmp'; rm -rf /")).toBe("cd -- '/tmp'\\''; rm -rf /'");
|
||||
expect(formatRemoteCd('~/My Dir')).toBe('cd -- "$HOME/"\'My Dir\'');
|
||||
|
||||
const badCtrlPty = await api('/api/terminal/sessions', {
|
||||
method: 'POST',
|
||||
body: { serverId: 'bastion', cwd: '/tmp\nbad', cols: 80, rows: 24 },
|
||||
});
|
||||
expect(badCtrlPty.status).toBe(400);
|
||||
|
||||
const quotedCwdPty = await api('/api/terminal/sessions', {
|
||||
method: 'POST',
|
||||
body: { serverId: 'bastion', cwd: '/tmp; rm -rf /', cols: 80, rows: 24 },
|
||||
});
|
||||
expect(quotedCwdPty.status).toBe(201);
|
||||
const qPtyId = String((quotedCwdPty.data.session as { sessionId: string }).sessionId);
|
||||
await new Promise((r) => setTimeout(r, 80));
|
||||
const qExport = await api(`/api/terminal/sessions/${qPtyId}/export?format=plain`, { raw: true });
|
||||
expect(qExport.text).toContain("cd -- '/tmp; rm -rf /'");
|
||||
await api(`/api/terminal/sessions/${qPtyId}`, { method: 'DELETE' });
|
||||
|
||||
const ptyRes = await api('/api/terminal/sessions', {
|
||||
method: 'POST',
|
||||
body: { serverId: 'bastion', cwd: '/tmp', cols: 80, rows: 24 },
|
||||
});
|
||||
expect(ptyRes.status).toBe(201);
|
||||
const ptyId = String((ptyRes.data.session as { sessionId: string }).sessionId);
|
||||
await new Promise((r) => setTimeout(r, 150));
|
||||
|
||||
const castRes = await api(`/api/terminal/sessions/${ptyId}/export?format=cast`, { raw: true });
|
||||
expect(castRes.status).toBe(200);
|
||||
const header = JSON.parse(castRes.text.trim().split('\n')[0]!) as { version: number; width: number };
|
||||
expect(header.version).toBe(2);
|
||||
expect(header.width).toBe(80);
|
||||
|
||||
const reconPty = await api(`/api/terminal/sessions/${ptyId}/reconnect`, {
|
||||
method: 'POST',
|
||||
body: {},
|
||||
});
|
||||
expect(reconPty.status).toBe(200);
|
||||
expect((reconPty.data.session as { exited: boolean }).exited).toBe(false);
|
||||
await api(`/api/terminal/sessions/${ptyId}`, { method: 'DELETE' });
|
||||
|
||||
// SFTP v1.1: touch, chown (sudo via MockSshServer), search, bulk-delete, symlink escape refusal
|
||||
const touchRes = await api('/api/servers/bastion/sftp/touch', {
|
||||
method: 'POST',
|
||||
body: { path: '/touched.txt' },
|
||||
});
|
||||
expect(touchRes.status).toBe(201);
|
||||
expect(fs.existsSync(path.join(mock.sftpRootDir, 'touched.txt'))).toBe(true);
|
||||
|
||||
const chownRes = await api('/api/servers/bastion/sftp/chown', {
|
||||
method: 'POST',
|
||||
body: { path: '/touched.txt', uid: 1000, gid: 1000, sudo: true },
|
||||
});
|
||||
expect(chownRes.status).toBe(200);
|
||||
expect(seenExecs.some((c) => c.includes('chown 1000:1000'))).toBe(true);
|
||||
|
||||
const searchRes = await api('/api/servers/bastion/sftp/search?path=/&q=needle');
|
||||
expect(searchRes.status).toBe(200);
|
||||
expect(searchRes.data.matches).toContain('/sub/needle.conf');
|
||||
expect(seenExecs.some((c) => c.startsWith("find '/' -maxdepth 5 -iname '*needle*'"))).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
const bulkDel = await api('/api/servers/bastion/sftp/bulk-delete', {
|
||||
method: 'POST',
|
||||
body: { paths: ['/touched.txt', '/alpha.log'], recursive: false },
|
||||
});
|
||||
expect(bulkDel.status).toBe(200);
|
||||
expect((bulkDel.data.deleted as string[]).length).toBe(2);
|
||||
|
||||
// Symlink inspection + safe symlink deletion (lstat unlinks symlink without touching target dir)
|
||||
const targetDir = path.join(mock.sftpRootDir, 'keep-dir');
|
||||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(targetDir, 'precious.txt'), 'do-not-delete');
|
||||
fs.symlinkSync(targetDir, path.join(mock.sftpRootDir, 'link-to-dir'));
|
||||
|
||||
const symStat = await api('/api/servers/bastion/sftp/stat?path=/escape-link');
|
||||
expect(symStat.status).toBe(200);
|
||||
expect((symStat.data.entry as { type: string }).type).toBe('symlink');
|
||||
|
||||
const delLink = await api(
|
||||
'/api/servers/bastion/sftp/entry?path=/link-to-dir&recursive=1',
|
||||
{ method: 'DELETE' },
|
||||
);
|
||||
expect(delLink.status).toBe(200);
|
||||
expect(fs.existsSync(path.join(targetDir, 'precious.txt'))).toBe(true);
|
||||
expect(fs.existsSync(path.join(mock.sftpRootDir, 'link-to-dir'))).toBe(false);
|
||||
|
||||
const nullPath = await api('/api/servers/bastion/sftp/text?path=/bad%00path');
|
||||
expect(nullPath.status).toBeGreaterThanOrEqual(400);
|
||||
|
||||
// SOCKS5 tunnel without targetPort + TTL countdown metadata
|
||||
const socksCreate = await api('/api/tunnels', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
serverId: 'bastion',
|
||||
tunnel: {
|
||||
id: 'socks-tun',
|
||||
name: 'SOCKS5 Local',
|
||||
mode: 'socks5',
|
||||
targetHost: '127.0.0.1',
|
||||
targetPort: 0,
|
||||
ttlSec: 120,
|
||||
autoStart: false,
|
||||
},
|
||||
start: true,
|
||||
},
|
||||
});
|
||||
expect(socksCreate.status).toBe(201);
|
||||
const tList = await api('/api/tunnels');
|
||||
const socksItem = (tList.data.tunnels as Array<{
|
||||
tunnel: { id: string; mode: string; ttlSec?: number };
|
||||
active: boolean;
|
||||
localBoundPort?: number;
|
||||
expiresAt?: number;
|
||||
}>).find((t) => t.tunnel.id === 'socks-tun');
|
||||
expect(socksItem?.active).toBe(true);
|
||||
expect(socksItem?.expiresAt).toBeGreaterThan(Date.now());
|
||||
|
||||
// SOCKS5 method negotiation (0x05 0x01 0x00 -> 0x05 0x00)
|
||||
const socksReply = await new Promise<Buffer>((resolve, reject) => {
|
||||
const sock = net.connect(socksItem!.localBoundPort!, '127.0.0.1', () => {
|
||||
sock.write(Buffer.from([0x05, 0x01, 0x00]));
|
||||
});
|
||||
sock.once('data', (d) => {
|
||||
sock.destroy();
|
||||
resolve(d);
|
||||
});
|
||||
sock.once('error', reject);
|
||||
});
|
||||
expect(socksReply[0]).toBe(0x05);
|
||||
expect(socksReply[1]).toBe(0x00);
|
||||
|
||||
// Without isolated proxyPort/subdomain & allowSameOriginProxy=false -> 403 PROXY_ORIGIN_ISOLATION_REQUIRED
|
||||
const proxyCreate = await api('/api/tunnels', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
serverId: 'bastion',
|
||||
tunnel: {
|
||||
id: 'web-noiso',
|
||||
name: 'NoIso Web',
|
||||
mode: 'http-proxy',
|
||||
targetHost: '127.0.0.1',
|
||||
targetPort: 9999,
|
||||
autoStart: false,
|
||||
},
|
||||
start: true,
|
||||
},
|
||||
});
|
||||
expect(proxyCreate.status).toBe(201);
|
||||
const noIsoTicket = await api('/api/tunnels/bastion/web-noiso/proxy-ticket', {
|
||||
method: 'POST',
|
||||
body: {},
|
||||
});
|
||||
expect(noIsoTicket.status).toBe(403);
|
||||
expect(noIsoTicket.data.error).toBe('PROXY_ISOLATION_NOT_CONFIGURED');
|
||||
} finally {
|
||||
await serverNoIso.close();
|
||||
fs.rmSync(dataDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue