sshBackend.test.ts 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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 fakeClient = {
  317. exec: (
  318. command: string,
  319. callback: (error: Error | null, channel: FakeExecChannel) => void,
  320. ) => {
  321. const channel = new FakeExecChannel();
  322. callback(null, channel);
  323. if (command === `/bin/sh -c ${quotePosixShellArgForTest("uname -s")}`) {
  324. emitExecResult(channel, {
  325. stdout: "Darwin\n",
  326. exitCode: 0,
  327. exitBeforeData: true,
  328. });
  329. return;
  330. }
  331. if (command === `/bin/sh -c ${quotePosixShellArgForTest("uname -m")}`) {
  332. emitExecResult(channel, {
  333. stdout: "arm64\n",
  334. exitCode: 0,
  335. });
  336. return;
  337. }
  338. emitExecResult(channel, { stdout: "", exitCode: 0 });
  339. },
  340. };
  341. const mutableBackend = backend as unknown as {
  342. client: typeof fakeClient;
  343. connected: boolean;
  344. };
  345. mutableBackend.client = fakeClient;
  346. mutableBackend.connected = true;
  347. await expect(backend.detect()).resolves.toEqual({
  348. platform: "darwin",
  349. arch: "arm64",
  350. });
  351. });
  352. it("exec 成功完成时不应输出无意义的完成日志", async () => {
  353. const backend = new SSHBackend({
  354. host: "example.com",
  355. username: "root",
  356. password: "secret",
  357. });
  358. const infoSpy = vi.spyOn(console, "log").mockImplementation(() => undefined);
  359. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  360. const fakeClient = {
  361. exec: (
  362. command: string,
  363. callback: (error: Error | null, channel: FakeExecChannel) => void,
  364. ) => {
  365. expectSSHExecCommand(command, "set -eu && echo very-long-command");
  366. const channel = new FakeExecChannel();
  367. callback(null, channel);
  368. emitExecResult(channel, { exitCode: 0 });
  369. },
  370. };
  371. const mutableBackend = backend as unknown as {
  372. client: typeof fakeClient;
  373. connected: boolean;
  374. };
  375. mutableBackend.client = fakeClient;
  376. mutableBackend.connected = true;
  377. const stream = await backend.exec("set -eu && echo very-long-command");
  378. await new Promise<void>((resolve) => stream.onClose(() => resolve()));
  379. expect(infoSpy).not.toHaveBeenCalledWith(expect.stringContaining("exec channel"));
  380. expect(warnSpy).not.toHaveBeenCalledWith(expect.stringContaining("exec channel"));
  381. expect(infoSpy).not.toHaveBeenCalledWith(expect.stringContaining("very-long-command"));
  382. infoSpy.mockRestore();
  383. warnSpy.mockRestore();
  384. });
  385. it("exec 应通过 POSIX shell 执行远端命令,避免 fish 默认 shell 解析部署脚本", async () => {
  386. const backend = new SSHBackend({
  387. host: "example.com",
  388. username: "root",
  389. password: "secret",
  390. });
  391. const rawCommand = "download=; if command -v curl >/dev/null 2>&1; then download=curl; fi";
  392. const executedCommands: string[] = [];
  393. const fakeClient = {
  394. exec: (
  395. command: string,
  396. callback: (error: Error | null, channel: FakeExecChannel) => void,
  397. ) => {
  398. executedCommands.push(command);
  399. expectSSHExecCommand(command, rawCommand);
  400. const channel = new FakeExecChannel();
  401. callback(null, channel);
  402. emitExecResult(channel, { exitCode: 0 });
  403. },
  404. };
  405. const mutableBackend = backend as unknown as {
  406. client: typeof fakeClient;
  407. connected: boolean;
  408. };
  409. mutableBackend.client = fakeClient;
  410. mutableBackend.connected = true;
  411. const stream = await backend.exec(rawCommand);
  412. await new Promise<void>((resolve) => stream.onClose(() => resolve()));
  413. expect(executedCommands).toHaveLength(1);
  414. });
  415. it("exec 失败完成时应保留退出码日志但不输出完整远端命令", async () => {
  416. const backend = new SSHBackend({
  417. host: "example.com",
  418. username: "root",
  419. password: "secret",
  420. });
  421. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  422. const fakeClient = {
  423. exec: (
  424. command: string,
  425. callback: (error: Error | null, channel: FakeExecChannel) => void,
  426. ) => {
  427. expectSSHExecCommand(command, "set -eu && echo very-long-command && exit 7");
  428. const channel = new FakeExecChannel();
  429. callback(null, channel);
  430. emitExecResult(channel, { exitCode: 7 });
  431. },
  432. };
  433. const mutableBackend = backend as unknown as {
  434. client: typeof fakeClient;
  435. connected: boolean;
  436. };
  437. mutableBackend.client = fakeClient;
  438. mutableBackend.connected = true;
  439. const stream = await backend.exec("set -eu && echo very-long-command && exit 7");
  440. await new Promise<void>((resolve) => stream.onClose(() => resolve()));
  441. expect(warnSpy).toHaveBeenCalledWith(
  442. expect.stringContaining("[ssh] exec channel failed: code=7"),
  443. );
  444. expect(warnSpy).not.toHaveBeenCalledWith(expect.stringContaining("very-long-command"));
  445. warnSpy.mockRestore();
  446. });
  447. it("ssh2 debug 不应输出下载阶段的高频 channel 数据包", () => {
  448. const backend = new SSHBackend({
  449. host: "example.com",
  450. username: "root",
  451. password: "secret",
  452. });
  453. const debugSpy = vi.spyOn(console, "debug").mockImplementation(() => undefined);
  454. const debug = (
  455. backend as unknown as {
  456. config: {
  457. debug?: (message: string) => void;
  458. };
  459. }
  460. ).config.debug;
  461. try {
  462. if (!debug) {
  463. return;
  464. }
  465. debug("Inbound: CHANNEL_EXTENDED_DATA (r:27, 1)");
  466. debug("Inbound: CHANNEL_DATA (r:27, 1024)");
  467. debug("Outbound: CHANNEL_WINDOW_ADJUST (r:27, 2097152)");
  468. debug("DEBUG: Client: Trying password auth");
  469. const debugLines = debugSpy.mock.calls.map((call) => String(call[0] ?? ""));
  470. expect(debugLines.some((line) => line.includes("CHANNEL_EXTENDED_DATA"))).toBe(false);
  471. expect(debugLines.some((line) => line.includes("CHANNEL_DATA"))).toBe(false);
  472. expect(debugLines.some((line) => line.includes("CHANNEL_WINDOW_ADJUST"))).toBe(false);
  473. expect(debugLines.some((line) => line.includes("Trying password auth"))).toBe(true);
  474. } finally {
  475. debugSpy.mockRestore();
  476. }
  477. });
  478. it("首次 SFTP 写入失败后,同 backend 的后续上传应直接使用 exec pipe", async () => {
  479. const tempDir = await mkdtemp(join(tmpdir(), "ssh-backend-upload-"));
  480. const localFilePath = join(tempDir, "node");
  481. const localContent = "hello ssh fallback";
  482. await writeFile(localFilePath, localContent, "utf8");
  483. const backend = new SSHBackend({
  484. host: "example.com",
  485. username: "root",
  486. password: "secret",
  487. });
  488. const attemptedSftpPaths: string[] = [];
  489. const execUploadedContents: string[] = [];
  490. const executedCommands: string[] = [];
  491. const secondUploadProgress: Array<{ uploadedBytes: number; totalBytes: number }> = [];
  492. const failingSftpError = Object.assign(new Error("No such file or directory"), {
  493. code: 2,
  494. });
  495. const fakeClient = {
  496. exec: (
  497. command: string,
  498. callback: (error: Error | null, channel: FakeExecChannel | FakeUploadExecChannel) => void,
  499. ) => {
  500. executedCommands.push(command);
  501. if (command === `/bin/sh -c ${quotePosixShellArgForTest('printf %s "$HOME"')}`) {
  502. const channel = new FakeExecChannel();
  503. callback(null, channel);
  504. emitExecResult(channel, {
  505. stdout: "/root",
  506. exitCode: 0,
  507. });
  508. return;
  509. }
  510. if (
  511. command === `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server'")}`
  512. ) {
  513. const channel = new FakeExecChannel();
  514. callback(null, channel);
  515. emitExecResult(channel, { exitCode: 0 });
  516. return;
  517. }
  518. if (
  519. command ===
  520. `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server' && cat > '/root/.zcode/server/node.new'")}`
  521. ) {
  522. callback(
  523. null,
  524. new FakeUploadExecChannel((content) => {
  525. execUploadedContents.push(content);
  526. }),
  527. );
  528. return;
  529. }
  530. throw new Error(`Unexpected command: ${command}`);
  531. },
  532. sftp: (
  533. callback: (
  534. error: Error | null,
  535. sftp: {
  536. createWriteStream: (remotePath: string) => Writable;
  537. end: () => void;
  538. },
  539. ) => void,
  540. ) => {
  541. callback(null, {
  542. createWriteStream: (remotePath) => {
  543. attemptedSftpPaths.push(remotePath);
  544. return new FailingSftpWriteStream(failingSftpError);
  545. },
  546. end: () => {},
  547. });
  548. },
  549. };
  550. const mutableBackend = backend as unknown as {
  551. client: typeof fakeClient;
  552. connected: boolean;
  553. };
  554. mutableBackend.client = fakeClient;
  555. mutableBackend.connected = true;
  556. await expect(
  557. backend.upload(localFilePath, "~/.zcode/server/node.new"),
  558. ).resolves.toBeUndefined();
  559. await expect(
  560. backend.upload(localFilePath, "~/.zcode/server/node.new", {
  561. onProgress: (event) => secondUploadProgress.push(event),
  562. }),
  563. ).resolves.toBeUndefined();
  564. expect(attemptedSftpPaths).toEqual(["/root/.zcode/server/node.new"]);
  565. expect(execUploadedContents).toEqual([localContent, localContent]);
  566. expect(secondUploadProgress.at(-1)).toEqual({
  567. uploadedBytes: Buffer.byteLength(localContent),
  568. totalBytes: Buffer.byteLength(localContent),
  569. });
  570. const abortedUpload = new AbortController();
  571. abortedUpload.abort();
  572. await expect(
  573. backend.upload(localFilePath, "~/.zcode/server/node.new", {
  574. signal: abortedUpload.signal,
  575. }),
  576. ).rejects.toThrow("Remote upload canceled");
  577. expect(execUploadedContents).toEqual([localContent, localContent]);
  578. expect(
  579. executedCommands.includes(
  580. `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server' && cat > '/root/.zcode/server/node.new'")}`,
  581. ),
  582. ).toBe(true);
  583. });
  584. it("首次 SFTP session 失败后,同 backend 的后续上传应直接使用 exec pipe", async () => {
  585. const tempDir = await mkdtemp(join(tmpdir(), "ssh-backend-sftp-session-"));
  586. const localFilePath = join(tempDir, "node");
  587. const localContent = "hello ssh session fallback";
  588. await writeFile(localFilePath, localContent, "utf8");
  589. const backend = new SSHBackend({
  590. host: "example.com",
  591. username: "root",
  592. password: "secret",
  593. });
  594. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  595. const execUploadedContents: string[] = [];
  596. let sftpAttempts = 0;
  597. const fakeClient = {
  598. exec: (
  599. command: string,
  600. callback: (error: Error | null, channel: FakeExecChannel | FakeUploadExecChannel) => void,
  601. ) => {
  602. if (command === `/bin/sh -c ${quotePosixShellArgForTest('printf %s "$HOME"')}`) {
  603. const channel = new FakeExecChannel();
  604. callback(null, channel);
  605. emitExecResult(channel, { stdout: "/root", exitCode: 0 });
  606. return;
  607. }
  608. if (
  609. command === `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server'")}`
  610. ) {
  611. const channel = new FakeExecChannel();
  612. callback(null, channel);
  613. emitExecResult(channel, { exitCode: 0 });
  614. return;
  615. }
  616. if (
  617. command ===
  618. `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server' && cat > '/root/.zcode/server/node.new'")}`
  619. ) {
  620. callback(
  621. null,
  622. new FakeUploadExecChannel((content) => execUploadedContents.push(content)),
  623. );
  624. return;
  625. }
  626. throw new Error(`Unexpected command: ${command}`);
  627. },
  628. sftp: (callback: (error: Error | null, sftp: never) => void) => {
  629. sftpAttempts += 1;
  630. callback(
  631. Object.assign(new Error("SFTP subsystem unavailable"), { code: 4 }),
  632. undefined as never,
  633. );
  634. },
  635. };
  636. const mutableBackend = backend as unknown as {
  637. client: typeof fakeClient;
  638. connected: boolean;
  639. };
  640. mutableBackend.client = fakeClient;
  641. mutableBackend.connected = true;
  642. try {
  643. await expect(
  644. backend.upload(localFilePath, "~/.zcode/server/node.new"),
  645. ).resolves.toBeUndefined();
  646. await expect(
  647. backend.upload(localFilePath, "~/.zcode/server/node.new"),
  648. ).resolves.toBeUndefined();
  649. expect(sftpAttempts).toBe(1);
  650. expect(execUploadedContents).toEqual([localContent, localContent]);
  651. expect(
  652. warnSpy.mock.calls.filter((call) =>
  653. String(call[0] ?? "").includes(
  654. "switching node.new from sftp to exec pipe after sftp-session failure (FAILURE(code=4))",
  655. ),
  656. ),
  657. ).toHaveLength(1);
  658. } finally {
  659. warnSpy.mockRestore();
  660. }
  661. });
  662. it("本地文件读取失败不应把 backend 标记为 exec-upload-only", async () => {
  663. const tempDir = await mkdtemp(join(tmpdir(), "ssh-backend-local-read-"));
  664. const localFilePath = join(tempDir, "node");
  665. await writeFile(localFilePath, "first", "utf8");
  666. const backend = new SSHBackend({
  667. host: "example.com",
  668. username: "root",
  669. password: "secret",
  670. });
  671. const errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
  672. let sftpAttempts = 0;
  673. const fakeClient = {
  674. exec: (
  675. command: string,
  676. callback: (error: Error | null, channel: FakeExecChannel) => void,
  677. ) => {
  678. const channel = new FakeExecChannel();
  679. callback(null, channel);
  680. if (command === `/bin/sh -c ${quotePosixShellArgForTest('printf %s "$HOME"')}`) {
  681. emitExecResult(channel, { stdout: "/root", exitCode: 0 });
  682. return;
  683. }
  684. if (
  685. command === `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server'")}`
  686. ) {
  687. emitExecResult(channel, { exitCode: 0 });
  688. return;
  689. }
  690. throw new Error(`Unexpected command: ${command}`);
  691. },
  692. sftp: (
  693. callback: (
  694. error: Error | null,
  695. sftp: { createWriteStream: () => Writable; end: () => void },
  696. ) => void,
  697. ) => {
  698. sftpAttempts += 1;
  699. if (sftpAttempts === 1) {
  700. rmSync(localFilePath);
  701. }
  702. callback(null, {
  703. createWriteStream: () => new SuccessfulSftpWriteStream(),
  704. end: () => {},
  705. });
  706. },
  707. };
  708. const mutableBackend = backend as unknown as {
  709. client: typeof fakeClient;
  710. connected: boolean;
  711. };
  712. mutableBackend.client = fakeClient;
  713. mutableBackend.connected = true;
  714. try {
  715. await expect(backend.upload(localFilePath, "~/.zcode/server/node.new")).rejects.toThrow();
  716. await writeFile(localFilePath, "second", "utf8");
  717. await expect(
  718. backend.upload(localFilePath, "~/.zcode/server/node.new"),
  719. ).resolves.toBeUndefined();
  720. expect(sftpAttempts).toBe(2);
  721. } finally {
  722. errorSpy.mockRestore();
  723. }
  724. });
  725. it("upload 成功时应输出上传进度日志", async () => {
  726. const tempDir = await mkdtemp(join(tmpdir(), "ssh-backend-progress-"));
  727. const localFilePath = join(tempDir, "node");
  728. await writeFile(localFilePath, Buffer.alloc(96 * 1024, "a"));
  729. const backend = new SSHBackend({
  730. host: "example.com",
  731. username: "root",
  732. password: "secret",
  733. });
  734. const consoleLogSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  735. const fakeClient = {
  736. exec: (
  737. command: string,
  738. callback: (error: Error | null, channel: FakeExecChannel) => void,
  739. ) => {
  740. const channel = new FakeExecChannel();
  741. callback(null, channel);
  742. if (command === `/bin/sh -c ${quotePosixShellArgForTest('printf %s "$HOME"')}`) {
  743. emitExecResult(channel, {
  744. stdout: "/root",
  745. exitCode: 0,
  746. });
  747. return;
  748. }
  749. if (
  750. command === `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server'")}`
  751. ) {
  752. emitExecResult(channel, { exitCode: 0 });
  753. return;
  754. }
  755. throw new Error(`Unexpected command: ${command}`);
  756. },
  757. sftp: (
  758. callback: (
  759. error: Error | null,
  760. sftp: {
  761. createWriteStream: (remotePath: string) => Writable;
  762. end: () => void;
  763. },
  764. ) => void,
  765. ) => {
  766. callback(null, {
  767. createWriteStream: (remotePath) => {
  768. expect(remotePath).toBe("/root/.zcode/server/node.new");
  769. return new SuccessfulSftpWriteStream();
  770. },
  771. end: () => {},
  772. });
  773. },
  774. };
  775. const mutableBackend = backend as unknown as {
  776. client: typeof fakeClient;
  777. connected: boolean;
  778. };
  779. mutableBackend.client = fakeClient;
  780. mutableBackend.connected = true;
  781. try {
  782. const progress: Array<{ uploadedBytes: number; totalBytes: number }> = [];
  783. await expect(
  784. backend.upload(localFilePath, "~/.zcode/server/node.new", {
  785. onProgress: (event) => progress.push(event),
  786. }),
  787. ).resolves.toBeUndefined();
  788. const progressLogs = consoleLogSpy.mock.calls
  789. .map((call) => String(call[0] ?? ""))
  790. .filter((line) => line.startsWith("[ssh] upload progress [sftp] (node.new):"));
  791. expect(progressLogs.length).toBeGreaterThan(0);
  792. expect(progressLogs.at(-1)).toContain("100.0%");
  793. expect(progressLogs.at(-1)).toContain("MB/s");
  794. expect(progress.at(-1)).toEqual({
  795. uploadedBytes: 96 * 1024,
  796. totalBytes: 96 * 1024,
  797. });
  798. } finally {
  799. consoleLogSpy.mockRestore();
  800. }
  801. });
  802. it("upload fallback 时应明确记录切换到 exec pipe", async () => {
  803. const tempDir = await mkdtemp(join(tmpdir(), "ssh-backend-fallback-log-"));
  804. const localFilePath = join(tempDir, "node");
  805. await writeFile(localFilePath, Buffer.alloc(96 * 1024, "a"));
  806. const backend = new SSHBackend({
  807. host: "example.com",
  808. username: "root",
  809. password: "secret",
  810. });
  811. const consoleLogSpy = vi.spyOn(console, "log").mockImplementation(() => {});
  812. const consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
  813. const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
  814. const failingSftpError = Object.assign(new Error("Failure"), {
  815. code: 4,
  816. });
  817. const fakeClient = {
  818. exec: (
  819. command: string,
  820. callback: (error: Error | null, channel: FakeExecChannel | FakeUploadExecChannel) => void,
  821. ) => {
  822. if (command === `/bin/sh -c ${quotePosixShellArgForTest('printf %s "$HOME"')}`) {
  823. const channel = new FakeExecChannel();
  824. callback(null, channel);
  825. emitExecResult(channel, {
  826. stdout: "/root",
  827. exitCode: 0,
  828. });
  829. return;
  830. }
  831. if (
  832. command === `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server'")}`
  833. ) {
  834. const channel = new FakeExecChannel();
  835. callback(null, channel);
  836. emitExecResult(channel, { exitCode: 0 });
  837. return;
  838. }
  839. if (
  840. command ===
  841. `/bin/sh -c ${quotePosixShellArgForTest("mkdir -p '/root/.zcode/server' && cat > '/root/.zcode/server/node.new'")}`
  842. ) {
  843. callback(null, new FakeUploadExecChannel((_content) => {}));
  844. return;
  845. }
  846. throw new Error(`Unexpected command: ${command}`);
  847. },
  848. sftp: (
  849. callback: (
  850. error: Error | null,
  851. sftp: {
  852. createWriteStream: (remotePath: string) => Writable;
  853. end: () => void;
  854. },
  855. ) => void,
  856. ) => {
  857. callback(null, {
  858. createWriteStream: (_remotePath) => new FailingSftpWriteStream(failingSftpError),
  859. end: () => {},
  860. });
  861. },
  862. };
  863. const mutableBackend = backend as unknown as {
  864. client: typeof fakeClient;
  865. connected: boolean;
  866. };
  867. mutableBackend.client = fakeClient;
  868. mutableBackend.connected = true;
  869. try {
  870. await expect(
  871. backend.upload(localFilePath, "~/.zcode/server/node.new"),
  872. ).resolves.toBeUndefined();
  873. const warnLines = consoleWarnSpy.mock.calls.map((call) => String(call[0] ?? ""));
  874. const logLines = consoleLogSpy.mock.calls.map((call) => String(call[0] ?? ""));
  875. const errorLines = consoleErrorSpy.mock.calls.map((call) => String(call[0] ?? ""));
  876. expect(
  877. warnLines.some((line) =>
  878. line.includes(
  879. "switching node.new from sftp to exec pipe after sftp-write failure (FAILURE(code=4))",
  880. ),
  881. ),
  882. ).toBe(true);
  883. expect(
  884. logLines.some((line) => line.includes("upload: started via exec pipe for node.new")),
  885. ).toBe(true);
  886. expect(
  887. logLines.some((line) => line.startsWith("[ssh] upload progress [exec] (node.new):")),
  888. ).toBe(true);
  889. expect(
  890. logLines.some((line) => line.includes("upload progress [sftp] (node.new): 100.0%")),
  891. ).toBe(false);
  892. expect(
  893. errorLines.filter((line) =>
  894. line.includes("upload: sftp write failed for node.new: FAILURE(code=4)"),
  895. ).length,
  896. ).toBe(0);
  897. expect(
  898. errorLines.some((line) => line.includes("upload: local read failed for node.new")),
  899. ).toBe(false);
  900. } finally {
  901. consoleLogSpy.mockRestore();
  902. consoleWarnSpy.mockRestore();
  903. consoleErrorSpy.mockRestore();
  904. }
  905. });
  906. });