wslBackend.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. import { EventEmitter } from "node:events";
  2. import { mkdtemp, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { PassThrough } from "node:stream";
  6. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  7. const mocks = vi.hoisted(() => ({
  8. execFile: vi.fn(),
  9. isWSLAvailable: vi.fn(),
  10. listWSLDistros: vi.fn(),
  11. spawn: vi.fn(),
  12. }));
  13. vi.mock("node:child_process", () => ({
  14. execFile: mocks.execFile,
  15. spawn: mocks.spawn,
  16. }));
  17. vi.mock("@zcode/server/remote/wsl-detect.js", () => ({
  18. isWSLAvailable: mocks.isWSLAvailable,
  19. listWSLDistros: mocks.listWSLDistros,
  20. }));
  21. import { WSLBackend, buildWslArgs } from "../src/remote/wsl-backend.js";
  22. const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");
  23. function createSpawnChild(options?: { closeOnStdinFinish?: boolean }) {
  24. const child = new EventEmitter() as EventEmitter & {
  25. kill: ReturnType<typeof vi.fn>;
  26. stderr: PassThrough;
  27. stdin: PassThrough;
  28. stdout: PassThrough;
  29. };
  30. child.kill = vi.fn(() => {
  31. queueMicrotask(() => child.emit("close", 1));
  32. return true;
  33. });
  34. child.stdin = new PassThrough();
  35. child.stdout = new PassThrough();
  36. child.stderr = new PassThrough();
  37. child.stdin.resume();
  38. if (options?.closeOnStdinFinish !== false) {
  39. child.stdin.on("finish", () => queueMicrotask(() => child.emit("close", 0)));
  40. }
  41. queueMicrotask(() => child.emit("spawn"));
  42. return child;
  43. }
  44. beforeEach(() => {
  45. Object.defineProperty(process, "platform", { configurable: true, value: "win32" });
  46. mocks.execFile.mockReset();
  47. mocks.isWSLAvailable.mockReset();
  48. mocks.listWSLDistros.mockReset();
  49. mocks.spawn.mockReset();
  50. mocks.isWSLAvailable.mockResolvedValue(true);
  51. mocks.listWSLDistros.mockResolvedValue([
  52. { isDefault: true, name: "Ubuntu-24.04", state: "Running", version: 2 },
  53. ]);
  54. mocks.execFile.mockImplementation(
  55. (
  56. _command: string,
  57. _args: string[],
  58. _options: unknown,
  59. callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void,
  60. ) => {
  61. const child = new EventEmitter();
  62. queueMicrotask(() => {
  63. callback(
  64. null,
  65. Buffer.from("Ubuntu-24.04\ntester\n/home/tester"),
  66. Buffer.alloc(0),
  67. );
  68. child.emit("close", 0);
  69. });
  70. return child as never;
  71. },
  72. );
  73. mocks.spawn.mockImplementation(() => createSpawnChild());
  74. });
  75. afterEach(() => {
  76. if (originalPlatform) Object.defineProperty(process, "platform", originalPlatform);
  77. });
  78. describe("buildWslArgs", () => {
  79. it("disposeAndWait 回收 detect 阶段由 execFile 创建的 wsl.exe", async () => {
  80. let child!: EventEmitter & { kill: ReturnType<typeof vi.fn>; stdin: null };
  81. mocks.execFile.mockImplementationOnce(
  82. (
  83. _command: string,
  84. _args: string[],
  85. _options: unknown,
  86. callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void,
  87. ) => {
  88. child = Object.assign(new EventEmitter(), {
  89. stdin: null,
  90. kill: vi.fn(() => {
  91. callback(new Error("killed"), Buffer.alloc(0), Buffer.alloc(0));
  92. child.emit("close", 1);
  93. return true;
  94. }),
  95. });
  96. return child as never;
  97. },
  98. );
  99. mocks.isWSLAvailable.mockImplementationOnce(
  100. async (executor: (args: string[]) => Promise<Buffer>) => {
  101. await executor(["--status"]);
  102. return true;
  103. },
  104. );
  105. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  106. const detecting = backend.detect();
  107. const detectionError = detecting.catch((error: unknown) => error);
  108. await vi.waitFor(() => expect(mocks.execFile).toHaveBeenCalledTimes(1));
  109. vi.useFakeTimers();
  110. try {
  111. const disposing = backend.disposeAndWait({ graceTimeoutMs: 300, killWaitTimeoutMs: 100 });
  112. await vi.advanceTimersByTimeAsync(300);
  113. await disposing;
  114. expect(child.kill).toHaveBeenCalledTimes(1);
  115. expect(mocks.execFile.mock.calls.flatMap((call) => call[1] as string[])).not.toContain(
  116. "--terminate",
  117. );
  118. await expect(detectionError).resolves.toMatchObject({ message: "killed" });
  119. } finally {
  120. vi.useRealTimers();
  121. }
  122. });
  123. it("disposeAndWait 回收 distro list 阶段由 execFile 创建的 wsl.exe", async () => {
  124. let child!: EventEmitter & { kill: ReturnType<typeof vi.fn>; stdin: null };
  125. mocks.execFile.mockImplementationOnce(
  126. (
  127. _command: string,
  128. _args: string[],
  129. _options: unknown,
  130. callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void,
  131. ) => {
  132. child = Object.assign(new EventEmitter(), {
  133. stdin: null,
  134. kill: vi.fn(() => {
  135. callback(new Error("list killed"), Buffer.alloc(0), Buffer.alloc(0));
  136. child.emit("close", 1);
  137. return true;
  138. }),
  139. });
  140. return child as never;
  141. },
  142. );
  143. mocks.listWSLDistros.mockImplementationOnce(
  144. async (executor: (args: string[]) => Promise<Buffer>) => {
  145. await executor(["-l", "-v", "--all"]);
  146. return [];
  147. },
  148. );
  149. const backend = new WSLBackend({ kind: "wsl" });
  150. const detecting = backend.detect();
  151. const detectionError = detecting.catch((error: unknown) => error);
  152. await vi.waitFor(() => expect(mocks.execFile).toHaveBeenCalledTimes(1));
  153. vi.useFakeTimers();
  154. try {
  155. const disposing = backend.disposeAndWait({ graceTimeoutMs: 300, killWaitTimeoutMs: 100 });
  156. await vi.advanceTimersByTimeAsync(300);
  157. await disposing;
  158. expect(child.kill).toHaveBeenCalledTimes(1);
  159. await expect(detectionError).resolves.toMatchObject({ message: "WSL backend 已释放,无法启动新命令" });
  160. } finally {
  161. vi.useRealTimers();
  162. }
  163. });
  164. it("回收开始后拒绝启动新的 WSL 子进程", async () => {
  165. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  166. await backend.disposeAndWait();
  167. await expect(backend.exec("zcode-server")).rejects.toThrow("WSL backend 已释放");
  168. expect(mocks.spawn).not.toHaveBeenCalled();
  169. });
  170. it("discovery pending 时完成回收后不再启动 WSL 子进程", async () => {
  171. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  172. await backend.resolveIdentity();
  173. let resumeDiscovery!: (available: boolean) => void;
  174. mocks.isWSLAvailable.mockImplementationOnce(
  175. () =>
  176. new Promise<boolean>((resolve) => {
  177. resumeDiscovery = resolve;
  178. }),
  179. );
  180. const executing = backend.exec("zcode-server");
  181. await vi.waitFor(() => expect(mocks.isWSLAvailable).toHaveBeenCalledTimes(2));
  182. await backend.disposeAndWait();
  183. resumeDiscovery(true);
  184. await expect(executing).rejects.toThrow("WSL backend 已释放");
  185. expect(mocks.spawn).not.toHaveBeenCalled();
  186. });
  187. it("disposeAndWait 只回收当前 backend 创建的 wsl.exe 子进程", async () => {
  188. let usingFakeTimers = false;
  189. try {
  190. let child!: ReturnType<typeof createSpawnChild>;
  191. mocks.spawn.mockImplementationOnce(() => {
  192. child = createSpawnChild({ closeOnStdinFinish: false });
  193. return child;
  194. });
  195. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  196. await backend.exec("zcode-server");
  197. vi.useFakeTimers();
  198. usingFakeTimers = true;
  199. const disposing = backend.disposeAndWait({ graceTimeoutMs: 300, killWaitTimeoutMs: 100 });
  200. expect(child.stdin.writableEnded).toBe(true);
  201. expect(child.kill).not.toHaveBeenCalled();
  202. await vi.advanceTimersByTimeAsync(300);
  203. await disposing;
  204. expect(child.kill).toHaveBeenCalledTimes(1);
  205. } finally {
  206. if (usingFakeTimers) {
  207. vi.useRealTimers();
  208. }
  209. }
  210. });
  211. it("子进程在 EOF 后正常退出时不执行 kill", async () => {
  212. let child!: ReturnType<typeof createSpawnChild>;
  213. mocks.spawn.mockImplementationOnce(() => {
  214. child = createSpawnChild();
  215. return child;
  216. });
  217. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  218. await backend.exec("zcode-server");
  219. await backend.disposeAndWait({ graceTimeoutMs: 300, killWaitTimeoutMs: 100 });
  220. expect(child.kill).not.toHaveBeenCalled();
  221. });
  222. it("uses the default distro user when no WSL user is provided", () => {
  223. expect(buildWslArgs(["bash", "-lc", "pwd"], "Ubuntu-24.04", null)).toEqual([
  224. "-d",
  225. "Ubuntu-24.04",
  226. "--exec",
  227. "bash",
  228. "-lc",
  229. "pwd",
  230. ]);
  231. });
  232. it("resolves the canonical distro name and actual Linux user", async () => {
  233. const backend = new WSLBackend({ kind: "wsl", distro: "ubuntu-24.04" });
  234. await expect(backend.resolveIdentity()).resolves.toEqual({
  235. distro: "Ubuntu-24.04",
  236. user: "tester",
  237. });
  238. expect(mocks.execFile).toHaveBeenCalledWith(
  239. "wsl.exe",
  240. expect.arrayContaining(["-d", "Ubuntu-24.04", "bash", "-lc"]),
  241. expect.any(Object),
  242. expect.any(Function),
  243. );
  244. });
  245. it("passes an explicit WSL user to wsl.exe", () => {
  246. expect(buildWslArgs(["bash", "-lc", "pwd"], "Ubuntu-24.04", "root")).toEqual([
  247. "-d",
  248. "Ubuntu-24.04",
  249. "-u",
  250. "root",
  251. "--exec",
  252. "bash",
  253. "-lc",
  254. "pwd",
  255. ]);
  256. });
  257. it("exec 与 execSimple 都以 --exec 直传 argv,命令不经默认 shell 二次解析", async () => {
  258. // Bug 场景:Source Server tar preflight 依赖局部变量 `$tar_tool`。wsl.exe 非 --exec 模式会把
  259. // `--` 之后的原始命令行交给用户默认 shell `-c`,Node 为参数加的双引号让外层 shell 先把
  260. // `"$tar_tool"` 展开成空串,远端输出 `tar=` 且退出码 0,被误判成「远端缺少 tar」。
  261. const preflightCommand =
  262. "tar_tool=; if command -v tar >/dev/null 2>&1; then tar_tool=tar; fi; printf 'tar=%s\\n' \"$tar_tool\"";
  263. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  264. await backend.exec(preflightCommand);
  265. expect(mocks.spawn).toHaveBeenCalledWith(
  266. "wsl.exe",
  267. ["-d", "Ubuntu-24.04", "-u", "tester", "--exec", "bash", "-lc", preflightCommand],
  268. expect.objectContaining({ stdio: "pipe" }),
  269. );
  270. for (const call of [...mocks.spawn.mock.calls, ...mocks.execFile.mock.calls]) {
  271. const args = call[1] as string[];
  272. if (!args.includes("bash")) continue;
  273. expect(args).not.toContain("--");
  274. expect(args.indexOf("--exec")).toBe(args.indexOf("bash") - 1);
  275. }
  276. });
  277. it("WSL NAT 下把不可达的 loopback 代理转换为宿主网关地址", async () => {
  278. mocks.execFile.mockImplementation(
  279. (
  280. _command: string,
  281. args: string[],
  282. _options: unknown,
  283. callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void,
  284. ) => {
  285. const shellCommand = args.at(-1) ?? "";
  286. const stdout = shellCommand.includes("/dev/tcp/172.21.240.1/")
  287. ? "reachable"
  288. : shellCommand.includes("/dev/tcp/")
  289. ? "unreachable"
  290. : shellCommand.includes("ip route show default")
  291. ? "route=172.21.240.1"
  292. : "Ubuntu-24.04\ntester\n/home/tester";
  293. const child = new EventEmitter();
  294. queueMicrotask(() => {
  295. callback(null, Buffer.from(stdout), Buffer.alloc(0));
  296. child.emit("close", 0);
  297. });
  298. return child as never;
  299. },
  300. );
  301. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  302. await expect(backend.resolveRuntimeProxy("http://127.0.0.1:7890")).resolves.toBe(
  303. "http://172.21.240.1:7890/",
  304. );
  305. });
  306. it("WSL mirrored 或代理可达时保留 loopback 代理地址", async () => {
  307. mocks.execFile.mockImplementation(
  308. (
  309. _command: string,
  310. args: string[],
  311. _options: unknown,
  312. callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void,
  313. ) => {
  314. const shellCommand = args.at(-1) ?? "";
  315. const stdout = shellCommand.includes("/dev/tcp/")
  316. ? "reachable"
  317. : "Ubuntu-24.04\ntester\n/home/tester";
  318. const child = new EventEmitter();
  319. queueMicrotask(() => {
  320. callback(null, Buffer.from(stdout), Buffer.alloc(0));
  321. child.emit("close", 0);
  322. });
  323. return child as never;
  324. },
  325. );
  326. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  327. await expect(backend.resolveRuntimeProxy("http://localhost:7890")).resolves.toBe(
  328. "http://localhost:7890/",
  329. );
  330. });
  331. it("非 loopback 代理和代理认证信息保持不变", async () => {
  332. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  333. await expect(
  334. backend.resolveRuntimeProxy("http://user:pass@proxy.example.com:7890/path"),
  335. ).resolves.toBe("http://user:pass@proxy.example.com:7890/path");
  336. expect(mocks.execFile).not.toHaveBeenCalled();
  337. });
  338. it("WSL 网关探测无法确认端口时保留 loopback 配置", async () => {
  339. mocks.execFile.mockImplementation(
  340. (
  341. _command: string,
  342. args: string[],
  343. _options: unknown,
  344. callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void,
  345. ) => {
  346. const shellCommand = args.at(-1) ?? "";
  347. const stdout = shellCommand.includes("/dev/tcp/")
  348. ? "unreachable"
  349. : shellCommand.includes("ip route show default")
  350. ? "route=172.21.240.1"
  351. : "Ubuntu-24.04\ntester\n/home/tester";
  352. const child = new EventEmitter();
  353. queueMicrotask(() => {
  354. callback(null, Buffer.from(stdout), Buffer.alloc(0));
  355. child.emit("close", 0);
  356. });
  357. return child as never;
  358. },
  359. );
  360. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  361. await expect(backend.resolveRuntimeProxy("http://127.0.0.1:7890")).resolves.toBe(
  362. "http://127.0.0.1:7890/",
  363. );
  364. });
  365. it("systemd-resolved 的 loopback stub 不会阻断 resolv.conf 回退", async () => {
  366. mocks.execFile.mockImplementation(
  367. (
  368. _command: string,
  369. args: string[],
  370. _options: unknown,
  371. callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void,
  372. ) => {
  373. const shellCommand = args.at(-1) ?? "";
  374. const stdout = shellCommand.includes("/dev/tcp/172.21.240.1/")
  375. ? "reachable"
  376. : shellCommand.includes("/dev/tcp/")
  377. ? "unreachable"
  378. : shellCommand.includes("ip route show default")
  379. ? "resolv=127.0.0.53 resolv=172.21.240.1"
  380. : "Ubuntu-24.04\ntester\n/home/tester";
  381. const child = new EventEmitter();
  382. queueMicrotask(() => {
  383. callback(null, Buffer.from(stdout), Buffer.alloc(0));
  384. child.emit("close", 0);
  385. });
  386. return child as never;
  387. },
  388. );
  389. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  390. await expect(backend.resolveRuntimeProxy("http://127.0.0.1:7890")).resolves.toBe(
  391. "http://172.21.240.1:7890/",
  392. );
  393. });
  394. it("自定义公网 DNS 不会被当成宿主网关探测", async () => {
  395. mocks.execFile.mockImplementation(
  396. (
  397. _command: string,
  398. args: string[],
  399. _options: unknown,
  400. callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void,
  401. ) => {
  402. const shellCommand = args.at(-1) ?? "";
  403. const stdout = shellCommand.includes("/dev/tcp/")
  404. ? "unreachable"
  405. : shellCommand.includes("ip route show default")
  406. ? "resolv=8.8.8.8"
  407. : "Ubuntu-24.04\ntester\n/home/tester";
  408. const child = new EventEmitter();
  409. queueMicrotask(() => {
  410. callback(null, Buffer.from(stdout), Buffer.alloc(0));
  411. child.emit("close", 0);
  412. });
  413. return child as never;
  414. },
  415. );
  416. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  417. await expect(backend.resolveRuntimeProxy("http://127.0.0.1:7890")).resolves.toBe(
  418. "http://127.0.0.1:7890/",
  419. );
  420. expect(
  421. mocks.execFile.mock.calls.some((call) =>
  422. (call[1] as string[]).at(-1)?.includes("/dev/tcp/8.8.8.8/"),
  423. ),
  424. ).toBe(false);
  425. });
  426. it("带 progress 选项时走 wsl exec pipe 并上报字节", async () => {
  427. const tempDir = await mkdtemp(join(tmpdir(), "wsl-upload-progress-"));
  428. const localPath = join(tempDir, "attachment.bin");
  429. await writeFile(localPath, Buffer.alloc(80 * 1024, "a"));
  430. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  431. const progress: Array<{ uploadedBytes: number; totalBytes: number }> = [];
  432. await backend.upload(localPath, "~/.zcode/tmp/attachment.bin", {
  433. onProgress: (event) => progress.push(event),
  434. });
  435. expect(mocks.spawn).toHaveBeenCalledWith(
  436. "wsl.exe",
  437. [
  438. "-d",
  439. "Ubuntu-24.04",
  440. "-u",
  441. "tester",
  442. "--exec",
  443. "bash",
  444. "-lc",
  445. "mkdir -p '/home/tester/.zcode/tmp' && cat > '/home/tester/.zcode/tmp/attachment.bin'",
  446. ],
  447. expect.any(Object),
  448. );
  449. expect(progress.at(-1)).toEqual({
  450. uploadedBytes: 80 * 1024,
  451. totalBytes: 80 * 1024,
  452. });
  453. });
  454. it("预取消 signal 不启动上传进程", async () => {
  455. const tempDir = await mkdtemp(join(tmpdir(), "wsl-upload-abort-"));
  456. const localPath = join(tempDir, "attachment.bin");
  457. await writeFile(localPath, "attachment");
  458. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  459. const controller = new AbortController();
  460. controller.abort();
  461. await expect(
  462. backend.upload(localPath, "~/.zcode/tmp/attachment.bin", {
  463. signal: controller.signal,
  464. }),
  465. ).rejects.toMatchObject({ name: "AbortError" });
  466. expect(mocks.spawn).not.toHaveBeenCalled();
  467. });
  468. });