sshBackend.test.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  1. import { EventEmitter } from "node:events";
  2. import { rmSync } from "node:fs";
  3. import { mkdtemp, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { Writable } from "node:stream";
  7. import { describe, expect, it, vi } from "vitest";
  8. import { SSHBackend } from "@zcode/server/remote/ssh-backend.js";
  9. class FakeExecChannel extends EventEmitter {
  10. readonly stderr = new EventEmitter();
  11. }
  12. class FakeUploadExecChannel extends EventEmitter {
  13. readonly stderr = new EventEmitter();
  14. readonly stdin: Writable;
  15. private readonly chunks: Buffer[] = [];
  16. constructor(onComplete: (content: string) => void) {
  17. super();
  18. this.stdin = new Writable({
  19. write: (chunk, _encoding, callback) => {
  20. this.chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  21. callback();
  22. },
  23. final: (callback) => {
  24. onComplete(Buffer.concat(this.chunks).toString("utf8"));
  25. queueMicrotask(() => {
  26. this.emit("exit", 0, null);
  27. this.emit("close", 0, null);
  28. });
  29. callback();
  30. },
  31. });
  32. }
  33. }
  34. class FailingSftpWriteStream extends Writable {
  35. constructor(
  36. private readonly failure: Error & {
  37. code: number;
  38. },
  39. ) {
  40. super();
  41. }
  42. override _write(
  43. _chunk: Buffer,
  44. _encoding: BufferEncoding,
  45. callback: (error?: Error | null) => void,
  46. ): void {
  47. callback(this.failure);
  48. }
  49. }
  50. class SuccessfulSftpWriteStream extends Writable {
  51. override _write(
  52. _chunk: Buffer,
  53. _encoding: BufferEncoding,
  54. callback: (error?: Error | null) => void,
  55. ): void {
  56. callback();
  57. }
  58. override _final(callback: (error?: Error | null) => void): void {
  59. queueMicrotask(() => {
  60. this.emit("close");
  61. });
  62. callback();
  63. }
  64. }
  65. function emitExecResult(
  66. channel: FakeExecChannel,
  67. options: {
  68. stdout?: string;
  69. stderr?: string;
  70. exitCode?: number;
  71. exitBeforeData?: boolean;
  72. },
  73. ): void {
  74. const stdout = options.stdout ?? "";
  75. const stderr = options.stderr ?? "";
  76. const exitCode = options.exitCode ?? 0;
  77. queueMicrotask(() => {
  78. const emitData = () => {
  79. if (stdout.length > 0) {
  80. channel.emit("data", Buffer.from(stdout, "utf8"));
  81. }
  82. if (stderr.length > 0) {
  83. channel.stderr.emit("data", Buffer.from(stderr, "utf8"));
  84. }
  85. };
  86. if (options.exitBeforeData) {
  87. channel.emit("exit", exitCode, null);
  88. emitData();
  89. } else {
  90. emitData();
  91. channel.emit("exit", exitCode, null);
  92. }
  93. channel.emit("close", exitCode, null);
  94. });
  95. }
  96. function quotePosixShellArgForTest(value: string): string {
  97. return `'${value.replaceAll("'", `'"'"'`)}'`;
  98. }
  99. function expectSSHExecCommand(command: string, rawCommand: string): void {
  100. expect(command).toBe(`/bin/sh -c ${quotePosixShellArgForTest(rawCommand)}`);
  101. }
  102. describe("SSHBackend", () => {
  103. it("ready 后 SSH client error 应触发一次断连事件", () => {
  104. const backend = new SSHBackend({
  105. host: "example.com",
  106. username: "root",
  107. password: "secret",
  108. });
  109. const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
  110. const events: Array<{ reason: string; error?: Error }> = [];
  111. const disposable = backend.onDidDisconnect((event) => {
  112. events.push(event);
  113. });
  114. const mutableBackend = backend as unknown as {
  115. client: EventEmitter;
  116. connected: boolean;
  117. };
  118. mutableBackend.connected = true;
  119. const error = new Error("socket reset");
  120. mutableBackend.client.emit("error", error);
  121. mutableBackend.client.emit("close");
  122. expect(events).toHaveLength(1);
  123. expect(events[0]?.reason).toBe("error");
  124. expect(events[0]?.error).toBe(error);
  125. disposable.dispose();
  126. backend.dispose();
  127. errorSpy.mockRestore();
  128. });
  129. it("ready 后 SSH client error 应先记录错误详情再触发断连事件", () => {
  130. const backend = new SSHBackend({
  131. host: "example.com",
  132. username: "root",
  133. password: "secret",
  134. });
  135. const events: string[] = [];
  136. const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {
  137. events.push("log-error");
  138. });
  139. const disposable = backend.onDidDisconnect(() => {
  140. events.push("disconnect");
  141. });
  142. const mutableBackend = backend as unknown as {
  143. client: EventEmitter;
  144. connected: boolean;
  145. };
  146. mutableBackend.connected = true;
  147. try {
  148. mutableBackend.client.emit("error", new Error("socket reset"));
  149. expect(events).toEqual(["log-error", "disconnect"]);
  150. } finally {
  151. disposable.dispose();
  152. backend.dispose();
  153. errorSpy.mockRestore();
  154. }
  155. });
  156. it("ready 后 SSH client close 应触发断连事件", () => {
  157. const backend = new SSHBackend({
  158. host: "example.com",
  159. username: "root",
  160. password: "secret",
  161. });
  162. const events: Array<{ reason: string }> = [];
  163. const disposable = backend.onDidDisconnect((event) => {
  164. events.push(event);
  165. });
  166. const mutableBackend = backend as unknown as {
  167. client: EventEmitter;
  168. connected: boolean;
  169. };
  170. mutableBackend.connected = true;
  171. mutableBackend.client.emit("close");
  172. expect(events).toEqual([{ reason: "close" }]);
  173. disposable.dispose();
  174. backend.dispose();
  175. });
  176. it("释放后不得使用旧凭据重新建立 SSH 连接", async () => {
  177. const backend = new SSHBackend({
  178. host: "example.com",
  179. username: "root",
  180. password: "old-password",
  181. });
  182. const fakeClient = {
  183. off: vi.fn(),
  184. end: vi.fn(),
  185. once: vi.fn(),
  186. connect: vi.fn(() => {
  187. throw new Error("unexpected reconnect");
  188. }),
  189. };
  190. const mutableBackend = backend as unknown as {
  191. client: typeof fakeClient;
  192. connected: boolean;
  193. };
  194. mutableBackend.client = fakeClient;
  195. mutableBackend.connected = false;
  196. backend.dispose();
  197. await expect(backend.exec("true")).rejects.toThrow("SSH backend 已释放");
  198. expect(fakeClient.connect).not.toHaveBeenCalled();
  199. });
  200. it("连接 ready 晚于释放屏障时不得继续执行远端命令", async () => {
  201. const backend = new SSHBackend({
  202. host: "example.com",
  203. username: "root",
  204. password: "old-password",
  205. });
  206. const fakeClient = Object.assign(new EventEmitter(), {
  207. connect: vi.fn(),
  208. end: vi.fn(),
  209. exec: vi.fn(() => {
  210. throw new Error("unexpected remote command");
  211. }),
  212. });
  213. const mutableBackend = backend as unknown as {
  214. client: typeof fakeClient;
  215. connected: boolean;
  216. };
  217. mutableBackend.client = fakeClient;
  218. mutableBackend.connected = false;
  219. const detecting = backend.detect();
  220. expect(fakeClient.connect).toHaveBeenCalledTimes(1);
  221. backend.dispose();
  222. fakeClient.emit("ready");
  223. await expect(detecting).rejects.toThrow("SSH backend 已释放");
  224. expect(fakeClient.exec).not.toHaveBeenCalled();
  225. });
  226. it("释放期间 end 之后的迟到 SSH error 不得逃逸为未捕获异常", () => {
  227. const backend = new SSHBackend({
  228. host: "example.com",
  229. username: "root",
  230. password: "old-password",
  231. });
  232. const fakeClient = Object.assign(new EventEmitter(), {
  233. connect: vi.fn(),
  234. end: vi.fn(),
  235. exec: vi.fn(),
  236. });
  237. const mutableBackend = backend as unknown as {
  238. client: typeof fakeClient;
  239. onClientError: (error: unknown) => void;
  240. };
  241. mutableBackend.client = fakeClient;
  242. fakeClient.on("error", mutableBackend.onClientError);
  243. backend.dispose();
  244. fakeClient.emit("end");
  245. expect(() => fakeClient.emit("error", new Error("late after end"))).not.toThrow();
  246. });
  247. it("握手超时后的迟到 SSH error 不得逃逸为未捕获异常", async () => {
  248. const backend = new SSHBackend({
  249. host: "example.com",
  250. username: "root",
  251. password: "old-password",
  252. });
  253. const fakeClient = Object.assign(new EventEmitter(), {
  254. connect: vi.fn(),
  255. end: vi.fn(),
  256. exec: vi.fn(() => {
  257. throw new Error("unexpected remote command");
  258. }),
  259. });
  260. const mutableBackend = backend as unknown as {
  261. client: typeof fakeClient;
  262. onClientError: (error: unknown) => void;
  263. };
  264. mutableBackend.client = fakeClient;
  265. // 构造 ssh2 的两次 error 顺序:第一次由 ready timeout 触发,第二次由 socket close 触发。
  266. fakeClient.on("error", mutableBackend.onClientError);
  267. const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
  268. try {
  269. const detecting = backend.detect();
  270. fakeClient.emit(
  271. "error",
  272. Object.assign(new Error("Timed out while waiting for handshake"), {
  273. level: "client-timeout",
  274. }),
  275. );
  276. await expect(detecting).rejects.toThrow("SSH 连接握手超时");
  277. backend.dispose();
  278. // ssh2 在 timeout 后销毁 socket,close/end 阶段仍可能再发出 error;该迟到事件必须被吞掉。
  279. expect(() =>
  280. fakeClient.emit("error", new Error("Connection lost before handshake")),
  281. ).not.toThrow();
  282. fakeClient.emit("close");
  283. } finally {
  284. errorSpy.mockRestore();
  285. }
  286. });
  287. it("连接检查完成后插入释放屏障时不得继续执行远端命令", async () => {
  288. const backend = new SSHBackend({
  289. host: "example.com",
  290. username: "root",
  291. password: "old-password",
  292. });
  293. const fakeClient = Object.assign(new EventEmitter(), {
  294. end: vi.fn(),
  295. exec: vi.fn(() => {
  296. throw new Error("unexpected remote command");
  297. }),
  298. });
  299. const mutableBackend = backend as unknown as {
  300. client: typeof fakeClient;
  301. connected: boolean;
  302. };
  303. mutableBackend.client = fakeClient;
  304. mutableBackend.connected = true;
  305. const executing = backend.exec("true");
  306. backend.dispose();
  307. await expect(executing).rejects.toThrow("SSH backend 已释放");
  308. expect(fakeClient.exec).not.toHaveBeenCalled();
  309. });
  310. it("detect 在 exit 先于 data 时不应丢失 platform 输出", async () => {
  311. const backend = new SSHBackend({
  312. host: "example.com",
  313. username: "root",
  314. password: "secret",
  315. });
  316. const executedCommands: string[] = [];
  317. const rawProbeCommand =
  318. "printf 'platform='; uname -s; printf 'arch='; uname -m; printf 'kernel='; " +
  319. "if [ -r /proc/sys/kernel/ostype ]; then cat /proc/sys/kernel/ostype; else printf '\\n'; fi";
  320. const fakeClient = {
  321. exec: (
  322. command: string,
  323. callback: (error: Error | null, channel: FakeExecChannel) => void,
  324. ) => {
  325. executedCommands.push(command);
  326. expectSSHExecCommand(command, rawProbeCommand);
  327. const channel = new FakeExecChannel();
  328. callback(null, channel);
  329. emitExecResult(channel, {
  330. stdout: "platform=Darwin\narch=arm64\nkernel=\n",
  331. exitCode: 0,
  332. exitBeforeData: true,
  333. });
  334. },
  335. };
  336. const mutableBackend = backend as unknown as {
  337. client: typeof fakeClient;
  338. connected: boolean;
  339. };
  340. mutableBackend.client = fakeClient;
  341. mutableBackend.connected = true;
  342. await expect(backend.detect()).resolves.toEqual({
  343. platform: "darwin",
  344. arch: "arm64",
  345. });
  346. expect(executedCommands).toHaveLength(1);
  347. });
  348. it("exec 成功完成时不应输出无意义的完成日志", async () => {
  349. const backend = new SSHBackend({
  350. host: "example.com",
  351. username: "root",
  352. password: "secret",
  353. });
  354. const infoSpy = vi.spyOn(console, "log").mockImplementation(() => undefined);
  355. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  356. const fakeClient = {
  357. exec: (
  358. command: string,
  359. callback: (error: Error | null, channel: FakeExecChannel) => void,
  360. ) => {
  361. expectSSHExecCommand(command, "set -eu && echo very-long-command");
  362. const channel = new FakeExecChannel();
  363. callback(null, channel);
  364. emitExecResult(channel, { exitCode: 0 });
  365. },
  366. };
  367. const mutableBackend = backend as unknown as {
  368. client: typeof fakeClient;
  369. connected: boolean;
  370. };
  371. mutableBackend.client = fakeClient;
  372. mutableBackend.connected = true;
  373. const stream = await backend.exec("set -eu && echo very-long-command");
  374. await new Promise<void>((resolve) => stream.onClose(() => resolve()));
  375. expect(infoSpy).not.toHaveBeenCalledWith(expect.stringContaining("exec channel"));
  376. expect(warnSpy).not.toHaveBeenCalledWith(expect.stringContaining("exec channel"));
  377. expect(infoSpy).not.toHaveBeenCalledWith(expect.stringContaining("very-long-command"));
  378. infoSpy.mockRestore();
  379. warnSpy.mockRestore();
  380. });
  381. it("exec 应通过 POSIX shell 执行远端命令,避免 fish 默认 shell 解析部署脚本", async () => {
  382. const backend = new SSHBackend({
  383. host: "example.com",
  384. username: "root",
  385. password: "secret",
  386. });
  387. const rawCommand = "download=; if command -v curl >/dev/null 2>&1; then download=curl; fi";
  388. const executedCommands: string[] = [];
  389. const fakeClient = {
  390. exec: (
  391. command: string,
  392. callback: (error: Error | null, channel: FakeExecChannel) => void,
  393. ) => {
  394. executedCommands.push(command);
  395. expectSSHExecCommand(command, rawCommand);
  396. const channel = new FakeExecChannel();
  397. callback(null, channel);
  398. emitExecResult(channel, { exitCode: 0 });
  399. },
  400. };
  401. const mutableBackend = backend as unknown as {
  402. client: typeof fakeClient;
  403. connected: boolean;
  404. };
  405. mutableBackend.client = fakeClient;
  406. mutableBackend.connected = true;
  407. const stream = await backend.exec(rawCommand);
  408. await new Promise<void>((resolve) => stream.onClose(() => resolve()));
  409. expect(executedCommands).toHaveLength(1);
  410. });
  411. it("exec 失败完成时应保留退出码日志但不输出完整远端命令", async () => {
  412. const backend = new SSHBackend({
  413. host: "example.com",
  414. username: "root",
  415. password: "secret",
  416. });
  417. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  418. const fakeClient = {
  419. exec: (
  420. command: string,
  421. callback: (error: Error | null, channel: FakeExecChannel) => void,
  422. ) => {
  423. expectSSHExecCommand(command, "set -eu && echo very-long-command && exit 7");
  424. const channel = new FakeExecChannel();
  425. callback(null, channel);
  426. emitExecResult(channel, { exitCode: 7 });
  427. },
  428. };
  429. const mutableBackend = backend as unknown as {
  430. client: typeof fakeClient;
  431. connected: boolean;
  432. };
  433. mutableBackend.client = fakeClient;
  434. mutableBackend.connected = true;
  435. const stream = await backend.exec("set -eu && echo very-long-command && exit 7");
  436. await new Promise<void>((resolve) => stream.onClose(() => resolve()));
  437. expect(warnSpy).toHaveBeenCalledWith(
  438. expect.stringContaining("[ssh] exec channel failed: code=7"),
  439. );
  440. expect(warnSpy).not.toHaveBeenCalledWith(expect.stringContaining("very-long-command"));
  441. warnSpy.mockRestore();
  442. });
  443. it("ssh2 debug 不应输出下载阶段的高频 channel 数据包", () => {
  444. const backend = new SSHBackend({
  445. host: "example.com",
  446. username: "root",
  447. password: "secret",
  448. });
  449. const debugSpy = vi.spyOn(console, "debug").mockImplementation(() => undefined);
  450. const debug = (
  451. backend as unknown as {
  452. config: {
  453. debug?: (message: string) => void;
  454. };
  455. }
  456. ).config.debug;
  457. try {
  458. if (!debug) {
  459. return;
  460. }
  461. debug("Inbound: CHANNEL_EXTENDED_DATA (r:27, 1)");
  462. debug("Inbound: CHANNEL_DATA (r:27, 1024)");
  463. debug("Outbound: CHANNEL_WINDOW_ADJUST (r:27, 2097152)");
  464. debug("DEBUG: Client: Trying password auth");
  465. const debugLines = debugSpy.mock.calls.map((call) => String(call[0] ?? ""));
  466. expect(debugLines.some((line) => line.includes("CHANNEL_EXTENDED_DATA"))).toBe(false);
  467. expect(debugLines.some((line) => line.includes("CHANNEL_DATA"))).toBe(false);
  468. expect(debugLines.some((line) => line.includes("CHANNEL_WINDOW_ADJUST"))).toBe(false);
  469. expect(debugLines.some((line) => line.includes("Trying password auth"))).toBe(true);
  470. } finally {
  471. debugSpy.mockRestore();
  472. }
  473. });
  474. it("首次 SFTP 写入失败后,同 backend 的后续上传应直接使用 exec pipe", async () => {
  475. const tempDir = await mkdtemp(join(tmpdir(), "ssh-backend-upload-"));
  476. const localFilePath = join(tempDir, "node");
  477. const localContent = "hello ssh fallback";
  478. await writeFile(localFilePath, localContent, "utf8");
  479. const backend = new SSHBackend({
  480. host: "example.com",
  481. username: "root",
  482. password: "secret",
  483. });
  484. const attemptedSftpPaths: string[] = [];
  485. const execUploadedContents: string[] = [];
  486. const executedCommands: string[] = [];
  487. const secondUploadProgress: Array<{ uploadedBytes: number; totalBytes: number }> = [];
  488. const failingSftpError = Object.assign(new Error("No such file or directory"), {
  489. code: 2,
  490. });
  491. const fakeClient = {
  492. exec: (
  493. command: string,
  494. callback: (error: Error | null, channel: FakeExecChannel | FakeUploadExecChannel) => void,
  495. ) => {
  496. executedCommands.push(command);
  497. if (command === `/bin/sh -c ${quotePosixShellArgForTest('printf %s "$HOME"')}`) {
  498. const channel = new FakeExecChannel();
  499. callback(null, channel);
  500. emitExecResult(channel, {
  501. stdout: "/root",
  502. exitCode: 0,
  503. });
  504. return;
  505. }
  506. if (
  507. command === `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server'")}`
  508. ) {
  509. const channel = new FakeExecChannel();
  510. callback(null, channel);
  511. emitExecResult(channel, { exitCode: 0 });
  512. return;
  513. }
  514. if (
  515. command ===
  516. `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server' && cat > '/root/.zcode/server/node.new'")}`
  517. ) {
  518. callback(
  519. null,
  520. new FakeUploadExecChannel((content) => {
  521. execUploadedContents.push(content);
  522. }),
  523. );
  524. return;
  525. }
  526. throw new Error(`Unexpected command: ${command}`);
  527. },
  528. sftp: (
  529. callback: (
  530. error: Error | null,
  531. sftp: {
  532. createWriteStream: (remotePath: string) => Writable;
  533. end: () => void;
  534. },
  535. ) => void,
  536. ) => {
  537. callback(null, {
  538. createWriteStream: (remotePath) => {
  539. attemptedSftpPaths.push(remotePath);
  540. return new FailingSftpWriteStream(failingSftpError);
  541. },
  542. end: () => {},
  543. });
  544. },
  545. };
  546. const mutableBackend = backend as unknown as {
  547. client: typeof fakeClient;
  548. connected: boolean;
  549. };
  550. mutableBackend.client = fakeClient;
  551. mutableBackend.connected = true;
  552. await expect(
  553. backend.upload(localFilePath, "~/.zcode/server/node.new"),
  554. ).resolves.toBeUndefined();
  555. await expect(
  556. backend.upload(localFilePath, "~/.zcode/server/node.new", {
  557. onProgress: (event) => secondUploadProgress.push(event),
  558. }),
  559. ).resolves.toBeUndefined();
  560. expect(attemptedSftpPaths).toEqual(["/root/.zcode/server/node.new"]);
  561. expect(execUploadedContents).toEqual([localContent, localContent]);
  562. expect(secondUploadProgress.at(-1)).toEqual({
  563. uploadedBytes: Buffer.byteLength(localContent),
  564. totalBytes: Buffer.byteLength(localContent),
  565. });
  566. const abortedUpload = new AbortController();
  567. abortedUpload.abort();
  568. await expect(
  569. backend.upload(localFilePath, "~/.zcode/server/node.new", {
  570. signal: abortedUpload.signal,
  571. }),
  572. ).rejects.toThrow("Remote upload canceled");
  573. expect(execUploadedContents).toEqual([localContent, localContent]);
  574. expect(
  575. executedCommands.includes(
  576. `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server' && cat > '/root/.zcode/server/node.new'")}`,
  577. ),
  578. ).toBe(true);
  579. });
  580. it("首次 SFTP session 失败后,同 backend 的后续上传应直接使用 exec pipe", async () => {
  581. const tempDir = await mkdtemp(join(tmpdir(), "ssh-backend-sftp-session-"));
  582. const localFilePath = join(tempDir, "node");
  583. const localContent = "hello ssh session fallback";
  584. await writeFile(localFilePath, localContent, "utf8");
  585. const backend = new SSHBackend({
  586. host: "example.com",
  587. username: "root",
  588. password: "secret",
  589. });
  590. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  591. const execUploadedContents: string[] = [];
  592. let sftpAttempts = 0;
  593. const fakeClient = {
  594. exec: (
  595. command: string,
  596. callback: (error: Error | null, channel: FakeExecChannel | FakeUploadExecChannel) => void,
  597. ) => {
  598. if (command === `/bin/sh -c ${quotePosixShellArgForTest('printf %s "$HOME"')}`) {
  599. const channel = new FakeExecChannel();
  600. callback(null, channel);
  601. emitExecResult(channel, { stdout: "/root", exitCode: 0 });
  602. return;
  603. }
  604. if (
  605. command === `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server'")}`
  606. ) {
  607. const channel = new FakeExecChannel();
  608. callback(null, channel);
  609. emitExecResult(channel, { exitCode: 0 });
  610. return;
  611. }
  612. if (
  613. command ===
  614. `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server' && cat > '/root/.zcode/server/node.new'")}`
  615. ) {
  616. callback(
  617. null,
  618. new FakeUploadExecChannel((content) => execUploadedContents.push(content)),
  619. );
  620. return;
  621. }
  622. throw new Error(`Unexpected command: ${command}`);
  623. },
  624. sftp: (callback: (error: Error | null, sftp: never) => void) => {
  625. sftpAttempts += 1;
  626. callback(
  627. Object.assign(new Error("SFTP subsystem unavailable"), { code: 4 }),
  628. undefined as never,
  629. );
  630. },
  631. };
  632. const mutableBackend = backend as unknown as {
  633. client: typeof fakeClient;
  634. connected: boolean;
  635. };
  636. mutableBackend.client = fakeClient;
  637. mutableBackend.connected = true;
  638. try {
  639. await expect(
  640. backend.upload(localFilePath, "~/.zcode/server/node.new"),
  641. ).resolves.toBeUndefined();
  642. await expect(
  643. backend.upload(localFilePath, "~/.zcode/server/node.new"),
  644. ).resolves.toBeUndefined();
  645. expect(sftpAttempts).toBe(1);
  646. expect(execUploadedContents).toEqual([localContent, localContent]);
  647. expect(
  648. warnSpy.mock.calls.filter((call) =>
  649. String(call[0] ?? "").includes(
  650. "switching node.new from sftp to exec pipe after sftp-session failure (FAILURE(code=4))",
  651. ),
  652. ),
  653. ).toHaveLength(1);
  654. } finally {
  655. warnSpy.mockRestore();
  656. }
  657. });
  658. it("本地文件读取失败不应把 backend 标记为 exec-upload-only", async () => {
  659. const tempDir = await mkdtemp(join(tmpdir(), "ssh-backend-local-read-"));
  660. const localFilePath = join(tempDir, "node");
  661. await writeFile(localFilePath, "first", "utf8");
  662. const backend = new SSHBackend({
  663. host: "example.com",
  664. username: "root",
  665. password: "secret",
  666. });
  667. const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
  668. let sftpAttempts = 0;
  669. const fakeClient = {
  670. exec: (
  671. command: string,
  672. callback: (error: Error | null, channel: FakeExecChannel) => void,
  673. ) => {
  674. const channel = new FakeExecChannel();
  675. callback(null, channel);
  676. if (command === `/bin/sh -c ${quotePosixShellArgForTest('printf %s "$HOME"')}`) {
  677. emitExecResult(channel, { stdout: "/root", exitCode: 0 });
  678. return;
  679. }
  680. if (
  681. command === `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server'")}`
  682. ) {
  683. emitExecResult(channel, { exitCode: 0 });
  684. return;
  685. }
  686. throw new Error(`Unexpected command: ${command}`);
  687. },
  688. sftp: (
  689. callback: (
  690. error: Error | null,
  691. sftp: { createWriteStream: () => Writable; end: () => void },
  692. ) => void,
  693. ) => {
  694. sftpAttempts += 1;
  695. if (sftpAttempts === 1) {
  696. rmSync(localFilePath);
  697. }
  698. callback(null, {
  699. createWriteStream: () => new SuccessfulSftpWriteStream(),
  700. end: () => {},
  701. });
  702. },
  703. };
  704. const mutableBackend = backend as unknown as {
  705. client: typeof fakeClient;
  706. connected: boolean;
  707. };
  708. mutableBackend.client = fakeClient;
  709. mutableBackend.connected = true;
  710. try {
  711. await expect(backend.upload(localFilePath, "~/.zcode/server/node.new")).rejects.toThrow();
  712. await writeFile(localFilePath, "second", "utf8");
  713. await expect(
  714. backend.upload(localFilePath, "~/.zcode/server/node.new"),
  715. ).resolves.toBeUndefined();
  716. expect(sftpAttempts).toBe(2);
  717. } finally {
  718. errorSpy.mockRestore();
  719. }
  720. });
  721. it("upload 成功时应输出上传进度日志", async () => {
  722. const tempDir = await mkdtemp(join(tmpdir(), "ssh-backend-progress-"));
  723. const localFilePath = join(tempDir, "node");
  724. await writeFile(localFilePath, Buffer.alloc(96 * 1024, "a"));
  725. const backend = new SSHBackend({
  726. host: "example.com",
  727. username: "root",
  728. password: "secret",
  729. });
  730. const consoleLogSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  731. const fakeClient = {
  732. exec: (
  733. command: string,
  734. callback: (error: Error | null, channel: FakeExecChannel) => void,
  735. ) => {
  736. const channel = new FakeExecChannel();
  737. callback(null, channel);
  738. if (command === `/bin/sh -c ${quotePosixShellArgForTest('printf %s "$HOME"')}`) {
  739. emitExecResult(channel, {
  740. stdout: "/root",
  741. exitCode: 0,
  742. });
  743. return;
  744. }
  745. if (
  746. command === `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server'")}`
  747. ) {
  748. emitExecResult(channel, { exitCode: 0 });
  749. return;
  750. }
  751. throw new Error(`Unexpected command: ${command}`);
  752. },
  753. sftp: (
  754. callback: (
  755. error: Error | null,
  756. sftp: {
  757. createWriteStream: (remotePath: string) => Writable;
  758. end: () => void;
  759. },
  760. ) => void,
  761. ) => {
  762. callback(null, {
  763. createWriteStream: (remotePath) => {
  764. expect(remotePath).toBe("/root/.zcode/server/node.new");
  765. return new SuccessfulSftpWriteStream();
  766. },
  767. end: () => {},
  768. });
  769. },
  770. };
  771. const mutableBackend = backend as unknown as {
  772. client: typeof fakeClient;
  773. connected: boolean;
  774. };
  775. mutableBackend.client = fakeClient;
  776. mutableBackend.connected = true;
  777. try {
  778. const progress: Array<{ uploadedBytes: number; totalBytes: number }> = [];
  779. await expect(
  780. backend.upload(localFilePath, "~/.zcode/server/node.new", {
  781. onProgress: (event) => progress.push(event),
  782. }),
  783. ).resolves.toBeUndefined();
  784. const progressLogs = consoleLogSpy.mock.calls
  785. .map((call) => String(call[0] ?? ""))
  786. .filter((line) => line.startsWith("[ssh] upload progress [sftp] (node.new):"));
  787. expect(progressLogs.length).toBeGreaterThan(0);
  788. expect(progressLogs.at(-1)).toContain("100.0%");
  789. expect(progressLogs.at(-1)).toContain("MB/s");
  790. expect(progress.at(-1)).toEqual({
  791. uploadedBytes: 96 * 1024,
  792. totalBytes: 96 * 1024,
  793. });
  794. } finally {
  795. consoleLogSpy.mockRestore();
  796. }
  797. });
  798. it("upload fallback 时应明确记录切换到 exec pipe", async () => {
  799. const tempDir = await mkdtemp(join(tmpdir(), "ssh-backend-fallback-log-"));
  800. const localFilePath = join(tempDir, "node");
  801. await writeFile(localFilePath, Buffer.alloc(96 * 1024, "a"));
  802. const backend = new SSHBackend({
  803. host: "example.com",
  804. username: "root",
  805. password: "secret",
  806. });
  807. const consoleLogSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  808. const consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
  809. const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
  810. const failingSftpError = Object.assign(new Error("Failure"), {
  811. code: 4,
  812. });
  813. const fakeClient = {
  814. exec: (
  815. command: string,
  816. callback: (error: Error | null, channel: FakeExecChannel | FakeUploadExecChannel) => void,
  817. ) => {
  818. if (command === `/bin/sh -c ${quotePosixShellArgForTest('printf %s "$HOME"')}`) {
  819. const channel = new FakeExecChannel();
  820. callback(null, channel);
  821. emitExecResult(channel, {
  822. stdout: "/root",
  823. exitCode: 0,
  824. });
  825. return;
  826. }
  827. if (
  828. command === `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server'")}`
  829. ) {
  830. const channel = new FakeExecChannel();
  831. callback(null, channel);
  832. emitExecResult(channel, { exitCode: 0 });
  833. return;
  834. }
  835. if (
  836. command ===
  837. `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server' && cat > '/root/.zcode/server/node.new'")}`
  838. ) {
  839. callback(null, new FakeUploadExecChannel((_content) => {}));
  840. return;
  841. }
  842. throw new Error(`Unexpected command: ${command}`);
  843. },
  844. sftp: (
  845. callback: (
  846. error: Error | null,
  847. sftp: {
  848. createWriteStream: (remotePath: string) => Writable;
  849. end: () => void;
  850. },
  851. ) => void,
  852. ) => {
  853. callback(null, {
  854. createWriteStream: (_remotePath) => new FailingSftpWriteStream(failingSftpError),
  855. end: () => {},
  856. });
  857. },
  858. };
  859. const mutableBackend = backend as unknown as {
  860. client: typeof fakeClient;
  861. connected: boolean;
  862. };
  863. mutableBackend.client = fakeClient;
  864. mutableBackend.connected = true;
  865. try {
  866. await expect(
  867. backend.upload(localFilePath, "~/.zcode/server/node.new"),
  868. ).resolves.toBeUndefined();
  869. const warnLines = consoleWarnSpy.mock.calls.map((call) => String(call[0] ?? ""));
  870. const logLines = consoleLogSpy.mock.calls.map((call) => String(call[0] ?? ""));
  871. const errorLines = consoleErrorSpy.mock.calls.map((call) => String(call[0] ?? ""));
  872. expect(
  873. warnLines.some((line) =>
  874. line.includes(
  875. "switching node.new from sftp to exec pipe after sftp-write failure (FAILURE(code=4))",
  876. ),
  877. ),
  878. ).toBe(true);
  879. expect(
  880. logLines.some((line) => line.includes("upload: started via exec pipe for node.new")),
  881. ).toBe(true);
  882. expect(
  883. logLines.some((line) => line.startsWith("[ssh] upload progress [exec] (node.new):")),
  884. ).toBe(true);
  885. expect(
  886. logLines.some((line) => line.includes("upload progress [sftp] (node.new): 100.0%")),
  887. ).toBe(false);
  888. expect(
  889. errorLines.filter((line) =>
  890. line.includes("upload: sftp write failed for node.new: FAILURE(code=4)"),
  891. ).length,
  892. ).toBe(0);
  893. expect(
  894. errorLines.some((line) => line.includes("upload: local read failed for node.new")),
  895. ).toBe(false);
  896. } finally {
  897. consoleLogSpy.mockRestore();
  898. consoleWarnSpy.mockRestore();
  899. consoleErrorSpy.mockRestore();
  900. }
  901. });
  902. });