installer-process-helper.test.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. import assert from "node:assert/strict";
  2. import { spawn } from "node:child_process";
  3. import { randomUUID } from "node:crypto";
  4. import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
  5. import { tmpdir } from "node:os";
  6. import { join, resolve } from "node:path";
  7. import { test } from "node:test";
  8. import { resolveRuntimeHostBuild, verifyRuntimeHostPe } from "../build-windows-runtime-host.mjs";
  9. const source = resolve(import.meta.dirname, "../windows-runtime-host");
  10. const logName = "ZCode-process-cleanup.log";
  11. const sentinel = "existing log must survive\r\n";
  12. function launch(executable, args, options = {}) {
  13. const child = spawn(executable, args, {
  14. shell: false,
  15. windowsHide: true,
  16. stdio: ["pipe", "pipe", "pipe"],
  17. timeout: 20000,
  18. ...options,
  19. });
  20. const running = { child, stdout: "", stderr: "" };
  21. child.stdout.setEncoding("utf8").on("data", (chunk) => (running.stdout += chunk));
  22. child.stderr.setEncoding("utf8").on("data", (chunk) => (running.stderr += chunk));
  23. // helper 可以先终止目标;随后关闭 stdin 时的 EPIPE 不能成为未处理异常。
  24. child.stdin.on("error", () => {});
  25. let spawnError;
  26. child.once("error", (error) => (spawnError = error));
  27. running.closed = new Promise((resolveClose) => {
  28. child.once("close", (code, signal) => resolveClose({ code, signal, error: spawnError }));
  29. });
  30. return running;
  31. }
  32. function diagnostic(running) {
  33. return `stdout:\n${running.stdout}\nstderr:\n${running.stderr}`;
  34. }
  35. async function expectExit(running, code) {
  36. const result = await running.closed;
  37. assert.ifError(result.error);
  38. assert.equal(result.signal, null, diagnostic(running));
  39. assert.equal(result.code, code, diagnostic(running));
  40. }
  41. function waitForOutput(running, pattern, from = 0) {
  42. return new Promise((resolveOutput, reject) => {
  43. const { child } = running;
  44. const cleanup = () => {
  45. clearTimeout(timer);
  46. child.stdout.off("data", check);
  47. child.off("close", ended);
  48. child.off("error", failed);
  49. };
  50. const failed = (error) => {
  51. cleanup();
  52. reject(error);
  53. };
  54. const check = () => {
  55. const match = running.stdout.slice(from).match(pattern);
  56. if (match) {
  57. cleanup();
  58. resolveOutput(match);
  59. }
  60. };
  61. const ended = () =>
  62. failed(new Error(`Fixture exited before ${pattern}: ${diagnostic(running)}`));
  63. // 此超时只限制失败用例,不用作进程就绪或状态同步。
  64. const timer = setTimeout(
  65. () => failed(new Error(`Fixture did not report ${pattern}: ${diagnostic(running)}`)),
  66. 5000,
  67. );
  68. child.stdout.on("data", check);
  69. child.once("close", ended);
  70. child.once("error", failed);
  71. check();
  72. if (child.exitCode !== null || child.signalCode !== null) ended();
  73. });
  74. }
  75. async function startFixture(t, executable, args) {
  76. const running = launch(executable, args);
  77. t.after(async () => {
  78. // ACL 可以拒绝新申请的终止句柄;用已建立的 stdin 通道回收夹具。
  79. running.child.stdin.write("q");
  80. running.child.stdin.end();
  81. await expectExit(running, 0);
  82. });
  83. const ready = await waitForOutput(running, /ready pid=(\d+)[^\r\n]*\r?\n/);
  84. assert.equal(Number(ready[1]), running.child.pid);
  85. return running;
  86. }
  87. async function expectAlive(running) {
  88. const from = running.stdout.length;
  89. const alive = waitForOutput(running, new RegExp(`alive pid=${running.child.pid}\\r?\\n`), from);
  90. running.child.stdin.write("p");
  91. await alive;
  92. assert.equal(running.child.exitCode, null, diagnostic(running));
  93. }
  94. function expectStage(running, stage, pid, error = 0) {
  95. assert.match(
  96. running.stdout,
  97. new RegExp(`(?:^|\\n)stage=${stage} pid=${pid} win32-error=${error}\\r?\\n`),
  98. diagnostic(running),
  99. );
  100. }
  101. test("CR03: process cleanup has no script compiler or shell launch dependency", async () => {
  102. const helper = await readFile(join(source, "installer-process-helper.cpp"), "utf8");
  103. assert.doesNotMatch(helper, /powershell|pwsh|Add-Type|\.ps1\b/i);
  104. assert.doesNotMatch(helper, /\b(?:CreateProcess\w*|ShellExecute\w*|WinExec|system|_popen)\s*\(/);
  105. });
  106. test(
  107. "Windows native installer process helper",
  108. { skip: process.platform !== "win32", timeout: 180000 },
  109. async (t) => {
  110. const work = await mkdtemp(join(tmpdir(), "installer-process-test-"));
  111. t.after(() => rm(work, { recursive: true, force: true, maxRetries: 3 }));
  112. const build = join(work, "build");
  113. const arch = process.arch;
  114. const plan = resolveRuntimeHostBuild(arch);
  115. for (const args of [
  116. ["-S", source, "-B", build, ...plan.configureArgs, "-DCMAKE_BUILD_TYPE=Release"],
  117. [
  118. "--build",
  119. build,
  120. "--config",
  121. "Release",
  122. "--target",
  123. "zcode-installer-process-helper",
  124. "zcode-installer-process-fixture",
  125. ],
  126. ]) {
  127. const cmake = launch(process.env.CMAKE || "cmake", args, { timeout: 120000 });
  128. cmake.child.stdin.end();
  129. await expectExit(cmake, 0);
  130. }
  131. const helper = join(build, "Release/zcode-installer-process-helper.exe");
  132. const fixture = join(build, "Release/zcode-installer-process-fixture.exe");
  133. for (const executable of [helper, fixture]) {
  134. verifyRuntimeHostPe(await readFile(executable), arch);
  135. }
  136. const emptyPath = join(work, "empty-path");
  137. await mkdir(emptyPath);
  138. const baseEnvironment = Object.fromEntries(
  139. Object.entries(process.env).filter(([key]) => !/^(?:path|temp|tmp)$/i.test(key)),
  140. );
  141. async function scenario(t) {
  142. const directory = await mkdtemp(join(work, "case-"));
  143. const targetDir = join(directory, "target install");
  144. const otherDir = join(directory, "other install");
  145. const temp = join(directory, "helper temp");
  146. await Promise.all([targetDir, otherDir, temp].map((path) => mkdir(path)));
  147. // 每例使用唯一 basename,绝不按真实产品进程名执行清理。
  148. const basename = `installer-test-${randomUUID()}.exe`;
  149. const target = join(targetDir, basename);
  150. const other = join(otherDir, basename);
  151. await Promise.all([target, other].map((path) => copyFile(fixture, path)));
  152. const log = join(temp, logName);
  153. await writeFile(log, sentinel);
  154. return {
  155. target,
  156. other,
  157. log,
  158. start: (executable, mode) => startFixture(t, executable, [mode]),
  159. run: async () => {
  160. assert.deepEqual(await readdir(emptyPath), []);
  161. // CR03:原生 helper 以绝对路径启动;PATH 和 cwd 均指向空目录。
  162. const running = launch(helper, [target], {
  163. cwd: emptyPath,
  164. env: { ...baseEnvironment, PATH: emptyPath, TEMP: temp, TMP: temp },
  165. });
  166. running.child.stdin.end();
  167. await running.closed;
  168. return running;
  169. },
  170. };
  171. }
  172. await t.test("CR03: empty PATH succeeds when no target is running", async (t) => {
  173. const context = await scenario(t);
  174. const result = await context.run();
  175. await expectExit(result, 0);
  176. expectStage(result, "stop-completed", 0);
  177. });
  178. await t.test("other-path same-name process denies terminate but permits query", async (t) => {
  179. const context = await scenario(t);
  180. const other = await context.start(context.other, "--restricted");
  181. assert.match(other.stdout, /terminate-open-error=5 query-open-error=0/);
  182. const result = await context.run();
  183. await expectExit(result, 0);
  184. expectStage(result, "stop-completed", 0);
  185. assert.doesNotMatch(result.stdout, new RegExp(`pid=${other.child.pid}\\b`));
  186. await expectAlive(other);
  187. });
  188. await t.test(
  189. "normal target terminates while the restricted other-path process survives",
  190. async (t) => {
  191. const context = await scenario(t);
  192. const other = await context.start(context.other, "--restricted");
  193. const target = await context.start(context.target, "--normal");
  194. const result = await context.run();
  195. await expectExit(result, 0);
  196. expectStage(result, "matched", target.child.pid);
  197. expectStage(result, "exited", target.child.pid);
  198. expectStage(result, "stop-completed", 0);
  199. await expectExit(target, 0);
  200. await expectAlive(other);
  201. const log = await readFile(context.log, "utf8");
  202. assert.ok(log.startsWith(sentinel));
  203. assert.ok(log.endsWith(result.stdout.replace(/\r\n/g, "\n")));
  204. },
  205. );
  206. for (const [mode, stage] of [
  207. ["--restricted", "terminate-open-failed"],
  208. ["--deny-query", "query-open-failed"],
  209. ]) {
  210. await t.test(`target ${mode} returns 2 with real ERROR_ACCESS_DENIED`, async (t) => {
  211. const context = await scenario(t);
  212. const target = await context.start(context.target, mode);
  213. assert.match(target.stdout, /terminate-open-error=5/);
  214. assert.match(
  215. target.stdout,
  216. new RegExp(`query-open-error=${mode === "--deny-query" ? 5 : 0}`),
  217. );
  218. const result = await context.run();
  219. await expectExit(result, 2);
  220. expectStage(result, stage, target.child.pid, 5);
  221. assert.doesNotMatch(result.stdout, /stage=stop-completed/);
  222. await expectAlive(target);
  223. });
  224. }
  225. for (const [mode, openError, writeError] of [
  226. ["--log-readonly", 5, 0],
  227. ["--log-exclusive", 32, 0],
  228. ["--log-append-failure", 0, 33],
  229. ]) {
  230. for (const restricted of [false, true]) {
  231. await t.test(
  232. `${mode} preserves ${restricted ? "failure (2)" : "success (0)"}`,
  233. async (t) => {
  234. const context = await scenario(t);
  235. const holder = await startFixture(t, fixture, [mode, context.log]);
  236. // 夹具使用与 helper 相同的打开和追加参数,证明真实 Win32 故障已生效。
  237. assert.match(
  238. holder.stdout,
  239. new RegExp(`log-open-error=${openError} log-write-error=${writeError}`),
  240. );
  241. const target = await context.start(
  242. context.target,
  243. restricted ? "--restricted" : "--normal",
  244. );
  245. const result = await context.run();
  246. await expectExit(result, restricted ? 2 : 0);
  247. if (restricted) {
  248. expectStage(result, "terminate-open-failed", target.child.pid, 5);
  249. assert.doesNotMatch(result.stdout, /stage=stop-completed/);
  250. await expectAlive(target);
  251. } else {
  252. expectStage(result, "matched", target.child.pid);
  253. expectStage(result, "exited", target.child.pid);
  254. expectStage(result, "stop-completed", 0);
  255. await expectExit(target, 0);
  256. }
  257. await expectAlive(holder);
  258. holder.child.stdin.write("q");
  259. holder.child.stdin.end();
  260. await expectExit(holder, 0);
  261. assert.equal(await readFile(context.log, "utf8"), sentinel);
  262. },
  263. );
  264. }
  265. }
  266. assert.deepEqual(await readdir(emptyPath), []);
  267. },
  268. );