Debian Codegraph @

test/common/webdriver_bidi.py

raw
1 #
2 # Copyright (C) 2024 Red Hat, Inc.
3 # SPDX-License-Identifier: LGPL-2.1-or-later
4
5
6 """BiDi session/API driver
7
8 This directly talks the https://w3c.github.io/webdriver-bidi/ protocol from async Python,
9 without any node/JS in between. The only dependencies are aiohttp, firefox, and/or
10 chromedriver+chromium (or headless_shell).
11 """
12
13 import asyncio
14 import collections
15 import contextlib
16 import json
17 import logging
18 import os
19 import socket
20 import sys
21 import tempfile
22 from collections.abc import AsyncIterator, Iterator
23 from dataclasses import dataclass
24 from pathlib import Path
25 from typing import Any, AsyncIterable, Iterable, Self
26
27 import aiohttp
28
29 log_proto = logging.getLogger("bidi.proto")
30 log_command = logging.getLogger("bidi.command")
31
32
33 JsonObject = dict[str, Any]
34
35
36 class WebdriverError(RuntimeError):
37 pass
38
39
40 @dataclass
41 class ConsoleMessage:
42 level: str # like "info"
43 type: str # usually "console"
44 timestamp: int
45 args: list[object]
46 text: str
47
48 def __init__(self, message_params: JsonObject) -> None:
49 self.level = message_params["level"]
50 self.type = message_params["type"]
51 self.timestamp = message_params["timestamp"]
52 self.args = message_params.get("args", [])
53 self.text = message_params["text"]
54
55 def __str__(self) -> str:
56 return f"> {self.level}: {self.text}"
57
58
59 class ConsoleLog(Iterable[ConsoleMessage], AsyncIterable[ConsoleMessage]):
60 def __init__(self) -> None:
61 self.ready = asyncio.Event()
62 self.log = collections.deque[ConsoleMessage]()
63 self.eof = False
64
65 def append(self, message: ConsoleMessage) -> None:
66 self.log.append(message)
67 self.ready.set()
68
69 def close(self) -> None:
70 self.eof = True
71 self.ready.set()
72
73 def __iter__(self) -> Iterator[ConsoleMessage]:
74 """Iterates over all items currently in the log. If .eof is false,
75 then more items might still be added."""
76 return iter(self.log)
77
78 async def __aiter__(self) -> AsyncIterator[ConsoleMessage]:
79 """Iterates over all items in the log, waiting for the next item to
80 come, and only stopping once the browser session is closed. Consumes
81 the log entries."""
82 while not self.eof:
83 if len(self.log):
84 yield self.log.popleft()
85 else:
86 self.ready.clear()
87 await self.ready.wait()
88
89
90 @dataclass
91 class BidiSession:
92 ws_url: str
93 session_url: str
94 process: asyncio.subprocess.Process
95
96
97 # Return port numbers that were free at the time of checking
98 # They might be in use again by the time the function returns...
99 def pick_ports(count: int) -> list[int]:
100 sockets: list[socket.socket] = []
101 ports: list[int] = []
102
103 try:
104 for _ in range(count):
105 sock = socket.socket()
106 sock.bind(('127.0.0.1', 0))
107 sockets.append(sock)
108 ports.append(sock.getsockname()[1])
109 finally:
110 for s in sockets:
111 s.close()
112
113 return ports
114
115
116 def jsquote(js: object) -> str:
117 return json.dumps(js)
118
119
120 def unpack_value(raw: Any) -> Any:
121 """Convert a WebDriver type/value object into a plain Python object"""
122
123 if not isinstance(raw, dict):
124 return raw
125 try:
126 type_ = raw["type"]
127 except KeyError as e:
128 raise ValueError(f"No type in {raw!r}") from e
129 if type_ in ["undefined", "null"]:
130 return None
131 if type_ in ["string", "boolean", "number"]:
132 return raw["value"]
133 # serialized BiDi objects, don't touch
134 if type_ in ["function", "node", "window"]:
135 return raw
136 if type_ == "array":
137 return [unpack_value(v) for v in raw["value"]]
138 if type_ == "object":
139 obj = {}
140 for k, v in raw["value"]:
141 obj[k] = unpack_value(v)
142 return obj
143 raise ValueError(f"Unknown type in {raw!r}")
144
145
146 # FIXME: No current way to say `contextlib.AbstractAsyncContextManager[Self]`
147 class WebdriverBidi:
148 http_session: aiohttp.ClientSession
149
150 def __init__(self, *, headless: bool = False) -> None:
151 self.headless = headless
152 self.last_id = 0
153 self.pending_commands: dict[int, asyncio.Future[JsonObject]] = {}
154 self.logs = ConsoleLog()
155 self.bidi_session: BidiSession | None = None
156 self.future_wait_page_load = None
157 self.top_context: str | None = None # top-level browsingContext
158 self.context: str | None # currently selected context (top or iframe)
159
160 # NB: nothing accesses self.homedir_temp. It's only to hold the reference.
161 self.homedir_temp = tempfile.TemporaryDirectory(prefix="cockpit-test-browser-home-")
162 self.homedir = Path(self.homedir_temp.name)
163 self.download_dir = self.homedir / 'Downloads'
164 self.download_dir.mkdir()
165
166 async def start_bidi_session(self) -> None:
167 raise NotImplementedError
168
169 async def close_bidi_session(self) -> None:
170 raise NotImplementedError
171
172 async def close(self) -> None:
173 assert self.bidi_session is not None
174 log_proto.debug("cleaning up webdriver")
175
176 await self.ws.close()
177 await self.close_bidi_session()
178 try:
179 self.bidi_session.process.terminate()
180 except ProcessLookupError:
181 # Already gone? No problem.
182 pass
183 await self.bidi_session.process.wait()
184 self.bidi_session = None
185 await self.http_session.close()
186
187 await self.task_reader
188
189 def ws_done_callback(self, _task: asyncio.Task[None]) -> None:
190 for fut in self.pending_commands.values():
191 if not fut.done():
192 fut.set_exception(WebdriverError("websocket closed"))
193 self.logs.close()
194
195 async def start_session(self) -> None:
196 self.http_session = aiohttp.ClientSession(raise_for_status=True)
197 await self.start_bidi_session()
198 assert self.bidi_session
199 self.ws = await self.http_session.ws_connect(self.bidi_session.ws_url)
200 self.task_reader = asyncio.create_task(self.ws_reader(self.ws), name="bidi_reader")
201 self.task_reader.add_done_callback(self.ws_done_callback)
202
203 await self.bidi("session.subscribe", events=[
204 "log.entryAdded", "browsingContext.domContentLoaded",
205 ])
206
207 # wait for browser to initialize default context
208 for _ in range(10):
209 realms = (await self.bidi("script.getRealms"))["realms"]
210 if len(realms) > 0:
211 self.top_context = realms[0]["context"]
212 self.context = self.top_context
213 break
214 await asyncio.sleep(0.5)
215 else:
216 raise WebdriverError("timed out waiting for default realm")
217
218 async def __aenter__(self) -> Self:
219 await self.start_session()
220 return self
221
222 async def __aexit__(self, *_excinfo: Any) -> None:
223 if self.bidi_session is not None:
224 await self.close()
225
226 async def ws_reader(self, ws: aiohttp.client.ClientWebSocketResponse) -> None:
227 async for msg in ws:
228 if msg.type == aiohttp.WSMsgType.TEXT:
229 data = json.loads(msg.data)
230 log_proto.debug("ws TEXT → %r", data)
231 id_ = data.get("id")
232 if id_ in self.pending_commands:
233 log_proto.debug("ws_reader: resolving pending command %i", id_)
234 pending_command = self.pending_commands[id_]
235 if data["type"] == "success":
236 if data["result"].get("type") == "exception":
237 pending_command.set_exception(
238 WebdriverError(data["result"]["exceptionDetails"]["text"]))
239 else:
240 pending_command.set_result(data["result"])
241 elif data["type"] == "exception":
242 pending_command.set_exception(
243 WebdriverError(data["exceptionDetails"]["text"]))
244 elif data["type"] == "error":
245 pending_command.set_exception(
246 WebdriverError(f"{data['error']}: {data.get('message', '')}"))
247 else:
248 pending_command.set_exception(
249 WebdriverError(f"unknown response type: {data!r}"))
250 del self.pending_commands[id_]
251 continue
252
253 if data["type"] == "event":
254 if data["method"] == "log.entryAdded":
255 message = ConsoleMessage(data["params"])
256 self.logs.append(message)
257 print(str(message), file=sys.stderr)
258 continue
259 if data["method"] == "browsingContext.domContentLoaded":
260 if self.future_wait_page_load:
261 log_command.debug("page loaded: %r, resolving wait page load future", data["params"])
262 self.future_wait_page_load.set_result(data["params"]["url"])
263 else:
264 log_command.debug("page loaded: %r (not awaited)", data["params"])
265 continue
266
267 log_proto.warning("ws_reader: unhandled message %r", data)
268 elif msg.type == aiohttp.WSMsgType.ERROR:
269 log_proto.error("BiDi failure: %s", msg)
270 break
271
272 async def bidi(self, method: str, *, quiet: bool = False, timeout: int = 10, **params: Any) -> JsonObject:
273 """Send a Webdriver BiDi command and return the JSON response
274
275 Most commands ought to be quick, so the default timeout is 10 seconds.
276 Set a custom one if you call a function which waits/polls for something
277 for a non-trivial duration.
278 """
279 tag = self.last_id
280 self.last_id += 1
281
282 payload = json.dumps({"id": tag, "method": method, "params": params})
283 log_command.info("← %s(%r) [id %i]", method, 'quiet' if quiet else params, tag)
284 await self.ws.send_str(payload)
285 future = asyncio.get_event_loop().create_future()
286 self.pending_commands[tag] = future
287 res = await asyncio.wait_for(future, timeout=timeout)
288 if "result" in res:
289 log_proto.debug("[id %i] unpacking raw result %r", tag, res["result"])
290 value = unpack_value(res["result"])
291 res["result"] = value
292 if not quiet:
293 log_command.info("→ %r", res)
294 return res
295
296 # this is mostly unused; testlib uses ph_find() due to sizzle
297 async def locate(self, selector: str) -> str:
298 r = await self.bidi("browsingContext.locateNodes", context=self.context,
299 locator={"type": "css", "value": selector})
300 nodes = r["nodes"]
301 if len(nodes) == 0:
302 raise WebdriverError(f"no element found for {selector}")
303 if len(nodes) > 1:
304 raise WebdriverError(f"selector {selector} is ambiguous: {nodes}")
305 log_command.info("locate(%s) = %r", selector, nodes[0])
306 return nodes[0]
307
308 async def switch_to_frame(self, name: str) -> None:
309 self.switch_to_top()
310 frame = await self.locate(f"iframe[name='{name}']")
311 cw = await self.bidi("script.callFunction",
312 functionDeclaration="f => f.contentWindow",
313 arguments=[frame],
314 awaitPromise=False,
315 target={"context": self.top_context})
316 self.context = cw["result"]["value"]["context"]
317 log_command.info("← switch_to_frame(%s)", name)
318
319 def switch_to_top(self) -> None:
320 self.context = self.top_context
321 log_command.info("← switch_to_top")
322
323 def in_top_context(self) -> bool:
324 return self.context == self.top_context
325
326 @contextlib.contextmanager
327 def restore_context(self) -> Iterator[None]:
328 saved = self.context
329 try:
330 yield
331 finally:
332 self.context = saved
333
334
335 class ChromiumBidi(WebdriverBidi):
336 def __init__(self, *, headless: bool = False) -> None:
337 super().__init__(headless=headless)
338 self.cdp_ws: aiohttp.client.ClientWebSocketResponse | None = None
339
340 async def start_bidi_session(self) -> None:
341 assert self.bidi_session is None
342
343 candidate_binaries = ["/usr/bin/chromium-browser", "/usr/bin/chromium"]
344 if self.headless:
345 candidate_binaries.append("/usr/lib64/chromium-browser/headless_shell")
346 binaries = [path for path in candidate_binaries if os.path.exists(path)]
347 if not binaries:
348 raise WebdriverError(f"no Chromium binary found: tried {' '.join(candidate_binaries)}")
349 chrome_binary = binaries[0]
350 log_proto.debug("webdriver chromium binary: %s", chrome_binary)
351
352 session_args = {"capabilities": {
353 "alwaysMatch": {
354 "webSocketUrl": True,
355 "acceptInsecureCerts": True,
356 "goog:chromeOptions": {
357 "binary": chrome_binary,
358 "args": [
359 "--font-render-hinting=none",
360 "--disable-pushstate-throttle",
361 # HACK: For Cockpit-Files downloading uses `window.open` which is sometimes allowed depending
362 # on unpredictable and unknown heuristics
363 "--disable-popup-blocking",
364 ] + (["--headless"] if self.headless else []),
365 },
366 }
367 }}
368
369 [webdriver_port] = pick_ports(1)
370 driver = await asyncio.create_subprocess_exec(
371 "chromedriver", "--port=" + str(webdriver_port),
372 env=dict(os.environ, HOME=str(self.homedir)))
373
374 wd_url = f"http://localhost:{webdriver_port}"
375
376 # webdriver needs some time to launch
377 for retry in range(1, 10):
378 try:
379 async with self.http_session.post(f"{wd_url}/session",
380 data=json.dumps(session_args).encode()) as resp:
381 session_info = json.loads(await resp.text())["value"]
382 log_proto.debug("webdriver session request: %r %r", resp, session_info)
383 break
384 except (IOError, aiohttp.client.ClientResponseError) as e:
385 log_proto.debug("waiting for webdriver: %s", e)
386 await asyncio.sleep(0.1 * retry)
387 else:
388 raise WebdriverError("could not connect to chromedriver")
389
390 self.cdp_address = session_info["capabilities"]["goog:chromeOptions"]["debuggerAddress"]
391 self.last_cdp_id = 0
392
393 self.bidi_session = BidiSession(
394 session_url=f"{wd_url}/session/{session_info['sessionId']}",
395 ws_url=session_info["capabilities"]["webSocketUrl"],
396 process=driver)
397 log_proto.debug("Established chromium session %r, CDP address %s", self.bidi_session, self.cdp_address)
398
399 async def close_cdp_session(self) -> None:
400 if self.cdp_ws is not None:
401 await self.cdp_ws.close()
402 self.cdp_ws = None
403
404 async def close_bidi_session(self) -> None:
405 assert self.bidi_session is not None
406 await self.close_cdp_session()
407 await self.http_session.delete(self.bidi_session.session_url)
408
409 async def cdp(self, method: str, **params: Any) -> dict[str, Any]:
410 """Send a Chrome DevTools command and return the JSON response
411
412 This is currently *not* safe for enabling events! These should be handled via BiDi,
413 this is only an escape hatch for CDP specific functionality such as Profiler.
414 """
415 if self.cdp_ws is None:
416 # unfortunately we have to hold on to the open ws after sending .enable() commands,
417 # otherwise they'll reset when closing and re-opening
418 self.cdp_ws = await self.http_session.ws_connect(
419 f"ws://{self.cdp_address}/devtools/page/{self.top_context}",
420 # coverage data can be big
421 max_msg_size=16000000)
422
423 reply = None
424 payload = json.dumps({"id": self.last_cdp_id, "method": method, "params": params})
425 log_command.info("CDP ← %r", payload)
426 await self.cdp_ws.send_str(payload)
427 async for msg in self.cdp_ws:
428 if msg.type == aiohttp.WSMsgType.TEXT:
429 reply = json.loads(msg.data)
430 if reply.get("id") == self.last_cdp_id:
431 break
432 else:
433 log_proto.warning("CDP message: %r", reply)
434 else:
435 log_proto.debug("CDP non-text message: %r", msg)
436 log_command.info("CDP → %r", reply)
437 assert reply
438 self.last_cdp_id += 1
439 return reply
440
441
442 # We could do this with https://github.com/mozilla/geckodriver/releases with a similar protocol as ChromeBidi
443 # But let's use https://firefox-source-docs.mozilla.org/testing/marionette/Protocol.html directly, fewer moving parts
444 class FirefoxBidi(WebdriverBidi):
445 async def start_bidi_session(self) -> None:
446 [marionette_port, bidi_port] = pick_ports(2)
447
448 self.profiledir = self.homedir / "profile"
449 self.profiledir.mkdir()
450 (self.profiledir / "user.js").write_text(f"""
451 // https://bugzilla.mozilla.org/show_bug.cgi?id=1947402
452 user_pref('remote.events.async.enabled', false);
453
454 // set this to "Trace" for debugging BiDi interactions
455 user_pref('remote.log.level', 'Warn');
456 user_pref('remote.log.truncate', false);
457 // enable remote logs on stdout
458 user_pref('browser.dom.window.dump.enabled', true);
459
460 user_pref("app.update.auto", false);
461 user_pref("datareporting.policy.dataSubmissionEnabled", false);
462 user_pref("toolkit.telemetry.reportingpolicy.firstRun", false);
463 user_pref("dom.disable_beforeunload", true);
464 user_pref("browser.download.dir", "{self.download_dir}");
465 user_pref("browser.download.folderList", 2);
466 user_pref("signon.rememberSignons", false);
467 user_pref("dom.navigation.locationChangeRateLimit.count", 9999);
468 user_pref('marionette.port', {marionette_port});
469 """)
470
471 driver = await asyncio.create_subprocess_exec(
472 "firefox", "-profile", str(self.profiledir), "--marionette", "--no-remote",
473 f"--remote-debugging-port={bidi_port}",
474 *(["-headless"] if self.headless else []), "about:blank")
475
476 # needs some time to launch
477 for _ in range(1, 30):
478 try:
479 # we must keep this socket open throughout the lifetime of that session
480 reader, self.writer_marionette = await asyncio.open_connection("127.0.0.1", marionette_port)
481 break
482 except ConnectionRefusedError as e:
483 log_proto.debug("waiting for firefox marionette: %s", e)
484 await asyncio.sleep(1)
485 else:
486 raise WebdriverError("could not connect to firefox marionette")
487
488 reply = await reader.read(1024)
489 if b'"marionetteProtocol":3' not in reply:
490 raise WebdriverError(f"unexpected marionette reply: {reply.decode()}")
491 cmd = '[0,1,"WebDriver:NewSession",{"webSocketUrl":true,"acceptInsecureCerts":true}]'
492 self.writer_marionette.write(f"{len(cmd)}:{cmd}".encode())
493 await self.writer_marionette.drain()
494 reply = await reader.read(1024)
495 # cut off length prefix
496 reply = json.loads(reply[reply.index(b":") + 1:].decode())
497 if not isinstance(reply, list) or len(reply) != 4 or not isinstance(reply[3], dict):
498 raise WebdriverError(f"unexpected marionette session request reply: {reply!r}")
499 log_proto.debug("marionette session request reply: %s", reply)
500
501 url = reply[3]["capabilities"]["webSocketUrl"]
502 self.bidi_session = BidiSession(session_url=url, ws_url=url, process=driver)
503 log_proto.debug("Established firefox session %r", self.bidi_session)
504
505 async def close_bidi_session(self) -> None:
506 self.writer_marionette.close()
507 await self.writer_marionette.wait_closed()