auto-update-ca-constraints-smoke.mjs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. import assert from "node:assert/strict";
  2. import { createServer } from "node:https";
  3. import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
  4. import { createRequire } from "node:module";
  5. import { resolve } from "node:path";
  6. import { build } from "esbuild";
  7. import { _electron } from "playwright-core";
  8. import forge from "node-forge";
  9. const desktop = resolve(import.meta.dirname, "..");
  10. const require = createRequire(import.meta.url);
  11. await mkdir(resolve(desktop, ".e2e-artifacts"), { recursive: true });
  12. const artifact = await mkdtemp(resolve(desktop, ".e2e-artifacts/ca-constraints-"));
  13. const home = resolve(artifact, "home");
  14. await mkdir(resolve(home, ".zcode/v2"), { recursive: true });
  15. const keys = Array.from({ length: 3 }, () => forge.pki.rsa.generateKeyPair(2048));
  16. let serial = 2000;
  17. const pem = forge.pki.certificateToPem;
  18. const asn = forge.asn1;
  19. const seq = (children) => asn.create(asn.Class.UNIVERSAL, asn.Type.SEQUENCE, true, children);
  20. function certificate(name, key, issuer, signer, extensions, ca = false) {
  21. const cert = forge.pki.createCertificate();
  22. cert.publicKey = key.publicKey;
  23. cert.serialNumber = (++serial).toString(16);
  24. cert.validity.notBefore = new Date(Date.now() - 86400000);
  25. cert.validity.notAfter = new Date(Date.now() + 86400000);
  26. cert.setSubject([{ name: "commonName", value: name }]);
  27. cert.setIssuer(issuer?.subject.attributes ?? cert.subject.attributes);
  28. cert.setExtensions([{ name: "basicConstraints", critical: true, cA: ca }, ...extensions]);
  29. cert.sign(signer.privateKey, forge.md.sha256.create());
  30. return cert;
  31. }
  32. const usage = { name: "keyUsage", critical: true, keyCertSign: true };
  33. const root = certificate("Constraint Root", keys[0], null, keys[0], [usage], true);
  34. const caPath = resolve(artifact, "root.pem");
  35. await writeFile(caPath, pem(root));
  36. function constraint(permitted, excluded = [], minimum = 0) {
  37. const subtree = ([type, value]) =>
  38. seq([
  39. asn.create(asn.Class.CONTEXT_SPECIFIC, type, false, value),
  40. ...(minimum ? [asn.create(asn.Class.CONTEXT_SPECIFIC, 0, false, "\x01")] : []),
  41. ]);
  42. return {
  43. id: "2.5.29.30",
  44. critical: true,
  45. value: asn
  46. .toDer(
  47. seq([
  48. ...(permitted.length
  49. ? [asn.create(asn.Class.CONTEXT_SPECIFIC, 0, true, permitted.map(subtree))]
  50. : []),
  51. ...(excluded.length
  52. ? [asn.create(asn.Class.CONTEXT_SPECIFIC, 1, true, excluded.map(subtree))]
  53. : []),
  54. ]),
  55. )
  56. .getBytes(),
  57. };
  58. }
  59. const dns = (value) => [2, value];
  60. const ip = (value) => [7, String.fromCharCode(...value)];
  61. const parentDns = constraint([dns(".allowed.invalid")]);
  62. const narrowDns = constraint([dns(".sub.allowed.invalid")]);
  63. const parentIp = constraint([ip([127, 0, 0, 0, 255, 0, 0, 0])]);
  64. const narrowIp = constraint([ip([127, 0, 0, 0, 255, 255, 0, 0])]);
  65. const loopbackV6 = [...Array(15).fill(0), 1];
  66. const exactV6 = constraint([ip([...loopbackV6, ...Array(16).fill(255)])]);
  67. const rangeV6 = constraint([
  68. ip([...Array(16).fill(0), ...Array(8).fill(255), ...Array(8).fill(0)]),
  69. ]);
  70. const badUsage = (value) => ({ id: "2.5.29.15", critical: true, value });
  71. const definitions = [
  72. { name: "valid-dns", expected: true },
  73. {
  74. name: "ca-integer-key-usage",
  75. usage: badUsage(
  76. asn.toDer(asn.create(asn.Class.UNIVERSAL, asn.Type.INTEGER, false, "\x04")).getBytes(),
  77. ),
  78. },
  79. { name: "ca-undefined-usage-bit", usage: badUsage("\x03\x03\x00\x04\x01") },
  80. { name: "ca-crl-only", usage: { name: "keyUsage", critical: true, cRLSign: true } },
  81. {
  82. name: "dns-widen",
  83. parent: parentDns,
  84. child: constraint([dns(".evil.invalid")]),
  85. host: "host.evil.invalid",
  86. },
  87. { name: "dns-narrow", parent: parentDns, child: narrowDns, expected: true },
  88. {
  89. name: "dns-excluded",
  90. parent: parentDns,
  91. child: constraint([], [dns("host.sub.allowed.invalid")]),
  92. },
  93. {
  94. name: "dns-second-san-outside",
  95. parent: parentDns,
  96. child: narrowDns,
  97. extraNames: [{ type: 2, value: "host.evil.invalid" }],
  98. },
  99. { name: "ipv4-narrow", parent: parentIp, child: narrowIp, host: "127.0.0.1", expected: true },
  100. {
  101. name: "ipv4-widen",
  102. parent: constraint([ip([10, 0, 0, 0, 255, 0, 0, 0])]),
  103. child: narrowIp,
  104. host: "127.0.0.1",
  105. },
  106. {
  107. name: "ipv4-excluded",
  108. parent: parentIp,
  109. child: constraint([], [ip([127, 0, 0, 1, 255, 255, 255, 255])]),
  110. host: "127.0.0.1",
  111. },
  112. { name: "unsupported-mail-constraint", parent: constraint([[1, ".example.invalid"]]) },
  113. { name: "unsupported-minimum", parent: constraint([dns(".allowed.invalid")], [], 1) },
  114. { name: "constrained-wildcard", parent: parentDns, wildcard: true },
  115. { name: "constrained-cn-only", parent: parentDns, cnOnly: true },
  116. { name: "ipv6-narrow", parent: rangeV6, child: exactV6, host: "::1", expected: true },
  117. {
  118. name: "ipv6-widen",
  119. parent: constraint([ip([32, 1, ...Array(14).fill(0), ...Array(16).fill(255)])]),
  120. child: exactV6,
  121. host: "::1",
  122. },
  123. {
  124. name: "ipv6-excluded",
  125. parent: rangeV6,
  126. child: constraint([], [ip([...loopbackV6, ...Array(16).fill(255)])]),
  127. host: "::1",
  128. },
  129. ];
  130. const cases = [];
  131. const servers = [];
  132. for (const d of definitions) {
  133. const parent = certificate(
  134. "Parent " + d.name,
  135. keys[1],
  136. root,
  137. keys[0],
  138. [d.usage ?? usage, ...(d.parent ? [d.parent] : [])],
  139. true,
  140. );
  141. const child = certificate(
  142. "Child " + d.name,
  143. keys[2],
  144. parent,
  145. keys[1],
  146. [usage, ...(d.child ? [d.child] : [])],
  147. true,
  148. );
  149. const host = d.host ?? "host.sub.allowed.invalid";
  150. const names =
  151. host === "127.0.0.1" || host === "::1"
  152. ? [{ type: 7, ip: host }]
  153. : [{ type: 2, value: d.wildcard ? "*.sub.allowed.invalid" : host }];
  154. const leaf = certificate(host, keys[0], child, keys[2], [
  155. { name: "keyUsage", critical: true, digitalSignature: true },
  156. ...(!d.cnOnly
  157. ? [{ name: "subjectAltName", altNames: [...names, ...(d.extraNames ?? [])] }]
  158. : []),
  159. ]);
  160. const chain = [leaf, child, parent, root].map((cert) => pem(cert));
  161. const server = createServer(
  162. { key: forge.pki.privateKeyToPem(keys[0].privateKey), cert: chain.join("") },
  163. (_req, res) => res.end("verified"),
  164. );
  165. await new Promise((done) => server.listen(0, host === "::1" ? "::1" : "127.0.0.1", done));
  166. servers.push(server);
  167. cases.push({
  168. name: d.name,
  169. host,
  170. chain,
  171. port: server.address().port,
  172. expected: d.expected ?? false,
  173. });
  174. }
  175. // 显式配置的单证书锚不必具备 CA 签发用途,但仍受叶证书的全部安全约束。
  176. const directAnchors = [pem(root)];
  177. for (const definition of [
  178. { name: "self-signed-ca-false", expected: true },
  179. { name: "self-signed-ca-true-signature-only", ca: true, expected: true },
  180. { name: "self-signed-wrong-host", wrongHost: true },
  181. { name: "self-signed-expired", expired: true },
  182. { name: "self-signed-future", future: true },
  183. { name: "self-signed-wrong-signature", wrongSignature: true },
  184. { name: "self-signed-unknown-critical", unknownCritical: true },
  185. { name: "self-signed-crl-only", crlOnly: true },
  186. { name: "self-signed-rsa-1024", weakKey: true },
  187. { name: "self-signed-unconfigured", unconfigured: true },
  188. { name: "self-signed-sha1", sha1: true },
  189. { name: "self-signed-client-only", clientOnly: true },
  190. ]) {
  191. const key = definition.weakKey ? forge.pki.rsa.generateKeyPair(1024) : keys[0];
  192. const extensions = [
  193. {
  194. name: "keyUsage",
  195. critical: true,
  196. digitalSignature: !definition.crlOnly,
  197. cRLSign: !!definition.crlOnly,
  198. },
  199. {
  200. name: "subjectAltName",
  201. altNames: [{ type: 7, ip: definition.wrongHost ? "127.0.0.2" : "127.0.0.1" }],
  202. },
  203. {
  204. name: "extKeyUsage",
  205. serverAuth: !definition.clientOnly,
  206. clientAuth: !!definition.clientOnly,
  207. },
  208. ];
  209. if (definition.unknownCritical)
  210. extensions.push({
  211. id: "1.2.3.4.5.6.7.8.1",
  212. critical: true,
  213. value: asn.toDer(seq([])).getBytes(),
  214. });
  215. const anchor = certificate(definition.name, key, null, key, extensions, !!definition.ca);
  216. if (definition.expired) anchor.validity.notAfter = new Date(Date.now() - 3600000);
  217. if (definition.future) anchor.validity.notBefore = new Date(Date.now() + 3600000);
  218. anchor.sign(
  219. definition.wrongSignature ? keys[1].privateKey : key.privateKey,
  220. definition.sha1 ? forge.md.sha1.create() : forge.md.sha256.create(),
  221. );
  222. const value = pem(anchor);
  223. if (!definition.unconfigured) directAnchors.push(value);
  224. const server = createServer(
  225. { key: forge.pki.privateKeyToPem(key.privateKey), cert: value, ciphers: "DEFAULT:@SECLEVEL=0" },
  226. (_req, res) => res.end("verified"),
  227. );
  228. await new Promise((done) => server.listen(0, "127.0.0.1", done));
  229. servers.push(server);
  230. cases.push({
  231. name: definition.name,
  232. host: "127.0.0.1",
  233. chain: [value],
  234. port: server.address().port,
  235. expected: definition.expected ?? false,
  236. });
  237. }
  238. // CA 文件常被直接配置为 fullchain;附带叶证书不得抢先成为常规建链的锚。
  239. const bundleRoot = certificate("Bundle Root", keys[0], null, keys[0], [usage], true);
  240. const bundleIntermediate = certificate(
  241. "Bundle Intermediate",
  242. keys[1],
  243. bundleRoot,
  244. keys[0],
  245. [usage],
  246. true,
  247. );
  248. const pinIssuer = certificate("Unconfigured Pin Issuer", keys[0], null, keys[0], [usage], true);
  249. for (const definition of [
  250. { name: "bundle-root-and-leaf", expected: true },
  251. { name: "bundle-full-chain", intermediate: true, expected: true },
  252. { name: "bundle-ca-flag-leaf-signature-only", ca: true, expected: true },
  253. { name: "pinned-non-self-issued", pinOnly: true, expected: false },
  254. ]) {
  255. const issuer = definition.pinOnly
  256. ? pinIssuer
  257. : definition.intermediate
  258. ? bundleIntermediate
  259. : bundleRoot;
  260. const leaf = certificate(
  261. definition.name,
  262. keys[2],
  263. issuer,
  264. definition.intermediate ? keys[1] : keys[0],
  265. [
  266. { name: "keyUsage", critical: true, digitalSignature: true },
  267. { name: "subjectAltName", altNames: [{ type: 7, ip: "127.0.0.1" }] },
  268. { name: "extKeyUsage", serverAuth: true },
  269. ],
  270. !!definition.ca,
  271. );
  272. const configured = definition.pinOnly
  273. ? [leaf]
  274. : definition.intermediate
  275. ? [leaf, bundleIntermediate, bundleRoot]
  276. : [bundleRoot, leaf];
  277. directAnchors.push(...configured.map(pem));
  278. const chain = [leaf, ...(definition.intermediate ? [bundleIntermediate] : [])].map(pem);
  279. const server = createServer(
  280. { key: forge.pki.privateKeyToPem(keys[2].privateKey), cert: chain.join("") },
  281. (_req, res) => res.end("verified"),
  282. );
  283. await new Promise((done) => server.listen(0, "127.0.0.1", done));
  284. servers.push(server);
  285. cases.push({
  286. name: definition.name,
  287. host: "127.0.0.1",
  288. chain,
  289. port: server.address().port,
  290. expected: definition.expected,
  291. });
  292. }
  293. await writeFile(caPath, directAnchors.join("\n"));
  294. await writeFile(
  295. resolve(home, ".zcode/v2/setting.json"),
  296. JSON.stringify({
  297. locale: "en-US",
  298. httpProxyCaCertPath: caPath,
  299. embeddedBrowserAllowInsecureCertificates: true,
  300. autoDownloadAndInstallUpdates: false,
  301. }),
  302. );
  303. const appArg = process.argv.indexOf("--app");
  304. await writeFile(resolve(artifact, "cases.json"), JSON.stringify(cases, null, 2));
  305. const executable = appArg >= 0 ? process.argv[appArg + 1] : require("electron");
  306. assert(executable, "--app requires an executable");
  307. const entry = resolve(artifact, "main.mjs");
  308. if (appArg < 0) {
  309. await build({
  310. stdin: {
  311. resolveDir: desktop,
  312. contents: `
  313. import {app, BrowserWindow, session} from 'electron';
  314. import {readFile} from 'node:fs/promises';
  315. import {applyDesktopChromiumNetworkPolicies, createCustomCaCertificateVerifyProc, readCustomCaCertificatesFromPem} from './src/main/desktopNetworkPolicy.ts';
  316. void (async () => {
  317. app.setPath('userData', ${JSON.stringify(resolve(artifact, "user-data"))});
  318. await app.whenReady();
  319. await applyDesktopChromiumNetworkPolicies(session,{httpProxyCaCertPath:${JSON.stringify(caPath)}}, {info(){},warn(){}});
  320. globalThis.verifyPolicy=createCustomCaCertificateVerifyProc(readCustomCaCertificatesFromPem(await readFile(${JSON.stringify(caPath)},'utf8')));
  321. const window = new BrowserWindow({show:false});
  322. await window.loadURL('data:text/html,CA%20constraints');
  323. })().catch(error => { console.error(error); app.exit(1); });
  324. `,
  325. },
  326. bundle: true,
  327. platform: "node",
  328. format: "esm",
  329. outfile: entry,
  330. external: ["electron", "electron-updater", "pkijs"],
  331. plugins: [
  332. {
  333. name: "unused-browser-partition",
  334. setup(b) {
  335. b.onResolve({ filter: /^\.\/browserDataManager\.js$/ }, () => ({
  336. path: "partition",
  337. namespace: "fixture",
  338. }));
  339. b.onLoad({ filter: /.*/, namespace: "fixture" }, () => ({
  340. contents: 'export const EMBEDDED_BROWSER_PARTITION="persist:embedded-browser";',
  341. }));
  342. },
  343. },
  344. ],
  345. });
  346. }
  347. const env = {
  348. ...process.env,
  349. HOME: home,
  350. ZCODE_DATA_BASE_DIR: home,
  351. ZCODE_DESKTOP_HOME_DIR: home,
  352. ZCODE_DESKTOP_USER_DATA_DIR: resolve(artifact, "user-data"),
  353. ZCODE_DESKTOP_SESSION_DATA_DIR: resolve(artifact, "session"),
  354. ZCODE_DESKTOP_APPLICATION_NAME: "ZCode CA Constraints Acceptance",
  355. };
  356. delete env.ELECTRON_RUN_AS_NODE;
  357. let application;
  358. let output = "";
  359. try {
  360. application = await _electron.launch({
  361. executablePath: executable,
  362. args: [...(appArg < 0 ? [entry] : []), "--host-resolver-rules=MAP *.invalid 127.0.0.1"],
  363. env,
  364. cwd: home,
  365. });
  366. for (const stream of [application.process().stdout, application.process().stderr])
  367. stream?.on("data", (data) => {
  368. output += data;
  369. process.stdout.write(data);
  370. });
  371. await application.firstWindow();
  372. const result = await application.evaluate(async ({ app }, inputs) => {
  373. const { createRequire } = process.getBuiltinModule("node:module");
  374. const { autoUpdater, CancellationToken } = createRequire(app.getAppPath() + "/package.json")(
  375. "electron-updater",
  376. );
  377. const results = [];
  378. for (const c of inputs) {
  379. console.info("CA constraint case", c.name);
  380. let policyCode;
  381. if (globalThis.verifyPolicy) {
  382. let certificate;
  383. for (const data of [...c.chain].reverse()) certificate = { data, issuerCert: certificate };
  384. policyCode = await new Promise((done) =>
  385. globalThis.verifyPolicy({ hostname: c.host, errorCode: -202, certificate }, done),
  386. );
  387. }
  388. const token = new CancellationToken();
  389. let accepted = false,
  390. timedOut = false;
  391. const timer = setTimeout(() => {
  392. timedOut = true;
  393. token.cancel();
  394. }, 5000);
  395. try {
  396. accepted =
  397. (await autoUpdater.httpExecutor.request(
  398. { protocol: "https:", hostname: c.host, port: c.port, path: "/" },
  399. token,
  400. )) === "verified";
  401. } catch {
  402. } finally {
  403. clearTimeout(timer);
  404. }
  405. results.push({ name: c.name, expected: c.expected, policyCode, accepted, timedOut });
  406. }
  407. return { version: app.getVersion(), packaged: app.isPackaged, results };
  408. }, cases);
  409. await writeFile(resolve(artifact, "result.json"), JSON.stringify(result, null, 2));
  410. for (const c of result.results) {
  411. if (appArg < 0) assert.equal(c.policyCode, c.expected ? 0 : -3, c.name + " policy");
  412. assert.equal(c.timedOut, false, c.name + " timeout");
  413. assert.equal(c.accepted, c.expected, c.name + " HTTPS");
  414. }
  415. console.log(JSON.stringify({ artifact, passed: cases.length, ...result }));
  416. } finally {
  417. await writeFile(resolve(artifact, "application.log"), output);
  418. await application?.close();
  419. await Promise.all(
  420. servers.map(
  421. (server) =>
  422. new Promise((done) => {
  423. server.closeAllConnections();
  424. server.close(done);
  425. }),
  426. ),
  427. );
  428. console.log("CA_CONSTRAINTS_ARTIFACT", artifact);
  429. }