desktopNetworkPolicy.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. import forge from "node-forge";
  2. import { describe, expect, it, vi } from "vitest";
  3. import type { Session } from "electron";
  4. import {
  5. applyDesktopChromiumNetworkPolicies,
  6. applyDesktopSessionNetworkPolicy,
  7. buildElectronProxyConfig,
  8. certificateChainMatchesCustomCa,
  9. createCustomCaCertificateVerifyProc,
  10. readCustomCaFingerprintsFromPem,
  11. } from "../src/main/desktopNetworkPolicy.js";
  12. import { EMBEDDED_BROWSER_PARTITION } from "../src/main/browserDataManager.js";
  13. describe("desktopNetworkPolicy", () => {
  14. it("applies the startup network policy only to the default and embedded Browser sessions", async () => {
  15. const defaultSession = createSessionStub();
  16. const embeddedBrowserSession = createSessionStub();
  17. const codingPlanSession = createSessionStub();
  18. const sessionProvider = {
  19. defaultSession: defaultSession.session,
  20. fromPartition: vi.fn((partition: string) =>
  21. partition === EMBEDDED_BROWSER_PARTITION
  22. ? embeddedBrowserSession.session
  23. : codingPlanSession.session,
  24. ),
  25. };
  26. const logger = {
  27. info: vi.fn(),
  28. warn: vi.fn(),
  29. };
  30. await applyDesktopChromiumNetworkPolicies(
  31. sessionProvider,
  32. {
  33. httpProxy: "http://127.0.0.1:7890",
  34. httpProxyNoProxy: "localhost,127.0.0.1",
  35. },
  36. logger,
  37. );
  38. expect(sessionProvider.fromPartition).toHaveBeenCalledTimes(1);
  39. expect(sessionProvider.fromPartition).toHaveBeenCalledWith(EMBEDDED_BROWSER_PARTITION);
  40. for (const target of [defaultSession, embeddedBrowserSession]) {
  41. expect(target.setProxy).toHaveBeenCalledWith({
  42. mode: "fixed_servers",
  43. proxyBypassRules: "localhost,127.0.0.1",
  44. proxyRules: "http://127.0.0.1:7890",
  45. });
  46. expect(target.closeAllConnections).toHaveBeenCalledTimes(1);
  47. expect(target.setCertificateVerifyProc).toHaveBeenCalledWith(null);
  48. }
  49. expect(codingPlanSession.setProxy).not.toHaveBeenCalled();
  50. });
  51. it("falls back to the system proxy only on the embedded Browser session when the setting is empty", async () => {
  52. const defaultSession = createSessionStub();
  53. const embeddedBrowserSession = createSessionStub();
  54. const sessionProvider = {
  55. defaultSession: defaultSession.session,
  56. fromPartition: vi.fn(() => embeddedBrowserSession.session),
  57. };
  58. const logger = { info: vi.fn(), warn: vi.fn() };
  59. await applyDesktopChromiumNetworkPolicies(sessionProvider, {}, logger);
  60. // Bug 原因:留空曾被翻译成 `direct`,而 Electron 的 `direct` 是「永不使用代理」,
  61. // 会连本机系统代理一起屏蔽。内置浏览器是用户的浏览出口,需要代理才能访问的站点
  62. // 会直接 ERR_CONNECTION_TIMED_OUT,与用户本机浏览器行为漂移。
  63. expect(embeddedBrowserSession.setProxy).toHaveBeenCalledWith({ mode: "system" });
  64. // defaultSession 承载 ZCode 自身的后端与模型流量,留空时保持显式收敛,不受系统代理影响。
  65. expect(defaultSession.setProxy).toHaveBeenCalledWith({ mode: "direct" });
  66. });
  67. it("continues configuring the embedded Browser session when the default session fails", async () => {
  68. const defaultError = new Error("default session proxy failed");
  69. const defaultSession = createSessionStub({ setProxyError: defaultError });
  70. const embeddedBrowserSession = createSessionStub();
  71. const sessionProvider = {
  72. defaultSession: defaultSession.session,
  73. fromPartition: vi.fn(() => embeddedBrowserSession.session),
  74. };
  75. const logger = {
  76. info: vi.fn(),
  77. warn: vi.fn(),
  78. };
  79. await applyDesktopChromiumNetworkPolicies(sessionProvider, {}, logger);
  80. expect(defaultSession.closeAllConnections).not.toHaveBeenCalled();
  81. expect(embeddedBrowserSession.setProxy).toHaveBeenCalledWith({ mode: "system" });
  82. expect(embeddedBrowserSession.closeAllConnections).toHaveBeenCalledTimes(1);
  83. expect(embeddedBrowserSession.setCertificateVerifyProc).toHaveBeenCalledWith(null);
  84. expect(logger.warn).toHaveBeenCalledWith(
  85. "[desktop-network] default-session network policy apply failed:",
  86. defaultError,
  87. );
  88. });
  89. it("accepts every certificate on the embedded Browser session when insecure certificates are allowed", async () => {
  90. const defaultSession = createSessionStub();
  91. const embeddedBrowserSession = createSessionStub();
  92. const sessionProvider = {
  93. defaultSession: defaultSession.session,
  94. fromPartition: vi.fn(() => embeddedBrowserSession.session),
  95. };
  96. const logger = { info: vi.fn(), warn: vi.fn() };
  97. await applyDesktopChromiumNetworkPolicies(
  98. sessionProvider,
  99. { embeddedBrowserAllowInsecureCertificates: true },
  100. logger,
  101. );
  102. const embeddedProc = embeddedBrowserSession.setCertificateVerifyProc.mock.calls.at(0)?.[0];
  103. expect(embeddedProc).toBeTypeOf("function");
  104. const results: number[] = [];
  105. embeddedProc?.(
  106. buildVerifyRequest(generateSelfSignedCertPem("Untrusted Intranet")),
  107. (result: number) => results.push(result),
  108. );
  109. expect(results).toEqual([0]);
  110. });
  111. it("keeps the default session on strict verification when insecure certificates are allowed", async () => {
  112. const defaultSession = createSessionStub();
  113. const embeddedBrowserSession = createSessionStub();
  114. const sessionProvider = {
  115. defaultSession: defaultSession.session,
  116. fromPartition: vi.fn(() => embeddedBrowserSession.session),
  117. };
  118. const logger = { info: vi.fn(), warn: vi.fn() };
  119. await applyDesktopChromiumNetworkPolicies(
  120. sessionProvider,
  121. { embeddedBrowserAllowInsecureCertificates: true },
  122. logger,
  123. );
  124. // 放行只属于内置浏览器出口;defaultSession 承载 ZCode 自身的后端与模型流量,必须保持严格校验。
  125. expect(defaultSession.setCertificateVerifyProc).toHaveBeenCalledWith(null);
  126. });
  127. it("keeps every session on strict verification when insecure certificates are disabled", async () => {
  128. const defaultSession = createSessionStub();
  129. const embeddedBrowserSession = createSessionStub();
  130. const sessionProvider = {
  131. defaultSession: defaultSession.session,
  132. fromPartition: vi.fn(() => embeddedBrowserSession.session),
  133. };
  134. const logger = { info: vi.fn(), warn: vi.fn() };
  135. await applyDesktopChromiumNetworkPolicies(
  136. sessionProvider,
  137. { embeddedBrowserAllowInsecureCertificates: false },
  138. logger,
  139. );
  140. expect(defaultSession.setCertificateVerifyProc).toHaveBeenCalledWith(null);
  141. expect(embeddedBrowserSession.setCertificateVerifyProc).toHaveBeenCalledWith(null);
  142. });
  143. it("prefers blanket acceptance over the custom CA chain check when both are configured", async () => {
  144. const targetSession = createSessionStub();
  145. const logger = { info: vi.fn(), warn: vi.fn() };
  146. await applyDesktopSessionNetworkPolicy(
  147. targetSession.session,
  148. { httpProxyCaCertPath: "/definitely/missing/root-ca.pem" },
  149. logger,
  150. { allowInsecureCertificates: true },
  151. );
  152. const proc = targetSession.setCertificateVerifyProc.mock.calls.at(0)?.[0];
  153. expect(proc).toBeTypeOf("function");
  154. const results: number[] = [];
  155. proc?.(buildVerifyRequest(generateSelfSignedCertPem("Intranet")), (result: number) =>
  156. results.push(result),
  157. );
  158. expect(results).toEqual([0]);
  159. });
  160. it("builds a fixed-server proxy config from the explicit setting", () => {
  161. expect(
  162. buildElectronProxyConfig("127.0.0.1:7890", " localhost, 127.0.0.1 ,.example.com "),
  163. ).toEqual({
  164. mode: "fixed_servers",
  165. proxyBypassRules: "localhost,127.0.0.1,.example.com",
  166. proxyRules: "http://127.0.0.1:7890",
  167. });
  168. });
  169. it("uses direct mode when the explicit proxy setting is empty", () => {
  170. expect(buildElectronProxyConfig(" ")).toEqual({ mode: "direct" });
  171. });
  172. it("falls back to the requested mode when the explicit proxy setting is empty", () => {
  173. expect(buildElectronProxyConfig(" ", "localhost", "system")).toEqual({ mode: "system" });
  174. });
  175. it("keeps the explicit proxy config regardless of the fallback mode", () => {
  176. // 兜底模式只在留空时生效;显式代理仍必须原样落到 fixed_servers,避免设置页配置被系统代理顶掉。
  177. expect(buildElectronProxyConfig("127.0.0.1:7890", "localhost", "system")).toEqual({
  178. mode: "fixed_servers",
  179. proxyBypassRules: "localhost",
  180. proxyRules: "http://127.0.0.1:7890",
  181. });
  182. });
  183. it("accepts only certificate chains that include the configured custom CA", () => {
  184. const trustedPem = generateSelfSignedCertPem("Trusted Test CA");
  185. const untrustedPem = generateSelfSignedCertPem("Other Test CA");
  186. const trustedFingerprints = readCustomCaFingerprintsFromPem(trustedPem);
  187. const proc = createCustomCaCertificateVerifyProc(trustedFingerprints);
  188. const acceptedResults: number[] = [];
  189. const rejectedResults: number[] = [];
  190. expect(proc).not.toBeNull();
  191. expect(
  192. certificateChainMatchesCustomCa({ data: trustedPem, issuerCert: null }, trustedFingerprints),
  193. ).toBe(true);
  194. expect(
  195. certificateChainMatchesCustomCa(
  196. { data: untrustedPem, issuerCert: null },
  197. trustedFingerprints,
  198. ),
  199. ).toBe(false);
  200. proc?.(buildVerifyRequest(trustedPem), (result) => acceptedResults.push(result));
  201. proc?.(buildVerifyRequest(untrustedPem), (result) => rejectedResults.push(result));
  202. expect(acceptedResults).toEqual([0]);
  203. expect(rejectedResults).toEqual([-3]);
  204. });
  205. });
  206. function createSessionStub(options: { setProxyError?: Error } = {}) {
  207. const setProxy = vi.fn(async () => {
  208. if (options.setProxyError) throw options.setProxyError;
  209. });
  210. const closeAllConnections = vi.fn(async () => {});
  211. const setCertificateVerifyProc = vi.fn();
  212. return {
  213. session: {
  214. setProxy,
  215. closeAllConnections,
  216. setCertificateVerifyProc,
  217. } as unknown as Session,
  218. setProxy,
  219. closeAllConnections,
  220. setCertificateVerifyProc,
  221. };
  222. }
  223. type VerifyRequest = Parameters<NonNullable<Parameters<Session["setCertificateVerifyProc"]>[0]>>[0];
  224. /** 构造一条「Chromium 已判定证书不受信」的校验请求,用于驱动 verifyProc 的拒绝分支。 */
  225. function buildVerifyRequest(certPem: string): VerifyRequest {
  226. return {
  227. certificate: { data: certPem, issuerCert: null },
  228. hostname: "intranet.test",
  229. isIssuedByKnownRoot: false,
  230. validatedCertificate: { data: certPem, issuerCert: null },
  231. verificationResult: "CERT_AUTHORITY_INVALID",
  232. errorCode: -202,
  233. } as unknown as VerifyRequest;
  234. }
  235. function generateSelfSignedCertPem(commonName: string): string {
  236. const keys = forge.pki.rsa.generateKeyPair(1024);
  237. const cert = forge.pki.createCertificate();
  238. cert.publicKey = keys.publicKey;
  239. cert.serialNumber = "01";
  240. cert.validity.notBefore = new Date("2026-01-01T00:00:00Z");
  241. cert.validity.notAfter = new Date("2036-01-01T00:00:00Z");
  242. const attrs = [{ name: "commonName", value: commonName }];
  243. cert.setSubject(attrs);
  244. cert.setIssuer(attrs);
  245. cert.setExtensions([
  246. { name: "basicConstraints", cA: true, critical: true },
  247. { name: "keyUsage", keyCertSign: true, cRLSign: true },
  248. ]);
  249. cert.sign(keys.privateKey, forge.md.sha256.create());
  250. return forge.pki.certificateToPem(cert);
  251. }