dockerBackendDockerCommand.test.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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 { fileURLToPath } from "node:url";
  7. import { beforeEach, describe, expect, it, vi } from "vitest";
  8. const mocks = vi.hoisted(() => ({
  9. execFile: vi.fn(),
  10. isDockerAvailable: vi.fn(),
  11. listDockerContainers: vi.fn(),
  12. resolveDockerCommand: vi.fn(),
  13. spawn: vi.fn(),
  14. }));
  15. vi.mock("node:child_process", () => ({
  16. execFile: mocks.execFile,
  17. spawn: mocks.spawn,
  18. }));
  19. vi.mock("@zcode/server/remote/docker-detect.js", () => ({
  20. isDockerAvailable: mocks.isDockerAvailable,
  21. listDockerContainers: mocks.listDockerContainers,
  22. resolveDockerCommand: mocks.resolveDockerCommand,
  23. }));
  24. import { DockerBackend } from "@zcode/server/remote/docker-backend.js";
  25. const RESOLVED_DOCKER_COMMAND = "/resolved/bin/docker";
  26. function createBackend(): DockerBackend {
  27. return new DockerBackend({
  28. kind: "docker",
  29. container: "zcode-dev",
  30. });
  31. }
  32. function createSpawnChild() {
  33. const child = new EventEmitter() as EventEmitter & {
  34. stderr: PassThrough;
  35. stdin: PassThrough;
  36. stdout: PassThrough;
  37. };
  38. child.stdin = new PassThrough();
  39. child.stdout = new PassThrough();
  40. child.stderr = new PassThrough();
  41. queueMicrotask(() => child.emit("spawn"));
  42. return child;
  43. }
  44. function resolveDockerExecStdout(args: string[]): string {
  45. const shellCommand = args.at(-1) ?? "";
  46. if (shellCommand === "printf %s ~") {
  47. return "/root";
  48. }
  49. if (shellCommand === "uname -s") {
  50. return "Linux\n";
  51. }
  52. if (shellCommand === "uname -m") {
  53. return "arm64\n";
  54. }
  55. if (shellCommand.includes("ingress-token")) {
  56. return "test-ingress-token\n";
  57. }
  58. if (shellCommand.includes("/proc/sys/kernel/ostype")) {
  59. return "Linux\n";
  60. }
  61. return "";
  62. }
  63. describe("DockerBackend docker command resolution", () => {
  64. beforeEach(() => {
  65. mocks.execFile.mockReset();
  66. mocks.spawn.mockReset();
  67. mocks.isDockerAvailable.mockReset();
  68. mocks.listDockerContainers.mockReset();
  69. mocks.resolveDockerCommand.mockReset();
  70. mocks.resolveDockerCommand.mockReturnValue(RESOLVED_DOCKER_COMMAND);
  71. mocks.isDockerAvailable.mockResolvedValue(true);
  72. mocks.listDockerContainers.mockResolvedValue([
  73. {
  74. id: "abc123",
  75. image: "ubuntu:24.04",
  76. name: "zcode-dev",
  77. state: "running",
  78. status: "Up 2 minutes",
  79. },
  80. ]);
  81. mocks.execFile.mockImplementation(
  82. (
  83. _command: string,
  84. args: string[],
  85. _options: unknown,
  86. callback: (error: Error | null, stdout: string, stderr: string) => void,
  87. ) => {
  88. queueMicrotask(() => callback(null, resolveDockerExecStdout(args), ""));
  89. return {} as never;
  90. },
  91. );
  92. mocks.spawn.mockImplementation(() => createSpawnChild());
  93. });
  94. it.each(["", " ", "-it", "--privileged", "bad name", "bad/name", "bad\nname"])(
  95. "直接执行与 home 文件读取在调用 CLI 前拒绝非法容器引用 %j",
  96. async (container) => {
  97. const backend = new DockerBackend({ kind: "docker", container });
  98. await expect(backend.exec("printf ok")).rejects.toThrow("Invalid Docker container reference");
  99. await expect(backend.readFile("~/.zcode/ingress-token")).rejects.toThrow(
  100. "Invalid Docker container reference",
  101. );
  102. expect(mocks.spawn).not.toHaveBeenCalled();
  103. expect(mocks.execFile).not.toHaveBeenCalled();
  104. expect(mocks.listDockerContainers).not.toHaveBeenCalled();
  105. },
  106. );
  107. it.each(["dev_1.test-name", "a".repeat(64), "abc123", " zcode-dev "])(
  108. "直接路径接受名称和 ID 且不增加 CLI 往返:%j",
  109. async (container) => {
  110. const backend = new DockerBackend({ kind: "docker", container });
  111. await backend.exec("printf ok");
  112. await backend.readFile("~/.zcode/ingress-token");
  113. expect(mocks.spawn).toHaveBeenCalledOnce();
  114. expect(mocks.execFile).toHaveBeenCalledOnce();
  115. expect(mocks.spawn.mock.calls[0]![1][2]).toBe(container.trim());
  116. expect(mocks.execFile.mock.calls[0]![1][2]).toBe(container.trim());
  117. expect(mocks.listDockerContainers).not.toHaveBeenCalled();
  118. },
  119. );
  120. it("exec 链路中的 docker exec 使用解析后的 Docker CLI", async () => {
  121. const backend = createBackend();
  122. await backend.exec("printf ok");
  123. expect(mocks.execFile).not.toHaveBeenCalled();
  124. expect(mocks.spawn).toHaveBeenCalledWith(
  125. RESOLVED_DOCKER_COMMAND,
  126. ["exec", "-i", "zcode-dev", "sh", "-lc", "printf ok"],
  127. expect.any(Object),
  128. );
  129. await backend.exec("printf again");
  130. expect(mocks.isDockerAvailable).not.toHaveBeenCalled();
  131. expect(mocks.listDockerContainers).not.toHaveBeenCalled();
  132. });
  133. it("无进度上传也应由容器用户流式写入,避免 docker cp 文件所有权错配", async () => {
  134. mocks.spawn.mockImplementation(() => {
  135. const child = createSpawnChild();
  136. child.stdin.resume();
  137. child.stdin.on("finish", () => queueMicrotask(() => child.emit("close", 0)));
  138. return child;
  139. });
  140. const backend = createBackend();
  141. await backend.upload(fileURLToPath(import.meta.url), "~/.zcode/server/server.tgz");
  142. expect(mocks.spawn).toHaveBeenCalledWith(
  143. RESOLVED_DOCKER_COMMAND,
  144. ["exec", "-i", "zcode-dev", "sh", "-lc", "cat > '/root/.zcode/server/server.tgz'"],
  145. expect.any(Object),
  146. );
  147. expect(mocks.execFile.mock.calls.some((call) => (call[1] as string[])[0] === "cp")).toBe(false);
  148. expect(
  149. [...mocks.execFile.mock.calls, ...mocks.spawn.mock.calls].every(
  150. (call) => call[0] === RESOLVED_DOCKER_COMMAND,
  151. ),
  152. ).toBe(true);
  153. });
  154. it("流式上传失败时应保留容器 stderr 诊断", async () => {
  155. mocks.spawn.mockImplementation(() => {
  156. const child = createSpawnChild();
  157. child.stdin.resume();
  158. child.stdin.on("finish", () =>
  159. queueMicrotask(() => {
  160. child.stderr.write("cat: /root/file: Permission denied\n");
  161. child.stderr.end();
  162. child.emit("close", 1);
  163. }),
  164. );
  165. return child;
  166. });
  167. const backend = createBackend();
  168. await expect(backend.upload(fileURLToPath(import.meta.url), "/root/file")).rejects.toThrow(
  169. "Permission denied",
  170. );
  171. });
  172. it("直接读取 home 相对文件时不预跑 Docker 可用性、容器列表或 home 探测", async () => {
  173. const backend = createBackend();
  174. await expect(backend.readFile("~/.zcode/server/run/ingress-token")).resolves.toBe(
  175. "test-ingress-token\n",
  176. );
  177. expect(mocks.isDockerAvailable).not.toHaveBeenCalled();
  178. expect(mocks.listDockerContainers).not.toHaveBeenCalled();
  179. expect(mocks.execFile).toHaveBeenCalledTimes(1);
  180. expect(mocks.execFile).toHaveBeenCalledWith(
  181. RESOLVED_DOCKER_COMMAND,
  182. ["exec", "-i", "zcode-dev", "sh", "-lc", "cat \"$HOME\"/'.zcode/server/run/ingress-token'"],
  183. expect.any(Object),
  184. expect.any(Function),
  185. );
  186. });
  187. it("带 progress 选项时改走 exec 流式上传并上报字节", async () => {
  188. const tempDir = await mkdtemp(join(tmpdir(), "docker-upload-progress-"));
  189. const localPath = join(tempDir, "attachment.bin");
  190. await writeFile(localPath, Buffer.alloc(96 * 1024, "a"));
  191. mocks.spawn.mockImplementation(() => {
  192. const child = createSpawnChild();
  193. child.stdin.resume();
  194. child.stdin.on("finish", () => queueMicrotask(() => child.emit("close", 0)));
  195. return child;
  196. });
  197. const backend = createBackend();
  198. const progress: Array<{ uploadedBytes: number; totalBytes: number }> = [];
  199. await backend.upload(localPath, "~/.zcode/tmp/attachment.bin", {
  200. onProgress: (event) => progress.push(event),
  201. });
  202. expect(mocks.spawn).toHaveBeenCalledWith(
  203. RESOLVED_DOCKER_COMMAND,
  204. ["exec", "-i", "zcode-dev", "sh", "-lc", "cat > '/root/.zcode/tmp/attachment.bin'"],
  205. expect.any(Object),
  206. );
  207. expect(progress.at(-1)).toEqual({
  208. uploadedBytes: 96 * 1024,
  209. totalBytes: 96 * 1024,
  210. });
  211. });
  212. });