wslBackend.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. "--",
  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. "--",
  252. "bash",
  253. "-lc",
  254. "pwd",
  255. ]);
  256. });
  257. it("WSL NAT 下把不可达的 loopback 代理转换为宿主网关地址", async () => {
  258. mocks.execFile.mockImplementation(
  259. (
  260. _command: string,
  261. args: string[],
  262. _options: unknown,
  263. callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void,
  264. ) => {
  265. const shellCommand = args.at(-1) ?? "";
  266. const stdout = shellCommand.includes("/dev/tcp/172.21.240.1/")
  267. ? "reachable"
  268. : shellCommand.includes("/dev/tcp/")
  269. ? "unreachable"
  270. : shellCommand.includes("ip route show default")
  271. ? "route=172.21.240.1"
  272. : "Ubuntu-24.04\ntester\n/home/tester";
  273. const child = new EventEmitter();
  274. queueMicrotask(() => {
  275. callback(null, Buffer.from(stdout), Buffer.alloc(0));
  276. child.emit("close", 0);
  277. });
  278. return child as never;
  279. },
  280. );
  281. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  282. await expect(backend.resolveRuntimeProxy("http://127.0.0.1:7890")).resolves.toBe(
  283. "http://172.21.240.1:7890/",
  284. );
  285. });
  286. it("WSL mirrored 或代理可达时保留 loopback 代理地址", async () => {
  287. mocks.execFile.mockImplementation(
  288. (
  289. _command: string,
  290. args: string[],
  291. _options: unknown,
  292. callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void,
  293. ) => {
  294. const shellCommand = args.at(-1) ?? "";
  295. const stdout = shellCommand.includes("/dev/tcp/")
  296. ? "reachable"
  297. : "Ubuntu-24.04\ntester\n/home/tester";
  298. const child = new EventEmitter();
  299. queueMicrotask(() => {
  300. callback(null, Buffer.from(stdout), Buffer.alloc(0));
  301. child.emit("close", 0);
  302. });
  303. return child as never;
  304. },
  305. );
  306. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  307. await expect(backend.resolveRuntimeProxy("http://localhost:7890")).resolves.toBe(
  308. "http://localhost:7890/",
  309. );
  310. });
  311. it("非 loopback 代理和代理认证信息保持不变", async () => {
  312. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  313. await expect(
  314. backend.resolveRuntimeProxy("http://user:pass@proxy.example.com:7890/path"),
  315. ).resolves.toBe("http://user:pass@proxy.example.com:7890/path");
  316. expect(mocks.execFile).not.toHaveBeenCalled();
  317. });
  318. it("WSL 网关探测无法确认端口时保留 loopback 配置", async () => {
  319. mocks.execFile.mockImplementation(
  320. (
  321. _command: string,
  322. args: string[],
  323. _options: unknown,
  324. callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void,
  325. ) => {
  326. const shellCommand = args.at(-1) ?? "";
  327. const stdout = shellCommand.includes("/dev/tcp/")
  328. ? "unreachable"
  329. : shellCommand.includes("ip route show default")
  330. ? "route=172.21.240.1"
  331. : "Ubuntu-24.04\ntester\n/home/tester";
  332. const child = new EventEmitter();
  333. queueMicrotask(() => {
  334. callback(null, Buffer.from(stdout), Buffer.alloc(0));
  335. child.emit("close", 0);
  336. });
  337. return child as never;
  338. },
  339. );
  340. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  341. await expect(backend.resolveRuntimeProxy("http://127.0.0.1:7890")).resolves.toBe(
  342. "http://127.0.0.1:7890/",
  343. );
  344. });
  345. it("systemd-resolved 的 loopback stub 不会阻断 resolv.conf 回退", async () => {
  346. mocks.execFile.mockImplementation(
  347. (
  348. _command: string,
  349. args: string[],
  350. _options: unknown,
  351. callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void,
  352. ) => {
  353. const shellCommand = args.at(-1) ?? "";
  354. const stdout = shellCommand.includes("/dev/tcp/172.21.240.1/")
  355. ? "reachable"
  356. : shellCommand.includes("/dev/tcp/")
  357. ? "unreachable"
  358. : shellCommand.includes("ip route show default")
  359. ? "resolv=127.0.0.53 resolv=172.21.240.1"
  360. : "Ubuntu-24.04\ntester\n/home/tester";
  361. const child = new EventEmitter();
  362. queueMicrotask(() => {
  363. callback(null, Buffer.from(stdout), Buffer.alloc(0));
  364. child.emit("close", 0);
  365. });
  366. return child as never;
  367. },
  368. );
  369. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  370. await expect(backend.resolveRuntimeProxy("http://127.0.0.1:7890")).resolves.toBe(
  371. "http://172.21.240.1:7890/",
  372. );
  373. });
  374. it("自定义公网 DNS 不会被当成宿主网关探测", async () => {
  375. mocks.execFile.mockImplementation(
  376. (
  377. _command: string,
  378. args: string[],
  379. _options: unknown,
  380. callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void,
  381. ) => {
  382. const shellCommand = args.at(-1) ?? "";
  383. const stdout = shellCommand.includes("/dev/tcp/")
  384. ? "unreachable"
  385. : shellCommand.includes("ip route show default")
  386. ? "resolv=8.8.8.8"
  387. : "Ubuntu-24.04\ntester\n/home/tester";
  388. const child = new EventEmitter();
  389. queueMicrotask(() => {
  390. callback(null, Buffer.from(stdout), Buffer.alloc(0));
  391. child.emit("close", 0);
  392. });
  393. return child as never;
  394. },
  395. );
  396. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  397. await expect(backend.resolveRuntimeProxy("http://127.0.0.1:7890")).resolves.toBe(
  398. "http://127.0.0.1:7890/",
  399. );
  400. expect(
  401. mocks.execFile.mock.calls.some((call) =>
  402. (call[1] as string[]).at(-1)?.includes("/dev/tcp/8.8.8.8/"),
  403. ),
  404. ).toBe(false);
  405. });
  406. it("带 progress 选项时走 wsl exec pipe 并上报字节", async () => {
  407. const tempDir = await mkdtemp(join(tmpdir(), "wsl-upload-progress-"));
  408. const localPath = join(tempDir, "attachment.bin");
  409. await writeFile(localPath, Buffer.alloc(80 * 1024, "a"));
  410. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  411. const progress: Array<{ uploadedBytes: number; totalBytes: number }> = [];
  412. await backend.upload(localPath, "~/.zcode/tmp/attachment.bin", {
  413. onProgress: (event) => progress.push(event),
  414. });
  415. expect(mocks.spawn).toHaveBeenCalledWith(
  416. "wsl.exe",
  417. [
  418. "-d",
  419. "Ubuntu-24.04",
  420. "-u",
  421. "tester",
  422. "--",
  423. "bash",
  424. "-lc",
  425. "mkdir -p '/home/tester/.zcode/tmp' && cat > '/home/tester/.zcode/tmp/attachment.bin'",
  426. ],
  427. expect.any(Object),
  428. );
  429. expect(progress.at(-1)).toEqual({
  430. uploadedBytes: 80 * 1024,
  431. totalBytes: 80 * 1024,
  432. });
  433. });
  434. it("预取消 signal 不启动上传进程", async () => {
  435. const tempDir = await mkdtemp(join(tmpdir(), "wsl-upload-abort-"));
  436. const localPath = join(tempDir, "attachment.bin");
  437. await writeFile(localPath, "attachment");
  438. const backend = new WSLBackend({ kind: "wsl", distro: "Ubuntu-24.04" });
  439. const controller = new AbortController();
  440. controller.abort();
  441. await expect(
  442. backend.upload(localPath, "~/.zcode/tmp/attachment.bin", {
  443. signal: controller.signal,
  444. }),
  445. ).rejects.toMatchObject({ name: "AbortError" });
  446. expect(mocks.spawn).not.toHaveBeenCalled();
  447. });
  448. });