runtimeCommandEnv.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { delimiter, dirname, join } from "node:path";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import {
  6. ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY,
  7. readZCodeToolEnvPassthroughEnv,
  8. } from "@zcode/shared";
  9. import {
  10. buildLoginShellEnvPatch,
  11. buildRuntimeProcessEnvPatch,
  12. captureLoginShellEnvSnapshot,
  13. normalizeRuntimeProcessEnv,
  14. prepareRuntimeProcessEnvPatch,
  15. } from "../src/runtime-tools/runtimeCommandEnv.js";
  16. const originalVitest = process.env.VITEST;
  17. describe("runtimeCommandEnv", () => {
  18. afterEach(() => {
  19. vi.useRealTimers();
  20. if (originalVitest == null) {
  21. delete process.env.VITEST;
  22. } else {
  23. process.env.VITEST = originalVitest;
  24. }
  25. });
  26. it("seals user network env before host runtime sanitization", () => {
  27. process.env.VITEST = "1";
  28. const patch = buildRuntimeProcessEnvPatch({
  29. HTTP_PROXY: "http://shell-proxy:8080",
  30. NODE_ENV: "development",
  31. NODE_EXTRA_CA_CERTS: "/tmp/shell-ca.pem",
  32. PATH: "/usr/bin:/bin",
  33. npm_config_proxy: "http://npm-proxy:8080",
  34. });
  35. expect(patch.HTTP_PROXY).toBeUndefined();
  36. expect(patch.NODE_ENV).toBeUndefined();
  37. expect(patch.NODE_EXTRA_CA_CERTS).toBeUndefined();
  38. expect(patch[ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]).toBeDefined();
  39. expect(readZCodeToolEnvPassthroughEnv(patch)).toMatchObject({
  40. HTTP_PROXY: "http://shell-proxy:8080",
  41. NODE_EXTRA_CA_CERTS: "/tmp/shell-ca.pem",
  42. npm_config_proxy: "http://npm-proxy:8080",
  43. });
  44. });
  45. it("keeps POSIX bootstrap paths when login shell capture is unavailable", () => {
  46. process.env.VITEST = "1";
  47. const patch = buildRuntimeProcessEnvPatch({
  48. PATH: "/usr/bin:/bin",
  49. });
  50. const pathEntries = patch.PATH?.split(":") ?? [];
  51. if (process.platform === "darwin") {
  52. expect(pathEntries).toContain("/opt/homebrew/bin");
  53. expect(pathEntries).toContain("/usr/local/bin");
  54. } else if (process.platform !== "win32") {
  55. expect(pathEntries).toContain("/usr/local/bin");
  56. expect(pathEntries).toContain("/usr/local/sbin");
  57. }
  58. });
  59. it("keeps user commands ahead of bundled runtime tools on PATH", () => {
  60. process.env.VITEST = "1";
  61. const root = mkdtempSync(join(tmpdir(), "zcode-runtime-tool-path-order-"));
  62. const systemBin = join(root, "system-bin");
  63. const binarySuffix = process.platform === "win32" ? ".exe" : "";
  64. const runtimeBinaries = {
  65. ZCODE_BFS_BINARY: join(root, "runtime", "bfs", `bfs${binarySuffix}`),
  66. ZCODE_RG_BINARY: join(root, "runtime", "ripgrep", `rg${binarySuffix}`),
  67. ZCODE_UGREP_BINARY: join(root, "runtime", "ugrep", `ugrep${binarySuffix}`),
  68. } as const;
  69. try {
  70. mkdirSync(systemBin, { recursive: true });
  71. for (const binaryPath of Object.values(runtimeBinaries)) {
  72. mkdirSync(dirname(binaryPath), { recursive: true });
  73. writeFileSync(binaryPath, "runtime tool\n");
  74. if (process.platform !== "win32") chmodSync(binaryPath, 0o755);
  75. }
  76. const patch = buildRuntimeProcessEnvPatch({
  77. PATH: systemBin,
  78. ...runtimeBinaries,
  79. });
  80. const pathEntries = patch.PATH?.split(delimiter) ?? [];
  81. const systemIndex = pathEntries.indexOf(systemBin);
  82. expect(systemIndex).toBeGreaterThanOrEqual(0);
  83. for (const binaryPath of Object.values(runtimeBinaries)) {
  84. expect(pathEntries.indexOf(dirname(binaryPath))).toBeGreaterThan(systemIndex);
  85. }
  86. } finally {
  87. rmSync(root, { recursive: true, force: true });
  88. }
  89. });
  90. it("normalizes Windows Path casing before building the runtime patch", () => {
  91. const userPath = "C:\\Users\\demo\\bin;C:\\Program Files\\Git\\cmd;C:\\Windows\\System32";
  92. const normalized = normalizeRuntimeProcessEnv(
  93. {
  94. PATH: "C:\\dotenv-only-bin",
  95. Path: userPath,
  96. },
  97. "win32",
  98. );
  99. const patch = buildRuntimeProcessEnvPatch(normalized, null, {
  100. platform: "win32",
  101. windowsNodePaths: [],
  102. });
  103. expect(normalized).toEqual({ PATH: userPath });
  104. expect(patch.PATH).toEqual(expect.stringMatching(/^C:\\Users\\demo\\bin;/));
  105. expect(patch.PATH).toContain("C:\\Program Files\\Git\\cmd");
  106. expect(Object.keys(patch).filter((key) => key.toUpperCase() === "PATH")).toEqual(["PATH"]);
  107. });
  108. it("inherits login shell env required by cd hook based version managers", () => {
  109. const patch = buildLoginShellEnvPatch({
  110. AUTOENV_ENV_FILENAME: ".env",
  111. CHRUBY_ROOT: "/opt/chruby",
  112. DIRENV_CONFIG: "/Users/dev/.config/direnv",
  113. FNM_DIR: "/Users/dev/.fnm",
  114. FNM_MULTISHELL_PATH: "/tmp/fnm-shell",
  115. GEM_HOME: "/Users/dev/.gem/ruby/3.4.0",
  116. GEM_PATH: "/Users/dev/.gem/ruby/3.4.0:/opt/ruby/gems",
  117. GOENV_ROOT: "/Users/dev/.goenv",
  118. GVM_ROOT: "/Users/dev/.gvm",
  119. HTTP_PROXY: "http://shell-proxy:8080",
  120. JENV_ROOT: "/Users/dev/.jenv",
  121. MISE_DATA_DIR: "/Users/dev/.local/share/mise",
  122. MY_RUBY_HOME: "/Users/dev/.rvm/rubies/ruby-3.4.0",
  123. NODE_OPTIONS: "--openssl-legacy-provider",
  124. NODENV_ROOT: "/Users/dev/.nodenv",
  125. NVM_CD_FLAGS: "-q",
  126. PYENV_VERSION: "project-env",
  127. PYENV_VIRTUALENV_DISABLE_PROMPT: "1",
  128. RBENV_ROOT: "/Users/dev/.rbenv",
  129. RUBIES: "/opt/rubies",
  130. SDKMAN_CANDIDATES_DIR: "/Users/dev/.sdkman/candidates",
  131. SDKMAN_PLATFORM: "darwinarm64",
  132. gvm_go_name: "go1.22",
  133. rvm_path: "/Users/dev/.rvm",
  134. rvm_prefix: "/Users/dev",
  135. });
  136. expect(patch).toMatchObject({
  137. AUTOENV_ENV_FILENAME: ".env",
  138. CHRUBY_ROOT: "/opt/chruby",
  139. DIRENV_CONFIG: "/Users/dev/.config/direnv",
  140. FNM_DIR: "/Users/dev/.fnm",
  141. FNM_MULTISHELL_PATH: "/tmp/fnm-shell",
  142. GEM_HOME: "/Users/dev/.gem/ruby/3.4.0",
  143. GEM_PATH: "/Users/dev/.gem/ruby/3.4.0:/opt/ruby/gems",
  144. GOENV_ROOT: "/Users/dev/.goenv",
  145. GVM_ROOT: "/Users/dev/.gvm",
  146. JENV_ROOT: "/Users/dev/.jenv",
  147. MISE_DATA_DIR: "/Users/dev/.local/share/mise",
  148. MY_RUBY_HOME: "/Users/dev/.rvm/rubies/ruby-3.4.0",
  149. NODENV_ROOT: "/Users/dev/.nodenv",
  150. NVM_CD_FLAGS: "-q",
  151. PYENV_VERSION: "project-env",
  152. PYENV_VIRTUALENV_DISABLE_PROMPT: "1",
  153. RBENV_ROOT: "/Users/dev/.rbenv",
  154. RUBIES: "/opt/rubies",
  155. SDKMAN_CANDIDATES_DIR: "/Users/dev/.sdkman/candidates",
  156. SDKMAN_PLATFORM: "darwinarm64",
  157. gvm_go_name: "go1.22",
  158. rvm_path: "/Users/dev/.rvm",
  159. rvm_prefix: "/Users/dev",
  160. });
  161. expect(patch.HTTP_PROXY).toBeUndefined();
  162. expect(patch.NODE_OPTIONS).toBeUndefined();
  163. const passthrough = readZCodeToolEnvPassthroughEnv(patch);
  164. expect(passthrough).toMatchObject({
  165. HTTP_PROXY: "http://shell-proxy:8080",
  166. });
  167. expect(passthrough.NODE_OPTIONS).toBeUndefined();
  168. });
  169. it("captures PATH and inherited fields with one asynchronous login shell call", async () => {
  170. const executeShell = vi.fn(async () =>
  171. [
  172. "shell startup chatter",
  173. "__ZCODE_LOGIN_ENV_START__\0",
  174. "PATH=/Users/dev/.local/bin:/usr/bin:/bin\0",
  175. "FNM_DIR=/Users/dev/.fnm\0",
  176. "HTTP_PROXY=http://shell-proxy:8080\0",
  177. "__ZCODE_LOGIN_ENV_END__\0",
  178. ].join(""),
  179. );
  180. const snapshot = await captureLoginShellEnvSnapshot({
  181. baseEnv: { PATH: "/usr/bin:/bin" },
  182. platform: "darwin",
  183. shellPath: "/bin/zsh",
  184. executeShell,
  185. });
  186. expect(executeShell).toHaveBeenCalledTimes(1);
  187. expect(executeShell).toHaveBeenCalledWith(
  188. "/bin/zsh",
  189. ["-ilc", expect.stringContaining("env -0")],
  190. expect.objectContaining({
  191. env: expect.objectContaining({ PATH: expect.stringContaining("/usr/bin") }),
  192. }),
  193. );
  194. expect(snapshot).toEqual({
  195. PATH: "/Users/dev/.local/bin:/usr/bin:/bin",
  196. FNM_DIR: "/Users/dev/.fnm",
  197. HTTP_PROXY: "http://shell-proxy:8080",
  198. });
  199. });
  200. it("settles login shell capture at the hard deadline even when the executor never settles", async () => {
  201. vi.useFakeTimers();
  202. let executionSignal: AbortSignal | undefined;
  203. const snapshotPromise = captureLoginShellEnvSnapshot({
  204. baseEnv: { PATH: "/usr/bin:/bin" },
  205. platform: "darwin",
  206. shellPath: "/bin/zsh",
  207. timeoutMs: 25,
  208. executeShell: (_shellPath, _shellArgs, options) => {
  209. executionSignal = options.signal;
  210. return new Promise(() => {});
  211. },
  212. });
  213. await vi.advanceTimersByTimeAsync(25);
  214. await expect(snapshotPromise).resolves.toBeNull();
  215. expect(executionSignal?.aborted).toBe(true);
  216. });
  217. it.runIf(process.platform !== "win32")(
  218. "kills the login-shell process group when a descendant keeps stdio open",
  219. async () => {
  220. const root = mkdtempSync(join(tmpdir(), "zcode-login-shell-deadline-"));
  221. const shellPath = join(root, "shell-with-background-child.sh");
  222. try {
  223. writeFileSync(
  224. shellPath,
  225. "#!/bin/sh\n(trap '' HUP TERM; sleep 30) &\nexec /bin/sh \"$@\"\n",
  226. );
  227. chmodSync(shellPath, 0o755);
  228. const startedAt = Date.now();
  229. const snapshot = await captureLoginShellEnvSnapshot({
  230. baseEnv: { PATH: "/usr/bin:/bin" },
  231. platform: process.platform,
  232. shellPath,
  233. timeoutMs: 100,
  234. });
  235. expect(snapshot).toBeNull();
  236. expect(Date.now() - startedAt).toBeLessThan(2_000);
  237. } finally {
  238. rmSync(root, { recursive: true, force: true });
  239. }
  240. },
  241. );
  242. it("builds the complete runtime patch from one precomputed snapshot", async () => {
  243. const captureSnapshot = vi.fn(async () => ({
  244. PATH: ["/Users/dev/.local/bin", "/usr/bin", "/bin"].join(delimiter),
  245. FNM_DIR: "/Users/dev/.fnm",
  246. HTTP_PROXY: "http://shell-proxy:8080",
  247. }));
  248. const patch = await prepareRuntimeProcessEnvPatch(
  249. { PATH: ["/usr/bin", "/bin"].join(delimiter) },
  250. { captureSnapshot },
  251. );
  252. expect(captureSnapshot).toHaveBeenCalledTimes(1);
  253. expect(patch.PATH?.split(delimiter)[0]).toBe("/Users/dev/.local/bin");
  254. expect(patch.FNM_DIR).toBe("/Users/dev/.fnm");
  255. expect(readZCodeToolEnvPassthroughEnv(patch)).toMatchObject({
  256. HTTP_PROXY: "http://shell-proxy:8080",
  257. });
  258. });
  259. });