desktopNetworkPolicy.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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(
  163. "127.0.0.1:7890",
  164. " localhost, 127.0.0.1 ,.example.com ",
  165. ),
  166. ).toEqual({
  167. mode: "fixed_servers",
  168. proxyBypassRules: "localhost,127.0.0.1,.example.com",
  169. proxyRules: "http://127.0.0.1:7890",
  170. });
  171. });
  172. it("uses direct mode when the explicit proxy setting is empty", () => {
  173. expect(buildElectronProxyConfig(" ")).toEqual({ mode: "direct" });
  174. });
  175. it("falls back to the requested mode when the explicit proxy setting is empty", () => {
  176. expect(buildElectronProxyConfig(" ", "localhost", "system")).toEqual({ mode: "system" });
  177. });
  178. it("keeps the explicit proxy config regardless of the fallback mode", () => {
  179. // 兜底模式只在留空时生效;显式代理仍必须原样落到 fixed_servers,避免设置页配置被系统代理顶掉。
  180. expect(buildElectronProxyConfig("127.0.0.1:7890", "localhost", "system")).toEqual({
  181. mode: "fixed_servers",
  182. proxyBypassRules: "localhost",
  183. proxyRules: "http://127.0.0.1:7890",
  184. });
  185. });
  186. it("applies proxy config and resets renderer certificate policy from settings", async () => {
  187. const targetSession = {
  188. setProxy: vi.fn(() => Promise.resolve()),
  189. closeAllConnections: vi.fn(() => Promise.resolve()),
  190. setCertificateVerifyProc: vi.fn(),
  191. } as unknown as Session;
  192. const logger = {
  193. info: vi.fn(),
  194. warn: vi.fn(),
  195. };
  196. await applyDesktopSessionNetworkPolicy(
  197. targetSession,
  198. {
  199. httpProxy: "http://127.0.0.1:7890",
  200. httpProxyNoProxy: "localhost,127.0.0.1",
  201. },
  202. logger,
  203. );
  204. expect(targetSession.setProxy).toHaveBeenCalledWith({
  205. mode: "fixed_servers",
  206. proxyBypassRules: "localhost,127.0.0.1",
  207. proxyRules: "http://127.0.0.1:7890",
  208. });
  209. expect(targetSession.closeAllConnections).toHaveBeenCalledTimes(1);
  210. expect(targetSession.setCertificateVerifyProc).toHaveBeenCalledWith(null);
  211. });
  212. it("accepts only certificate chains that include the configured custom CA", () => {
  213. const trustedPem = generateSelfSignedCertPem("Trusted Test CA");
  214. const untrustedPem = generateSelfSignedCertPem("Other Test CA");
  215. const trustedFingerprints = readCustomCaFingerprintsFromPem(trustedPem);
  216. const proc = createCustomCaCertificateVerifyProc(trustedFingerprints);
  217. const acceptedResults: number[] = [];
  218. const rejectedResults: number[] = [];
  219. expect(proc).not.toBeNull();
  220. expect(
  221. certificateChainMatchesCustomCa(
  222. { data: trustedPem, issuerCert: null },
  223. trustedFingerprints,
  224. ),
  225. ).toBe(true);
  226. expect(
  227. certificateChainMatchesCustomCa(
  228. { data: untrustedPem, issuerCert: null },
  229. trustedFingerprints,
  230. ),
  231. ).toBe(false);
  232. proc?.(buildVerifyRequest(trustedPem), (result) => acceptedResults.push(result));
  233. proc?.(buildVerifyRequest(untrustedPem), (result) => rejectedResults.push(result));
  234. expect(acceptedResults).toEqual([0]);
  235. expect(rejectedResults).toEqual([-3]);
  236. });
  237. });
  238. function createSessionStub(options: { setProxyError?: Error } = {}) {
  239. const setProxy = vi.fn(async () => {
  240. if (options.setProxyError) throw options.setProxyError;
  241. });
  242. const closeAllConnections = vi.fn(async () => {});
  243. const setCertificateVerifyProc = vi.fn();
  244. return {
  245. session: {
  246. setProxy,
  247. closeAllConnections,
  248. setCertificateVerifyProc,
  249. } as unknown as Session,
  250. setProxy,
  251. closeAllConnections,
  252. setCertificateVerifyProc,
  253. };
  254. }
  255. type VerifyRequest = Parameters<
  256. NonNullable<Parameters<Session["setCertificateVerifyProc"]>[0]>
  257. >[0];
  258. /** 构造一条「Chromium 已判定证书不受信」的校验请求,用于驱动 verifyProc 的拒绝分支。 */
  259. function buildVerifyRequest(certPem: string): VerifyRequest {
  260. return {
  261. certificate: { data: certPem, issuerCert: null },
  262. hostname: "intranet.test",
  263. isIssuedByKnownRoot: false,
  264. validatedCertificate: { data: certPem, issuerCert: null },
  265. verificationResult: "CERT_AUTHORITY_INVALID",
  266. errorCode: -202,
  267. } as unknown as VerifyRequest;
  268. }
  269. function generateSelfSignedCertPem(commonName: string): string {
  270. const keys = forge.pki.rsa.generateKeyPair(1024);
  271. const cert = forge.pki.createCertificate();
  272. cert.publicKey = keys.publicKey;
  273. cert.serialNumber = "01";
  274. cert.validity.notBefore = new Date("2026-01-01T00:00:00Z");
  275. cert.validity.notAfter = new Date("2036-01-01T00:00:00Z");
  276. const attrs = [{ name: "commonName", value: commonName }];
  277. cert.setSubject(attrs);
  278. cert.setIssuer(attrs);
  279. cert.setExtensions([
  280. { name: "basicConstraints", cA: true, critical: true },
  281. { name: "keyUsage", keyCertSign: true, cRLSign: true },
  282. ]);
  283. cert.sign(keys.privateKey, forge.md.sha256.create());
  284. return forge.pki.certificateToPem(cert);
  285. }