GCoordinator/tests/tunnels-and-proxy.test.ts

418 lines
14 KiB
TypeScript

import fs from 'node:fs';
import http from 'node:http';
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, vi } from 'vitest';
import WebSocket, { WebSocketServer } from 'ws';
import { createGCoordinatorServer } from '../src/server/app.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('; ');
}
}
async function startUpstreamHttpWsServer() {
let sawCookieHeader: string | undefined;
const httpSrv = http.createServer((req, res) => {
sawCookieHeader = req.headers.cookie;
if (req.url === '/hello') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: true, sawCookie: req.headers.cookie ?? null }));
return;
}
if (req.url === '/redir') {
res.writeHead(302, { Location: '/login' });
res.end();
return;
}
if (req.url === '/echo' && req.method === 'POST') {
const chunks: Buffer[] = [];
req.on('data', (c: Buffer) => chunks.push(c));
req.on('end', () => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(Buffer.concat(chunks));
});
return;
}
res.writeHead(404);
res.end('not found');
});
const wss = new WebSocketServer({ server: httpSrv, path: '/ws' });
wss.on('connection', (sock) => {
sock.on('message', (msg) => {
sock.send(`echo:${msg.toString()}`);
});
});
await new Promise<void>((resolve) => {
httpSrv.listen(0, '127.0.0.1', () => resolve());
});
const addr = httpSrv.address();
const port = typeof addr === 'object' && addr ? addr.port : 0;
return {
port,
getLastCookie: () => sawCookieHeader,
close: async () => {
wss.close();
await new Promise<void>((r) => httpSrv.close(() => r()));
},
};
}
afterEach(async () => {
while (cleanups.length > 0) {
await cleanups.pop()!();
}
});
describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TCP Forwards', () => {
it('proxies HTTP + WebSocket over SSH behind hub auth & Safe Mode, runs local-tcp & remote-tcp, and tears down on Panic Lock', async () => {
const upstream = await startUpstreamHttpWsServer();
cleanups.push(() => upstream.close());
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p3-tunnels-'));
const server = await createGCoordinatorServer({
dataDir,
port: 0,
host: '127.0.0.1',
proxyPort: 0,
publicDir: path.resolve('dist/public'),
watchConfig: false,
});
cleanups.push(async () => {
await server.close();
fs.rmSync(dataDir, { recursive: true, force: true });
});
const baseUrl = `http://127.0.0.1:${server.port}`;
const jar = new CookieJar();
let csrfToken = '';
const api = async (
pathname: string,
opts: { method?: string; body?: unknown } = {},
) => {
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);
const data = await res.json().catch(() => ({}));
return { status: res.status, data: data as Record<string, unknown> };
};
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/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 boot = await api('/api/auth/bootstrap', {
method: 'POST',
body: {
username: 'admin',
password: 'phase3-tunnel-password',
totpCode: totp.generate(),
secretBase32,
initialSafeMode: false,
},
});
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken);
expect(
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
).toBe(200);
await api('/api/vault/init', { method: 'POST', body: {} });
const keyRes = await api('/api/vault/generate-ed25519', {
method: 'POST',
body: { id: 'tun-key', name: 'Tunnel Key' },
});
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());
await api('/api/servers', {
method: 'POST',
body: {
id: 'app1',
name: 'App 1',
host: '127.0.0.1',
port: sshPort,
username: 'ops',
credentialId: 'tun-key',
pollIntervalSec: 300,
},
});
await api('/api/servers/app1/reconnect', { method: 'POST' });
await api('/api/servers/app1/tofu/approve', {
method: 'POST',
body: { fingerprint: mock.hostFingerprint },
});
// 1. Create & start http-proxy tunnel
const createHttpProxy = await api('/api/tunnels', {
method: 'POST',
body: {
serverId: 'app1',
tunnel: {
id: 'web-ui',
name: 'Upstream Web UI',
mode: 'http-proxy',
targetHost: '127.0.0.1',
targetPort: upstream.port,
autoStart: false,
},
start: true,
},
});
expect(createHttpProxy.status).toBe(201);
// Unauthenticated /proxy blocked with 401
const unauthProxy = await fetch(`${baseUrl}/proxy/web-ui/hello`);
expect(unauthProxy.status).toBe(401);
// Same-origin /proxy is blocked with 403 by default; test isolated proxyPort ticket flow first!
const blockedSameOrigin = await api('/proxy/web-ui/hello');
expect(blockedSameOrigin.status).toBe(403);
expect(blockedSameOrigin.data.error).toBe('PROXY_ORIGIN_ISOLATION_REQUIRED');
const ticketRes = await api('/api/tunnels/app1/web-ui/proxy-ticket', {
method: 'POST',
body: {},
});
expect(ticketRes.status).toBe(200);
expect(ticketRes.data.mode).toBe('port');
const launchUrl = String(ticketRes.data.launchUrl);
const proxyBaseUrl = `http://127.0.0.1:${server.proxyPort}`;
// Redeem single-use ticket on isolated proxy origin to receive scoped gcoord_proxy_sid cookie
const proxyJar = new CookieJar();
const ticketHit = await fetch(launchUrl, { redirect: 'manual' });
expect(ticketHit.status).toBe(302);
proxyJar.updateFrom(ticketHit);
expect(proxyJar.header()).toContain('gcoord_proxy_sid=');
const isoHello = await fetch(`${proxyBaseUrl}/proxy/web-ui/hello`, {
headers: { Cookie: proxyJar.header() },
});
expect(isoHello.status).toBe(200);
const isoHelloData = (await isoHello.json()) as { ok: boolean };
expect(isoHelloData.ok).toBe(true);
expect(upstream.getLastCookie() ?? '').not.toContain('gcoord_sid');
expect(upstream.getLastCookie() ?? '').not.toContain('gcoord_proxy_sid');
// Also enable allowSameOriginProxy explicitly to test same-origin backwards compatibility
expect(
(
await api('/api/auth/security-policy', {
method: 'PUT',
body: { allowSameOriginProxy: true },
})
).status,
).toBe(200);
// Authenticated GET & POST JSON stream through proxy without exposing hub session cookies
const authedHello = await api('/proxy/web-ui/hello');
expect(authedHello.status).toBe(200);
expect(authedHello.data.ok).toBe(true);
expect(upstream.getLastCookie() ?? '').not.toContain('gcoord_sid');
const authedPost = await api('/proxy/web-ui/echo', {
method: 'POST',
body: { ping: 'tunnel-body-intact' },
});
expect(authedPost.status).toBe(200);
expect(authedPost.data.ping).toBe('tunnel-body-intact');
const redirRes = await fetch(`${baseUrl}/proxy/web-ui/redir`, {
headers: { Cookie: jar.header() },
redirect: 'manual',
});
expect(redirRes.status).toBe(302);
expect(redirRes.headers.get('location')).toBe('/proxy/web-ui/login');
// Safe Mode blocks mutating POST through proxy while allowing GET
await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: true } });
const safeGet = await api('/proxy/web-ui/hello');
expect(safeGet.status).toBe(200);
const safePost = await api('/proxy/web-ui/echo', {
method: 'POST',
body: { blocked: true },
});
expect(safePost.status).toBe(423);
await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: false } });
// Authenticated WS upgrade through /proxy/web-ui/ws
await new Promise<void>((resolve, reject) => {
const evil = new WebSocket(`ws://127.0.0.1:${server.port}/proxy/web-ui/ws`, {
headers: {
Cookie: jar.header(),
Host: `127.0.0.1:${server.port}`,
Origin: 'https://evil.example',
},
});
evil.once('unexpected-response', (_r, res) => {
expect(res.statusCode).toBe(403);
resolve();
});
evil.once('error', reject);
});
const proxyWsReply = await new Promise<string>((resolve, reject) => {
const pws = new WebSocket(`ws://127.0.0.1:${server.port}/proxy/web-ui/ws`, {
headers: {
Cookie: jar.header(),
Host: `127.0.0.1:${server.port}`,
Origin: baseUrl,
},
});
pws.once('open', () => pws.send('ws-through-ssh'));
pws.once('message', (d) => {
pws.close();
resolve(d.toString());
});
pws.once('error', reject);
});
expect(proxyWsReply).toBe('echo:ws-through-ssh');
// 2. Local TCP (L) tunnel
const localTcpRes = await api('/api/tunnels', {
method: 'POST',
body: {
serverId: 'app1',
tunnel: {
id: 'tcp-local',
name: 'Local TCP Forward',
mode: 'local-tcp',
bindHost: '127.0.0.1',
targetHost: '127.0.0.1',
targetPort: upstream.port,
autoStart: false,
},
start: true,
},
});
expect(localTcpRes.status).toBe(201);
const localTunnel = (
localTcpRes.data.tunnels as Array<{
tunnel: { id: string };
localBoundPort?: number;
}>
).find((t) => t.tunnel.id === 'tcp-local')!;
expect(localTunnel.localBoundPort).toBeGreaterThan(0);
const localHttp = await fetch(`http://127.0.0.1:${localTunnel.localBoundPort}/hello`);
expect(localHttp.status).toBe(200);
expect(((await localHttp.json()) as { ok: boolean }).ok).toBe(true);
// 3. Remote TCP (R) tunnel targets 127.0.0.1 -> blocked by Zero-Trust egress guard unless allowlisted
const blockedRemoteTcp = await api('/api/tunnels', {
method: 'POST',
body: {
serverId: 'app1',
tunnel: {
id: 'tcp-remote',
name: 'Remote TCP Reverse',
mode: 'remote-tcp',
bindHost: '127.0.0.1',
targetHost: '127.0.0.1',
targetPort: upstream.port,
autoStart: false,
},
start: true,
},
});
expect(blockedRemoteTcp.data.startError).toBeTruthy();
// Allow 127.0.0.1/32 in egressAllowedCidrs -> Remote TCP (R) starts and forwards cleanly
expect(
(
await api('/api/auth/security-policy', {
method: 'PUT',
body: { egressAllowedCidrs: ['127.0.0.1/32'] },
})
).status,
).toBe(200);
const remoteTcpRes = await api('/api/tunnels', {
method: 'POST',
body: {
serverId: 'app1',
tunnel: {
id: 'tcp-remote',
name: 'Remote TCP Reverse',
mode: 'remote-tcp',
bindHost: '127.0.0.1',
targetHost: '127.0.0.1',
targetPort: upstream.port,
autoStart: false,
},
start: true,
},
});
expect(remoteTcpRes.status).toBe(201);
const remoteTunnel = (
remoteTcpRes.data.tunnels as Array<{
tunnel: { id: string };
remoteBoundPort?: number;
}>
).find((t) => t.tunnel.id === 'tcp-remote')!;
expect(remoteTunnel.remoteBoundPort).toBeGreaterThan(0);
const remoteHttp = await fetch(`http://127.0.0.1:${remoteTunnel.remoteBoundPort}/hello`);
expect(remoteHttp.status).toBe(200);
expect(((await remoteHttp.json()) as { ok: boolean }).ok).toBe(true);
// 4. Panic Lock tears down all active tunnel listeners immediately
await api('/api/security/panic-lock', { method: 'POST' });
await expect(
new Promise<void>((resolve, reject) => {
const s = net.connect(localTunnel.localBoundPort!, '127.0.0.1', () => {
s.destroy();
resolve();
});
s.once('error', reject);
}),
).rejects.toThrow();
});
});