test(phase-3): extend MockSshServer with PTY/SFTP/forwardIn and add Phase 3 E2E suites

This commit is contained in:
tyuXX 2026-11-26 21:48:29 +00:00
parent c4a0df8ef2
commit 8e37da50eb
4 changed files with 1572 additions and 5 deletions

View file

@ -1,5 +1,9 @@
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import net from 'node:net';
import ssh2, { type Connection, type Server } from 'ssh2';
import os from 'node:os';
import path from 'node:path';
import ssh2, { type Attributes, type Connection, type Server } from 'ssh2';
import { computeOpenSshFingerprint } from '../../src/server/security/vault.js';
export interface MockSshOptions {
@ -9,6 +13,7 @@ export interface MockSshOptions {
os?: 'Linux' | 'FreeBSD' | 'Darwin';
authorizedKeys?: string[];
allowTcpForward?: boolean;
sftpRootDir?: string;
onExec?: (
command: string,
stdin: string,
@ -23,24 +28,82 @@ function unquoteSinglePosix(quoted: string): string {
return s;
}
function toSftpAttrs(st: fs.Stats): Attributes {
return {
mode: st.mode,
uid: st.uid,
gid: st.gid,
size: st.size,
atime: Math.floor(st.atimeMs / 1000),
mtime: Math.floor(st.mtimeMs / 1000),
};
}
function mapSftpFlags(flags: number): number {
const M = ssh2.utils.sftp.OPEN_MODE;
const read = (flags & M.READ) !== 0;
const write = (flags & M.WRITE) !== 0;
let out = read && write ? fs.constants.O_RDWR : write ? fs.constants.O_WRONLY : fs.constants.O_RDONLY;
if ((flags & M.CREAT) !== 0) out |= fs.constants.O_CREAT;
if ((flags & M.TRUNC) !== 0) out |= fs.constants.O_TRUNC;
if ((flags & M.APPEND) !== 0) out |= fs.constants.O_APPEND;
if ((flags & M.EXCL) !== 0) out |= fs.constants.O_EXCL;
return out;
}
export class MockSshServer {
public port = 0;
public hostFingerprint = '';
public authorizedKeys: string[];
public pollCount = 0;
public lastSudoStdin = '';
public lastPtySize: { cols: number; rows: number } | null = null;
public ptyCount = 0;
public readonly sftpRootDir: string;
private readonly ownsSftpRoot: boolean;
private hostPrivateKey: string;
private server: Server | null = null;
private readonly activeConns = new Set<Connection>();
private readonly remoteForwarders = new Map<string, net.Server>();
constructor(public readonly options: MockSshOptions) {
this.authorizedKeys = [...(options.authorizedKeys ?? [])];
if (options.sftpRootDir) {
this.sftpRootDir = path.resolve(options.sftpRootDir);
fs.mkdirSync(this.sftpRootDir, { recursive: true });
this.ownsSftpRoot = false;
} else {
this.sftpRootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mock-ssh-sftp-'));
this.ownsSftpRoot = true;
}
const kp = ssh2.utils.generateKeyPairSync('ed25519', { comment: 'mock-host' });
this.hostPrivateKey = kp.private;
this.hostFingerprint = computeOpenSshFingerprint(kp.public.trim());
}
private resolveVirtualPath(vPath: string): { normPosix: string; absPath: string } {
const trimmed = vPath.trim();
let candidate = trimmed;
if (!candidate || candidate === '.' || candidate === '~') {
candidate = '/';
} else if (candidate.startsWith('~/')) {
candidate = `/${candidate.slice(2)}`;
} else if (!candidate.startsWith('/')) {
candidate = `/${candidate}`;
}
const normPosix = path.posix.normalize(candidate);
const rel = normPosix === '/' ? '' : normPosix.slice(1);
const absPath = path.resolve(this.sftpRootDir, rel);
if (
absPath !== this.sftpRootDir &&
!absPath.startsWith(`${this.sftpRootDir}${path.sep}`)
) {
throw new Error(`Path escapes SFTP root: ${vPath}`);
}
return { normPosix, absPath };
}
async start(listenPort = 0): Promise<number> {
if (this.server) return this.port;
@ -74,6 +137,15 @@ export class MockSshServer {
}
async close(): Promise<void> {
for (const srv of this.remoteForwarders.values()) {
try {
srv.close();
} catch {
// Ignore close errors
}
}
this.remoteForwarders.clear();
for (const c of this.activeConns) {
try {
c.end();
@ -87,6 +159,9 @@ export class MockSshServer {
this.server = null;
await new Promise<void>((resolve) => s.close(() => resolve()));
}
if (this.ownsSftpRoot) {
fs.rmSync(this.sftpRootDir, { recursive: true, force: true });
}
}
get activeConnectionCount(): number {
@ -162,16 +237,135 @@ export class MockSshServer {
});
});
(client as unknown as NodeJS.EventEmitter).on(
'request',
(
accept: ((port?: number) => void) | undefined,
reject: (() => void) | undefined,
name: string,
info: { bindAddr: string; bindPort: number },
) => {
if (name === 'tcpip-forward') {
if (this.options.allowTcpForward === false) {
reject?.();
return;
}
const fwdSrv = net.createServer((sock) => {
const addr = fwdSrv.address();
const boundPort = typeof addr === 'object' && addr ? addr.port : info.bindPort;
client.forwardOut(
info.bindAddr,
boundPort,
sock.remoteAddress ?? '127.0.0.1',
sock.remotePort ?? 0,
(err, channel) => {
if (err) {
sock.destroy();
return;
}
sock.pipe(channel);
channel.pipe(sock);
sock.on('close', () => channel.destroy());
channel.on('close', () => sock.destroy());
},
);
});
fwdSrv.listen(info.bindPort || 0, '127.0.0.1', () => {
const addr = fwdSrv.address();
const chosenPort = typeof addr === 'object' && addr ? addr.port : info.bindPort;
this.remoteForwarders.set(`${info.bindAddr}:${chosenPort}`, fwdSrv);
accept?.(chosenPort);
});
return;
}
if (name === 'cancel-tcpip-forward') {
const key = `${info.bindAddr}:${info.bindPort}`;
const fwdSrv = this.remoteForwarders.get(key);
if (fwdSrv) {
this.remoteForwarders.delete(key);
fwdSrv.close(() => accept?.());
} else {
accept?.();
}
}
},
);
client.on('session', (accept) => {
const session = accept();
session.on('pty', (acceptPty, _rejectPty, info) => {
this.lastPtySize = { cols: info.cols, rows: info.rows };
acceptPty?.();
});
session.on('window-change', (acceptWin, _rejectWin, info) => {
this.lastPtySize = { cols: info.cols, rows: info.rows };
acceptWin?.();
});
session.on('shell', (acceptShell) => {
this.ptyCount += 1;
const stream = acceptShell();
let cwd = '/';
let lineBuf = '';
stream.write('\x1b[32mmock$\x1b[0m ');
stream.on('data', (chunk: Buffer) => {
const text = chunk.toString('utf8');
for (const ch of text) {
if (ch === '\x03') {
lineBuf = '';
stream.write('^C\r\n\x1b[32mmock$\x1b[0m ');
continue;
}
if (ch === '\r' || ch === '\n') {
const cmd = lineBuf.trim();
lineBuf = '';
stream.write('\r\n');
if (cmd === 'exit') {
stream.exit(0);
stream.end();
return;
}
if (cmd === 'pwd') {
stream.write(`${cwd}\r\n`);
} else if (cmd.startsWith('cd ')) {
const rawArg = unquoteSinglePosix(cmd.slice(3).replace(/^--\s+/, '').trim());
cwd = rawArg.startsWith('/') ? path.posix.normalize(rawArg) : path.posix.normalize(path.posix.join(cwd, rawArg));
} else if (cmd.startsWith('echo ')) {
stream.write(`${cmd.slice(5)}\r\n`);
} else if (cmd) {
stream.write(`ran:${cmd}\r\n`);
}
stream.write('\x1b[32mmock$\x1b[0m ');
continue;
}
lineBuf += ch;
stream.write(ch);
}
});
});
session.on('sftp', (acceptSftp) => {
this.attachSftpServer(acceptSftp());
});
session.on('exec', (acceptExec, _rejectExec, info) => {
const stream = acceptExec();
const stdinChunks: Buffer[] = [];
stream.on('data', (chunk: Buffer) => {
stdinChunks.push(chunk);
});
stream.on('end', () => {
let finished = false;
const finishExec = () => {
if (finished) return;
finished = true;
const stdinText = Buffer.concat(stdinChunks).toString('utf8');
const binaryResult = this.evaluateBinaryCommand(info.command);
if (binaryResult) {
if (!stream.writable || stream.writableEnded) return;
if (binaryResult.stdout.length > 0) stream.write(binaryResult.stdout);
if (binaryResult.stderr && stream.stderr.writable && !stream.stderr.writableEnded) {
stream.stderr.write(binaryResult.stderr);
}
stream.exit(binaryResult.exitCode);
stream.end();
return;
}
const result = this.evaluateCommand(info.command, stdinText);
if (!stream.writable || stream.writableEnded) return;
if (result.stdout) stream.write(result.stdout);
@ -180,7 +374,17 @@ export class MockSshServer {
}
stream.exit(result.exitCode);
stream.end();
};
stream.on('data', (chunk: Buffer) => {
stdinChunks.push(chunk);
});
stream.on('end', finishExec);
// When pty is allocated on exec (e.g. interactive debug-shell), client keeps stdin open until command exits
setTimeout(() => {
if (!finished && stdinChunks.length === 0) {
finishExec();
}
}, 15);
});
});
});
@ -335,4 +539,273 @@ export class MockSshServer {
return { stdout: `ok:${command}\n`, exitCode: 0 };
}
private evaluateBinaryCommand(
rawCommand: string,
): { stdout: Buffer; stderr?: string; exitCode: number } | null {
// Support streamed SFTP folder archive command in integration tests
const tarMatch = /tar -C ('(?:[^']|'\\'')*'|\S+) -cf - ('(?:[^']|'\\'')*'|\S+) \| gzip -c/.exec(
rawCommand,
);
if (tarMatch) {
try {
const virtualParent = unquoteSinglePosix(tarMatch[1]!);
const baseName = unquoteSinglePosix(tarMatch[2]!);
const { absPath: absParent } = this.resolveVirtualPath(virtualParent);
const outBuf = execFileSync('tar', ['-C', absParent, '-czf', '-', baseName]);
return { stdout: outBuf, exitCode: 0 };
} catch (err) {
return {
stdout: Buffer.alloc(0),
stderr: err instanceof Error ? err.message : String(err),
exitCode: 1,
};
}
}
return null;
}
private attachSftpServer(sftp: ssh2.SFTPWrapper): void {
const SC = ssh2.utils.sftp.STATUS_CODE;
let nextId = 1;
const files = new Map<number, { fd: number; absPath: string }>();
const dirs = new Map<number, { absPath: string; done: boolean }>();
const makeHandle = (id: number): Buffer => {
const b = Buffer.allocUnsafe(4);
b.writeUInt32BE(id, 0);
return b;
};
const readId = (h: Buffer): number => h.readUInt32BE(0);
const sendErr = (reqId: number, err: unknown) => {
const code = (err as { code?: string })?.code;
sftp.status(reqId, code === 'ENOENT' ? SC.NO_SUCH_FILE : SC.FAILURE, String(err));
};
sftp.on('REALPATH', (reqId, reqPath) => {
try {
const { normPosix, absPath } = this.resolveVirtualPath(reqPath);
const st = fs.existsSync(absPath) ? fs.statSync(absPath) : fs.statSync(this.sftpRootDir);
sftp.name(reqId, [
{
filename: normPosix,
longname: normPosix,
attrs: toSftpAttrs(st),
},
]);
} catch (err) {
sendErr(reqId, err);
}
});
sftp.on('STAT', (reqId, reqPath) => {
try {
const { absPath } = this.resolveVirtualPath(reqPath);
sftp.attrs(reqId, toSftpAttrs(fs.statSync(absPath)));
} catch (err) {
sendErr(reqId, err);
}
});
sftp.on('LSTAT', (reqId, reqPath) => {
try {
const { absPath } = this.resolveVirtualPath(reqPath);
sftp.attrs(reqId, toSftpAttrs(fs.lstatSync(absPath)));
} catch (err) {
sendErr(reqId, err);
}
});
sftp.on('FSTAT', (reqId, handle) => {
const entry = files.get(readId(handle));
if (!entry) {
sftp.status(reqId, SC.FAILURE);
return;
}
sftp.attrs(reqId, toSftpAttrs(fs.fstatSync(entry.fd)));
});
sftp.on('OPENDIR', (reqId, reqPath) => {
try {
const { absPath } = this.resolveVirtualPath(reqPath);
if (!fs.statSync(absPath).isDirectory()) {
sftp.status(reqId, SC.FAILURE, 'Not a directory');
return;
}
const id = nextId++;
dirs.set(id, { absPath, done: false });
sftp.handle(reqId, makeHandle(id));
} catch (err) {
sendErr(reqId, err);
}
});
sftp.on('READDIR', (reqId, handle) => {
const entry = dirs.get(readId(handle));
if (!entry) {
sftp.status(reqId, SC.FAILURE);
return;
}
if (entry.done) {
sftp.status(reqId, SC.EOF);
return;
}
entry.done = true;
try {
const items = fs.readdirSync(entry.absPath);
sftp.name(
reqId,
items.map((name) => {
const st = fs.lstatSync(path.join(entry.absPath, name));
return {
filename: name,
longname: `${st.isDirectory() ? 'd' : '-'}rwxr-xr-x 1 mock mock ${st.size} Jan 1 00:00 ${name}`,
attrs: toSftpAttrs(st),
};
}),
);
} catch (err) {
sendErr(reqId, err);
}
});
sftp.on('OPEN', (reqId, filename, flags, attrs) => {
try {
const { absPath } = this.resolveVirtualPath(filename);
const mode = attrs?.mode ? attrs.mode & 0o7777 : 0o644;
const fd = fs.openSync(absPath, mapSftpFlags(flags), mode);
const id = nextId++;
files.set(id, { fd, absPath });
sftp.handle(reqId, makeHandle(id));
} catch (err) {
sendErr(reqId, err);
}
});
sftp.on('READ', (reqId, handle, offset, len) => {
const entry = files.get(readId(handle));
if (!entry) {
sftp.status(reqId, SC.FAILURE);
return;
}
const buf = Buffer.allocUnsafe(len);
const bytesRead = fs.readSync(entry.fd, buf, 0, len, offset);
if (bytesRead === 0) {
sftp.status(reqId, SC.EOF);
return;
}
sftp.data(reqId, buf.subarray(0, bytesRead));
});
sftp.on('WRITE', (reqId, handle, offset, data) => {
const entry = files.get(readId(handle));
if (!entry) {
sftp.status(reqId, SC.FAILURE);
return;
}
fs.writeSync(entry.fd, data, 0, data.length, offset);
sftp.status(reqId, SC.OK);
});
sftp.on('CLOSE', (reqId, handle) => {
const id = readId(handle);
const f = files.get(id);
if (f) {
files.delete(id);
fs.closeSync(f.fd);
sftp.status(reqId, SC.OK);
return;
}
if (dirs.delete(id)) {
sftp.status(reqId, SC.OK);
return;
}
sftp.status(reqId, SC.OK);
});
sftp.on('MKDIR', (reqId, reqPath) => {
try {
const { absPath } = this.resolveVirtualPath(reqPath);
fs.mkdirSync(absPath);
sftp.status(reqId, SC.OK);
} catch (err) {
sendErr(reqId, err);
}
});
sftp.on('RMDIR', (reqId, reqPath) => {
try {
const { absPath } = this.resolveVirtualPath(reqPath);
fs.rmdirSync(absPath);
sftp.status(reqId, SC.OK);
} catch (err) {
sendErr(reqId, err);
}
});
sftp.on('REMOVE', (reqId, reqPath) => {
try {
const { absPath } = this.resolveVirtualPath(reqPath);
fs.unlinkSync(absPath);
sftp.status(reqId, SC.OK);
} catch (err) {
sendErr(reqId, err);
}
});
sftp.on('RENAME', (reqId, oldPath, newPath) => {
try {
const a = this.resolveVirtualPath(oldPath).absPath;
const b = this.resolveVirtualPath(newPath).absPath;
fs.renameSync(a, b);
sftp.status(reqId, SC.OK);
} catch (err) {
sendErr(reqId, err);
}
});
sftp.on('SETSTAT', (reqId, reqPath, attrs) => {
try {
const { absPath } = this.resolveVirtualPath(reqPath);
if (attrs.mode !== undefined) {
fs.chmodSync(absPath, attrs.mode & 0o7777);
}
sftp.status(reqId, SC.OK);
} catch (err) {
sendErr(reqId, err);
}
});
sftp.on('FSETSTAT', (reqId, handle, attrs) => {
const entry = files.get(readId(handle));
if (!entry) {
sftp.status(reqId, SC.FAILURE);
return;
}
if (attrs.mode !== undefined) {
fs.fchmodSync(entry.fd, attrs.mode & 0o7777);
}
sftp.status(reqId, SC.OK);
});
sftp.on('EXTENDED', (reqId, extName, extData) => {
if (extName === 'posix-rename@openssh.com') {
try {
const len1 = extData.readUInt32BE(0);
const oldPath = extData.subarray(4, 4 + len1).toString('utf8');
const len2 = extData.readUInt32BE(4 + len1);
const newPath = extData.subarray(8 + len1, 8 + len1 + len2).toString('utf8');
fs.renameSync(
this.resolveVirtualPath(oldPath).absPath,
this.resolveVirtualPath(newPath).absPath,
);
sftp.status(reqId, SC.OK);
} catch (err) {
sendErr(reqId, err);
}
return;
}
sftp.status(reqId, SC.OP_UNSUPPORTED);
});
}
}