| 1 | |
| 2 | |
| 3 | import assert from "node:assert/strict"; |
| 4 | import { spawn } from "node:child_process"; |
| 5 | import { once } from "node:events"; |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; |
| 7 | import { tmpdir } from "node:os"; |
| 8 | import { join } from "node:path"; |
| 9 | import { setTimeout as delay } from "node:timers/promises"; |
| 10 | import { auditBrowser } from "../internal/cage/browser-audit.mjs"; |
| 11 | |
| 12 | assert.equal(process.platform, "linux", "Run this check in the Linux guest"); |
| 13 | assert.ok(process.env.DISPLAY, "Provide an isolated X display"); |
| 14 | const directory = await mkdtemp(join(tmpdir(), "cage-audit-smoke-")); |
| 15 | const chrome = spawn( |
| 16 | process.env.CAGE_TEST_CHROMIUM || "/usr/bin/chromium", |
| 17 | [ |
| 18 | `--user-data-dir=${directory}`, |
| 19 | "--remote-debugging-pipe", |
| 20 | "--no-first-run", |
| 21 | "--no-default-browser-check", |
| 22 | "--disable-background-networking", |
| 23 | "about:blank", |
| 24 | ], |
| 25 | { stdio: ["ignore", "ignore", "pipe", "pipe", "pipe"] }, |
| 26 | ); |
| 27 | let sequence = 0, |
| 28 | buffer = Buffer.alloc(0), |
| 29 | stderr = "", |
| 30 | exit; |
| 31 | const pending = new Map(); |
| 32 | chrome.stderr.on("data", (chunk) => { |
| 33 | stderr = (stderr + chunk).slice(-64000); |
| 34 | }); |
| 35 | chrome.stdio[3].on("error", () => {}); |
| 36 | chrome.on("exit", (code, signal) => { |
| 37 | exit = { code, signal }; |
| 38 | for (const call of pending.values()) { |
| 39 | clearTimeout(call.timer); |
| 40 | call.reject(new Error(`Chromium exited: ${JSON.stringify(exit)}`)); |
| 41 | } |
| 42 | pending.clear(); |
| 43 | }); |
| 44 | chrome.stdio[4].on("data", (chunk) => { |
| 45 | buffer = Buffer.concat([buffer, chunk]); |
| 46 | let end; |
| 47 | while ((end = buffer.indexOf(0)) >= 0) { |
| 48 | const message = JSON.parse(buffer.subarray(0, end)); |
| 49 | buffer = buffer.subarray(end + 1); |
| 50 | const call = pending.get(message.id); |
| 51 | if (!call) continue; |
| 52 | pending.delete(message.id); |
| 53 | clearTimeout(call.timer); |
| 54 | if (message.error) call.reject(new Error(message.error.message)); |
| 55 | else call.resolve(message.result); |
| 56 | } |
| 57 | }); |
| 58 | function cdp(method, params = {}, sessionId, timeout = 10000) { |
| 59 | return new Promise((resolve, reject) => { |
| 60 | if (exit) |
| 61 | return reject(new Error(`Chromium exited: ${JSON.stringify(exit)}`)); |
| 62 | const id = ++sequence; |
| 63 | const timer = setTimeout(() => { |
| 64 | pending.delete(id); |
| 65 | reject(new Error(`Timeout: ${method}`)); |
| 66 | }, timeout); |
| 67 | pending.set(id, { resolve, reject, timer }); |
| 68 | chrome.stdio[3].write( |
| 69 | JSON.stringify({ id, method, params, sessionId }) + "\0", |
| 70 | ); |
| 71 | }); |
| 72 | } |
| 73 | try { |
| 74 | const version = await cdp("Browser.getVersion"); |
| 75 | console.log(JSON.stringify({ browser: version.product })); |
| 76 | await cdp("Target.setDiscoverTargets", { discover: true }); |
| 77 | const { targetInfos } = await cdp("Target.getTargets"); |
| 78 | const userPage = targetInfos.find((page) => page.type === "page"); |
| 79 | assert.ok(userPage); |
| 80 | const { sessionId } = await cdp("Target.attachToTarget", { |
| 81 | targetId: userPage.targetId, |
| 82 | flatten: true, |
| 83 | }); |
| 84 | await cdp( |
| 85 | "Runtime.evaluate", |
| 86 | { |
| 87 | expression: |
| 88 | "document.title = 'Cage test page'; document.body.innerHTML = '<input value=unsaved-text>'; window.cageTestState = 42;", |
| 89 | }, |
| 90 | sessionId, |
| 91 | ); |
| 92 | const state = async () => |
| 93 | ( |
| 94 | await cdp( |
| 95 | "Runtime.evaluate", |
| 96 | { |
| 97 | expression: |
| 98 | "JSON.stringify({title:document.title,input:document.querySelector('input').value,state:window.cageTestState,focus:document.hasFocus()})", |
| 99 | returnByValue: true, |
| 100 | }, |
| 101 | sessionId, |
| 102 | ) |
| 103 | ).result.value; |
| 104 | const before = await state(); |
| 105 | const excluded = new Set(); |
| 106 | const clean = async () => { |
| 107 | assert.equal(excluded.size, 0); |
| 108 | assert.deepEqual( |
| 109 | (await cdp("Target.getBrowserContexts")).browserContextIds, |
| 110 | [], |
| 111 | ); |
| 112 | |
| 113 | |
| 114 | let pages; |
| 115 | const deadline = Date.now() + 2000; |
| 116 | do { |
| 117 | pages = (await cdp("Target.getTargets")).targetInfos |
| 118 | .filter(page => page.type === "page").map(page => page.targetId); |
| 119 | if (pages.length === 1 && pages[0] === userPage.targetId) break; |
| 120 | await delay(25); |
| 121 | } while (Date.now() < deadline); |
| 122 | assert.deepEqual(pages, [userPage.targetId]); |
| 123 | assert.equal(await state(), before, "The user's page or focus changed"); |
| 124 | }; |
| 125 | for (let index = 0; index < 20; index++) { |
| 126 | const result = await auditBrowser(cdp, excluded, false, "UTC"); |
| 127 | assert.equal(result.expected_timezone, "UTC"); |
| 128 | assert.match(result.platform, /Linux/); |
| 129 | await clean(); |
| 130 | } |
| 131 | await assert.rejects( |
| 132 | auditBrowser(cdp, excluded, false, "Invalid/Timezone"), |
| 133 | /浏览器(?:配置)?诊断未完成/, |
| 134 | ); |
| 135 | await clean(); |
| 136 | |
| 137 | let networkStatus = "diagnostic endpoint unavailable"; |
| 138 | try { |
| 139 | const network = await auditBrowser(cdp, excluded, true, "UTC"); |
| 140 | assert.equal(typeof network.network.status, "number"); |
| 141 | networkStatus = network.network.status; |
| 142 | } catch (error) { |
| 143 | |
| 144 | |
| 145 | assert.match(error.message, /诊断页面无法连接|诊断页面尚未就绪|Timeout: Page.navigate/); |
| 146 | } |
| 147 | await clean(); |
| 148 | console.log( |
| 149 | JSON.stringify({ |
| 150 | audits: 22, |
| 151 | networkStatus, |
| 152 | resourcesClean: true, |
| 153 | userPagePreserved: true, |
| 154 | }), |
| 155 | ); |
| 156 | |
| 157 | |
| 158 | for (let seconds = 5; seconds <= 75; seconds += 5) { |
| 159 | await delay(5000); |
| 160 | await clean(); |
| 161 | if (seconds % 15 === 0) |
| 162 | console.log(JSON.stringify({ aliveSeconds: seconds })); |
| 163 | } |
| 164 | assert.ok( |
| 165 | !stderr.includes("rph_with_bc_reference"), |
| 166 | "Chromium reported a dangling context", |
| 167 | ); |
| 168 | console.log( |
| 169 | "PASS: browser survived deferred cleanup with its page and focus intact", |
| 170 | ); |
| 171 | } finally { |
| 172 | if (!exit) { |
| 173 | const exited = once(chrome, "exit"); |
| 174 | chrome.kill("SIGTERM"); |
| 175 | const kill = setTimeout(() => chrome.kill("SIGKILL"), 5000); |
| 176 | await exited; |
| 177 | clearTimeout(kill); |
| 178 | } |
| 179 | await rm(directory, { recursive: true, force: true }); |
| 180 | } |