auto-update-network-smoke.mjs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. import assert from "node:assert/strict";
  2. import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
  3. import { createRequire } from "node:module";
  4. import { resolve } from "node:path";
  5. import { build } from "esbuild";
  6. import { _electron } from "playwright-core";
  7. // 用真实 updater Session 和 HTTP executor 验证出口,不改用户配置或下载真实安装包。
  8. const desktopDir = resolve(import.meta.dirname, "..");
  9. const require = createRequire(resolve(desktopDir, "package.json"));
  10. await mkdir(resolve(desktopDir, ".e2e-artifacts"), { recursive: true });
  11. const artifactDir = await mkdtemp(resolve(desktopDir, ".e2e-artifacts/update-network-"));
  12. // 正式主进程使用 ESM;CJS fixture 会掩盖第三方 CommonJS 包的命名导入错误。
  13. const entry = resolve(artifactDir, "main.mjs");
  14. async function runFixture() {
  15. const { app, BrowserWindow, session } = await import("electron");
  16. const { createServer } = await import("node:http");
  17. const { createHash } = await import("node:crypto");
  18. const { readFile, writeFile } = await import("node:fs/promises");
  19. const { createServer: createHttpsServer } = await import("node:https");
  20. const { default: forge } = await import("node-forge");
  21. const { default: pkg, CancellationToken } = await import("electron-updater");
  22. const {
  23. applyDesktopChromiumNetworkPolicies,
  24. createCustomCaCertificateVerifyProc,
  25. readCustomCaCertificatesFromPem,
  26. } = await import("./src/main/desktopNetworkPolicy.ts");
  27. app.setPath("userData", FIXTURE_DIR + "/user-data");
  28. await app.whenReady();
  29. const { autoUpdater } = pkg;
  30. const bytes = Buffer.alloc(256 * 1024, 37);
  31. const requests = [];
  32. const policyLogs = [];
  33. const policyLogger = {
  34. info: (message) => {
  35. policyLogs.push(String(message));
  36. console.info(message);
  37. },
  38. warn: (...args) => console.warn(...args),
  39. };
  40. let interrupt = false;
  41. const proxy = createServer((req, res) => {
  42. requests.push(req.url);
  43. res.writeHead(200, { "Content-Length": bytes.length });
  44. if (interrupt) {
  45. interrupt = false;
  46. res.write(bytes.subarray(0, 4096));
  47. setImmediate(() => res.destroy());
  48. } else res.end(bytes);
  49. });
  50. const direct = createServer((_req, res) => res.end("bypassed"));
  51. await Promise.all(
  52. [proxy, direct].map(
  53. (server) => new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)),
  54. ),
  55. );
  56. await applyDesktopChromiumNetworkPolicies(
  57. session,
  58. {
  59. httpProxy: "http://127.0.0.1:" + proxy.address().port,
  60. httpProxyNoProxy: "127.0.0.1",
  61. embeddedBrowserAllowInsecureCertificates: true,
  62. },
  63. policyLogger,
  64. );
  65. const updater = autoUpdater.netSession;
  66. const route = await updater.resolveProxy("http://update-download.invalid/package.zip");
  67. globalThis.fixtureRoute = route;
  68. const sha512 = createHash("sha512").update(bytes).digest("base64");
  69. const destination = FIXTURE_DIR + "/package.zip";
  70. const options = () => ({ cancellationToken: new CancellationToken(), sha512 });
  71. globalThis.runDownload = async () => {
  72. interrupt = true;
  73. let interrupted = false;
  74. try {
  75. await autoUpdater.httpExecutor.download(
  76. new URL("http://update-download.invalid/interrupted.zip"),
  77. destination,
  78. options(),
  79. );
  80. } catch {
  81. interrupted = true;
  82. }
  83. await autoUpdater.httpExecutor.download(
  84. new URL("http://update-download.invalid/package.zip"),
  85. destination,
  86. options(),
  87. );
  88. const bypass = await autoUpdater.httpExecutor.request({
  89. protocol: "http:",
  90. hostname: "127.0.0.1",
  91. port: direct.address().port,
  92. path: "/bypass",
  93. });
  94. const keys = forge.pki.rsa.generateKeyPair(2048);
  95. const cert = forge.pki.createCertificate();
  96. cert.publicKey = keys.publicKey;
  97. cert.serialNumber = "01";
  98. cert.validity.notBefore = new Date(Date.now() - 60 * 60_000);
  99. cert.validity.notAfter = new Date(Date.now() + 24 * 60 * 60_000);
  100. cert.setSubject([{ name: "commonName", value: "localhost" }]);
  101. cert.setIssuer(cert.subject.attributes);
  102. cert.setExtensions([
  103. { name: "basicConstraints", cA: true },
  104. { name: "subjectAltName", altNames: [{ type: 7, ip: "127.0.0.1" }] },
  105. ]);
  106. cert.sign(keys.privateKey, forge.md.sha256.create());
  107. const pem = forge.pki.certificateToPem(cert);
  108. const tls = createHttpsServer(
  109. { key: forge.pki.privateKeyToPem(keys.privateKey), cert: pem },
  110. (_req, res) => res.end("trusted"),
  111. );
  112. await new Promise((resolve) => tls.listen(0, "127.0.0.1", resolve));
  113. const tlsOptions = {
  114. protocol: "https:",
  115. hostname: "127.0.0.1",
  116. port: tls.address().port,
  117. path: "/",
  118. };
  119. let rejectedUntrusted = false;
  120. try {
  121. await autoUpdater.httpExecutor.request(tlsOptions);
  122. } catch {
  123. rejectedUntrusted = true;
  124. }
  125. // 使用另一张证书,避免 Chromium 复用上一轮对相同证书的负缓存。
  126. cert.serialNumber = "02";
  127. cert.sign(keys.privateKey, forge.md.sha256.create());
  128. const trustedPem = forge.pki.certificateToPem(cert);
  129. tls.setSecureContext({ key: forge.pki.privateKeyToPem(keys.privateKey), cert: trustedPem });
  130. const caPath = FIXTURE_DIR + "/fixture-ca.pem";
  131. await writeFile(caPath, trustedPem);
  132. await applyDesktopChromiumNetworkPolicies(
  133. session,
  134. {
  135. httpProxy: "http://127.0.0.1:" + proxy.address().port,
  136. httpProxyNoProxy: "127.0.0.1",
  137. httpProxyCaCertPath: caPath,
  138. embeddedBrowserAllowInsecureCertificates: true,
  139. },
  140. policyLogger,
  141. );
  142. const trusted = await autoUpdater.httpExecutor.request(tlsOptions);
  143. // 自定义根只增加信任,不能使其它 TLS 错误变成成功。
  144. const rootKeys = forge.pki.rsa.generateKeyPair(2048);
  145. const leafKeys = forge.pki.rsa.generateKeyPair(2048);
  146. const rootCert = forge.pki.createCertificate();
  147. rootCert.publicKey = rootKeys.publicKey;
  148. rootCert.serialNumber = "100";
  149. rootCert.validity.notBefore = new Date(Date.now() - 86400000);
  150. rootCert.validity.notAfter = new Date(Date.now() + 86400000);
  151. rootCert.setSubject([{ name: "commonName", value: "Fixture Root" }]);
  152. rootCert.setIssuer(rootCert.subject.attributes);
  153. rootCert.setExtensions([
  154. { name: "basicConstraints", critical: true, cA: true },
  155. { name: "keyUsage", critical: true, keyCertSign: true },
  156. ]);
  157. rootCert.sign(rootKeys.privateKey, forge.md.sha256.create());
  158. const rootPem = forge.pki.certificateToPem(rootCert);
  159. await writeFile(caPath, rootPem);
  160. await applyDesktopChromiumNetworkPolicies(
  161. session,
  162. { httpProxyCaCertPath: caPath, embeddedBrowserAllowInsecureCertificates: true },
  163. policyLogger,
  164. );
  165. const boundary = {};
  166. const weakKeys = forge.pki.rsa.generateKeyPair(1024);
  167. for (const [index, name] of [
  168. "valid-root",
  169. "valid-intermediate",
  170. "aki-intermediate-serial",
  171. "nonca-intermediate",
  172. "pathlen-blocked",
  173. "wrong-host",
  174. "expired",
  175. "not-yet-valid",
  176. "wrong-signature",
  177. "client-only",
  178. "sha1-signed",
  179. "rsa-1024",
  180. ].entries()) {
  181. const leaf = forge.pki.createCertificate();
  182. leaf.publicKey = name === "rsa-1024" ? weakKeys.publicKey : leafKeys.publicKey;
  183. leaf.serialNumber = (200 + index).toString(16);
  184. leaf.validity.notBefore = new Date(
  185. Date.now() + (name === "not-yet-valid" ? 86400000 : -86400000),
  186. );
  187. leaf.validity.notAfter = new Date(Date.now() + (name === "expired" ? -3600000 : 172800000));
  188. leaf.setSubject([
  189. { name: "commonName", value: name === "wrong-host" ? "wrong.invalid" : "127.0.0.1" },
  190. ]);
  191. const hasIntermediate = [
  192. "valid-intermediate",
  193. "aki-intermediate-serial",
  194. "nonca-intermediate",
  195. "pathlen-blocked",
  196. ].includes(name);
  197. const currentRoot = forge.pki.certificateFromPem(rootPem);
  198. currentRoot.serialNumber = (400 + index).toString(16);
  199. currentRoot.setExtensions([
  200. {
  201. name: "basicConstraints",
  202. critical: true,
  203. cA: true,
  204. pathLenConstraint: name === "pathlen-blocked" ? 0 : 1,
  205. },
  206. { name: "keyUsage", critical: true, keyCertSign: true },
  207. ]);
  208. currentRoot.sign(rootKeys.privateKey, forge.md.sha256.create());
  209. const currentRootPem = forge.pki.certificateToPem(currentRoot);
  210. await writeFile(caPath, currentRootPem);
  211. await applyDesktopChromiumNetworkPolicies(
  212. session,
  213. { httpProxyCaCertPath: caPath, embeddedBrowserAllowInsecureCertificates: true },
  214. policyLogger,
  215. );
  216. const intermediate = forge.pki.createCertificate();
  217. intermediate.publicKey = keys.publicKey;
  218. intermediate.serialNumber = (500 + index).toString(16);
  219. intermediate.validity.notBefore = rootCert.validity.notBefore;
  220. intermediate.validity.notAfter = rootCert.validity.notAfter;
  221. intermediate.setSubject([{ name: "commonName", value: "Fixture Intermediate" }]);
  222. intermediate.setIssuer(currentRoot.subject.attributes);
  223. intermediate.setExtensions([
  224. { name: "basicConstraints", critical: true, cA: name !== "nonca-intermediate" },
  225. { name: "keyUsage", critical: true, keyCertSign: true },
  226. ]);
  227. intermediate.sign(rootKeys.privateKey, forge.md.sha256.create());
  228. leaf.setIssuer(
  229. hasIntermediate ? intermediate.subject.attributes : currentRoot.subject.attributes,
  230. );
  231. leaf.setExtensions([
  232. { name: "basicConstraints", critical: true, cA: false },
  233. {
  234. name: "subjectAltName",
  235. altNames:
  236. name === "wrong-host"
  237. ? [{ type: 2, value: "wrong.invalid" }]
  238. : [{ type: 7, ip: "127.0.0.1" }],
  239. },
  240. {
  241. name: "extKeyUsage",
  242. serverAuth: name !== "client-only",
  243. clientAuth: name === "client-only",
  244. },
  245. ]);
  246. if (name === "aki-intermediate-serial") {
  247. leaf.setExtensions([
  248. ...leaf.extensions,
  249. {
  250. name: "authorityKeyIdentifier",
  251. authorityCertIssuer: intermediate.issuer,
  252. serialNumber: intermediate.serialNumber,
  253. },
  254. ]);
  255. }
  256. leaf.sign(
  257. name === "wrong-signature" || hasIntermediate ? keys.privateKey : rootKeys.privateKey,
  258. name === "sha1-signed" ? forge.md.sha1.create() : forge.md.sha256.create(),
  259. );
  260. const server = createHttpsServer(
  261. {
  262. key: forge.pki.privateKeyToPem(
  263. name === "rsa-1024" ? weakKeys.privateKey : leafKeys.privateKey,
  264. ),
  265. cert:
  266. forge.pki.certificateToPem(leaf) +
  267. (hasIntermediate ? forge.pki.certificateToPem(intermediate) : "") +
  268. currentRootPem,
  269. },
  270. (_req, res) => res.end("verified"),
  271. );
  272. await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
  273. try {
  274. boundary[name] = {
  275. accepted:
  276. (await autoUpdater.httpExecutor.request({
  277. protocol: "https:",
  278. hostname: "127.0.0.1",
  279. port: server.address().port,
  280. path: "/",
  281. })) === "verified",
  282. };
  283. } catch {
  284. boundary[name] = { accepted: false };
  285. } finally {
  286. await new Promise((resolve) => server.close(resolve));
  287. }
  288. }
  289. // 叶证书没有进入 PKIjs 的 CA 扩展检查;同时核对策略返回值及真实 HTTPS 请求。
  290. await writeFile(caPath, rootPem);
  291. await applyDesktopChromiumNetworkPolicies(
  292. session,
  293. { httpProxyCaCertPath: caPath },
  294. policyLogger,
  295. );
  296. for (const [index, name] of [
  297. "critical-unknown",
  298. "noncritical-unknown",
  299. "critical-unsupported",
  300. "usage-crl-only",
  301. "usage-key-encipherment-only",
  302. "usage-key-agreement-only",
  303. "usage-digital-signature",
  304. "usage-signature-and-encipherment",
  305. "usage-absent",
  306. ].entries()) {
  307. const leaf = forge.pki.createCertificate();
  308. leaf.publicKey = leafKeys.publicKey;
  309. leaf.serialNumber = (1000 + index).toString(16);
  310. leaf.validity = rootCert.validity;
  311. leaf.setSubject([{ name: "commonName", value: "127.0.0.1" }]);
  312. leaf.setIssuer(rootCert.subject.attributes);
  313. const extensions = [
  314. { name: "basicConstraints", critical: true, cA: false },
  315. { name: "subjectAltName", altNames: [{ type: 7, ip: "127.0.0.1" }] },
  316. { name: "extKeyUsage", serverAuth: true },
  317. ];
  318. if (name.includes("unknown") || name === "critical-unsupported") {
  319. extensions.push({
  320. id: name === "critical-unsupported" ? "2.5.29.16" : "1.2.3.4.5.6.7.8.1",
  321. critical: name !== "noncritical-unknown",
  322. value: forge.asn1
  323. .toDer(
  324. forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.SEQUENCE, true, []),
  325. )
  326. .getBytes(),
  327. });
  328. } else if (name !== "usage-absent") {
  329. extensions.push({
  330. name: "keyUsage",
  331. critical: true,
  332. digitalSignature:
  333. name.includes("digital-signature") || name === "usage-signature-and-encipherment",
  334. keyEncipherment: name.includes("encipherment"),
  335. keyAgreement: name.includes("agreement"),
  336. cRLSign: name === "usage-crl-only",
  337. });
  338. }
  339. leaf.setExtensions(extensions);
  340. leaf.sign(rootKeys.privateKey, forge.md.sha256.create());
  341. const pem = forge.pki.certificateToPem(leaf);
  342. const verify = createCustomCaCertificateVerifyProc(readCustomCaCertificatesFromPem(rootPem));
  343. const policyCode = await new Promise((resolve) =>
  344. verify(
  345. {
  346. hostname: "127.0.0.1",
  347. errorCode: -202,
  348. certificate: { data: pem, issuerCert: { data: rootPem } },
  349. },
  350. resolve,
  351. ),
  352. );
  353. const server = createHttpsServer(
  354. { key: forge.pki.privateKeyToPem(leafKeys.privateKey), cert: pem + rootPem },
  355. (_req, res) => res.end("verified"),
  356. );
  357. await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
  358. try {
  359. boundary[name] = {
  360. policyCode,
  361. accepted:
  362. (await autoUpdater.httpExecutor.request({
  363. protocol: "https:",
  364. hostname: "127.0.0.1",
  365. port: server.address().port,
  366. path: "/",
  367. })) === "verified",
  368. };
  369. } catch {
  370. boundary[name] = { policyCode, accepted: false };
  371. } finally {
  372. await new Promise((resolve) => server.close(resolve));
  373. }
  374. }
  375. for (const [index, oid] of ["2.5.29.15", "2.5.29.30", "2.5.29.32", "2.5.29.30-ca"].entries()) {
  376. const intermediateCase = oid.endsWith("-ca");
  377. const invalidExtension = {
  378. id: oid.replace("-ca", ""),
  379. critical: true,
  380. value: forge.asn1
  381. .toDer(
  382. forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false, "\x80"),
  383. )
  384. .getBytes(),
  385. };
  386. const issuer = intermediateCase ? forge.pki.createCertificate() : rootCert;
  387. if (intermediateCase) {
  388. issuer.publicKey = keys.publicKey;
  389. issuer.serialNumber = "1200";
  390. issuer.validity = rootCert.validity;
  391. issuer.setSubject([{ name: "commonName", value: "Malformed Intermediate" }]);
  392. issuer.setIssuer(rootCert.subject.attributes);
  393. issuer.setExtensions([
  394. { name: "basicConstraints", cA: true },
  395. { name: "keyUsage", keyCertSign: true },
  396. invalidExtension,
  397. ]);
  398. issuer.sign(rootKeys.privateKey, forge.md.sha256.create());
  399. }
  400. const leaf = forge.pki.createCertificate();
  401. leaf.publicKey = leafKeys.publicKey;
  402. leaf.serialNumber = (1100 + index).toString(16);
  403. leaf.validity = rootCert.validity;
  404. leaf.setSubject([{ name: "commonName", value: "127.0.0.1" }]);
  405. leaf.setIssuer(issuer.subject.attributes);
  406. leaf.setExtensions([
  407. { name: "basicConstraints", cA: false },
  408. { name: "subjectAltName", altNames: [{ type: 7, ip: "127.0.0.1" }] },
  409. ...(intermediateCase ? [] : [invalidExtension]),
  410. ]);
  411. leaf.sign(intermediateCase ? keys.privateKey : rootKeys.privateKey, forge.md.sha256.create());
  412. const pem = forge.pki.certificateToPem(leaf);
  413. const verify = createCustomCaCertificateVerifyProc(readCustomCaCertificatesFromPem(rootPem));
  414. const issuerCert = intermediateCase
  415. ? { data: forge.pki.certificateToPem(issuer), issuerCert: { data: rootPem } }
  416. : { data: rootPem };
  417. const code = await new Promise((resolve) =>
  418. verify(
  419. { hostname: "127.0.0.1", errorCode: -202, certificate: { data: pem, issuerCert } },
  420. resolve,
  421. ),
  422. );
  423. boundary["malformed-" + oid] = { policyCode: code };
  424. }
  425. // AKI 两种编码应等价;错误名称、序列号及签名不能借兼容处理绕过验证。
  426. await writeFile(caPath, rootPem);
  427. await applyDesktopChromiumNetworkPolicies(
  428. session,
  429. { httpProxyCaCertPath: caPath },
  430. policyLogger,
  431. );
  432. const checkCertificate = async (name, certificate, key) => {
  433. const server = createHttpsServer({ key, cert: certificate }, (_request, response) =>
  434. response.end("verified"),
  435. );
  436. await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
  437. try {
  438. boundary[name] = {
  439. accepted:
  440. (await autoUpdater.httpExecutor.request({
  441. protocol: "https:",
  442. hostname: "127.0.0.1",
  443. port: server.address().port,
  444. path: "/",
  445. })) === "verified",
  446. };
  447. } catch {
  448. boundary[name] = { accepted: false };
  449. } finally {
  450. await new Promise((resolve) => server.close(resolve));
  451. }
  452. };
  453. for (const [index, name] of [
  454. "aki-keyid",
  455. "aki-issuer-serial",
  456. "aki-wrong-serial",
  457. "aki-wrong-issuer",
  458. "aki-wrong-signature",
  459. ].entries()) {
  460. const leaf = forge.pki.createCertificate();
  461. leaf.publicKey = leafKeys.publicKey;
  462. leaf.serialNumber = (800 + index).toString(16);
  463. leaf.validity = rootCert.validity;
  464. leaf.setSubject([{ name: "commonName", value: "127.0.0.1" }]);
  465. leaf.setIssuer(rootCert.subject.attributes);
  466. leaf.setExtensions([
  467. { name: "basicConstraints", cA: false },
  468. { name: "subjectAltName", altNames: [{ type: 7, ip: "127.0.0.1" }] },
  469. { name: "extKeyUsage", serverAuth: true },
  470. name === "aki-keyid"
  471. ? {
  472. name: "authorityKeyIdentifier",
  473. keyIdentifier: rootCert.generateSubjectKeyIdentifier().getBytes(),
  474. }
  475. : {
  476. name: "authorityKeyIdentifier",
  477. authorityCertIssuer: name === "aki-wrong-issuer" ? leaf.subject : rootCert.issuer,
  478. serialNumber: name === "aki-wrong-serial" ? "ffff" : rootCert.serialNumber,
  479. },
  480. ]);
  481. leaf.sign(
  482. name === "aki-wrong-signature" ? keys.privateKey : rootKeys.privateKey,
  483. forge.md.sha256.create(),
  484. );
  485. await checkCertificate(
  486. name,
  487. forge.pki.certificateToPem(leaf) + rootPem,
  488. forge.pki.privateKeyToPem(leafKeys.privateKey),
  489. );
  490. }
  491. // forge 不签 RSA-PSS;只在测试夹具内由 OpenSSL 生成合成证书。
  492. const { execFile } = await import("node:child_process");
  493. const { promisify } = await import("node:util");
  494. const openssl = promisify(execFile);
  495. const keyPath = FIXTURE_DIR + "/pss-leaf.key";
  496. const rootKeyPath = FIXTURE_DIR + "/pss-root.key";
  497. const rootPath = FIXTURE_DIR + "/pss-root.pem";
  498. const csrPath = FIXTURE_DIR + "/pss-leaf.csr";
  499. const extensionPath = FIXTURE_DIR + "/pss.ext";
  500. await writeFile(keyPath, forge.pki.privateKeyToPem(leafKeys.privateKey));
  501. await writeFile(rootKeyPath, forge.pki.privateKeyToPem(rootKeys.privateKey));
  502. await writeFile(rootPath, rootPem);
  503. await writeFile(
  504. extensionPath,
  505. "subjectAltName=IP:127.0.0.1\nbasicConstraints=CA:FALSE\nextendedKeyUsage=serverAuth\nauthorityKeyIdentifier=none\n",
  506. );
  507. await openssl("openssl", [
  508. "req",
  509. "-new",
  510. "-key",
  511. keyPath,
  512. "-subj",
  513. "/CN=127.0.0.1",
  514. "-out",
  515. csrPath,
  516. ]);
  517. for (const [index, name] of ["pss-sha1", "pss-sha256", "pss-mgf1-sha1"].entries()) {
  518. const certPath = FIXTURE_DIR + "/" + name + ".pem";
  519. await openssl("openssl", [
  520. "x509",
  521. "-req",
  522. "-in",
  523. csrPath,
  524. "-CA",
  525. rootPath,
  526. "-CAkey",
  527. rootKeyPath,
  528. "-set_serial",
  529. String(900 + index),
  530. "-days",
  531. "1",
  532. "-extfile",
  533. extensionPath,
  534. name === "pss-sha1" ? "-sha1" : "-sha256",
  535. "-sigopt",
  536. "rsa_padding_mode:pss",
  537. "-sigopt",
  538. "rsa_mgf1_md:" + (name === "pss-sha256" ? "sha256" : "sha1"),
  539. "-out",
  540. certPath,
  541. ]);
  542. const certificate = await readFile(certPath, "utf8");
  543. const verify = createCustomCaCertificateVerifyProc(readCustomCaCertificatesFromPem(rootPem));
  544. const policyCode = await new Promise((resolve) =>
  545. verify(
  546. {
  547. hostname: "127.0.0.1",
  548. errorCode: -202,
  549. certificate: { data: certificate, issuerCert: { data: rootPem } },
  550. },
  551. resolve,
  552. ),
  553. );
  554. await checkCertificate(name, certificate + rootPem, await readFile(keyPath, "utf8"));
  555. boundary[name].policyCode = policyCode;
  556. }
  557. const circularCertificate = (subject, issuer, key, signer, serial) => {
  558. const value = forge.pki.createCertificate();
  559. value.publicKey = key.publicKey;
  560. value.serialNumber = serial;
  561. value.validity.notBefore = new Date(Date.now() - 86400000);
  562. value.validity.notAfter = new Date(Date.now() + 86400000);
  563. value.setSubject([{ name: "commonName", value: subject }]);
  564. value.setIssuer([{ name: "commonName", value: issuer }]);
  565. value.setExtensions([
  566. { name: "basicConstraints", cA: true },
  567. { name: "subjectAltName", altNames: [{ type: 7, ip: "127.0.0.1" }] },
  568. ]);
  569. value.sign(signer.privateKey, forge.md.sha256.create());
  570. return forge.pki.certificateToPem(value);
  571. };
  572. const circular = createHttpsServer(
  573. {
  574. key: forge.pki.privateKeyToPem(keys.privateKey),
  575. cert:
  576. circularCertificate("cycle-a", "cycle-b", keys, leafKeys, "701") +
  577. circularCertificate("cycle-b", "cycle-a", leafKeys, keys, "702"),
  578. },
  579. (_req, res) => res.end("must-not-accept"),
  580. );
  581. await new Promise((resolve) => circular.listen(0, "127.0.0.1", resolve));
  582. const cancellation = new CancellationToken();
  583. let timedOut = false;
  584. const deadline = setTimeout(() => {
  585. timedOut = true;
  586. cancellation.cancel();
  587. }, 5000);
  588. try {
  589. await autoUpdater.httpExecutor.request(
  590. { protocol: "https:", hostname: "127.0.0.1", port: circular.address().port, path: "/" },
  591. cancellation,
  592. );
  593. boundary.circular = { accepted: true, timedOut };
  594. } catch {
  595. boundary.circular = { accepted: false, timedOut };
  596. } finally {
  597. clearTimeout(deadline);
  598. await new Promise((resolve) => circular.close(resolve));
  599. }
  600. await applyDesktopChromiumNetworkPolicies(session, {}, policyLogger);
  601. const emptyProxyRoute = await updater.resolveProxy(
  602. "http://update-download.invalid/package.zip",
  603. );
  604. return {
  605. boundary,
  606. rejectedUntrusted,
  607. trusted,
  608. emptyProxyRoute,
  609. route,
  610. interrupted,
  611. requests,
  612. policyLogs,
  613. bypass,
  614. downloaded: (await readFile(destination)).length,
  615. };
  616. };
  617. const win = new BrowserWindow({ show: false });
  618. await win.loadURL("data:text/html,network fixture");
  619. }
  620. await build({
  621. stdin: {
  622. resolveDir: desktopDir,
  623. contents:
  624. "(" +
  625. runFixture.toString() +
  626. ")().catch(error => { console.error(error); process.exit(1); });",
  627. },
  628. define: { FIXTURE_DIR: JSON.stringify(artifactDir) },
  629. outfile: entry,
  630. bundle: true,
  631. platform: "node",
  632. format: "esm",
  633. external: ["electron", "electron-updater", "node-forge", "pkijs"],
  634. plugins: [
  635. {
  636. name: "network-only-browser-partition",
  637. setup(api) {
  638. api.onResolve({ filter: /^\.\/browserDataManager\.js$/ }, () => ({
  639. path: "partition",
  640. namespace: "fixture",
  641. }));
  642. api.onLoad({ filter: /.*/, namespace: "fixture" }, () => ({
  643. contents: 'export const EMBEDDED_BROWSER_PARTITION = "persist:embedded-browser";',
  644. }));
  645. },
  646. },
  647. ],
  648. });
  649. const env = { ...process.env };
  650. delete env.ELECTRON_RUN_AS_NODE;
  651. let electronApp;
  652. let output = "";
  653. try {
  654. electronApp = await _electron.launch({ executablePath: require("electron"), args: [entry], env });
  655. for (const stream of [electronApp.process().stdout, electronApp.process().stderr]) {
  656. stream?.on("data", (chunk) => {
  657. output += chunk.toString();
  658. });
  659. }
  660. await electronApp.firstWindow();
  661. const route = await electronApp.evaluate(() => globalThis.fixtureRoute);
  662. assert.match(route, /^PROXY 127\.0\.0\.1:/, "更新器遗漏设置页代理,测试域名将错误直连");
  663. const result = await electronApp.evaluate(() => globalThis.runDownload());
  664. assert.equal(result.interrupted, true);
  665. assert.equal(result.rejectedUntrusted, true);
  666. assert.equal(result.trusted, "trusted");
  667. assert.equal(result.boundary.circular.accepted, false);
  668. assert.equal(result.boundary.circular.timedOut, false);
  669. await writeFile(resolve(artifactDir, "result.json"), JSON.stringify(result, null, 2));
  670. for (const name of [
  671. "critical-unknown",
  672. "critical-unsupported",
  673. "usage-crl-only",
  674. "usage-key-encipherment-only",
  675. "usage-key-agreement-only",
  676. ]) {
  677. assert.equal(result.boundary[name].policyCode, -3, name + " policy");
  678. assert.equal(result.boundary[name].accepted, false, name + " HTTPS");
  679. }
  680. for (const name of [
  681. "noncritical-unknown",
  682. "usage-digital-signature",
  683. "usage-signature-and-encipherment",
  684. "usage-absent",
  685. ]) {
  686. assert.equal(result.boundary[name].policyCode, 0, name + " policy");
  687. assert.equal(result.boundary[name].accepted, true, name + " HTTPS");
  688. }
  689. for (const oid of ["2.5.29.15", "2.5.29.30", "2.5.29.32", "2.5.29.30-ca"])
  690. assert.equal(result.boundary["malformed-" + oid].policyCode, -3, oid + " malformed critical");
  691. assert.equal(result.boundary["pss-sha1"].policyCode, -3, "PSS SHA1 policy");
  692. assert.equal(result.boundary["pss-mgf1-sha1"].policyCode, -3, "PSS MGF1 SHA1 policy");
  693. assert.equal(result.boundary["pss-sha256"].policyCode, 0, "PSS SHA256 policy");
  694. for (const name of ["aki-keyid", "aki-issuer-serial", "pss-sha256"])
  695. assert.equal(result.boundary[name].accepted, true, name);
  696. for (const name of [
  697. "aki-wrong-serial",
  698. "aki-wrong-issuer",
  699. "aki-wrong-signature",
  700. "pss-sha1",
  701. "pss-mgf1-sha1",
  702. ])
  703. assert.equal(result.boundary[name].accepted, false, name);
  704. assert.equal(result.boundary["valid-root"].accepted, true);
  705. assert.equal(result.boundary["valid-intermediate"].accepted, true);
  706. assert.equal(result.boundary["aki-intermediate-serial"].accepted, true);
  707. for (const name of [
  708. "nonca-intermediate",
  709. "pathlen-blocked",
  710. "wrong-host",
  711. "expired",
  712. "not-yet-valid",
  713. "wrong-signature",
  714. "client-only",
  715. "sha1-signed",
  716. "rsa-1024",
  717. ])
  718. assert.equal(result.boundary[name].accepted, false, name);
  719. assert.equal(result.emptyProxyRoute, "DIRECT");
  720. assert.equal(result.downloaded, 256 * 1024);
  721. assert.equal(result.bypass, "bypassed");
  722. for (const name of ["default-session", "auto-updater", "embedded-browser"]) {
  723. assert.ok(
  724. result.policyLogs.some((message) =>
  725. message.startsWith(`[desktop-network] ${name} proxy mode=`),
  726. ),
  727. `network policy log is missing Session name: ${name}`,
  728. );
  729. }
  730. assert.deepEqual(result.requests, [
  731. "http://update-download.invalid/interrupted.zip",
  732. "http://update-download.invalid/package.zip",
  733. ]);
  734. assert.equal((await readFile(resolve(artifactDir, "package.zip"))).length, result.downloaded);
  735. await writeFile(resolve(artifactDir, "result.json"), JSON.stringify(result, null, 2));
  736. console.log("auto-update network smoke: PASS", artifactDir);
  737. } finally {
  738. await writeFile(resolve(artifactDir, "electron.log"), output);
  739. await electronApp?.close().catch(() => {});
  740. }