windowsChromeAppBoundKey.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  2. import { execFile } from "node:child_process";
  3. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { promisify } from "node:util";
  7. import { createEncodedPowerShellArgs } from "../scripts/powershell-command.mjs";
  8. vi.mock("electron", () => ({ app: { isPackaged: false } }));
  9. import {
  10. createSanitizedHelperEnvironment,
  11. readWindowsChromeAppBoundKey,
  12. WindowsChromeAppBoundImportError,
  13. } from "../src/main/windowsChromeAppBoundKey.js";
  14. const logger = { info: vi.fn(), warn: vi.fn() };
  15. const execFileAsync = promisify(execFile);
  16. let tempRoot = "";
  17. beforeEach(async () => {
  18. tempRoot = await mkdtemp(join(tmpdir(), "zcode-app-bound-test-"));
  19. vi.clearAllMocks();
  20. });
  21. afterEach(async () => {
  22. await rm(tempRoot, { recursive: true, force: true });
  23. });
  24. async function createFixture(): Promise<{ helperPath: string; userDataDir: string }> {
  25. const helperRoot = join(tempRoot, "browser-import");
  26. const helperPath = join(helperRoot, "zcode-browser-import-helper.exe");
  27. const userDataDir = join(tempRoot, "User Data");
  28. await mkdir(helperRoot, { recursive: true });
  29. await mkdir(userDataDir, { recursive: true });
  30. await writeFile(helperPath, "synthetic helper fixture");
  31. await writeFile(
  32. join(userDataDir, "Local State"),
  33. JSON.stringify({
  34. os_crypt: {
  35. app_bound_encrypted_key: Buffer.concat([Buffer.from("APPB"), Buffer.alloc(64, 3)]).toString(
  36. "base64",
  37. ),
  38. },
  39. }),
  40. );
  41. return { helperPath, userDataDir };
  42. }
  43. function decodeEncodedPowerShellCommand(args: string[]): string {
  44. expect(args.slice(0, 4)).toEqual(["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand"]);
  45. expect(args).toHaveLength(5);
  46. return Buffer.from(args[4]!, "base64").toString("utf16le");
  47. }
  48. describe("windowsChromeAppBoundKey", () => {
  49. it("净化环境固定 EXE 扩展并允许 PowerShell 启动原生 helper", async () => {
  50. const env = createSanitizedHelperEnvironment({
  51. ...process.env,
  52. PATHEXT: ".CMD;.VBS",
  53. });
  54. expect(env.PATHEXT).toBe(".EXE");
  55. if (process.platform !== "win32") return;
  56. const powershellPath = join(
  57. process.env.SYSTEMROOT ?? "C:\\Windows",
  58. "System32",
  59. "WindowsPowerShell",
  60. "v1.0",
  61. "powershell.exe",
  62. );
  63. const commandPath = process.env.COMSPEC ?? "C:\\Windows\\System32\\cmd.exe";
  64. const marker = "zcode-native-helper-ok";
  65. const { stdout } = await execFileAsync(
  66. powershellPath,
  67. createEncodedPowerShellArgs(
  68. "$response=& $zcodeArg0 /d /c $zcodeArg1;[Console]::Out.Write(($response -join ''))",
  69. [commandPath, `echo ${marker}`],
  70. ),
  71. { env, windowsHide: true },
  72. );
  73. expect(stdout.trim()).toBe(marker);
  74. });
  75. it("原生服务直接校验原始 broker 身份并可强制停止残留服务", async () => {
  76. const [source, buildSource] = await Promise.all([
  77. readFile(
  78. join(import.meta.dirname, "../native/windows-browser-import-helper/Program.cs"),
  79. "utf8",
  80. ),
  81. readFile(
  82. join(import.meta.dirname, "../scripts/build-windows-browser-import-helper.mjs"),
  83. "utf8",
  84. ),
  85. ]);
  86. expect(source).toContain('RequireArgument(serviceArguments, "--broker-pid")');
  87. expect(source).toContain("ConnectPipeClient(systemPipeName, servicePid, false)");
  88. expect(source).toMatch(/ServiceControlHandler[\s\S]*serviceStopEvent\.Set\(\)/);
  89. expect(source).toContain("TerminateProcess(serviceProcess");
  90. expect(source).toContain("MonitorBrokerAndDeadline(brokerPipe, parentPid");
  91. expect(source).toContain("MonitorHostAndDeadline(hostPid");
  92. expect(source).toContain("DateTime.UtcNow >= deadline");
  93. expect(source).toContain("brokerPipe.Dispose()");
  94. expect(source).toContain('WriteError("broker_initialization_failed")');
  95. expect(source).toContain('WriteError("controller_handshake_failed")');
  96. expect(source).toContain('WriteError("service_channel_failed")');
  97. expect(source).toContain(
  98. "VerifyPipeClient(pipe.SafePipeHandle, GetSelfPath(), elevated.Id, false)",
  99. );
  100. expect(source).toContain("VerifyProcessImagePathHandle(brokerProcess, GetSelfPath())");
  101. expect(source).toContain("VerifyPipeClient(pipe.SafePipeHandle, GetSelfPath(), brokerPid)");
  102. expect(buildSource).toContain('targetArch === "arm64" && !process.env.ZCODE_CSC_PATH');
  103. expect(buildSource).toContain('`/platform:${targetArch}`');
  104. });
  105. it("服务端命名管道以异步模式创建以支持有界等待", async () => {
  106. const source = await readFile(
  107. join(import.meta.dirname, "../native/windows-browser-import-helper/Program.cs"),
  108. "utf8",
  109. );
  110. const serverStart = source.indexOf("private static NamedPipeServerStream CreatePipeServer");
  111. const clientStart = source.indexOf("private static NamedPipeClientStream ConnectPipeClient");
  112. expect(serverStart).toBeGreaterThanOrEqual(0);
  113. expect(clientStart).toBeGreaterThan(serverStart);
  114. const serverSource = source.slice(serverStart, clientStart);
  115. expect(serverSource).toContain("PipeOptions.Asynchronous");
  116. expect(serverSource).not.toContain("PipeOptions.None");
  117. expect(source).toContain(
  118. '".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation',
  119. );
  120. expect(source).toContain("pipe.BeginWaitForConnection(null, null)");
  121. });
  122. it("只通过 stdin/stdout 协议传递 APPB 密文并返回 32 字节密钥", async () => {
  123. const fixture = await createFixture();
  124. const runHelper = vi.fn(async (_path: string, args: string[], input?: string) => {
  125. if (args[0] === "--version") {
  126. return {
  127. exitCode: 0,
  128. stdout: "ZCODE_BROWSER_IMPORT_HELPER\t2\tx64\t3.4.0\ttest",
  129. };
  130. }
  131. expect(args).toEqual(["--broker", "--parent-pid", String(process.pid)]);
  132. expect(input).toMatch(/^ZCODE_BROWSER_IMPORT_V1\t/);
  133. expect(input).not.toContain("chrome.exe\t");
  134. return {
  135. exitCode: 0,
  136. stdout: `ZCODE_BROWSER_IMPORT_V1\tOK\t${Buffer.alloc(32, 7).toString("base64")}`,
  137. };
  138. });
  139. const key = await readWindowsChromeAppBoundKey({
  140. chromeExecutablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  141. helperPath: fixture.helperPath,
  142. isPackaged: false,
  143. logger,
  144. processArch: "x64",
  145. runHelper,
  146. userDataDir: fixture.userDataDir,
  147. });
  148. expect(key).toEqual(Buffer.alloc(32, 7));
  149. expect(runHelper).toHaveBeenCalledTimes(2);
  150. });
  151. it("把用户取消 UAC 映射为稳定错误码", async () => {
  152. const fixture = await createFixture();
  153. const runHelper = vi.fn(async (_path: string, args: string[]) =>
  154. args[0] === "--version"
  155. ? {
  156. exitCode: 0,
  157. stdout: "ZCODE_BROWSER_IMPORT_HELPER\t2\tx64\t3.4.0\ttest",
  158. }
  159. : { exitCode: 0, stdout: "ZCODE_BROWSER_IMPORT_V1\tERR\televation_cancelled" },
  160. );
  161. await expect(
  162. readWindowsChromeAppBoundKey({
  163. chromeExecutablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  164. helperPath: fixture.helperPath,
  165. isPackaged: false,
  166. logger,
  167. processArch: "x64",
  168. runHelper,
  169. userDataDir: fixture.userDataDir,
  170. }),
  171. ).rejects.toMatchObject({ code: "chrome_cookie_elevation_cancelled" });
  172. });
  173. it("只把白名单 helper 失败原因写入本地日志", async () => {
  174. const fixture = await createFixture();
  175. const runHelper = vi.fn(async (_path: string, args: string[]) =>
  176. args[0] === "--version"
  177. ? {
  178. exitCode: 0,
  179. stdout: "ZCODE_BROWSER_IMPORT_HELPER\t2\tx64\t3.4.0\ttest",
  180. }
  181. : { exitCode: 0, stdout: "ZCODE_BROWSER_IMPORT_V1\tERR\tcng_failed" },
  182. );
  183. await expect(
  184. readWindowsChromeAppBoundKey({
  185. chromeExecutablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  186. helperPath: fixture.helperPath,
  187. isPackaged: false,
  188. logger,
  189. processArch: "x64",
  190. runHelper,
  191. userDataDir: fixture.userDataDir,
  192. }),
  193. ).rejects.toMatchObject({ code: "chrome_cookie_app_bound_decryption_failed" });
  194. expect(logger.warn).toHaveBeenCalledWith(
  195. "[browser-data] Windows Chrome App-Bound helper 返回失败",
  196. { reason: "cng_failed" },
  197. );
  198. });
  199. it("把原生服务通道阶段失败原因写入本地日志", async () => {
  200. const fixture = await createFixture();
  201. const runHelper = vi.fn(async (_path: string, args: string[]) =>
  202. args[0] === "--version"
  203. ? {
  204. exitCode: 0,
  205. stdout: "ZCODE_BROWSER_IMPORT_HELPER\t2\tx64\t3.4.0\ttest",
  206. }
  207. : { exitCode: 0, stdout: "ZCODE_BROWSER_IMPORT_V1\tERR\tservice_channel_failed" },
  208. );
  209. await expect(
  210. readWindowsChromeAppBoundKey({
  211. chromeExecutablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  212. helperPath: fixture.helperPath,
  213. isPackaged: false,
  214. logger,
  215. processArch: "x64",
  216. runHelper,
  217. userDataDir: fixture.userDataDir,
  218. }),
  219. ).rejects.toMatchObject({ code: "chrome_cookie_app_bound_decryption_failed" });
  220. expect(logger.warn).toHaveBeenCalledWith(
  221. "[browser-data] Windows Chrome App-Bound helper 返回失败",
  222. { reason: "service_channel_failed" },
  223. );
  224. });
  225. it("未知 helper 响应只记录 invalid_response 而不记录原文", async () => {
  226. const fixture = await createFixture();
  227. const secretMarker = "secret-path-or-key-material";
  228. const runHelper = vi.fn(async (_path: string, args: string[]) =>
  229. args[0] === "--version"
  230. ? {
  231. exitCode: 0,
  232. stdout: "ZCODE_BROWSER_IMPORT_HELPER\t2\tx64\t3.4.0\ttest",
  233. }
  234. : {
  235. exitCode: 0,
  236. stdout: `ZCODE_BROWSER_IMPORT_V1\tERR\t${secretMarker}`,
  237. },
  238. );
  239. await expect(
  240. readWindowsChromeAppBoundKey({
  241. chromeExecutablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  242. helperPath: fixture.helperPath,
  243. isPackaged: false,
  244. logger,
  245. processArch: "x64",
  246. runHelper,
  247. userDataDir: fixture.userDataDir,
  248. }),
  249. ).rejects.toMatchObject({ code: "chrome_cookie_app_bound_decryption_failed" });
  250. expect(logger.warn).toHaveBeenCalledWith(
  251. "[browser-data] Windows Chrome App-Bound helper 返回失败",
  252. { reason: "invalid_response" },
  253. );
  254. expect(JSON.stringify(logger.warn.mock.calls)).not.toContain(secretMarker);
  255. });
  256. it("畸形 helper 响应只记录 invalid_response 而不记录原文", async () => {
  257. const fixture = await createFixture();
  258. const rawResponse = "raw-helper-output-must-not-leak";
  259. const runHelper = vi.fn(async (_path: string, args: string[]) =>
  260. args[0] === "--version"
  261. ? {
  262. exitCode: 0,
  263. stdout: "ZCODE_BROWSER_IMPORT_HELPER\t2\tx64\t3.4.0\ttest",
  264. }
  265. : { exitCode: 1, stdout: rawResponse },
  266. );
  267. await expect(
  268. readWindowsChromeAppBoundKey({
  269. chromeExecutablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  270. helperPath: fixture.helperPath,
  271. isPackaged: false,
  272. logger,
  273. processArch: "x64",
  274. runHelper,
  275. userDataDir: fixture.userDataDir,
  276. }),
  277. ).rejects.toMatchObject({ code: "chrome_cookie_app_bound_decryption_failed" });
  278. expect(logger.warn).toHaveBeenCalledWith(
  279. "[browser-data] Windows Chrome App-Bound helper 返回失败",
  280. { reason: "invalid_response" },
  281. );
  282. expect(JSON.stringify(logger.warn.mock.calls)).not.toContain(rawResponse);
  283. });
  284. it("发布态签名不匹配时在启动 helper 前 fail closed", async () => {
  285. const fixture = await createFixture();
  286. const runHelper = vi.fn();
  287. const verifySignature = vi.fn(async () => false);
  288. await expect(
  289. readWindowsChromeAppBoundKey({
  290. appExecutablePath: join(tempRoot, "ZCode.exe"),
  291. chromeExecutablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  292. helperPath: fixture.helperPath,
  293. isPackaged: true,
  294. logger,
  295. processArch: "x64",
  296. resourcesPath: tempRoot,
  297. runHelper,
  298. userDataDir: fixture.userDataDir,
  299. verifySignature,
  300. }),
  301. ).rejects.toBeInstanceOf(WindowsChromeAppBoundImportError);
  302. expect(runHelper).not.toHaveBeenCalled();
  303. });
  304. it("发布态签名校验绑定的文件摘要不一致时 fail closed", async () => {
  305. const fixture = await createFixture();
  306. const runHelper = vi.fn();
  307. await expect(
  308. readWindowsChromeAppBoundKey({
  309. appExecutablePath: join(tempRoot, "ZCode.exe"),
  310. chromeExecutablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  311. helperPath: fixture.helperPath,
  312. isPackaged: true,
  313. logger,
  314. processArch: "x64",
  315. resourcesPath: tempRoot,
  316. runHelper,
  317. userDataDir: fixture.userDataDir,
  318. verifySignature: vi.fn(async () => "different-file-digest"),
  319. }),
  320. ).rejects.toMatchObject({ code: "chrome_cookie_helper_verification_failed" });
  321. expect(runHelper).not.toHaveBeenCalled();
  322. });
  323. it("发布态 helper 在校验后被替换时不发送解密请求", async () => {
  324. const fixture = await createFixture();
  325. const verifySignature = vi.fn(async () => true);
  326. const runHelper = vi.fn(async (executablePath: string, args: string[]) => {
  327. const command = decodeEncodedPowerShellCommand(args);
  328. if (command.includes("--version")) {
  329. return {
  330. exitCode: 0,
  331. stdout: "ZCODE_BROWSER_IMPORT_HELPER\t2\tx64\t3.4.0\ttest",
  332. };
  333. }
  334. expect(executablePath).toBe("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe");
  335. expect(command).toContain("FileShare]::Read");
  336. await writeFile(fixture.helperPath, "replaced after verification");
  337. return {
  338. exitCode: 23,
  339. stdout: "ZCODE_BROWSER_IMPORT_V1\tERR\thelper_verification_failed",
  340. };
  341. });
  342. await expect(
  343. readWindowsChromeAppBoundKey({
  344. appExecutablePath: join(tempRoot, "ZCode.exe"),
  345. chromeExecutablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  346. expectedAppVersion: "3.4.0",
  347. expectedBuildCommit: "test",
  348. helperPath: fixture.helperPath,
  349. isPackaged: true,
  350. logger,
  351. processArch: "x64",
  352. resourcesPath: tempRoot,
  353. runHelper,
  354. trustedPowerShellPath:
  355. "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
  356. userDataDir: fixture.userDataDir,
  357. verifySignature,
  358. }),
  359. ).rejects.toMatchObject({ code: "chrome_cookie_helper_verification_failed" });
  360. });
  361. it("发布态 helper 构建版本与应用不一致时 fail closed", async () => {
  362. const fixture = await createFixture();
  363. const runHelper = vi.fn(async (_path: string, args: string[]) =>
  364. decodeEncodedPowerShellCommand(args).includes("--version")
  365. ? {
  366. exitCode: 0,
  367. stdout: "ZCODE_BROWSER_IMPORT_HELPER\t2\tx64\t3.4.0\tbuild-a",
  368. }
  369. : {
  370. exitCode: 0,
  371. stdout: `ZCODE_BROWSER_IMPORT_V1\tOK\t${Buffer.alloc(32, 7).toString("base64")}`,
  372. },
  373. );
  374. await expect(
  375. readWindowsChromeAppBoundKey({
  376. appExecutablePath: join(tempRoot, "ZCode.exe"),
  377. chromeExecutablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  378. expectedAppVersion: "3.4.0",
  379. expectedBuildCommit: "build-b",
  380. helperPath: fixture.helperPath,
  381. isPackaged: true,
  382. logger,
  383. processArch: "x64",
  384. resourcesPath: tempRoot,
  385. runHelper,
  386. trustedPowerShellPath:
  387. "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
  388. userDataDir: fixture.userDataDir,
  389. verifySignature: vi.fn(async () => true),
  390. }),
  391. ).rejects.toMatchObject({ code: "chrome_cookie_helper_verification_failed" });
  392. expect(runHelper).toHaveBeenCalledTimes(1);
  393. });
  394. it("发布态由可信 PowerShell 持有已验证 helper 文件锁后再启动 broker", async () => {
  395. const fixture = await createFixture();
  396. const trustedPowerShellPath = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
  397. const runHelper = vi.fn(
  398. async (
  399. executablePath: string,
  400. args: string[],
  401. _input?: string,
  402. beforeInput?: () => Promise<void>,
  403. ) => {
  404. const command = decodeEncodedPowerShellCommand(args);
  405. if (command.includes("--version")) {
  406. expect(executablePath).toBe(trustedPowerShellPath);
  407. expect(command).toContain("FileShare]::Read");
  408. return {
  409. exitCode: 0,
  410. stdout: "ZCODE_BROWSER_IMPORT_HELPER\t2\tx64\t3.4.0\tbuild-a",
  411. };
  412. }
  413. expect(executablePath).toBe(trustedPowerShellPath);
  414. expect(command).toContain("FileShare]::Read");
  415. expect(command).not.toContain(fixture.helperPath);
  416. expect(command).toContain(Buffer.from(fixture.helperPath, "utf8").toString("base64"));
  417. await beforeInput?.();
  418. return {
  419. exitCode: 0,
  420. stdout: `ZCODE_BROWSER_IMPORT_V1\tOK\t${Buffer.alloc(32, 7).toString("base64")}`,
  421. };
  422. },
  423. );
  424. const key = await readWindowsChromeAppBoundKey({
  425. appExecutablePath: join(tempRoot, "ZCode.exe"),
  426. chromeExecutablePath: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
  427. expectedAppVersion: "3.4.0",
  428. expectedBuildCommit: "build-a",
  429. helperPath: fixture.helperPath,
  430. isPackaged: true,
  431. logger,
  432. processArch: "x64",
  433. resourcesPath: tempRoot,
  434. runHelper,
  435. trustedPowerShellPath,
  436. userDataDir: fixture.userDataDir,
  437. verifySignature: vi.fn(async () => true),
  438. });
  439. expect(key).toEqual(Buffer.alloc(32, 7));
  440. });
  441. });