plugin-extension-network.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. // PLM-EXT-H3:扩展进程的网络跟随设置页(docs/plugins/extension-host.md §12.1、§18.1 H3、§18.4 GitLab 第 2 步)。
  2. // 隔离 HOME:纯 JS fixture 扩展 e2e-ext-network(test/e2e/fixtures/fs/plugins/plugin-extension-network/)经
  3. // plugins.dirs 加载,激活时用全局 fetch 请求 https://gitlab.e2e.example.invalid/api/v4/version。
  4. // 用例起一个 E2E 抓包代理(MITM,自己的 CA,对这个地址回固定响应),在真实设置页填代理、No Proxy 与自定义证书,
  5. // 每改一次经命令中心「重新加载扩展」生效:
  6. // a 设置页没有代理:沿用 Main 环境里的白名单变量(capture 模式下是 WDIO 的上游抓包代理);本用例的代理收不到请求。
  7. // b 只有代理:请求经代理,但代理的证书不受信任,以 TLS 错误失败;代理记录里没有这个请求。
  8. // c 代理 + 自定义证书:请求成功,拿到固定响应;代理记录里有它。
  9. // 不需要模型。运行时证据:Main 日志([extension-host] 的 network 行与 fixture 的 E2E_NETWORK_*)、抓包记录、设置文件。
  10. import { cp, mkdir, readFile, writeFile } from "node:fs/promises";
  11. import { join, resolve } from "node:path";
  12. import {
  13. TID_SETTINGS_BACK_BUTTON,
  14. TID_SETTINGS_PAGE,
  15. TID_SETTINGS_SECTION_NAV,
  16. TID_TASK_SETTINGS_BUTTON,
  17. testId,
  18. } from "@zcode/shared/test-ids";
  19. import {
  20. DEFAULT_WORKSPACE,
  21. clearAppData,
  22. clickTestIdByDom,
  23. getE2EAppDataPaths,
  24. readSettings,
  25. seedSettings,
  26. waitForTestIdByDom,
  27. } from "#e2e/helpers/desktop-app";
  28. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart-runtime";
  29. import { createExtensionLog, writePluginDirsConfig } from "#e2e/helpers/extension-host-views";
  30. import {
  31. DEFAULT_E2E_NETWORK_CAPTURE_NO_PROXY,
  32. startE2ENetworkCaptureProxy,
  33. type E2ENetworkCaptureArtifact,
  34. type E2ENetworkCaptureProxy,
  35. } from "#e2e/helpers/network-capture-proxy";
  36. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  37. import {
  38. capturePluginManualReview,
  39. requirePluginManualReview,
  40. setPluginPresentation,
  41. } from "#e2e/helpers/plugin-management-lifecycle";
  42. const CASE_ID = "PLM-EXT-H3";
  43. // WDIO 以 packages/desktop 为 cwd;按 cwd 解析,晋级移动 spec 后路径不变。
  44. const FIXTURE_ROOT = resolve(
  45. process.cwd(),
  46. "test/e2e/fixtures/fs/plugins/plugin-extension-network",
  47. );
  48. const PLUGIN = "e2e-ext-network";
  49. const PLUGIN_ID = `${PLUGIN}@inline`;
  50. const TARGET_HOST = "gitlab.e2e.example.invalid";
  51. const TARGET_PATH = "/api/v4/version";
  52. const MOCK_BODY = JSON.stringify({ version: "E2E_GITLAB_VERSION" });
  53. // 与其他抓包用例相同的直连名单:本机与 E2E 依赖的站点不经代理。
  54. const NO_PROXY = DEFAULT_E2E_NETWORK_CAPTURE_NO_PROXY;
  55. /** 设置页输入框的占位文字里稳定的一段(中英文相同)。 */
  56. const PROXY_PLACEHOLDER = "127.0.0.1:7890";
  57. const CA_PLACEHOLDER = "root-ca.pem";
  58. const NO_PROXY_PLACEHOLDER = "*.corp.com";
  59. const evidence: Record<string, unknown> = {};
  60. const log = createExtensionLog();
  61. let proxy: E2ENetworkCaptureProxy | null = null;
  62. async function seedFixture(): Promise<void> {
  63. const target = join(getE2EAppDataPaths().homeDir, "fixtures", "extension-network");
  64. await mkdir(target, { recursive: true });
  65. await cp(join(FIXTURE_ROOT, PLUGIN), join(target, PLUGIN), { recursive: true, force: true });
  66. await writePluginDirsConfig([join(target, PLUGIN)], [PLUGIN_ID]);
  67. }
  68. async function openGeneralSettings(): Promise<void> {
  69. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  70. timeout: 15000,
  71. timeoutMsg: "the settings button should be visible",
  72. });
  73. await waitForTestIdByDom(TID_SETTINGS_PAGE, { timeout: 15000 });
  74. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "general"), {
  75. timeout: 15000,
  76. timeoutMsg: "settings should expose the general section",
  77. });
  78. }
  79. async function closeSettings(): Promise<void> {
  80. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  81. timeout: 15000,
  82. timeoutMsg: "the settings back button should be visible",
  83. });
  84. }
  85. /** 设置页网络卡片的一行:按占位文字找输入框,填值,再点同一行的「保存」(输入后才可用)。 */
  86. async function saveNetworkSetting(placeholder: string, value: string): Promise<void> {
  87. const typed = await browser.execute(
  88. (hint, next) => {
  89. const input = Array.from(document.querySelectorAll<HTMLInputElement>("input")).find(
  90. (element) => (element.placeholder ?? "").includes(hint),
  91. );
  92. if (!input) return false;
  93. input.scrollIntoView({ block: "center" });
  94. Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, next);
  95. input.dispatchEvent(new InputEvent("input", { bubbles: true, data: next }));
  96. return true;
  97. },
  98. placeholder,
  99. value,
  100. );
  101. if (!typed) throw new Error(`the settings page should show the input "${placeholder}"`);
  102. await browser.waitUntil(
  103. async () =>
  104. browser.execute((hint) => {
  105. const input = Array.from(document.querySelectorAll<HTMLInputElement>("input")).find(
  106. (element) => (element.placeholder ?? "").includes(hint),
  107. );
  108. const button = input?.closest(".border-t")?.querySelector<HTMLButtonElement>("button");
  109. if (!button || button.disabled) return false;
  110. button.click();
  111. return true;
  112. }, placeholder),
  113. { timeout: 10000, timeoutMsg: `the save button for "${placeholder}" should be enabled` },
  114. );
  115. }
  116. async function runReloadFromCommandCenter(): Promise<void> {
  117. await $('[data-testid="sidebar-search-open"]').click();
  118. const input = $('[role="dialog"] [cmdk-input]');
  119. await input.waitForDisplayed({ timeout: 10000 });
  120. await input.setValue(">重新加载扩展");
  121. await browser.waitUntil(
  122. async () =>
  123. browser.execute(() => {
  124. const item = Array.from(
  125. document.querySelectorAll<HTMLElement>('[role="dialog"] [cmdk-item]'),
  126. ).find((element) => /重新加载扩展|Reload extensions/.test(element.textContent ?? ""));
  127. if (!item) return false;
  128. item.click();
  129. return true;
  130. }),
  131. { timeout: 10000, timeoutMsg: "command center should list 重新加载扩展" },
  132. );
  133. }
  134. async function waitForLogAfter(
  135. from: number,
  136. predicate: (line: string) => boolean,
  137. message: string,
  138. timeout = 60000,
  139. ): Promise<string> {
  140. let found = "";
  141. await browser.waitUntil(
  142. async () => {
  143. found = (await log.lines()).slice(from).find(predicate) ?? "";
  144. return Boolean(found);
  145. },
  146. { timeout, interval: 500, timeoutMsg: message },
  147. );
  148. return found;
  149. }
  150. /** 抓包代理记录里请求了目标地址的条目。 */
  151. async function targetRecords(): Promise<E2ENetworkCaptureArtifact["records"]> {
  152. if (!proxy) return [];
  153. const artifact = JSON.parse(
  154. await readFile(proxy.artifactPath, "utf8").catch(() => '{"records":[]}'),
  155. ) as E2ENetworkCaptureArtifact;
  156. return artifact.records.filter(
  157. (record) => record.host === TARGET_HOST && record.path === TARGET_PATH,
  158. );
  159. }
  160. /** 等扩展进程的一个新代际报出网络来源与 fetch 结果。 */
  161. async function waitForGeneration(from: number, label: string) {
  162. const network = await waitForLogAfter(
  163. from,
  164. (line) =>
  165. line.includes("[extension-host]") && / network proxy=\w+ noProxy=\w+ ca=\w+/.test(line),
  166. `${label}: the supervisor should log the network sources`,
  167. );
  168. const env = await waitForLogAfter(
  169. from,
  170. (line) => line.includes("E2E_NETWORK_ENV"),
  171. `${label}: the extension should log its network environment`,
  172. );
  173. const fetched = await waitForLogAfter(
  174. from,
  175. (line) => line.includes("E2E_NETWORK_FETCH"),
  176. `${label}: the extension should finish its fetch`,
  177. );
  178. const proxyLog = await waitForLogAfter(
  179. from,
  180. (line) => line.includes("environment proxy:"),
  181. `${label}: the extension host should log the environment proxy`,
  182. );
  183. return { network, env, fetched, proxyLog };
  184. }
  185. describe("PLM-EXT-H3 扩展进程的网络跟随设置页", () => {
  186. after(async () => {
  187. await writeFile(
  188. join(process.env.ZCODE_E2E_ARTIFACT_DIR ?? process.cwd(), "plm-ext-h3-evidence.json"),
  189. JSON.stringify(evidence, null, 2),
  190. ).catch(() => undefined);
  191. await proxy?.stop();
  192. proxy = null;
  193. await clearAppData();
  194. });
  195. it("代理与自定义证书从设置页进入扩展进程,重新加载扩展后生效", async function () {
  196. this.timeout(600000);
  197. requirePluginManualReview();
  198. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR ?? process.cwd();
  199. proxy = await startE2ENetworkCaptureProxy({
  200. artifactPath: join(artifactDir, "plm-ext-h3-network-capture.json"),
  201. caDir: join(artifactDir, "plm-ext-h3-ca"),
  202. responseMocks: [
  203. {
  204. host: TARGET_HOST,
  205. method: "GET",
  206. path: TARGET_PATH,
  207. body: MOCK_BODY,
  208. headers: { "content-type": "application/json" },
  209. },
  210. ],
  211. });
  212. evidence.proxyUrl = proxy.proxyUrl;
  213. evidence.caCertPath = proxy.caCertPath;
  214. await seedFixture();
  215. // 修复原因(第一次运行的证据:gen=1 就是 proxy=settings ca=settings):manual-review 默认是 capture 模式,
  216. // WDIO 在 worker 开始时把自己的上游抓包代理与 CA 写进 setting.json 给 agent 用。本用例从「设置页没有代理」开始,
  217. // 所以在旧进程退出后、新进程启动前清掉这三项;本用例不发模型请求。
  218. await restartIntoWorkspacePreservingProfile(DEFAULT_WORKSPACE, {
  219. afterElectronProcessExit: async () => {
  220. evidence.harnessNetworkSettings = await readSettings().then((settings) => ({
  221. httpProxy: Boolean(settings.httpProxy),
  222. httpProxyNoProxy: Boolean(settings.httpProxyNoProxy),
  223. httpProxyCaCertPath: Boolean(settings.httpProxyCaCertPath),
  224. }));
  225. await seedSettings({
  226. httpProxy: undefined,
  227. httpProxyNoProxy: undefined,
  228. httpProxyCaCertPath: undefined,
  229. });
  230. await log.mark();
  231. },
  232. });
  233. await prepareV4ConversationE2E();
  234. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  235. // Main 的环境可能已有代理与 CA:capture 模式下 WDIO 把上游抓包代理的变量写进自己的环境,Electron 继承它。
  236. // 扩展进程的代理、No Proxy 与 CA 只来自设置页(与 CLI 相同,用户决策):Main 环境里的这些变量一律不传。
  237. // 这里记下 Main 环境有没有它们,证明 (a) 的直连不是因为环境本来就是空的。
  238. const envProxy = ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"].some(
  239. (key) => process.env[key],
  240. );
  241. const envNoProxy = ["NO_PROXY", "no_proxy"].some((key) => process.env[key]);
  242. const envCa = Boolean(process.env.NODE_EXTRA_CA_CERTS);
  243. evidence.mainEnvNetwork = { envProxy, envNoProxy, envCa };
  244. // (a) 设置页没有代理:直连(.invalid 解析不到),扩展进程里没有任何代理与 CA 变量。本用例的代理收不到请求。
  245. const direct = await waitForGeneration(0, "without a settings proxy");
  246. evidence.direct = direct;
  247. expect(direct.network).toContain("network proxy=none noProxy=none ca=none");
  248. expect(direct.env).not.toMatch(
  249. /(HTTPS?_PROXY|https?_proxy|NO_PROXY|no_proxy|NODE_EXTRA_CA_CERTS)=set/,
  250. );
  251. expect(direct.proxyLog).toContain("environment proxy: not configured");
  252. expect(direct.fetched).not.toContain("E2E_GITLAB_VERSION");
  253. expect(await targetRecords()).toEqual([]);
  254. // (b) 设置页填代理与 No Proxy,重新加载扩展:请求经本用例的代理,但它的证书不受信任,以 TLS 错误失败。
  255. await openGeneralSettings();
  256. await saveNetworkSetting(PROXY_PLACEHOLDER, proxy.proxyUrl);
  257. await saveNetworkSetting(NO_PROXY_PLACEHOLDER, NO_PROXY);
  258. await browser.waitUntil(
  259. async () => {
  260. const settings = await readSettings();
  261. return settings.httpProxy === proxy?.proxyUrl && settings.httpProxyNoProxy === NO_PROXY;
  262. },
  263. { timeout: 15000, timeoutMsg: "the proxy and No Proxy should be saved in setting.json" },
  264. );
  265. await closeSettings();
  266. const linesBeforeProxy = (await log.lines()).length;
  267. await runReloadFromCommandCenter();
  268. const proxied = await waitForGeneration(linesBeforeProxy, "with a proxy and no CA");
  269. evidence.proxiedWithoutCa = proxied;
  270. expect(proxied.network).toContain("network proxy=settings noProxy=settings ca=none");
  271. expect(proxied.env).toContain(
  272. "HTTPS_PROXY=set https_proxy=set HTTP_PROXY=set http_proxy=set NO_PROXY=set no_proxy=set",
  273. );
  274. expect(proxied.proxyLog).toContain("environment proxy: enabled noProxy=set");
  275. expect(proxied.fetched).toMatch(/E2E_NETWORK_FETCH error code=\S*(CERT|SIGNATURE|SELF_SIGNED)/);
  276. expect(await targetRecords()).toEqual([]);
  277. // (c) 再填自定义证书(代理的 CA),重新加载扩展:请求成功,代理记录里有它。
  278. await openGeneralSettings();
  279. await saveNetworkSetting(CA_PLACEHOLDER, proxy.caCertPath);
  280. await browser.waitUntil(
  281. async () => (await readSettings()).httpProxyCaCertPath === proxy?.caCertPath,
  282. { timeout: 15000, timeoutMsg: "the custom certificate should be saved in setting.json" },
  283. );
  284. await capturePluginManualReview(CASE_ID, "network-settings-zh-CN-zai-light");
  285. await setPluginPresentation({ locale: "en-US", theme: "zai-dark", width: 1400, height: 900 });
  286. await browser.execute((hint) => {
  287. Array.from(document.querySelectorAll<HTMLInputElement>("input"))
  288. .find((element) => (element.placeholder ?? "").includes(hint))
  289. ?.scrollIntoView({ block: "center" });
  290. }, CA_PLACEHOLDER);
  291. await capturePluginManualReview(CASE_ID, "network-settings-en-US-zai-dark");
  292. await setPluginPresentation({ locale: "zh-CN", theme: "zai-light", width: 1400, height: 900 });
  293. await closeSettings();
  294. const linesBeforeCa = (await log.lines()).length;
  295. await runReloadFromCommandCenter();
  296. const trusted = await waitForGeneration(linesBeforeCa, "with a proxy and the CA");
  297. evidence.proxiedWithCa = trusted;
  298. expect(trusted.network).toContain("network proxy=settings noProxy=settings ca=settings");
  299. expect(trusted.env).toContain("NODE_EXTRA_CA_CERTS=set");
  300. expect(trusted.fetched).toContain("E2E_NETWORK_FETCH ok status=200");
  301. expect(trusted.fetched).toContain("E2E_GITLAB_VERSION");
  302. let records: Awaited<ReturnType<typeof targetRecords>> = [];
  303. await browser.waitUntil(
  304. async () => {
  305. records = await targetRecords();
  306. return records.some((record) => record.status === "complete");
  307. },
  308. { timeout: 15000, timeoutMsg: "the proxy should record the extension's request" },
  309. );
  310. evidence.proxyRecords = records.map(({ host, path, method, protocol, status, statusCode }) => ({
  311. host,
  312. path,
  313. method,
  314. protocol,
  315. status,
  316. statusCode,
  317. }));
  318. expect(records[0]).toMatchObject({ protocol: "https", method: "GET", statusCode: 200 });
  319. // 日志不带代理地址与证书路径(代理地址可能带账号密码)。
  320. const networkLines = (await log.lines()).filter(
  321. (line) => line.includes(" network proxy=") || line.includes("environment proxy:"),
  322. );
  323. evidence.networkLines = networkLines;
  324. expect(JSON.stringify(networkLines)).not.toContain(proxy.proxyUrl);
  325. expect(JSON.stringify(networkLines)).not.toContain(proxy.caCertPath);
  326. });
  327. });