Compare commits

..
5 changed files with 279 additions and 368 deletions

No files matched your search

-99
View File
@@ -1,99 +0,0 @@
"""What the window e2e tests share: a headed session of the product, and a wait on a condition of a page.
The sessions are HEADED on purpose. ``headless=True`` gives every session a display of its own (a fresh Xvfb on Linux, a fresh Win32 desktop on
Windows), so two of them never see each other; the focus and occlusion tests need two windows on ONE display, which is what two headed sessions of the
same run have (the Linux e2e runs under ``xvfb-run``). Both sessions use the same seed, so both windows are the same declared window and the second one
covers the first completely.
The first session is the one of the test's own thread; the second one lives in a thread of its own (``in_a_thread_of_its_own``, the pattern of
``test_popups_reach_the_client_e2e.py``): an open sync client keeps its asyncio loop marked as running in the thread that started it, and a second sync client
refuses to start there ("It looks like you are using Playwright Sync API inside the asyncio loop"). A sync client's objects belong to the thread that made
them, so everything the test does with the second session is handed to that thread (``run``).
"""
from __future__ import annotations
import contextlib
import queue
import threading
from typing import Any, Callable, Dict, Iterator, Optional
from _waits import Watch, watch
#: The seed only has to give two sessions the same window.
SEED = 21
#: The deadline of a wait for something that must happen, in seconds.
DEADLINE_S = 30
def launch(firefox_binary: str, *, extra_prefs: Optional[Dict[str, Any]] = None, pin: Optional[Dict[str, Any]] = None, headless: bool = False):
"""A session of the product (RFP off, the engine declared as the core launches it); ``extra_prefs`` and ``pin`` only where a test needs them."""
from invisible_playwright import InvisiblePlaywright
return InvisiblePlaywright(seed=SEED, binary_path=firefox_binary, headless=headless, locale="en-US", timezone="America/New_York",
extra_prefs=extra_prefs, pin=pin)
def wait_for_condition(page, sample: Callable[[], Any], done: Callable[[Any], Any], what: str, seconds: float = DEADLINE_S) -> Watch:
"""Until ``done(sample())``, reading the page between two looks. Red after ``seconds`` with what was seen on the way."""
result = watch(sample, done, seconds, lambda: page.wait_for_timeout(100))
assert result.ok, "%s; seen: %s" % (what, result.render())
return result
class SecondSession:
"""A session that lives in a thread of its own: ``run(fn)`` calls ``fn(session)`` in that thread and gives back its result or raises its error."""
def __init__(self) -> None:
self._jobs: "queue.Queue[Optional[tuple]]" = queue.Queue()
def run(self, fn: Callable[[Any], Any]) -> Any:
box: Dict[str, Any] = {}
done = threading.Event()
self._jobs.put((fn, box, done))
assert done.wait(300), "the second session did not answer within 300 s"
if "error" in box:
raise box["error"]
return box.get("value")
@contextlib.contextmanager
def in_a_thread_of_its_own(firefox_binary: str, *, extra_prefs: Optional[Dict[str, Any]] = None) -> Iterator[SecondSession]:
"""A second headed session on the same display, started and closed in a thread with no asyncio loop; the test keeps the first one in its own thread."""
handle = SecondSession()
up = threading.Event()
failure: Dict[str, BaseException] = {}
def serve() -> None:
try:
with launch(firefox_binary, extra_prefs=extra_prefs) as session:
up.set()
while True:
job = handle._jobs.get()
if job is None:
return
fn, box, done = job
try:
box["value"] = fn(session)
except BaseException as exc: # handed back to the test's thread by ``run``
box["error"] = exc
finally:
done.set()
except BaseException as exc: # the launch or the close of the session
failure["error"] = exc
finally:
up.set()
worker = threading.Thread(target=serve, name="second-session", daemon=True)
worker.start()
assert up.wait(300), "the second session did not start within 300 s"
if "error" in failure:
raise failure["error"]
try:
yield handle
finally:
handle._jobs.put(None)
worker.join(120)
assert not worker.is_alive(), "the second session did not close within 120 s"
if "error" in failure:
raise failure["error"]
@@ -1,81 +0,0 @@
"""A page keeps the focus when another session takes the display, and loses it only to its own session.
What it fixes: with ``zoom.stealth.focus.ignore_os_deactivation`` (the core declares it true, one value for every session) the window does not give up its
activation when the SYSTEM takes it: another application, or another session's window on the same display. A page reads ``document.hasFocus()`` and the
``blur`` event; without the pref a second visible session made the first one read ``hasFocus()`` false (4 times in 4 on one display) while nothing in its own
session had moved. When the session opens a window of its own the window it replaces is lowered with the blur any Firefox gives.
The hooks: ``AppWindow::WindowDeactivated`` (the early return) and ``AppWindow::WindowActivated`` (``StealthLowerActiveWindow``, which lowers the active window
with its own action id before Mozilla's raise) in ``xpfe/appshell/AppWindow.cpp`` of the series, folder ``fingerprint/screen-window/focus``.
The steps: session A opens a page that records ``focus`` and ``blur``; session B, headed on the same display, opens a window and takes the focus. A's page
still reads ``hasFocus()`` true and has recorded no ``blur``. Then A opens a second page of its own: the first page records its ``blur`` and reads
``hasFocus()`` false, the new one reads it true.
The control, in the same test: ``extra_prefs={"zoom.stealth.focus.ignore_os_deactivation": False}``, the same steps up to B taking the display, and A's page
reads ``hasFocus()`` false. It runs first, so a runner where the second session does not take the focus is red there and not a green that means nothing.
Both sessions are headed on one display (the Linux e2e runs under ``xvfb-run``; Windows has the interactive desktop of the runner).
"""
from __future__ import annotations
import pytest
from _window_sessions import in_a_thread_of_its_own, launch, wait_for_condition
pytestmark = pytest.mark.e2e
PREF = "zoom.stealth.focus.ignore_os_deactivation"
RECORD = """() => {
window.__events = [];
for (const type of ['focus', 'blur']) window.addEventListener(type, () => window.__events.push(type));
return document.hasFocus();
}"""
HAS_FOCUS = "() => document.hasFocus()"
EVENTS = "() => window.__events"
TWO_FRAMES = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))"
def takes_the_focus(b):
"""Runs in the second session's own thread: opens a window and waits until its page has the focus."""
taker = b.new_page()
taker.goto("about:blank")
wait_for_condition(taker, lambda: taker.evaluate(HAS_FOCUS), lambda focused: focused is True, "the second session's page never took the focus")
def another_session_takes_the_display(firefox_binary, keeps, with_own_page=False):
"""What A's page reads once B's window has the focus, and (``with_own_page``) once A has opened a page of its own."""
extra = None if keeps else {PREF: False}
with launch(firefox_binary, extra_prefs=extra) as a:
first = a.new_page()
first.goto("about:blank")
first.evaluate(RECORD)
wait_for_condition(first, lambda: first.evaluate(HAS_FOCUS), lambda focused: focused is True, "the page never had the focus of its own window")
with in_a_thread_of_its_own(firefox_binary) as b:
b.run(takes_the_focus)
if keeps:
first.evaluate(TWO_FRAMES)
else:
wait_for_condition(first, lambda: first.evaluate(HAS_FOCUS), lambda focused: focused is False,
"the first page still has the focus although another session's window took it")
seen = {"has_focus": first.evaluate(HAS_FOCUS), "events": first.evaluate(EVENTS)}
if with_own_page:
own = a.new_page()
own.goto("about:blank")
wait_for_condition(own, lambda: (own.evaluate(HAS_FOCUS), first.evaluate(EVENTS), first.evaluate(HAS_FOCUS)),
lambda state: state[0] is True and state[1].count("blur") == 1 and state[2] is False,
"a page of the session's own did not take the focus from the first with one blur")
seen["after_own_page"] = (own.evaluate(HAS_FOCUS), first.evaluate(EVENTS), first.evaluate(HAS_FOCUS))
return seen
def test_a_page_keeps_focus_when_another_session_takes_the_display(firefox_binary):
control = another_session_takes_the_display(firefox_binary, keeps=False)
assert control["has_focus"] is False, "control: without the pref the first page still has the focus: %r" % control
kept = another_session_takes_the_display(firefox_binary, keeps=True, with_own_page=True)
assert kept["has_focus"] is True, "with the pref the first page lost the focus to another session: %r" % kept
assert "blur" not in kept["events"], "with the pref the first page recorded a blur when another session took the display: %r" % kept
assert kept["has_focus"] != control["has_focus"]
own_focused, events, first_focused = kept["after_own_page"]
assert own_focused is True and events.count("blur") == 1 and first_focused is False, "a page of the session's own did not replace the first one with one blur: %r" % kept
-112
View File
@@ -1,112 +0,0 @@
"""Fullscreen is decided from the declared screen, with no window manager to answer it.
What it fixes: on an X display with no window manager (Xvfb, the way the engine runs on Linux servers) GTK's fullscreen is a request nobody answers, so
Mozilla refuses it: the DOM goes fullscreen and the window does not (``display-mode: fullscreen`` false, ``innerHeight`` the work area). Retail Windows
decides it itself and gives the screen. With the engine active the widget decides it too, from the screen the core declared: after ``requestFullscreen()``
the page reads ``innerWidth x innerHeight`` equal to the declared screen and ``display-mode: fullscreen``.
The hook: ``nsWindow::MakeFullScreen`` in ``widget/gtk/nsWindow.cpp`` of the series, folder ``fingerprint/screen-window/occlusion`` (the marker names
``fingerprint/screen-window/geometry``, whose function ``StealthMakeFullScreenWithoutWM`` in ``widget/gtk/StealthFullscreenGtk.cpp`` it calls). On Windows
the same reading is held by ``nsIWidget::InfallibleMakeFullScreen`` and the Win32 rules of the same folder (``geometry``).
The screen is pinned to 1600x900, which no runner has (the Linux display is 1920x1080, the Windows runner's monitor 1024x768 or 1920x1080), so a window that
filled the host would read differently from the declared one.
The control, in the same test: the engine inactive (``zoom.stealth.fpp.hw_seed`` 0: the engine is on when it is above 0) keeps Mozilla's behaviour. On
Linux without a window manager that is the refusal (``display-mode: fullscreen`` false and the window not the declared screen); on Windows, which always has a
window manager and a widget that decides fullscreen, it is the host's monitor, not the declared screen. The same click, the same pinned screen; only the engine
differs.
The click is real input (``page.mouse``): ``requestFullscreen`` needs a user gesture. A page reads it from ``innerWidth``, ``innerHeight``,
``matchMedia('(display-mode: fullscreen)')`` and ``document.fullscreenElement``.
"""
from __future__ import annotations
import http.server
import sys
import threading
import pytest
from _servers import LocalServer
from _window_sessions import launch, wait_for_condition
pytestmark = pytest.mark.e2e
#: The device pixel ratio is pinned too: the core declares 1.5 for some personas (Windows runner), and a page reads the screen and the window in
#: CSS pixels, declared / dpr (1067x600), which is not what this test is about.
DECLARED = {"screen.width": 1600, "screen.height": 900, "screen.dpr": 1.0}
PAGE = (b"<!doctype html><html><head><meta charset=utf-8><title>fullscreen</title></head><body style=\"margin:0\">"
b"<button id=go style=\"position:fixed;left:20px;top:20px;width:160px;height:40px;margin:0\">fullscreen</button>"
b"<script>"
b"window.__how = null; window.__error = null;"
b"for (const t of ['fullscreenchange', 'fullscreenerror']) document.addEventListener(t, () => { window.__how = window.__how || t; });"
b"document.getElementById('go').addEventListener('click', () => {"
b" document.documentElement.requestFullscreen().catch(e => { window.__error = String(e); });"
b"});"
b"</script></body></html>")
GEOMETRY = """() => ({
innerWidth, innerHeight,
screen: [screen.width, screen.height],
displayModeFullscreen: matchMedia('(display-mode: fullscreen)').matches,
fullscreenElement: document.fullscreenElement !== null,
})"""
HOW = "() => [window.__how, window.__error]"
@pytest.fixture
def page_url():
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(PAGE)))
self.end_headers()
self.wfile.write(PAGE)
def log_message(self, *args):
pass
with LocalServer(("127.0.0.1", 0), Handler) as server:
threading.Thread(target=server.serve_forever, daemon=True).start()
try:
yield "http://127.0.0.1:%d/" % server.server_address[1]
finally:
server.shutdown()
def fullscreen_geometry(firefox_binary, page_url, engine_on):
"""The page's geometry once the window has held still after a click on a button that asks for fullscreen."""
extra = None if engine_on else {"zoom.stealth.fpp.hw_seed": 0}
with launch(firefox_binary, extra_prefs=extra, pin=DECLARED, headless=True) as browser:
page = browser.new_page()
page.goto(page_url)
page.mouse.move(90, 40)
page.mouse.click(100, 40)
wait_for_condition(page, lambda: page.evaluate(HOW), lambda how: how[0] is not None,
"the click on a button that asks for fullscreen was followed by neither fullscreenchange nor fullscreenerror")
seen = []
def held_still(geometry):
seen.append(geometry)
return len(seen) >= 4 and all(g == geometry for g in seen[-4:])
# a transition resizes in steps: the geometry counts once it has been the same for four looks in a row
wait_for_condition(page, lambda: page.evaluate(GEOMETRY), held_still, "the window never held still after the fullscreen request")
return dict(seen[-1], how=page.evaluate(HOW))
def test_fullscreen_without_a_window_manager_is_the_declared_screen(firefox_binary, page_url):
on = fullscreen_geometry(firefox_binary, page_url, engine_on=True)
assert on["screen"] == [1600, 900], "the pinned screen is not what the page reads: %r" % on
assert (on["innerWidth"], on["innerHeight"]) == (1600, 900), "with the engine on the fullscreen window is not the declared screen: %r" % on
assert on["displayModeFullscreen"] is True and on["fullscreenElement"] is True, "with the engine on the page does not read fullscreen: %r" % on
off = fullscreen_geometry(firefox_binary, page_url, engine_on=False)
assert (off["innerWidth"], off["innerHeight"]) != (1600, 900), "control: the engine inactive also gives the declared screen: %r" % off
if sys.platform != "win32":
# no window manager: Mozilla's refusal, the DOM fullscreen without the window
assert off["displayModeFullscreen"] is False, "control: without a window manager and without the engine the window went fullscreen: %r" % off
assert (on["innerWidth"], on["innerHeight"], on["displayModeFullscreen"]) != (off["innerWidth"], off["innerHeight"], off["displayModeFullscreen"])
+279
View File
@@ -0,0 +1,279 @@
"""An IPv6 literal a page asks for is judged by the declared network, and a destination behind a SOCKS proxy is left to the proxy.
What this fixes in place (characterisation of the published engine firefox-68; the engine hook is `nsSocketTransport::InitiateSocket` in
`netwerk/base/nsSocketTransport2.cpp`, the decision is `StealthConnect` / `StealthConnectError` in `netwerk/base/StealthIPv6Literal.cpp`, series folder
`network/ipv6-literal`):
* The session declares its host network in `STEALTHFOX_WEBRTC_NETWORK` (`v6=0`: no IPv6). A hostname then never resolves to AAAA, but a LITERAL
(`http://[2001:db8::1]/`) is handed to the socket by Firefox without any lookup, and the route table of the machine under the browser would decide.
The engine decides instead: a direct connection to a routable IPv6 literal fails before `connect()` is called, the way a Windows machine that has the
IPv6 stack and no IPv6 route fails it, and nothing is sent. The client reads it as `NS_ERROR_CONNECTION_REFUSED` (a failed `fetch` is a `TypeError`,
and `requestfailed` carries that text). A page reads this: whether `fetch("http://[<global IPv6>]/")` fails at once or hangs, and with which error, is
the first thing that tells a machine with an IPv6 route from one without.
* An IPv4-mapped literal (`::ffff:127.0.0.1`) is refused on every system and whatever the declaration says: Windows refuses `connect()` to a mapped
address on a socket that is IPv6-only (Firefox's are), and a dual-stack Linux socket would connect over IPv4. The listener below never sees it.
* A destination behind a SOCKS proxy is never judged: the proxy reaches it, not this host. The same literal that is refused with no proxy reaches the
proxy as a CONNECT whose destination is that address and port, as an IPv6 address (SOCKS5 address type 4), never as a name. How many times the
browser tries it (Mozilla retries a connection that did not answer at once) is Mozilla's code and is not fixed here: every CONNECT of the
navigation to the documentation destination has that shape, and there is at least one.
Not clocks: "refused by the engine" and "timed out" are told apart by the error (`TypeError` with the failure text `NS_ERROR_CONNECTION_REFUSED`, against a
`TimeoutError` of the 30 s deadline of the fetch), and by the listener having heard nothing; no duration is read anywhere.
Negative controls, in the same test:
* the listener is real: the same address by its IPv4 literal (`127.0.0.1`) reaches it, once, in the launches where the mapped literal does not;
* the mapped literal is refused with IPv6 declared on as well as off (a rule of its own: the declaration decides the other literals, not this one);
* behind the proxy the documentation-prefix literal that is refused direct IS carried: an engine that judged it behind SOCKS (or that always passed
`kDirect`) would make the proxy record no CONNECT, and the fetch would fail; and an engine that handed the proxy the literal in another shape (a
name, an IPv4 address) fails the shape assertion.
What this test cannot tell, by design: with IPv6 declared on, a global IPv6 literal goes to the OS, whose answer depends on the machine (a runner with no
IPv6 route answers `ENETUNREACH`, the same `NS_ERROR_CONNECTION_REFUSED` as the engine's), so the documentation-prefix fetch is judged only in the
declared-off launch and behind the proxy. The port is 80: Firefox bans port 9 (discard) before any connect, so a fetch to it never reaches the gate.
Hermetic: a local listener, a local SOCKS5 gateway of `tests/_socks_servers.py` that maps the documentation address to the listener and forwards
NOTHING else: the browser's own background traffic also arrives at the gateway, and every CONNECT to an address that is not the lab's is refused
(reply 5) and recorded. Every request, refused or carried, is recorded with its time since the launch, its SOCKS5 address type, its destination as received and
its port. The refused list is written, always, under `$RUNNER_TEMP/invpw-evidence/` (the folder the e2e jobs upload), so that a reader sees
what the browser asked for besides the literal.
"""
from __future__ import annotations
import json
import os
import pathlib
import socket
import socketserver
import struct
import threading
import time
import pytest
from _servers import LocalServer
from _socks_servers import EXIT, Gateway, _recv_exact
from _udp_line import egress_by_proxy, measure_servers
from _waits import wait_until
from test_declared_host_network_e2e import DUAL, NETWORK_ENV, V4_ONLY
pytestmark = pytest.mark.e2e
#: A global-unicast-looking address that no host routes (RFC 3849 documentation prefix): the gate answers for it, whatever the machine has.
DOCUMENTATION = "2001:db8::1"
DOCUMENTATION_HTTP = 80
#: What a failed connect of the engine is called by the browser (NSPR's PR_NETWORK_UNREACHABLE_ERROR and PR_ADDRESS_NOT_AVAILABLE_ERROR both end here).
REFUSED = "NS_ERROR_CONNECTION_REFUSED"
#: SOCKS5 address type of an IPv6 address (RFC 1928); 1 is IPv4, 3 a domain name.
ATYP_IPV6 = 4
#: The folder under ``$RUNNER_TEMP`` the e2e workflows upload (``invpw-evidence-*``).
EVIDENCE_FOLDER = "invpw-evidence"
#: The deadline of a fetch that must END (refused, or carried): far beyond a healthy run; what the page reads on a timeout is a `TimeoutError`, never a verdict.
FETCH_SECONDS = 30
_FETCH_JS = """async (url) => {
try {
const response = await fetch(url, {mode: 'no-cors', cache: 'no-store', signal: AbortSignal.timeout(%d)});
return {ok: true, type: response.type};
} catch (e) {
return {ok: false, name: e.name, message: String(e.message)};
}
}""" % (FETCH_SECONDS * 1000)
class _Listener:
"""A local HTTP-ish listener that remembers every connection it accepted and answers each with a tiny 200."""
def __init__(self) -> None:
self.connections: list = []
outer = self
class Handler(socketserver.BaseRequestHandler):
def handle(self) -> None:
outer.connections.append(self.client_address)
self.request.settimeout(FETCH_SECONDS)
try:
self.request.recv(65536)
self.request.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok")
except OSError:
pass
self.server = LocalServer(("127.0.0.1", 0), Handler)
self.port: int = self.server.server_address[1]
threading.Thread(target=self.server.serve_forever, daemon=True).start()
def __enter__(self) -> "_Listener":
return self
def __exit__(self, *exc) -> None:
self.server.shutdown()
self.server.server_close()
class _GatewayToALocalListener(Gateway):
"""The SOCKS5 gateway of the tests (UDP refused) that carries the documentation address to a local listener and forwards nothing else: the destination
it is asked for is what it records in ``connects`` (with its SOCKS5 address type in ``addresses``), what the listener hears is what it carried, and
every CONNECT to an address that is not the lab's is refused and recorded in ``refused``."""
def __init__(self, carried: dict) -> None:
self._carried = dict(carried)
#: Every address of a request the gateway read, as (host, port, address type), in order.
self.addresses: list = []
#: Every CONNECT that was not the lab's and was refused (reply 5, connection refused), as (host, port), in order.
self.refused: list = []
#: Every request, as a dict, for the evidence file: ``t`` (seconds, monotonic, since ``launch_started``), ``atyp`` (SOCKS5 address type: 1 IPv4,
#: 3 domain name, 4 IPv6), ``destination`` (as received: the NAME when the type is 3), ``port``, ``outcome``.
self.records: list = []
self._launch_t0 = time.monotonic()
self._current = threading.local()
super().__init__(udp="refuse", tcp_exit=EXIT, udp_exit=EXIT)
@staticmethod
def _address_of(c: socket.socket):
atyp = _recv_exact(c, 1)[0]
if atyp == 1:
host = socket.inet_ntoa(_recv_exact(c, 4))
elif atyp == 3:
host = _recv_exact(c, _recv_exact(c, 1)[0]).decode()
else:
host = socket.inet_ntop(socket.AF_INET6, _recv_exact(c, 16))
return host, struct.unpack("!H", _recv_exact(c, 2))[0], atyp
def launch_started(self) -> None:
"""Call just before the launch of the browser behind this gateway: the origin of the times of ``records``."""
self._launch_t0 = time.monotonic()
def _read_address(self, c: socket.socket):
host, port, atyp = self._address_of(c)
self.addresses.append((host, port, atyp))
record = {"t": round(time.monotonic() - self._launch_t0, 3), "atyp": atyp, "destination": host, "port": port,
"outcome": "answered by the lab (or not a CONNECT)"}
self.records.append(record)
self._current.record = record
return host, port
def _target(self, host: str, port: int):
return self._carried.get((host, port), (host, port))
def _open_upstream(self, target):
if target not in self._carried.values():
self.refused.append(target)
self._current.record["outcome"] = "refused"
raise OSError("the lab forwards nothing outside the lab: %s:%d" % target)
self._current.record["outcome"] = "carried to the listener of the lab"
return super()._open_upstream(target)
def documentation_connects(self) -> list:
"""Every request of the navigation to the documentation destination, in whatever shape it arrived: the host is told by its digits."""
return [(host, port, atyp) for host, port, atyp in self.addresses if "2001:db8" in host.lower()]
def _write_refused(gateway: "_GatewayToALocalListener") -> None:
"""What the gateway refused, always (a few lines): under ``$RUNNER_TEMP/invpw-evidence/`` the e2e jobs upload. Off a runner nothing is written."""
runner_temp = os.environ.get("RUNNER_TEMP")
if not runner_temp:
return
folder = pathlib.Path(runner_temp) / EVIDENCE_FOLDER / "ipv6-literal-refused-connects" / ("%d-%d" % (os.getpid(), int(time.time() * 1000)))
folder.mkdir(parents=True, exist_ok=True)
(folder / "refused-connects.json").write_text(json.dumps({
"refused": ["%s:%d" % target for target in gateway.refused],
"requests": gateway.records,
}, indent=2), encoding="utf-8")
def _launch(firefox_binary, gateway=None):
from invisible_playwright import InvisiblePlaywright
kw = {"seed": 42, "binary_path": firefox_binary, "headless": True, "timezone": "America/New_York"}
if gateway is not None:
kw.update(proxy=gateway.proxy, udp_stun_servers=measure_servers(gateway))
return InvisiblePlaywright(**kw)
def _try(page, failures, url, needle):
"""One fetch of ``url`` from the page: what the page read, and the failure texts the client reported for the request whose URL holds ``needle``."""
result = page.evaluate(_FETCH_JS, url)
if not result["ok"]:
wait_until(lambda: [text for seen, text in failures if needle in seen], FETCH_SECONDS, lambda: page.wait_for_timeout(50))
return result, [text for seen, text in failures if needle in seen]
def _page_of(browser):
page = browser.new_context().new_page()
failures: list = []
page.on("requestfailed", lambda request: failures.append((request.url, request.failure)))
page.goto("about:blank")
return page, failures
def _direct_launch(firefox_binary, monkeypatch, declaration, listener, with_documentation_prefix):
"""One launch with no proxy and ``declaration``: the IPv4 literal of the listener (control), the mapped literal of the same listener, and, when
asked, the documentation-prefix literal. Returns what was read and the connections the listener heard after each step."""
monkeypatch.setenv(NETWORK_ENV, declaration)
seen = {}
with _launch(firefox_binary) as browser:
page, failures = _page_of(browser)
before = len(listener.connections)
seen["control"] = _try(page, failures, "http://127.0.0.1:%d/" % listener.port, "127.0.0.1")
wait_until(lambda: len(listener.connections) > before, FETCH_SECONDS, lambda: page.wait_for_timeout(50))
seen["after_control"] = len(listener.connections) - before
seen["mapped"] = _try(page, failures, "http://[::ffff:127.0.0.1]:%d/" % listener.port, "[::ffff:")
seen["after_mapped"] = len(listener.connections) - before
if with_documentation_prefix:
seen["documentation"] = _try(page, failures, "http://[%s]:%d/" % (DOCUMENTATION, DOCUMENTATION_HTTP), "[%s]" % DOCUMENTATION)
return seen
def test_a_direct_ipv6_literal_is_refused_and_one_behind_socks_is_left_to_the_proxy(firefox_binary, monkeypatch):
from invisible_core import _geo
with _Listener() as direct, _Listener() as behind:
off = _direct_launch(firefox_binary, monkeypatch, V4_ONLY, direct, with_documentation_prefix=True)
on = _direct_launch(firefox_binary, monkeypatch, DUAL, direct, with_documentation_prefix=False)
# Behind a SOCKS5 gateway, IPv6 declared off as in the first launch: the documentation-prefix literal is the proxy's to reach.
gateway = _GatewayToALocalListener({(DOCUMENTATION, DOCUMENTATION_HTTP): ("127.0.0.1", behind.port)})
try:
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(gateway))
monkeypatch.setenv(NETWORK_ENV, V4_ONLY)
gateway.launch_started()
with _launch(firefox_binary, gateway) as browser:
page, failures = _page_of(browser)
proxied = _try(page, failures, "http://[%s]:%d/" % (DOCUMENTATION, DOCUMENTATION_HTTP), "[%s]" % DOCUMENTATION)
wait_until(lambda: behind.connections, FETCH_SECONDS, lambda: page.wait_for_timeout(50))
documentation = gateway.documentation_connects()
finally:
gateway.close()
_write_refused(gateway)
# The listener is real: its IPv4 literal reaches it, once per launch.
for name, seen in (("declared off", off), ("declared on", on)):
control, _failed = seen["control"]
assert control["ok"], "%s: the IPv4 literal of the local listener was not reached: %s" % (name, seen)
assert seen["after_control"] == 1, "%s: the listener heard %d connections for one fetch of its IPv4 literal: %s" % (name, seen["after_control"], seen)
# An IPv4-mapped literal is refused by the engine, declared off or on, and the listener hears nothing for it.
for name, seen in (("declared off", off), ("declared on", on)):
result, failed = seen["mapped"]
assert result["ok"] is False and result["name"] == "TypeError", (
"%s: the fetch of the mapped literal did not fail as a refused connection (a TimeoutError would be a connect that was attempted): %s" % (name, seen))
assert failed == [REFUSED], "%s: the client reported %r for the mapped literal, not the engine's refusal: %s" % (name, failed, seen)
assert seen["after_mapped"] == seen["after_control"], "%s: the listener heard a connection through the mapped literal: %s" % (name, seen)
# With IPv6 declared off, a direct documentation-prefix literal is refused by the engine: the same failure as a machine with no IPv6 route.
result, failed = off["documentation"]
assert result["ok"] is False and result["name"] == "TypeError", (
"declared off: the direct fetch of %s did not fail as a refused connection (a TimeoutError means a connect was attempted): %s" % (DOCUMENTATION, off))
assert failed == [REFUSED], "declared off: the client reported %r for the direct documentation-prefix literal: %s" % (failed, off)
# The same literal behind the SOCKS5 gateway is carried: every CONNECT of the navigation to the documentation destination is the IPv6 literal and port,
# as an IPv6 address (how many the browser makes is Mozilla's), and the listener behind it answered.
assert proxied[0] == {"ok": True, "type": "opaque"}, (
"the fetch of %s behind the SOCKS5 gateway was not carried (it is refused with no proxy): %s; failures %s; gateway requests %s" % (
DOCUMENTATION, proxied[0], proxied[1], gateway.addresses))
assert documentation, "the gateway was asked for no CONNECT to %s:%d: %s" % (DOCUMENTATION, DOCUMENTATION_HTTP, gateway.addresses)
assert set(documentation) == {(DOCUMENTATION, DOCUMENTATION_HTTP, ATYP_IPV6)}, (
"every CONNECT to the documentation destination should carry the IPv6 literal %s port %d as an IPv6 address (type %d): %s" % (
DOCUMENTATION, DOCUMENTATION_HTTP, ATYP_IPV6, documentation))
assert (DOCUMENTATION, DOCUMENTATION_HTTP) not in gateway.refused, "the gateway refused the destination of the lab: %s" % gateway.refused
assert len(behind.connections) >= 1, "the listener behind the gateway heard nothing"
-76
View File
@@ -1,76 +0,0 @@
"""A window that another one covers stays visible, unless occlusion tracking is enabled.
What it fixes: with ``widget.windows.window_occlusion_tracking.enabled`` and ``zoom.stealth.widget.occlusion_tracking.enabled`` false, as the core declares
them from one value, a page whose window is fully covered by a second window keeps ``document.visibilityState`` ``visible`` and gets no ``visibilitychange``.
Retail Windows with the tracker on says ``hidden`` there (and then throttles ``requestAnimationFrame`` to 1 Hz and the timers to 1000 ms); a session nobody
looks at must not read as backgrounded.
The hook: ``nsWindow::OnVisibilityNotifyEvent`` in ``widget/gtk/nsWindow.cpp`` of the series, folder ``fingerprint/screen-window/occlusion``: the condition of the
ternary that decides ``OCCLUDED`` or ``UNKNOWN`` reads the pref (``StealthOcclusionTracked``). On Windows the same declaration is Mozilla's own pref, so the same
page reading is the proof that the two builds do not disagree.
The control, in the same test: the two prefs true. The same two sessions, the same covering, and the covered page turns ``hidden``. Without it the first half
proves nothing (a window that was never covered is visible too); it runs first, so a runner on which two windows do not cover each other is red here and not a
green that means nothing.
Two sessions are launched on one display and both are headed: the Linux e2e runs under ``xvfb-run`` (no window manager, so the second window is mapped over the
first), Windows uses the interactive desktop of the runner (the second maximized window is created on top of the first and the tracker, when on, calculates
the cover). A page reads it from ``document.visibilityState`` and the ``visibilitychange`` event.
"""
from __future__ import annotations
import pytest
from _window_sessions import in_a_thread_of_its_own, launch, wait_for_condition
pytestmark = pytest.mark.e2e
#: The one decision, under both engine names (core: ``OCCLUSION_TRACKING``).
TRACKING_PREFS = ("widget.windows.window_occlusion_tracking.enabled", "zoom.stealth.widget.occlusion_tracking.enabled")
#: Records every change of visibility of the document, and answers the current state.
WATCH = """() => {
window.__visibility = [document.visibilityState];
document.addEventListener('visibilitychange', () => window.__visibility.push(document.visibilityState));
return document.visibilityState;
}"""
STATE = "() => document.visibilityState"
CHANGES = "() => window.__visibility"
#: Two painted frames: the page's own process has handled what the window system told it before this returns.
TWO_FRAMES = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))"
def opens_the_covering_window(second):
"""Runs in the second session's own thread: opens a window on the display and waits for two painted frames."""
cover = second.new_page()
cover.goto("about:blank")
cover.evaluate(TWO_FRAMES)
def second_window_over_the_first(firefox_binary, tracking):
"""(state, changes) of the first session's page after a second session's window is up over it.
``tracking`` is None for the product as it launches, or the value both tracking prefs are given."""
extra = None if tracking is None else {name: tracking for name in TRACKING_PREFS}
with launch(firefox_binary, extra_prefs=extra) as first, in_a_thread_of_its_own(firefox_binary) as second:
covered = first.new_page()
covered.goto("about:blank")
assert covered.evaluate(WATCH) == "visible", "the page was not visible before anything covered it"
second.run(opens_the_covering_window)
if tracking:
wait_for_condition(covered, lambda: covered.evaluate(STATE), lambda state: state == "hidden",
"a window that another one covers never turned hidden with occlusion tracking enabled")
else:
covered.evaluate(TWO_FRAMES)
return covered.evaluate(STATE), covered.evaluate(CHANGES)
def test_a_covered_window_stays_visible_unless_occlusion_tracking_is_enabled(firefox_binary):
tracked_state, tracked_changes = second_window_over_the_first(firefox_binary, True)
assert tracked_state == "hidden" and tracked_changes == ["visible", "hidden"], (
"control: with tracking enabled the covered page reads %r, changes %r" % (tracked_state, tracked_changes))
state, changes = second_window_over_the_first(firefox_binary, None)
assert state == "visible" and changes == ["visible"], (
"the product's covered page reads %r, changes %r: it must stay visible, with no visibilitychange" % (state, changes))
assert state != tracked_state, "enabled and disabled read the same: the declaration decides nothing"