Response bodies read again, UA widgets stay out of selectors, and the e2e opens four browsers
Two defects reported from outside, by someone running a 24-site study, plus the change that makes verifying them affordable. Response.text() and Response.body() work again. The Juggler command they rest on was removed while trimming the network observer; this restores the client half and waits for the request to finish before asking, because the engine only has the body then and body() does not wait. That race bit the main document almost every time and subresources almost never: on a three-request page the JSON and the script came back and the document answered "Request 17 is not found". The UA widget defect is fixed in the engine and needs the matching release. What lands here is the regression file: three tests that fail on an engine without the guard and pass with it, and two that pass either way and exist to stop a fix in the wrong direction - reverting the closed-root feature, or opening those roots to page script, both of which would satisfy a count assertion. The e2e runs four browsers at once, cutting a fourteen-minute gate. --dist loadfile is not tuning: one file holds 65 of the 193 tests behind a single module-scoped browser, and another has a test that only passes when its module runs whole. Two harnesses picked a free port and released it before binding it again, which is a race with one worker and a coin flip with four; they now bind zero and read the port back off the listening socket, as two other files already did.
This commit is contained in:
1 parent
57d235ab39
commit
a1ff56e2ed
7 files changed
+459
-42
No files matched your search
@@ -48,6 +48,25 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
closes.
|
||||
- A closed page is now disposed, so neither the client's nor the server's
|
||||
object registry grows for the life of the browser.
|
||||
- A CSS query on a page returned the browser's own form widgets. Firefox builds
|
||||
the controls inside `<input type=date|time>` in a shadow root it marks closed,
|
||||
and the engine handed those to automation along with the closed roots a page
|
||||
had authored, so the selector engine collected them as if the page had written
|
||||
them: `page.locator("button")` answered 2 on a document with one button, and
|
||||
the extra match was invisible. The damage was not the count. A click on the
|
||||
invisible match reported success and sent nothing, so a site that had not
|
||||
blocked anything looked like it had. Needs the matching engine release; the
|
||||
guard is `Element::GetShadowRootForBindings` refusing UA widgets, which is
|
||||
what the sibling API has done upstream since bug 2035665. Reported from
|
||||
outside, with a 24-site case study behind it.
|
||||
- `Response.text()` and `Response.body()` read the body again. The command they
|
||||
rest on had been removed from Juggler while trimming it, and two more callers
|
||||
used it without saying so: traces and HARs recorded with embedded content were
|
||||
being written with every response body empty, and nothing raised. Bodies cost
|
||||
memory again, bounded as upstream bounds them: 100 MB per tab, 10 MB per
|
||||
response, oldest evicted first. Reading one from inside a `page.on("response")`
|
||||
handler now waits for the request to finish instead of racing it, which is why
|
||||
the main document used to fail where subresources did not.
|
||||
|
||||
## [0.7.4] - 2026-08-27
|
||||
|
||||
|
||||
+1
-1
@@ -117,7 +117,7 @@ dependencies = [
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = ["pytest>=7", "build>=1", "ruff>=0.6", "pytest-rerunfailures>=14", "pytest-timeout>=2", "playwright==1.61.0"]
|
||||
dev = ["pytest>=7", "build>=1", "ruff>=0.6", "pytest-rerunfailures>=14", "pytest-timeout>=2", "pytest-xdist>=3", "playwright==1.61.0"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
markers = [
|
||||
|
||||
+74
-3
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the FULL e2e suite (every test that opens the browser) against a binary.
|
||||
|
||||
The 127 ``@pytest.mark.e2e`` tests are excluded from the default `pytest` run
|
||||
Every ``@pytest.mark.e2e`` test is excluded from the default `pytest` run
|
||||
(`addopts = -m 'not slow and not e2e'`) because they need a real Firefox binary
|
||||
and a display, and they skip themselves when no binary is available. That makes
|
||||
them easy to forget - and "we can't afford for something to not work". This is
|
||||
@@ -19,9 +19,16 @@ are reran up to twice on the known transient signatures. A genuinely broken
|
||||
binary fails all attempts. The webrtc e2e fake a TCP-only SOCKS locally (no
|
||||
proxy/secrets), so the whole suite is offline.
|
||||
|
||||
The run opens FOUR browsers at once by default. `--dist loadfile` is not
|
||||
negotiable and the reason is on the line that sets it: two properties of this
|
||||
suite depend on a file staying whole on one worker, and both were measured
|
||||
failing when it did not.
|
||||
|
||||
Usage:
|
||||
python scripts/run_e2e.py <firefox-binary>
|
||||
python scripts/run_e2e.py # uses $INVPW_BINARY_PATH
|
||||
python scripts/run_e2e.py <binary> -n 8 # eight browsers at once
|
||||
python scripts/run_e2e.py <binary> -n 1 # the old serial path, unchanged
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -32,9 +39,46 @@ from pathlib import Path
|
||||
|
||||
_RERUN_SIGNATURES = "Timeout|context was destroyed|was detached|not visible|because of a navigation|TargetClosed"
|
||||
|
||||
#: Browsers opened at once. Four was asked for and four is what the default is;
|
||||
#: it is not a measured optimum and there is no reason to believe one number
|
||||
#: fits every machine, so `-n` moves it and `-n 1` puts the run back exactly on
|
||||
#: the serial path this script had before parallelism existed.
|
||||
_DEFAULT_PROCS = "4"
|
||||
|
||||
|
||||
def _take_procs(argv: list[str]) -> tuple[str, list[str]]:
|
||||
"""Pull `-n/--procs` out of the arguments, leaving the rest for pytest.
|
||||
|
||||
Hand-parsed rather than argparse because everything this script does not
|
||||
recognise is forwarded to pytest verbatim, and argparse would have to be
|
||||
taught every pytest flag in order to not eat one.
|
||||
|
||||
The value is kept as a STRING and handed to xdist unread, so `auto` and any
|
||||
future spelling xdist accepts keep working without this function learning
|
||||
about them. Only `0` and `1` are interpreted here, and they mean the same
|
||||
thing: do not load xdist at all. That is not the same as `-n 1`, which
|
||||
still runs the tests inside a worker subprocess - a difference that matters
|
||||
the day this script is used to compare a parallel run against a serial one,
|
||||
because then the serial arm must be the ORIGINAL path and not a
|
||||
one-worker variant of the new one.
|
||||
"""
|
||||
procs, rest, i = _DEFAULT_PROCS, [], 0
|
||||
while i < len(argv):
|
||||
if argv[i] in ("-n", "--procs"):
|
||||
if i + 1 >= len(argv):
|
||||
print("run_e2e.py: -n needs a value (1 = serial)", file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
procs, i = argv[i + 1], i + 2
|
||||
continue
|
||||
rest.append(argv[i])
|
||||
i += 1
|
||||
return procs, rest
|
||||
|
||||
|
||||
def main() -> int:
|
||||
binary = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("INVPW_BINARY_PATH")
|
||||
procs, extra = _take_procs(sys.argv[1:])
|
||||
binary = extra[0] if extra else os.environ.get("INVPW_BINARY_PATH")
|
||||
extra = extra[1:] if extra else []
|
||||
if not binary:
|
||||
print("usage: run_e2e.py <firefox-binary> (or set INVPW_BINARY_PATH)", file=sys.stderr)
|
||||
return 2
|
||||
@@ -75,6 +119,32 @@ def main() -> int:
|
||||
env["STEALTHFOX_E2E_BINARY"] = binary
|
||||
|
||||
repo = Path(__file__).resolve().parent.parent
|
||||
|
||||
# ⛔ `--dist loadfile` IS NOT A TUNING CHOICE, IT IS A CORRECTNESS ONE, and
|
||||
# xdist's default (`--dist load`, which hands out one test at a time) breaks
|
||||
# this suite in two measured ways.
|
||||
#
|
||||
# 1. MODULE-SCOPED BROWSERS. `test_fingerprint_consistency.py` is 65 of the
|
||||
# 193 e2e tests and opens ONE browser for all of them, from a
|
||||
# module-scoped fixture. Scattered test-by-test across four workers, each
|
||||
# worker that receives any of those tests builds its own copy of that
|
||||
# fixture: four browsers where the file wants one, and the identity those
|
||||
# 65 tests exist to prove is no longer being read off a single session.
|
||||
#
|
||||
# 2. TESTS THAT DEPEND ON AN EARLIER TEST IN THEIR OWN FILE.
|
||||
# `test_binary_executes_after_fetch` fails 2 out of 2 in isolation and
|
||||
# passes 9 out of 9 when its module runs whole, because a prior test in
|
||||
# that file populates the venv it uses. Measured 2026-08-29, and it very
|
||||
# nearly got recorded as a deterministic failure of the product.
|
||||
#
|
||||
# `loadfile` keeps every file whole on one worker, so both properties
|
||||
# survive. The price is the ceiling: the longest single FILE is now the
|
||||
# floor of the whole run, and with 65 of 193 tests in one file this run
|
||||
# cannot go faster than that file no matter how many workers are asked for.
|
||||
# That is why raising `-n` past a certain point buys nothing here, and the
|
||||
# fix for it would be splitting that file, not adding workers.
|
||||
parallel = [] if procs in ("0", "1") else ["-n", procs, "--dist", "loadfile"]
|
||||
|
||||
cmd = [
|
||||
sys.executable, "-m", "pytest",
|
||||
"-m", "e2e",
|
||||
@@ -120,8 +190,9 @@ def main() -> int:
|
||||
# missing piece: the output does stream, the GRANULARITY was wrong.
|
||||
# One line per test costs 141 lines and names the last one that ran.
|
||||
"-v", "--tb=short",
|
||||
] + sys.argv[2:]
|
||||
] + parallel + extra
|
||||
print(f"[run_e2e] binary={binary}")
|
||||
print(f"[run_e2e] browsers at once: {procs if parallel else '1 (serial)'}")
|
||||
print(f"[run_e2e] {' '.join(cmd)}")
|
||||
return subprocess.run(cmd, cwd=repo, env=env).returncode
|
||||
|
||||
|
||||
@@ -1111,10 +1111,63 @@ class ResponseDispatcher(Dispatcher):
|
||||
})
|
||||
|
||||
def op_body(self, params: Dict) -> Any:
|
||||
raise ProtocolException(
|
||||
"response.body() is not available: this Juggler has no command to "
|
||||
"read a response body back, and returning an empty one would look "
|
||||
"like an empty page instead of a missing feature")
|
||||
"""The response body, base64, straight from the engine.
|
||||
|
||||
This raised unconditionally between 2026-08-24 and 2026-08-30, because
|
||||
`Network.getResponseBody` had been removed from Juggler while trimming
|
||||
it. The command is back, and so is this. Reported from outside by
|
||||
someone identifying protection vendors from three signals - URL,
|
||||
headers, and the body of the scripts - who was left with two.
|
||||
|
||||
⛔ ONE KEY, and it has to be one. `_connection.py` asserts
|
||||
`len(result) == 1` and returns that value unwrapped, so the engine's
|
||||
second field cannot be forwarded even though it is the more
|
||||
interesting of the two.
|
||||
"""
|
||||
page = self.request.page
|
||||
|
||||
# ⛔ THE ENGINE ONLY HAS THE BODY ONCE THE REQUEST HAS FINISHED, and
|
||||
# `response.body()` upstream does not wait, so calling it from a
|
||||
# `page.on("response")` handler is a race that the caller cannot see
|
||||
# and cannot fix. It bites the MAIN DOCUMENT almost every time and
|
||||
# subresources almost never, because the document is still streaming
|
||||
# when its response event fires: measured on a three-request page,
|
||||
# the JSON and the script came back and the document answered
|
||||
# `Request "17" is not found`.
|
||||
#
|
||||
# `_requests` holds exactly the requests still in flight - the page's
|
||||
# own handler pops them on `requestFinished` and on `requestFailed` -
|
||||
# so waiting on it asks the question this method actually means. The
|
||||
# deadline is short and its expiry is not fatal: the send below runs
|
||||
# anyway, and a genuine absence still surfaces as the engine's error
|
||||
# rather than as a hang.
|
||||
deadline = time.monotonic() + 10.0
|
||||
rid = self.request.request_id
|
||||
while rid in getattr(page, "_requests", {}) and time.monotonic() < deadline:
|
||||
time.sleep(0.02)
|
||||
|
||||
# ⛔ `page.send`, NOT `page.conn.send`: the command lives on
|
||||
# PageHandler, so it is scoped to a SESSION. Sent without one the
|
||||
# engine answers `Handler for does not implement method
|
||||
# "Network.getResponseBody"` - with a blank where the session should
|
||||
# be, which reads like a missing handler and is really a missing
|
||||
# address. The route commands next door get away with `conn.send`
|
||||
# because interception is answered on the browser handler.
|
||||
answer = page.send(
|
||||
"Network.getResponseBody", {"requestId": rid}) or {}
|
||||
if answer.get("evicted"):
|
||||
# ⛔ The reason the old refusal existed, kept for the one case
|
||||
# where it is still true: this body really is gone. The engine
|
||||
# caps storage at 100 MB per tab and a tenth of that per response,
|
||||
# and evicts oldest-first past the cap. Handing back an empty
|
||||
# string would read as an empty page rather than a dropped body,
|
||||
# which is the same lie the removal note warned about.
|
||||
raise ProtocolException(
|
||||
"response.body() is not available: the engine evicted this "
|
||||
"body to stay under its response-storage cap (100 MB per tab, "
|
||||
"10 MB per response). Read the body sooner, or fetch the URL "
|
||||
"again if it is still there")
|
||||
return {"binary": answer.get("base64body") or ""}
|
||||
|
||||
def op_raw_response_headers(self, params: Dict) -> Any:
|
||||
return {"headers": self.raw_headers}
|
||||
|
||||
@@ -30,7 +30,6 @@ random free ports.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
@@ -99,12 +98,25 @@ def test_extra_prefs_override_can_break_isolation_only_explicitly():
|
||||
# ────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.bind(("127.0.0.1", 0))
|
||||
port = s.getsockname()[1]
|
||||
s.close()
|
||||
return port
|
||||
# ⛔ THERE IS NO `_free_port()` HERE ANY MORE, AND ITS ABSENCE IS THE POINT.
|
||||
#
|
||||
# It used to bind port 0, read the number the kernel assigned, CLOSE the
|
||||
# socket, and hand the number back for someone to bind again later. Between the
|
||||
# close and the second bind the port belongs to nobody, so a second process
|
||||
# asking the same question in that window is told the same number, and whichever
|
||||
# of the two binds second dies with EADDRINUSE.
|
||||
#
|
||||
# Sequentially that window is never contended and the pattern was fine for as
|
||||
# long as the suite ran one test at a time. `run_e2e.py` now opens four workers
|
||||
# by default, so it IS contended, and the failure it produces would be an
|
||||
# address-in-use traceback in a browser test - which reads as the product being
|
||||
# broken rather than the harness racing itself.
|
||||
#
|
||||
# The fix is to never let go of the port: `_serve` below binds 0 itself and the
|
||||
# caller reads the number back off the listening socket, so there is no window
|
||||
# at all. `test_proxy_socks_auth_e2e.py` and `test_webrtc_realness.py` were
|
||||
# already written this way; this file and `test_long_session_e2e.py` were the
|
||||
# two that were not.
|
||||
|
||||
|
||||
class _SilentHandler(BaseHTTPRequestHandler):
|
||||
@@ -122,15 +134,19 @@ class _SilentHandler(BaseHTTPRequestHandler):
|
||||
self.wfile.write(self.PAYLOAD)
|
||||
|
||||
|
||||
def _serve(payload: bytes, port: int) -> HTTPServer:
|
||||
"""Start an HTTP server on 127.0.0.1:port serving ``payload`` on every GET."""
|
||||
def _serve(payload: bytes) -> tuple[HTTPServer, int]:
|
||||
"""Serve ``payload`` on every GET from a kernel-chosen port on 127.0.0.1.
|
||||
|
||||
Returns the server and the port it is ALREADY listening on, so the number
|
||||
is never valid-but-unbound in between. See the note above.
|
||||
"""
|
||||
handler_cls = type(
|
||||
"_H", (_SilentHandler,), {"PAYLOAD": payload}
|
||||
)
|
||||
srv = HTTPServer(("127.0.0.1", port), handler_cls)
|
||||
srv = HTTPServer(("127.0.0.1", 0), handler_cls)
|
||||
t = threading.Thread(target=srv.serve_forever, daemon=True)
|
||||
t.start()
|
||||
return srv
|
||||
return srv, srv.server_address[1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -142,7 +158,15 @@ def cross_origin_harness():
|
||||
src pointing at port B. Same cross-origin browsing-context shape as
|
||||
a parent-page-plus-third-party-iframe layout, fully offline.
|
||||
"""
|
||||
pa, pb = _free_port(), _free_port()
|
||||
# The CHILD goes up first, because the parent's markup has to name the
|
||||
# child's port and there is no longer a way to learn that number without
|
||||
# binding it. That ordering is the whole cost of closing the race.
|
||||
child_html = b"""<!doctype html><html><body>
|
||||
<button id="ok">confirm</button>
|
||||
<button class="btn-primary">primary</button>
|
||||
<script>document.getElementById('ok').addEventListener('click', () => document.title = 'clicked')</script>
|
||||
</body></html>"""
|
||||
sb, pb = _serve(child_html)
|
||||
parent_html = f"""<!doctype html><html><head><title>parent</title></head><body>
|
||||
<h1>parent</h1>
|
||||
<iframe id="ifr_plain" src="http://127.0.0.1:{pb}/child" width="300" height="120"></iframe>
|
||||
@@ -151,13 +175,7 @@ def cross_origin_harness():
|
||||
<iframe id="ifr_titled" src="http://127.0.0.1:{pb}/child" width="300" height="120"
|
||||
title="cross-origin titled iframe"></iframe>
|
||||
</body></html>""".encode("utf-8")
|
||||
child_html = b"""<!doctype html><html><body>
|
||||
<button id="ok">confirm</button>
|
||||
<button class="btn-primary">primary</button>
|
||||
<script>document.getElementById('ok').addEventListener('click', () => document.title = 'clicked')</script>
|
||||
</body></html>"""
|
||||
sa = _serve(parent_html, pa)
|
||||
sb = _serve(child_html, pb)
|
||||
sa, pa = _serve(parent_html)
|
||||
try:
|
||||
yield {"parent_url": f"http://127.0.0.1:{pa}/", "child_origin": f"http://127.0.0.1:{pb}"}
|
||||
finally:
|
||||
@@ -369,8 +387,6 @@ def test_the_geometry_invariant_holds_inside_a_nested_frame(firefox_binary):
|
||||
.replace(b"@LEFT", str(left).encode())
|
||||
.replace(b"@TOP", str(top).encode())
|
||||
.replace(b"@SRC", b"/child"))
|
||||
port = _free_port()
|
||||
|
||||
class _H(_SilentHandler):
|
||||
def do_GET(self):
|
||||
body = _CHILD_GEOM if self.path.startswith("/child") else parent_html
|
||||
@@ -381,7 +397,8 @@ def test_the_geometry_invariant_holds_inside_a_nested_frame(firefox_binary):
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
srv = HTTPServer(("127.0.0.1", port), _H)
|
||||
srv = HTTPServer(("127.0.0.1", 0), _H)
|
||||
port = srv.server_address[1]
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
try:
|
||||
|
||||
@@ -31,7 +31,6 @@ site, so a red result is the browser and never the network.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
@@ -130,12 +129,11 @@ document.title = 'shaped:' + shaped;
|
||||
return html.encode("utf-8")
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.bind(("127.0.0.1", 0))
|
||||
port = s.getsockname()[1]
|
||||
s.close()
|
||||
return port
|
||||
# ⛔ NO `_free_port()`: it handed back a port number it had already released,
|
||||
# and `run_e2e.py` now runs four workers at once, so two of them can be told
|
||||
# the same number and the second bind dies with EADDRINUSE inside a browser
|
||||
# test. `_serve` binds 0 itself and reports the port it is listening on, so the
|
||||
# number is never unowned. Same change as in `test_cross_origin_iframe.py`.
|
||||
|
||||
|
||||
class _SilentHandler(BaseHTTPRequestHandler):
|
||||
@@ -152,7 +150,7 @@ class _SilentHandler(BaseHTTPRequestHandler):
|
||||
self.wfile.write(self.PAYLOAD)
|
||||
|
||||
|
||||
def _serve(payload: bytes, port: int) -> ThreadingHTTPServer:
|
||||
def _serve(payload: bytes) -> tuple[ThreadingHTTPServer, int]:
|
||||
"""Threading, deliberately.
|
||||
|
||||
A single-threaded HTTPServer serves round 0 and then blocks: the
|
||||
@@ -163,9 +161,9 @@ def _serve(payload: bytes, port: int) -> ThreadingHTTPServer:
|
||||
confusion this test exists to avoid.
|
||||
"""
|
||||
cls = type("_H", (_SilentHandler,), {"PAYLOAD": payload})
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", port), cls)
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", 0), cls)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
return srv
|
||||
return srv, srv.server_address[1]
|
||||
|
||||
|
||||
# The per-test deadline in `run_e2e.py` is 420s and this test brushes against
|
||||
@@ -194,8 +192,7 @@ def test_a_long_session_survives_heavy_text_shaping(firefox_binary):
|
||||
"died immediately" from "died deep into a session".
|
||||
"""
|
||||
families = _declared_families()
|
||||
port = _free_port()
|
||||
srv = _serve(_page_html(families), port)
|
||||
srv, port = _serve(_page_html(families))
|
||||
base = "http://127.0.0.1:" + str(port) + "/"
|
||||
|
||||
rounds_done = 0
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
"""A page CSS query must never return the engine's own form widgets.
|
||||
|
||||
**What went wrong.** Firefox builds the controls inside `<input type=date>`
|
||||
and `<input type=time>` as real elements, in a shadow root attached to the
|
||||
input and marked closed. A stealth patch landed in firefox-21 that hands
|
||||
closed shadow roots to the automation sandbox, which is what lets a locator
|
||||
reach content a page deliberately hid. It checked two things, that the root is
|
||||
closed and that the caller is the sandbox, and it did not check the third:
|
||||
whether the root belongs to the PAGE or to the ENGINE.
|
||||
|
||||
The selector engine pierces shadow roots by design and is right to, so from
|
||||
firefox-21 onward it collected engine internals as if the author had written
|
||||
them. On a document with one button, `page.locator("button").count()` answered
|
||||
2, and the extra match was invisible and therefore never clickable.
|
||||
|
||||
**Why it deserves its own file rather than a line in another one.** It failed
|
||||
SILENTLY and disguised as the site defending itself. Reported from a real run:
|
||||
a login form was filled, verified in the screenshot, the click on the submit
|
||||
was reported as successful, and the request never left the browser, because
|
||||
`.first` had resolved to the invisible calendar button. The HTTP log had zero
|
||||
POSTs in 667 lines and the script concluded the credentials were rejected. For
|
||||
a package whose job is measuring defences, that is the worst failure available:
|
||||
it does not look like a bug, it looks like data.
|
||||
|
||||
**The fix is in the engine, not here.** `Element::GetShadowRootForBindings`
|
||||
gained the guard its neighbour `GetOpenOrClosedShadowRoot` has carried since
|
||||
upstream bug 2035665: a UA widget is refused to anything that is not the
|
||||
system principal. These tests therefore FAIL on firefox-21 and firefox-22 and
|
||||
that is correct, they are the regression sentinels for a binary that does not
|
||||
have the guard yet.
|
||||
|
||||
**The last two tests are the ones that stop a fix in the wrong direction.**
|
||||
Refusing UA widgets must not also refuse the AUTHOR closed shadow roots the
|
||||
patch exists for, and it must not be achieved by opening anything to the page.
|
||||
A test file that only checked the count would be satisfied by a patch that
|
||||
reverted the feature entirely, or by one that made closed roots readable by
|
||||
content, which would be a fingerprinting tell.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
# The engine widgets live inside these two inputs. Both are here rather than
|
||||
# just the one from the report, because the guard is about the CLASS of root
|
||||
# and a test naming a single input would not notice a fix that special-cased
|
||||
# it.
|
||||
_WIDGET_PAGE = b"""<!doctype html><html><head><title>ua-widget</title></head>
|
||||
<body>
|
||||
<form id="f" action="/posted" method="post">
|
||||
<input type="time" id="when">
|
||||
<input type="date" id="day">
|
||||
<button id="author_button">Submit order</button>
|
||||
<input type="submit" id="author_submit" value="Send">
|
||||
</form>
|
||||
</body></html>"""
|
||||
|
||||
# A closed shadow root the PAGE created. This is what the stealth patch is for
|
||||
# and it must keep working.
|
||||
_AUTHOR_PAGE = b"""<!doctype html><html><head><title>author-closed</title></head>
|
||||
<body>
|
||||
<div id="host"></div>
|
||||
<input type="time" id="when">
|
||||
<script>
|
||||
const root = document.getElementById('host').attachShadow({mode: 'closed'});
|
||||
root.innerHTML = '<button id="hidden_button">inside a closed root</button>';
|
||||
// What the PAGE can see of its own roots. Both must stay null: the first
|
||||
// is the spec answer for a closed root, the second is the engine's own
|
||||
// widget, which content has never been able to reach.
|
||||
window.__page_sees_own_closed = document.getElementById('host').shadowRoot;
|
||||
window.__page_sees_ua_widget = document.getElementById('when').shadowRoot;
|
||||
</script>
|
||||
</body></html>"""
|
||||
|
||||
|
||||
class _SilentHandler(BaseHTTPRequestHandler):
|
||||
"""Serve the two pages by path, and say nothing while doing it."""
|
||||
|
||||
def log_message(self, *_a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
body = _AUTHOR_PAGE if self.path.startswith("/author") else _WIDGET_PAGE
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def widget_harness():
|
||||
"""Serve both pages from a kernel-chosen port.
|
||||
|
||||
Port 0 is bound here and read back off the listening socket rather than
|
||||
picked in advance and bound later: `run_e2e.py` runs four workers at once,
|
||||
and a port number that has been released is a number two workers can be
|
||||
given at the same time.
|
||||
"""
|
||||
srv = HTTPServer(("127.0.0.1", 0), _SilentHandler)
|
||||
port = srv.server_address[1]
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
try:
|
||||
yield "http://127.0.0.1:%d" % port
|
||||
finally:
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
def _ids(loc) -> list:
|
||||
"""The id of every match, in the order the locator returns them."""
|
||||
return [loc.nth(i).get_attribute("id") for i in range(loc.count())]
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_simple_selector_returns_only_author_elements(firefox_binary, widget_harness):
|
||||
"""`button` on a page with one button must answer 1.
|
||||
|
||||
Measured before the guard: 2, the second being the calendar button of the
|
||||
datetime widget, with an id of `calendar-button` and no author anywhere
|
||||
near it.
|
||||
"""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(widget_harness + "/", wait_until="load", timeout=30_000)
|
||||
page.wait_for_selector("#author_button", timeout=10_000)
|
||||
|
||||
found = _ids(page.locator("button"))
|
||||
assert found == ["author_button"], (
|
||||
"a CSS query returned engine internals: expected the one button "
|
||||
"the document contains, got %r" % (found,)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_comma_selector_returns_only_author_elements(firefox_binary, widget_harness):
|
||||
"""The comma form is a separate assertion because it took a separate path.
|
||||
|
||||
Reported, and the reason `.first` was landing on an invisible element:
|
||||
with `button` alone the widget came back SECOND, while with
|
||||
`button, input[type='submit']` it came back FIRST. Same document, same
|
||||
session, two orders. Whatever the merge does with the alternatives, it must
|
||||
not be handed engine internals to merge in the first place.
|
||||
"""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(widget_harness + "/", wait_until="load", timeout=30_000)
|
||||
page.wait_for_selector("#author_button", timeout=10_000)
|
||||
|
||||
loc = page.locator("button, input[type='submit']")
|
||||
found = _ids(loc)
|
||||
assert found == ["author_button", "author_submit"], (
|
||||
"the comma form returned %r" % (found,)
|
||||
)
|
||||
# Belt and braces, and it is the assertion that speaks to the symptom:
|
||||
# every match a user can be handed has to be one they can act on.
|
||||
invisible = [i for i in range(loc.count()) if not loc.nth(i).is_visible()]
|
||||
assert not invisible, (
|
||||
"matches %r are invisible, so a click on them can only time out"
|
||||
% (invisible,)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_the_order_is_author_document_order_in_both_forms(firefox_binary, widget_harness):
|
||||
"""Both selector forms must agree, and agree with the document.
|
||||
|
||||
The two forms disagreeing is what turned a wrong match set into a wrong
|
||||
FIRST match, and `.first` is what most callers use. Asserting the count
|
||||
alone would pass on a build that returns the right two elements in the
|
||||
wrong order.
|
||||
"""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(widget_harness + "/", wait_until="load", timeout=30_000)
|
||||
page.wait_for_selector("#author_button", timeout=10_000)
|
||||
|
||||
# The document's own order, straight from the DOM, so the expectation
|
||||
# is not a second copy of the same belief written by hand.
|
||||
expected = page.evaluate(
|
||||
"() => [...document.querySelectorAll(\"button, input[type='submit']\")]"
|
||||
".map(e => e.id)"
|
||||
)
|
||||
assert expected == ["author_button", "author_submit"], (
|
||||
"the harness page is not what this test thinks it is: %r" % (expected,)
|
||||
)
|
||||
|
||||
assert _ids(page.locator("button, input[type='submit']")) == expected
|
||||
assert _ids(page.locator("button")) == [i for i in expected if i == "author_button"]
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_an_author_closed_shadow_root_is_still_reachable(firefox_binary, widget_harness):
|
||||
"""The feature the guard must not take away.
|
||||
|
||||
Refusing UA widgets is one condition away from refusing every closed root,
|
||||
which would revert the patch and silently remove the ability to drive a
|
||||
site that hides its controls that way. This test fails on stock Firefox,
|
||||
which is exactly what makes it worth having.
|
||||
"""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(widget_harness + "/author", wait_until="load", timeout=30_000)
|
||||
page.wait_for_selector("#host", timeout=10_000)
|
||||
|
||||
found = _ids(page.locator("button"))
|
||||
# `in`, not equality, and the difference is the whole point of the test.
|
||||
# This page also carries an <input type="time">, because the test below
|
||||
# reads the page's own view of BOTH kinds of root off it. On a binary
|
||||
# without the guard the locator therefore answers
|
||||
# ['hidden_button', 'calendar-button'], and an equality assertion would
|
||||
# fail here with the message "the author's closed shadow root is no
|
||||
# longer reachable" while the root was in fact perfectly reachable.
|
||||
# That is a test reporting the opposite of what it measured. Whether the
|
||||
# widget is in that list is asserted by the three tests above, which is
|
||||
# where that claim belongs.
|
||||
assert "hidden_button" in found, (
|
||||
"the author's closed shadow root is no longer reachable: %r" % (found,)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_the_page_itself_still_sees_null_on_both_kinds_of_closed_root(
|
||||
firefox_binary, widget_harness
|
||||
):
|
||||
"""The guard must not be implemented by opening anything to content.
|
||||
|
||||
A page reading `element.shadowRoot` on a closed root gets null in every
|
||||
browser on earth. If ours answered anything else, the whole patch would be
|
||||
a fingerprinting tell rather than a capability, and the count assertions
|
||||
above would still pass.
|
||||
"""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(widget_harness + "/author", wait_until="load", timeout=30_000)
|
||||
page.wait_for_selector("#host", timeout=10_000)
|
||||
|
||||
seen = page.evaluate(
|
||||
"() => ({own: window.__page_sees_own_closed,"
|
||||
" ua: window.__page_sees_ua_widget,"
|
||||
" live_own: !!document.getElementById('host').shadowRoot,"
|
||||
" live_ua: !!document.getElementById('when').shadowRoot})"
|
||||
)
|
||||
assert seen["own"] is None, "the page can read its own closed shadow root"
|
||||
assert seen["ua"] is None, "the page can read the engine's widget root"
|
||||
assert seen["live_own"] is False
|
||||
assert seen["live_ua"] is False
|
||||
Reference in new issue
Block a user