Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07018c00b7 | ||
|
|
98da306330 | ||
|
|
c3295c5b12 | ||
|
|
66e5b75cb6 | ||
|
|
3f372e4675 | ||
|
|
6b67a514e5 |
No files matched your search
@@ -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
|
||||
@@ -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"])
|
||||
@@ -0,0 +1,179 @@
|
||||
"""The engine never asks the host where it is: a page that asks for a position starts no location process and loads no location module.
|
||||
|
||||
What it fixes, in the published engine (firefox-68), for the hooks of `fingerprint/geolocation/no-host-provider`
|
||||
(`GeolocationService::Init`, `GeolocationSystem::*`, `PermissionObserver`, in `dom/geolocation` and `netwerk/...`): the position a page reads comes only
|
||||
from the declaration (the standard `geolocation` option of the context, which the core fills for every session). The engine does not ask the
|
||||
operating system for a position, for a Wi-Fi scan or for the privacy switch of the location. Retail Firefox on Windows does: the first position
|
||||
request makes the parent start a utility process of the kind `WINDOWS_UTILS` (`-sandboxingKind 3`, which runs the WinRT location provider) and load
|
||||
`geolocation.dll`, `locationframeworkps.dll`, `wlanapi.dll` and `capabilityaccessmanagerclient.dll`. A page cannot see a process, but it sees what
|
||||
that road gives (the position of the host, a delay, an error), and a host that has a location service answers differently from one that has not.
|
||||
|
||||
What the test does. One session (seed 42, no proxy), a context that declares a position no runner has (12.345, -45.678) and grants the permission, a
|
||||
page served from 127.0.0.1 (a secure context). The page runs `permissions.query`, `getCurrentPosition` and `watchPosition`. Then the test lists the
|
||||
engine processes below the test process (the executable is in the engine's folder) and reads, for each one it may read, the files mapped into it
|
||||
(`psutil` `memory_maps`: the DLLs on Windows, the shared objects on Linux) and its command line.
|
||||
|
||||
What it asserts:
|
||||
* Windows: none of `geolocation.dll`, `locationframeworkps.dll`, `wlanapi.dll`, `capabilityaccessmanagerclient.dll` is mapped in any engine process, and
|
||||
no process has `-sandboxingKind 3`;
|
||||
* Linux (the engine has no `WINDOWS_UTILS` there, so the Windows modules cannot exist; the form that holds on Linux is "no host location library"): none
|
||||
of the files mapped in an engine process is a location library of the host (`libgeoclue`, `libgeocode`, `libportal`), and no utility process
|
||||
is of a kind other than the generic one (`-sandboxingKind` 0) or the inference one;
|
||||
* the control, on both systems: the page was told the DECLARED position by `getCurrentPosition` and by `watchPosition` (so the calls ran to the end,
|
||||
and the answer came from the declaration, not from the host), `permissions.query` says `granted`, and the reading of the mapped files is not blind
|
||||
(the parent was readable and has `xul.dll` / `libxul.so` mapped). A test that listed nothing would pass without this.
|
||||
|
||||
The retail Firefox of the same window, which loads these modules, is not in this file (a test never runs another browser in the gate): the
|
||||
control is the declared answer plus the reading that sees a module that is certainly there.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
WINDOWS = sys.platform == "win32"
|
||||
|
||||
#: What retail Firefox on Windows maps once a page asks for a position (the WinRT provider and its capability checks).
|
||||
WINDOWS_LOCATION_MODULES = ("geolocation.dll", "locationframeworkps.dll", "wlanapi.dll", "capabilityaccessmanagerclient.dll")
|
||||
#: The Linux forms of the same idea: the location services of the desktop (GeoClue) and the portal.
|
||||
LINUX_LOCATION_LIBRARIES = ("libgeoclue", "libgeocode", "libportal")
|
||||
#: `SandboxingKind::WINDOWS_UTILS` of the engine's `ipc/glue/UtilityProcessSandboxing.h`: GENERIC_UTILITY 0, UTILITY_AUDIO_DECODING_WMF 1,
|
||||
#: MF_MEDIA_ENGINE_CDM 2, WINDOWS_UTILS 3.
|
||||
WINDOWS_UTILS_KIND = "3"
|
||||
#: Linux: GENERIC_UTILITY 0, HW_INFERENCE 1 (the only kinds the Linux engine has).
|
||||
LINUX_UTILITY_KINDS = ("0", "1")
|
||||
|
||||
#: A position no runner has: the page must read exactly this.
|
||||
POSITION = {"latitude": 12.345, "longitude": -45.678, "accuracy": 25}
|
||||
|
||||
PAGE = b"<!doctype html><html><head><meta charset=utf-8><title>geolocation</title></head><body><p>where</p></body></html>"
|
||||
|
||||
READ = """async () => {
|
||||
const position = (p) => ({lat: p.coords.latitude, lon: p.coords.longitude});
|
||||
const failure = (e) => ({error: e.code, message: e.message});
|
||||
const out = {secure: isSecureContext};
|
||||
out.permission = (await navigator.permissions.query({name: 'geolocation'})).state;
|
||||
out.current = await new Promise(resolve => {
|
||||
navigator.geolocation.getCurrentPosition(p => resolve(position(p)), e => resolve(failure(e)), {timeout: 30000});
|
||||
});
|
||||
out.watched = await new Promise(resolve => {
|
||||
const id = navigator.geolocation.watchPosition(
|
||||
p => { navigator.geolocation.clearWatch(id); resolve(position(p)); },
|
||||
e => { navigator.geolocation.clearWatch(id); resolve(failure(e)); },
|
||||
{timeout: 30000});
|
||||
});
|
||||
return out;
|
||||
}"""
|
||||
|
||||
|
||||
def _a_page_server():
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
timeout = 5
|
||||
|
||||
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.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(PAGE)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
server.daemon_threads = True
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server, "http://127.0.0.1:%d/" % server.server_address[1]
|
||||
|
||||
|
||||
def _engine_processes(binary):
|
||||
"""The processes below this one whose executable is in the engine's folder (the tree of THIS test, not the machine)."""
|
||||
import psutil
|
||||
|
||||
folder = os.path.normcase(os.path.dirname(os.path.realpath(binary)))
|
||||
found = []
|
||||
for proc in psutil.Process().children(recursive=True):
|
||||
try:
|
||||
exe = os.path.normcase(os.path.realpath(proc.exe()))
|
||||
except psutil.Error:
|
||||
continue
|
||||
if exe.startswith(folder):
|
||||
found.append(proc)
|
||||
return found
|
||||
|
||||
|
||||
def _describe(proc):
|
||||
"""(kind, command line, mapped file names in lower case or None when the process cannot be read)."""
|
||||
import psutil
|
||||
|
||||
try:
|
||||
cmd = proc.cmdline()
|
||||
except psutil.Error:
|
||||
cmd = []
|
||||
kind = cmd[-1] if "-contentproc" in cmd else "parent"
|
||||
try:
|
||||
mapped = {os.path.basename(m.path).lower() for m in proc.memory_maps(grouped=True)}
|
||||
except (psutil.Error, OSError):
|
||||
mapped = None
|
||||
return kind, cmd, mapped
|
||||
|
||||
|
||||
def _sandboxing_kind(cmd):
|
||||
return cmd[cmd.index("-sandboxingKind") + 1] if "-sandboxingKind" in cmd and cmd.index("-sandboxingKind") + 1 < len(cmd) else None
|
||||
|
||||
|
||||
def test_no_host_location_module_loads_and_no_windows_utils_process_starts(firefox_binary):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
server, url = _a_page_server()
|
||||
try:
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, humanize=False,
|
||||
locale="en-US", timezone="America/New_York") as browser:
|
||||
context = browser.new_context(geolocation=POSITION, permissions=["geolocation"])
|
||||
page = context.new_page()
|
||||
page.goto(url, wait_until="load", timeout=60_000)
|
||||
answer = page.evaluate(READ)
|
||||
described = [_describe(proc) for proc in _engine_processes(firefox_binary)]
|
||||
context.close()
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
# The control: the calls ran to the end and the answer is the declaration.
|
||||
declared = {"lat": POSITION["latitude"], "lon": POSITION["longitude"]}
|
||||
assert answer["secure"] is True and answer["permission"] == "granted", answer
|
||||
assert answer["current"] == declared, "getCurrentPosition did not answer the declared position: %r" % (answer,)
|
||||
assert answer["watched"] == declared, "watchPosition did not answer the declared position: %r" % (answer,)
|
||||
|
||||
# The reading is not blind: the parent was readable and has the engine's own library mapped.
|
||||
parents = [(cmd, mapped) for kind, cmd, mapped in described if kind == "parent"]
|
||||
assert parents, "no engine parent process below the test: %r" % ([(k, m is not None) for k, _c, m in described],)
|
||||
engine_library = "xul.dll" if WINDOWS else "libxul.so"
|
||||
readable_parent = [mapped for _cmd, mapped in parents if mapped is not None]
|
||||
assert readable_parent and any(engine_library in mapped for mapped in readable_parent), (
|
||||
"the mapped files of the parent cannot be read, or %s is not among them: the check below would pass with an empty list (%r)"
|
||||
% (engine_library, [sorted(m)[:8] if m else m for _c, m in parents]))
|
||||
|
||||
found = []
|
||||
kinds = []
|
||||
for kind, cmd, mapped in described:
|
||||
sandboxing = _sandboxing_kind(cmd)
|
||||
if sandboxing is not None:
|
||||
kinds.append((kind, sandboxing))
|
||||
for name in mapped or ():
|
||||
if WINDOWS and name in WINDOWS_LOCATION_MODULES:
|
||||
found.append((kind, name))
|
||||
if not WINDOWS and any(name.startswith(prefix) or prefix in name for prefix in LINUX_LOCATION_LIBRARIES):
|
||||
found.append((kind, name))
|
||||
assert found == [], "a process of the engine mapped a host location module: %s" % (found,)
|
||||
if WINDOWS:
|
||||
assert not [k for k in kinds if k[1] == WINDOWS_UTILS_KIND], "a utility process of the kind WINDOWS_UTILS was started: %s" % (kinds,)
|
||||
else:
|
||||
assert not [k for k in kinds if k[1] not in LINUX_UTILITY_KINDS], "a utility process of an unexpected kind was started: %s" % (kinds,)
|
||||
@@ -0,0 +1,163 @@
|
||||
"""A fresh profile keeps the startup script cache it wrote as a file mapping, not as a second copy on the heap (firefox-68, Linux and Windows).
|
||||
|
||||
What it fixes, in the published engine (firefox-68), for the hooks of `platform/script-cache` (`js/xpconnect/loader/ScriptPreloader.cpp` and `.h`, the own
|
||||
file `StealthScriptCache-inl.h`): the script preloader writes `<profile>/startupCache/scriptCache.bin` once the startup is over. On a WARM profile the
|
||||
cache is a file mapping (`explicit/script-preloader/non-heap/memmapped-cache`) and costs no heap. On a FRESH profile the same bytes were built in memory
|
||||
for the write and stayed on the heap for the whole session (16.5 MB measured in the parent, with the 13.3 MB file already on disk): the engine now maps the
|
||||
file it wrote and points every entry into the mapping (`AdoptWrittenCache`), and reports the mapping as
|
||||
`explicit/script-preloader/non-heap/memmapped-written-cache`, so the megabytes that left the heap appear somewhere. It is a memory property, not a
|
||||
fingerprint one: a page cannot read it. The preloader exists TWICE in the parent: `gScriptPreloader` (`scriptCache.bin`, the parent's scripts, about 14 MB) and `gChildScriptPreloader` (`scriptCache-child.bin`,
|
||||
the scripts for content processes, about 1.2 MB; `ScriptPreloader::GetChildSingleton` runs `InitCache(u"scriptCache-child")` in the parent too). Both register the
|
||||
same weak memory reporter, so the parent's report carries every path TWICE under the process name `""`, once per instance, in an order the engine does not fix; the
|
||||
test keeps ALL the amounts of a path (a dict that kept the last one made the warm session look as if it mapped 1.2 MB while 14.3 MB was on disk: run 44985244053,
|
||||
Linux 1207724 and Windows 1207732 reported, 14296776 and 14475288 on disk). The test also records, in every assertion message, the size of every file in
|
||||
`startupCache/` (when the cache was adopted, when the fresh session was over, at the warm start and when the warm report was read). The test reads the memory report of the parent (the engine's own reporters, `nsIMemoryReporterManager.getReports`,
|
||||
in chrome scope through Marionette: the route of `tests/webfont_probe.py`; `MOZ_REMOTE_ALLOW_SYSTEM_ACCESS` is set with `monkeypatch`).
|
||||
|
||||
What the test does. A NEW profile directory, a session on it. It waits on the CONDITION "`startupCache/scriptCache.bin` exists" (not on a timer), then on the
|
||||
condition "the parent reports a non-zero `memmapped-written-cache`" (the file appears when the write is moved into place and is adopted a moment after).
|
||||
It asserts, for that session: `memmapped-written-cache` equals the size of the file (non-zero), and `heap/saved-scripts` is below the size of the file (the
|
||||
heap copies are gone: without the hook it is about the size of the file). Then the SAME profile is opened again (warm): `memmapped-cache` equals the size of
|
||||
the file left on disk when the fresh session ended (it can be a rewrite of the shutdown, smaller than the adopted one) (the file is mapped under the name `scriptCache-current.bin`: a warm session moves `scriptCache.bin` aside when it opens it), and
|
||||
`memmapped-written-cache` is 0 unless the session wrote the cache again, in which case `scriptCache.bin` is back and it equals the new size.
|
||||
|
||||
Negative control: the warm session of the same profile. The fresh and the warm session differ in the two reporters in the way described (written is the size
|
||||
of the file in one and 0 in the other, read is 0 in one and the size in the other), so the reading cannot give the same number whatever the engine does.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from _waits import wait_until
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
MARIONETTE_ARGS = ["-marionette", "-remote-allow-system-access"]
|
||||
WRITTEN = "explicit/script-preloader/non-heap/memmapped-written-cache"
|
||||
READ_CACHE = "explicit/script-preloader/non-heap/memmapped-cache"
|
||||
SAVED = "explicit/script-preloader/heap/saved-scripts"
|
||||
LAUNCH = dict(seed=42, headless=True, humanize=False, locale="en-US", timezone="America/New_York")
|
||||
|
||||
#: The reports of the parent process (the process name of a reporter of this process is the empty string) under the script preloader.
|
||||
REPORT_JS = """
|
||||
const done = arguments[arguments.length - 1];
|
||||
const out = {};
|
||||
const manager = Cc["@mozilla.org/memory-reporter-manager;1"].getService(Ci.nsIMemoryReporterManager);
|
||||
manager.getReports(
|
||||
{callback(process, path, kind, units, amount, description) {
|
||||
if (process === "" && path.startsWith("explicit/script-preloader/")) { (out[path] = out[path] || []).push(amount); }
|
||||
}},
|
||||
null,
|
||||
{callback() { done(JSON.stringify(out)); }},
|
||||
null,
|
||||
false);
|
||||
"""
|
||||
|
||||
|
||||
def _reports(marionette):
|
||||
"""path -> sorted list of every amount reported under it (one per preloader instance: the parent's and the child's)."""
|
||||
answer = marionette.call("WebDriver:ExecuteAsyncScript", {"script": REPORT_JS, "args": []})
|
||||
return {path: sorted(amounts) for path, amounts in json.loads(answer["value"]).items()}
|
||||
|
||||
|
||||
def _files(profile):
|
||||
"""name -> size of every file in `<profile>/startupCache/` (empty if the folder is not there)."""
|
||||
folder = profile / "startupCache"
|
||||
if not folder.is_dir():
|
||||
return {}
|
||||
return {entry.name: entry.stat().st_size for entry in sorted(folder.iterdir()) if entry.is_file()}
|
||||
|
||||
|
||||
def _amounts(reports, path):
|
||||
return reports.get(path, [])
|
||||
|
||||
|
||||
def _session(binary, profile, port):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
return InvisiblePlaywright(binary_path=binary, profile_dir=profile, extra_args=MARIONETTE_ARGS,
|
||||
extra_prefs={"marionette.port": port}, **LAUNCH)
|
||||
|
||||
|
||||
def _open_marionette(port):
|
||||
import webfont_probe
|
||||
|
||||
marionette = webfont_probe._Marionette(port)
|
||||
marionette.call("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {}}})
|
||||
marionette.call("WebDriver:SetTimeouts", {"script": 240000})
|
||||
marionette.call("Marionette:SetContext", {"value": "chrome"})
|
||||
return marionette
|
||||
|
||||
|
||||
def test_a_fresh_profile_reports_its_written_cache_as_mapped(firefox_binary, monkeypatch, tmp_path):
|
||||
import webfont_probe
|
||||
|
||||
monkeypatch.setenv("MOZ_REMOTE_ALLOW_SYSTEM_ACCESS", "1") # the chrome-scope read of the memory report
|
||||
profile = tmp_path / "profile"
|
||||
cache = profile / "startupCache" / "scriptCache.bin"
|
||||
|
||||
# The fresh session: the cache is written during it and adopted.
|
||||
port = webfont_probe.marionette_port()
|
||||
marionette = None
|
||||
try:
|
||||
with _session(firefox_binary, profile, port) as context:
|
||||
page = context.new_page()
|
||||
page.goto("about:blank", timeout=60_000)
|
||||
written_file = wait_until(lambda: cache.exists() and cache.stat().st_size > 0, 180, lambda: page.wait_for_timeout(500))
|
||||
assert written_file, "the profile never got %s (the startup script cache is written once the startup is over)" % cache
|
||||
marionette = _open_marionette(port)
|
||||
seen = {}
|
||||
|
||||
def reported():
|
||||
seen.clear()
|
||||
seen.update(_reports(marionette))
|
||||
return cache.exists() and cache.stat().st_size in _amounts(seen, WRITTEN)
|
||||
|
||||
adopted = wait_until(reported, 60, lambda: page.wait_for_timeout(500))
|
||||
size = cache.stat().st_size
|
||||
fresh = dict(seen)
|
||||
files_adopted = _files(profile)
|
||||
finally:
|
||||
if marionette is not None:
|
||||
marionette.close()
|
||||
# The parent's own file is `scriptCache.bin`; the other amount under a path is the child preloader's (`scriptCache-child.bin`).
|
||||
assert adopted, "the parent never reported its written cache (%d bytes) as mapped (%s); reports (all amounts per path): %r; startupCache/ when adopted: %r" % (size, WRITTEN, fresh, files_adopted)
|
||||
assert size in _amounts(fresh, WRITTEN), "no mapping reported (%r) is the file written (%d bytes): %r; startupCache/: %r" % (_amounts(fresh, WRITTEN), size, fresh, files_adopted)
|
||||
assert max(_amounts(fresh, SAVED), default=0) < size, "the heap still holds the scripts of the cache that is on disk: %r (file %d bytes); startupCache/: %r" % (fresh, size, files_adopted)
|
||||
assert not any(_amounts(fresh, READ_CACHE)), "a fresh profile has no cache to read: %r; startupCache/: %r" % (fresh, files_adopted)
|
||||
|
||||
# Control: the same profile, warm. The cache of the file is read as a mapping and nothing written this session is reported unless it was rewritten.
|
||||
# The warm session maps the file that is on disk when the fresh session is OVER, not the one that was adopted while it ran: the cache can be written
|
||||
# again during the shutdown (`ScriptPreloader::InvalidateCache` starts a new write when the cache is invalidated after it was saved, and the file is
|
||||
# replaced), so the size to compare with is read here, after the exit.
|
||||
files_left = _files(profile)
|
||||
started_with = cache.stat().st_size if cache.exists() else 0
|
||||
assert started_with > 0, "the fresh session left no script cache for the warm session to open: %s; startupCache/: %r" % (cache, files_left)
|
||||
port = webfont_probe.marionette_port()
|
||||
marionette = None
|
||||
try:
|
||||
with _session(firefox_binary, profile, port) as context:
|
||||
page = context.new_page()
|
||||
page.goto("about:blank", timeout=60_000)
|
||||
marionette = _open_marionette(port)
|
||||
warm = _reports(marionette)
|
||||
# A warm session MOVES the file it found to `scriptCache-current.bin` when it opens the cache (`ScriptPreloader::OpenCache`) and maps that
|
||||
# one; `scriptCache.bin` is there again only once this session has written a cache of its own (about 3 s after the startup, and only if
|
||||
# it has something to save). So the file of this session is absent until then, and nothing is reported as written until it exists
|
||||
# (`WriteCache` moves the file into place BEFORE it adopts it, so a report that carries a written cache finds the file here).
|
||||
now = cache.stat().st_size if cache.exists() else 0
|
||||
files_warm = _files(profile)
|
||||
finally:
|
||||
if marionette is not None:
|
||||
marionette.close()
|
||||
# What the warm session opens: every file the fresh session left (`scriptCache.bin`, the parent's, and `scriptCache-child.bin`, the child's, when it was
|
||||
# written) is moved to `<name>-current.bin` and mapped, and each mapping is reported once under `memmapped-cache`.
|
||||
left = sorted(size for name, size in files_left.items() if name in ("scriptCache.bin", "scriptCache-child.bin"))
|
||||
details = "startupCache/ at the end of the fresh session %r (%d bytes adopted while it ran), at the warm start %r, when the warm report was read %r; warm reports (all amounts per path): %r" % (files_left, size, files_left, files_warm, warm)
|
||||
assert sorted(_amounts(warm, READ_CACHE)) == left, "the warm session did not map the cache files it found (%r bytes on disk when the fresh session ended): %s" % (left, details)
|
||||
assert started_with in _amounts(warm, READ_CACHE), "the warm session did not map the parent's cache (%d bytes): %s" % (started_with, details)
|
||||
current = sorted(size for name, size in files_warm.items() if name in ("scriptCache.bin", "scriptCache-child.bin"))
|
||||
assert all(amount in [0] + current for amount in _amounts(warm, WRITTEN)), "the warm session reports a written cache that is not one of its files (%r): %s" % (current, details)
|
||||
assert _amounts(warm, READ_CACHE) != _amounts(fresh, READ_CACHE), details
|
||||
@@ -0,0 +1,256 @@
|
||||
"""The launch counter is ONE plain GET to the address the engine carries, sent by the browser when it starts, before any page exists (firefox-68, Linux and Windows).
|
||||
|
||||
What it fixes, in the published engine (firefox-68), for the hooks of `platform/launch-counter` (`browser/components/BrowserGlue.sys.mjs`: the hook in
|
||||
`_beforeUIStartup`, which loads `StealthLaunchCounter.sys.mjs`): at start the parent process does `fetch(<counter address>, {method: "GET",
|
||||
credentials: "omit", cache: "no-store"})` once and swallows the errors. The counter is mandatory (no pref turns it off or moves it: the core refuses both)
|
||||
and it is part of the product, so a hook that is lost passes every test that never starts a browser and looks: the node test calls `fire()` directly. This
|
||||
is the test that starts the browser and counts what leaves.
|
||||
|
||||
How it observes a request to a host of the internet without a network. The browser is given an HTTP proxy of the test (the road of the browser's own
|
||||
requests: the counter is made by the parent, in no page). The proxy answers the `CONNECT` to the counter's host and terminates TLS with a leaf of a
|
||||
lab CA that the profile trusts (the CA is added to the profile with the engine's own xpcshell, `_lab_pki.add_ca_to_profile`), so it reads the GET itself:
|
||||
its method, its headers, its order. Every other request through the proxy is refused and recorded. Nothing leaves the machine. The address is read from the
|
||||
module the binary runs (`resource:///modules/StealthLaunchCounter.sys.mjs`, in the `browser/omni.ja` next to the executable): in core 68.80.0
|
||||
the core declares no counter address (no pref, no `USAGE_PING_URL`), the engine carries one constant, the same in every binary, and the test follows
|
||||
that constant in the binary under test, it does not copy it.
|
||||
|
||||
What the test asserts:
|
||||
* the GET arrives while NO page exists (the test waits for it before it opens a page, and the page server has received nothing at that moment);
|
||||
* it is a GET with no `Cookie`, `Authorization`, `Referer` or `Origin` (no credentials, nothing of a page) and it asks not to be cached (`Cache-Control:
|
||||
no-cache`, which is what `cache: "no-store"` sends);
|
||||
* once a page has been loaded and has made its own request to the same address, the proxy has seen exactly two GETs to it: the counter's and the page's.
|
||||
|
||||
Negative control: that page request. It goes through the same proxy to the same address, and the test tells it from the counter's by its `Referer`
|
||||
(a request of a page carries it, the counter's has none), so the count of two shows the proxy sees a page's request and that the counter's is not one
|
||||
of them, and a launch that sent the counter twice, or from the page, is red.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
import re
|
||||
import socket
|
||||
import ssl
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_core.jar import open_jar
|
||||
|
||||
from _lab_egress import LAB_EGRESS_IP
|
||||
from _lab_pki import LabCa, add_ca_to_profile
|
||||
from _servers import LocalServer
|
||||
from _socks_servers import declare_exit, forget_exit
|
||||
from _waits import wait_until
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
PAGE = b"<!doctype html><html><head><meta charset=utf-8><title>counter</title></head><body><p>page</p></body></html>"
|
||||
|
||||
|
||||
class Order:
|
||||
"""One order for what the two servers hear: the number of each request, across both."""
|
||||
|
||||
def __init__(self):
|
||||
self._numbers = itertools.count(1)
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def next(self):
|
||||
with self._lock:
|
||||
return next(self._numbers)
|
||||
|
||||
|
||||
class CounterProxy:
|
||||
"""An HTTP proxy on 127.0.0.1 that stands in for the counter's host: it terminates TLS for it and records the requests it reads there."""
|
||||
|
||||
def __init__(self, host, port, leaf, key, order):
|
||||
self.host, self.port, self.order = host, port, order
|
||||
self.gets = [] # every request read inside TLS for the counter's host, in order
|
||||
self.other = [] # every CONNECT or request for anything else: refused
|
||||
self.handshakes = []
|
||||
self._lock = threading.Lock()
|
||||
self._tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
self._tls.load_cert_chain(str(leaf), str(key))
|
||||
self._listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self._listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
self._listener.bind(("127.0.0.1", 0))
|
||||
self._listener.listen(32)
|
||||
self.server = "http://127.0.0.1:%d" % self._listener.getsockname()[1]
|
||||
self._closed = False
|
||||
threading.Thread(target=self._accept, daemon=True).start()
|
||||
|
||||
def close(self):
|
||||
self._closed = True
|
||||
try:
|
||||
self._listener.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _accept(self):
|
||||
while not self._closed:
|
||||
try:
|
||||
conn, _ = self._listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self._handle, args=(conn,), daemon=True).start()
|
||||
|
||||
@staticmethod
|
||||
def _read_head(sock):
|
||||
data = b""
|
||||
while b"\r\n\r\n" not in data:
|
||||
chunk = sock.recv(65536)
|
||||
if not chunk:
|
||||
return None
|
||||
data += chunk
|
||||
return data.split(b"\r\n\r\n", 1)[0].decode("latin-1")
|
||||
|
||||
@staticmethod
|
||||
def _parse(head):
|
||||
lines = head.split("\r\n")
|
||||
method, target = lines[0].split(" ")[:2]
|
||||
headers = {}
|
||||
for line in lines[1:]:
|
||||
name, _, value = line.partition(":")
|
||||
headers[name.strip().lower()] = value.strip()
|
||||
return method, target, headers
|
||||
|
||||
def _handle(self, conn):
|
||||
try:
|
||||
conn.settimeout(30)
|
||||
head = self._read_head(conn)
|
||||
if head is None:
|
||||
return
|
||||
method, target, _headers = self._parse(head)
|
||||
if method == "CONNECT" and target == "%s:%d" % (self.host, self.port):
|
||||
conn.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
||||
self._serve_tls(conn)
|
||||
else:
|
||||
with self._lock:
|
||||
self.other.append("%s %s" % (method, target))
|
||||
conn.sendall(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
|
||||
except (OSError, ssl.SSLError, ValueError):
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
conn.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _serve_tls(self, conn):
|
||||
try:
|
||||
tls = self._tls.wrap_socket(conn, server_side=True)
|
||||
except (ssl.SSLError, OSError) as failure:
|
||||
with self._lock:
|
||||
self.handshakes.append("failed: %s" % failure)
|
||||
return
|
||||
with self._lock:
|
||||
self.handshakes.append("ok")
|
||||
head = self._read_head(tls)
|
||||
if head is None: # a speculative connection that never sends a request
|
||||
return
|
||||
method, target, headers = self._parse(head)
|
||||
with self._lock:
|
||||
self.gets.append({"order": self.order.next(), "method": method, "target": target, "headers": headers})
|
||||
body = b"ping\n"
|
||||
tls.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s" % (len(body), body))
|
||||
|
||||
def seen(self):
|
||||
with self._lock:
|
||||
return list(self.gets)
|
||||
|
||||
|
||||
class PageServer:
|
||||
"""The page of the test, on 127.0.0.1; records the order of every request it gets."""
|
||||
|
||||
def __init__(self, order):
|
||||
import http.server
|
||||
|
||||
self.requests = []
|
||||
requests = self.requests
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
timeout = 5
|
||||
|
||||
def do_GET(self):
|
||||
requests.append((order.next(), self.path))
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(PAGE)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(PAGE)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
self._server = LocalServer(("127.0.0.1", 0), Handler)
|
||||
self.url = "http://127.0.0.1:%d/" % self._server.server_address[1]
|
||||
threading.Thread(target=self._server.serve_forever, daemon=True).start()
|
||||
|
||||
def close(self):
|
||||
self._server.shutdown()
|
||||
self._server.server_close()
|
||||
|
||||
|
||||
def counter_address(firefox_binary):
|
||||
"""The address the engine's launch counter fetches, read from the module the browser runs (the one constant of
|
||||
`StealthLaunchCounter.sys.mjs`, inside `browser/omni.ja` beside the executable), with the core's jar reader."""
|
||||
omni = Path(firefox_binary).resolve().parent / "browser" / "omni.ja"
|
||||
# The core's own reader (`invisible_core.jar`): the omni.ja of a PGO build is Mozilla's optimized jar, which zipfile refuses.
|
||||
source = open_jar(omni).read("modules/StealthLaunchCounter.sys.mjs").decode("utf-8")
|
||||
found = re.findall(r'USAGE_PING_URL\s*=\s*"([^"]+)"', source)
|
||||
assert len(found) == 1, "the counter module of %s declares %d addresses: %s" % (omni, len(found), found)
|
||||
return found[0]
|
||||
|
||||
|
||||
def test_the_browser_sends_one_plain_get_to_the_counter_before_any_page(firefox_binary, tmp_path):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
USAGE_PING_URL = counter_address(firefox_binary)
|
||||
|
||||
counter = urlsplit(USAGE_PING_URL)
|
||||
assert counter.scheme == "https" and counter.hostname, USAGE_PING_URL
|
||||
port = counter.port or 443
|
||||
|
||||
order = Order()
|
||||
ca = LabCa(tmp_path)
|
||||
leaf, key = ca.leaf("counter", [counter.hostname], [], None)
|
||||
profile = tmp_path / "profile"
|
||||
for line in add_ca_to_profile(firefox_binary, profile, ca.ca_b64, tmp_path / "xpcshell"):
|
||||
print("LAB-CA %s" % line)
|
||||
proxy = CounterProxy(counter.hostname, port, leaf, key, order)
|
||||
pages = PageServer(order)
|
||||
stop = threading.Event()
|
||||
declare_exit(proxy.server, LAB_EGRESS_IP) # the proxy says where it leaves from: no request of the exit goes to the internet
|
||||
try:
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, humanize=False,
|
||||
profile_dir=profile, proxy={"server": proxy.server}) as context:
|
||||
# Before any page: the counter arrives with no page of ours open, and the page server has heard nothing.
|
||||
arrived = wait_until(lambda: proxy.seen(), 120, lambda: stop.wait(0.25))
|
||||
at_that_moment = list(pages.requests)
|
||||
detail = ("handshakes %s; refused through the proxy: %s" % (proxy.handshakes[:6], proxy.other[:12]))
|
||||
assert arrived, "the browser sent no request to the counter's address %s after it started. %s" % (USAGE_PING_URL, detail)
|
||||
assert at_that_moment == [], "a page request had been made when the counter arrived: %s" % (at_that_moment,)
|
||||
first = proxy.seen()[0]
|
||||
|
||||
# The control: a page of ours makes its own request to the same address, through the same proxy.
|
||||
page = context.new_page()
|
||||
page.goto(pages.url, wait_until="load", timeout=60_000)
|
||||
page.evaluate("(u) => fetch(u, {mode: 'no-cors'}).then(() => 'done', () => 'failed')", USAGE_PING_URL)
|
||||
both = wait_until(lambda: len(proxy.seen()) >= 2, 60, lambda: stop.wait(0.25))
|
||||
gets = proxy.seen()
|
||||
finally:
|
||||
forget_exit(proxy.server)
|
||||
proxy.close()
|
||||
pages.close()
|
||||
|
||||
assert both, "the request of the page to the counter's address never reached the proxy: the sink would be blind to a second request. %s" % (detail,)
|
||||
assert len(gets) == 2, "expected the counter's GET and the page's, got %d: %s" % (len(gets), [(g["method"], g["target"]) for g in gets])
|
||||
assert gets[0] == first
|
||||
assert first["method"] == "GET" and first["target"] == counter.path + (("?" + counter.query) if counter.query else ""), first
|
||||
for forbidden in ("cookie", "authorization", "proxy-authorization", "referer", "origin"):
|
||||
assert forbidden not in first["headers"], "the counter's GET carries %s: %s" % (forbidden, first["headers"])
|
||||
assert "no-cache" in first["headers"].get("cache-control", "").lower(), first["headers"]
|
||||
# The page's own request is told apart by what only a page's request has.
|
||||
assert gets[1]["headers"].get("referer", "").startswith(pages.url[:-1]), gets[1]["headers"]
|
||||
@@ -0,0 +1,126 @@
|
||||
"""The telemetry ping sent at shutdown is sent by the engine's own background task, `firefox --backgroundtask pingsender` (firefox-68, Linux and Windows).
|
||||
|
||||
What it fixes, in the published engine (firefox-68), for the hooks of `stillborn/telemetry` (`toolkit/components/telemetry/app/TelemetrySend.sys.mjs`,
|
||||
`pings/BackgroundTask_pingsender.sys.mjs`, the own files `StealthPingsender.sys.mjs` and `StealthPingsenderRoute.sys.mjs`): the shutdown ping
|
||||
never goes through `pingsender[.exe]` (a separate program that takes its road from the host: WinINet's proxy settings on Windows, libcurl's
|
||||
environment on Linux) but through the engine itself, with necko, by the road of the session. A server that receives a ping sees who sent it: the
|
||||
background task is the one whose request says `User-Agent: pingsender/2.0`. The program of the host says another one, and a ping that
|
||||
left from the host's own address says where the browser is. The server of telemetry is a pref (`toolkit.telemetry.server`), so the test points it at a
|
||||
server of its own on 127.0.0.1: nothing leaves the machine.
|
||||
|
||||
The address the test gives the session is `http://localhost:<port>`, and that is part of what the engine does: the background task keeps the allowlist the
|
||||
standalone pingsender had (`ALLOWED_ENDPOINTS` in `BackgroundTask_pingsender.sys.mjs`: `localhost` and `incoming.telemetry.mozilla.org`), so a ping addressed to
|
||||
any other host, `127.0.0.1` included, is refused by the task before a request is made and the ping stays on disk.
|
||||
|
||||
What the test does. A session (seed 42, no proxy; the road of the session is decided by the launch) with the telemetry server pref at the fake endpoint
|
||||
is opened and closed. The session ENDS (`_session_end.EndingPlaywright`: the reaper has finished, so the sender is finished or ended), then the test
|
||||
reads what the endpoint received.
|
||||
|
||||
What it asserts:
|
||||
* at least one request reached the endpoint with `User-Agent: pingsender/2.0`, a POST to a path of the telemetry protocol (`/submit/telemetry/...`),
|
||||
with a body;
|
||||
* a second endpoint that the session was NOT pointed at received nothing (the pref is the address, there is no other).
|
||||
|
||||
Negative controls, each a session that must send nothing with that user agent: (1) the same session with `datareporting.healthreport.uploadEnabled`
|
||||
false (the switch retail Firefox has for it); (2) the same session pointed at an endpoint whose host is `127.0.0.1`, which the task's allowlist refuses.
|
||||
The test therefore fails when the ping leaves by another program (its user agent differs), when the session sends none, and when the allowlist stops
|
||||
refusing a host that is not on it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from _session_end import EndingPlaywright
|
||||
from _waits import wait_until
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
SERVER = "toolkit.telemetry.server"
|
||||
UPLOAD = "datareporting.healthreport.uploadEnabled"
|
||||
BACKGROUND_TASK_AGENT = "pingsender/2.0"
|
||||
|
||||
|
||||
class Endpoint:
|
||||
"""A telemetry endpoint on 127.0.0.1 (a port the OS gives) that records every request and answers 200."""
|
||||
|
||||
def __init__(self, host="localhost"):
|
||||
self.requests = []
|
||||
outer = self
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
timeout = 10
|
||||
|
||||
def _record(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
body = self.rfile.read(length) if length else b""
|
||||
outer.requests.append({"method": self.command, "path": self.path, "agent": self.headers.get("User-Agent"),
|
||||
"bytes": len(body)})
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
|
||||
do_POST = do_PUT = do_GET = _record
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
self._server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
self._server.daemon_threads = True
|
||||
threading.Thread(target=self._server.serve_forever, daemon=True).start()
|
||||
self.url = "http://%s:%d" % (host, self._server.server_address[1])
|
||||
|
||||
def by_agent(self, agent):
|
||||
return [r for r in self.requests if r["agent"] == agent]
|
||||
|
||||
def close(self):
|
||||
self._server.shutdown()
|
||||
self._server.server_close()
|
||||
|
||||
|
||||
def session(binary, endpoint, extra_prefs=None):
|
||||
"""One session pointed at ``endpoint``, opened and closed; it has ended (the sender included) when this returns."""
|
||||
prefs = {SERVER: endpoint.url}
|
||||
prefs.update(extra_prefs or {})
|
||||
with EndingPlaywright(seed=42, binary_path=binary, headless=True, humanize=False, locale="en-US",
|
||||
timezone="America/New_York", extra_prefs=prefs) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank", timeout=60_000)
|
||||
|
||||
|
||||
def test_the_shutdown_ping_is_sent_by_the_background_task_and_not_by_the_host_program(firefox_binary):
|
||||
endpoint, elsewhere = Endpoint(), Endpoint()
|
||||
stop = threading.Event()
|
||||
try:
|
||||
session(firefox_binary, endpoint)
|
||||
# The session has ended; the request of the sender is on the endpoint, or it comes within the time a healthy run allows.
|
||||
arrived = wait_until(lambda: endpoint.by_agent(BACKGROUND_TASK_AGENT), 60, lambda: stop.wait(0.25))
|
||||
seen = [(r["method"], r["path"][:60], r["agent"], r["bytes"]) for r in endpoint.requests]
|
||||
assert arrived, ("no request with `User-Agent: %s` reached the endpoint after the session ended; what it received: %s"
|
||||
% (BACKGROUND_TASK_AGENT, seen))
|
||||
pings = endpoint.by_agent(BACKGROUND_TASK_AGENT)
|
||||
assert all(r["method"] == "POST" and r["path"].startswith("/submit/telemetry/") and r["bytes"] > 0 for r in pings), pings
|
||||
assert elsewhere.requests == [], "an endpoint the session was not pointed at received %s" % (elsewhere.requests,)
|
||||
|
||||
# Control 1: with the upload switched off no ping leaves, so the request above is the product's and not the endpoint's own noise.
|
||||
control = Endpoint()
|
||||
try:
|
||||
session(firefox_binary, control, extra_prefs={UPLOAD: False})
|
||||
assert control.by_agent(BACKGROUND_TASK_AGENT) == [], (
|
||||
"a session with the upload switched off still sent a ping: %s" % (control.requests,))
|
||||
finally:
|
||||
control.close()
|
||||
|
||||
# Control 2: the same session, same upload switch, the endpoint named by an address that is not on the task's allowlist: the task refuses it.
|
||||
refused = Endpoint(host="127.0.0.1")
|
||||
try:
|
||||
session(firefox_binary, refused)
|
||||
assert refused.requests == [], (
|
||||
"a ping addressed to a host that is not on the background task's allowlist reached the endpoint: %s" % (refused.requests,))
|
||||
finally:
|
||||
refused.close()
|
||||
finally:
|
||||
endpoint.close()
|
||||
elsewhere.close()
|
||||
@@ -0,0 +1,141 @@
|
||||
"""The WebGPU adapter a page sees is the one the core declares, never the host's (firefox-68, Linux and Windows).
|
||||
|
||||
Hooks of `fingerprint/webgpu/adapter-declaration` (`dom/webgpu/Adapter.cpp`, `Instance.cpp`, `StealthWebGPUDeclaration.cpp`, `WebGPUParent.cpp`): while the
|
||||
engine is active (`zoom.stealth.fpp.hw_seed` > 0) the features, the limits and `isFallbackAdapter` of `navigator.gpu.requestAdapter()` come from the
|
||||
prefs `zoom.stealth.webgpu.features`, `zoom.stealth.webgpu.limits` and `zoom.stealth.webgpu.adapter` (the core declares 12 features and 35 limits of
|
||||
retail Firefox's Direct3D 12 backend for every persona, and the engine adds `core-features-and-limits` itself); `isFallbackAdapter` is true only for an
|
||||
adapter asked for with `forceFallbackAdapter`; `RequestDevice` is clamped to the real adapter, so a page that asks for the declared maxima gets a device;
|
||||
and a declared GPU without Direct3D 12 (`zoom.stealth.webgpu.adapter` = `none`) makes `requestAdapter()` resolve null. A page reads all of it with no
|
||||
permission (a secure context: the page is served from 127.0.0.1). The adapter of the host is a Vulkan driver on Linux (our own, bundled) and WARP or a
|
||||
GPU on Windows, and its features and limits differ from retail's.
|
||||
|
||||
Nothing is skipped: a runner with no adapter is a red test (the engine must give one: the bundled Vulkan on Linux, WARP on Windows).
|
||||
|
||||
Negative controls: in the first test the same read with the engine off (`hw_seed` 0) does not give the declared adapter (the host's, or null); in the second
|
||||
the same call with the declared adapter `d3d12` gives an adapter where `none` gives null (the pref is what decides), and an unknown `featureLevel` gives
|
||||
null on both.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
HW_SEED = "zoom.stealth.fpp.hw_seed"
|
||||
ADAPTER = "zoom.stealth.webgpu.adapter"
|
||||
PAGE = "/from-network"
|
||||
|
||||
#: The adapter as a page reads it: its features, its limits, `info.isFallbackAdapter`, whether a device at the declared maxima resolves, and the adapter
|
||||
#: asked for with `forceFallbackAdapter`. null when the page gets no adapter.
|
||||
READ_ADAPTER = """async () => {
|
||||
if (!navigator.gpu) return {gpu: false};
|
||||
const describe = async (adapter) => {
|
||||
if (!adapter) return null;
|
||||
const limits = {};
|
||||
for (const name in adapter.limits) limits[name] = adapter.limits[name];
|
||||
return {features: [...adapter.features].sort(), limits, fallback: adapter.info.isFallbackAdapter};
|
||||
};
|
||||
const adapter = await navigator.gpu.requestAdapter();
|
||||
const out = {gpu: true, adapter: await describe(adapter)};
|
||||
if (adapter) {
|
||||
const maxima = ['maxBufferSize', 'maxStorageBufferBindingSize', 'maxTextureDimension2D', 'maxBindGroups',
|
||||
'maxComputeWorkgroupStorageSize'];
|
||||
const required = {};
|
||||
for (const name of maxima) required[name] = adapter.limits[name];
|
||||
try {
|
||||
const device = await adapter.requestDevice({requiredLimits: required});
|
||||
const got = {};
|
||||
for (const name of maxima) got[name] = device.limits[name];
|
||||
out.device = {asked: required, got};
|
||||
} catch (e) {
|
||||
out.device = {error: String(e)};
|
||||
}
|
||||
}
|
||||
out.forced = await describe(await navigator.gpu.requestAdapter({forceFallbackAdapter: true}));
|
||||
return out;
|
||||
}"""
|
||||
|
||||
READ_NO_ADAPTER = """async () => {
|
||||
if (!navigator.gpu) return {gpu: false};
|
||||
const answer = async (options) => (await navigator.gpu.requestAdapter(options)) === null ? null : 'adapter';
|
||||
return {
|
||||
gpu: true,
|
||||
plain: await answer(),
|
||||
unknown_level: await answer({featureLevel: 'no-such-level'}),
|
||||
xr: await answer({xrCompatible: true}),
|
||||
};
|
||||
}"""
|
||||
|
||||
|
||||
def read(binary, url, expression, extra_prefs=None):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=binary, headless=True, humanize=False, locale="en-US",
|
||||
timezone="America/New_York", extra_prefs=extra_prefs) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(url, timeout=60_000)
|
||||
# The expression runs in the PAGE's realm, as a script of the page would: `page.evaluate` runs in the caller's world, where Firefox
|
||||
# cannot wrap the iterator of `adapter.features` (a set-like): "Xray wrapping of iterators not supported". The answer is written as
|
||||
# JSON into the DOM and the test waits on that condition.
|
||||
page.add_script_tag(content=(
|
||||
"(async () => { let out; try { out = await (%s)(); } catch (e) { out = {scriptError: String(e)}; }"
|
||||
" document.documentElement.setAttribute('data-read', JSON.stringify(out)); })();" % expression))
|
||||
page.wait_for_function("() => document.documentElement.hasAttribute('data-read')", timeout=60_000)
|
||||
answer = json.loads(page.evaluate("() => document.documentElement.getAttribute('data-read')"))
|
||||
assert not (isinstance(answer, dict) and "scriptError" in answer), answer
|
||||
return answer
|
||||
|
||||
|
||||
def declared():
|
||||
"""What the core declares, read from the core (the one place that holds it)."""
|
||||
from invisible_core.prefs import _WIN_WEBGPU_FEATURES, _WIN_WEBGPU_LIMITS
|
||||
|
||||
features = sorted(_WIN_WEBGPU_FEATURES.split(chr(10)) + ["core-features-and-limits"])
|
||||
limits = {name: int(value) for name, value in (line.split("=") for line in _WIN_WEBGPU_LIMITS.split(chr(10)))}
|
||||
return features, limits
|
||||
|
||||
|
||||
def test_the_page_sees_the_declared_adapter_e2e(firefox_binary, fixture_server):
|
||||
url = fixture_server + PAGE
|
||||
features, limits = declared()
|
||||
assert len(limits) == 35, len(limits)
|
||||
|
||||
on = read(firefox_binary, url, READ_ADAPTER)
|
||||
assert on["gpu"] is True, "navigator.gpu is missing: %r" % (on,)
|
||||
adapter = on["adapter"]
|
||||
assert adapter is not None, "requestAdapter() gave no adapter with the engine on: the engine must give one on every runner"
|
||||
assert adapter["features"] == features, adapter["features"]
|
||||
differing = {k: (adapter["limits"].get(k), limits.get(k)) for k in set(limits) | set(adapter["limits"])
|
||||
if adapter["limits"].get(k) != limits.get(k)}
|
||||
assert adapter["limits"] == limits, differing
|
||||
assert adapter["fallback"] is False
|
||||
# RequestDevice at the declared maxima resolves, and the device holds what was asked.
|
||||
assert on["device"].get("error") is None and on["device"]["asked"] == on["device"]["got"], on["device"]
|
||||
# An adapter asked for with forceFallbackAdapter is the fallback one, with the same declared features and limits.
|
||||
forced = on["forced"]
|
||||
assert forced is not None, "requestAdapter({forceFallbackAdapter: true}) gave no adapter"
|
||||
assert forced["fallback"] is True
|
||||
assert forced["features"] == features and forced["limits"] == limits
|
||||
|
||||
# Control: with the engine off the page does not read the declaration (the host's adapter, or none).
|
||||
off = read(firefox_binary, url, READ_ADAPTER, extra_prefs={HW_SEED: 0})
|
||||
assert off["gpu"] is True, off
|
||||
assert off["adapter"] != adapter, "the engine off answered the declared adapter: %r" % (off["adapter"],)
|
||||
|
||||
|
||||
def test_a_gpu_without_d3d12_has_no_adapter_e2e(firefox_binary, fixture_server):
|
||||
url = fixture_server + PAGE
|
||||
none = read(firefox_binary, url, READ_NO_ADAPTER, extra_prefs={ADAPTER: "none"})
|
||||
assert none["gpu"] is True, none
|
||||
# A declared GPU without Direct3D 12: requestAdapter resolves null, with or without options.
|
||||
assert none["plain"] is None and none["xr"] is None and none["unknown_level"] is None, none
|
||||
|
||||
# Control: the same call with the declared adapter `d3d12` answers an adapter (also with xrCompatible, which warns and goes on), and an
|
||||
# unknown featureLevel answers null as it does for stock.
|
||||
d3d12 = read(firefox_binary, url, READ_NO_ADAPTER, extra_prefs={ADAPTER: "d3d12"})
|
||||
assert d3d12["plain"] == "adapter", d3d12
|
||||
assert d3d12["xr"] == "adapter", d3d12
|
||||
assert d3d12["unknown_level"] is None, d3d12
|
||||
assert d3d12["plain"] != none["plain"]
|
||||
@@ -0,0 +1,46 @@
|
||||
"""`GPUDevice.prototype.importExternalTexture` exists on every operating system (firefox-68, Linux and Windows).
|
||||
|
||||
Hooks of `fingerprint/webgpu/adapter-declaration` (`modules/libpref/init/StaticPrefList.yaml`: `dom.webgpu.external-texture.enabled` is true on every OS;
|
||||
`gfx/thebes/gfxPlatform.cpp`: the force-disable for a system that is not Windows or macOS is off) and of `fingerprint/webgpu/external-texture-vulkan` (the
|
||||
Vulkan backend has external textures, so the API is real on Linux): upstream Firefox has the interface on Windows and macOS only, so a page could tell
|
||||
a Linux engine from a Windows one by `typeof GPUDevice.prototype.importExternalTexture`. The method is `[Func=ExternalTexturePrefEnabled]`: present
|
||||
when the pref (read once, at start) is true. A page reads it with no permission.
|
||||
|
||||
Negative control: the same read with the pref `dom.webgpu.external-texture.enabled` false (the stock value on Linux) has no such method.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
PREF = "dom.webgpu.external-texture.enabled"
|
||||
PAGE = "/from-network"
|
||||
|
||||
READ = """() => ({
|
||||
interface: typeof GPUDevice,
|
||||
method: typeof GPUDevice === 'undefined' ? 'no GPUDevice' : typeof GPUDevice.prototype.importExternalTexture,
|
||||
})"""
|
||||
|
||||
|
||||
def read(binary, url, extra_prefs=None):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=binary, headless=True, humanize=False, locale="en-US",
|
||||
timezone="America/New_York", extra_prefs=extra_prefs) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(url, timeout=60_000)
|
||||
return page.evaluate(READ)
|
||||
|
||||
|
||||
def test_importexternaltexture_exists_on_every_os_e2e(firefox_binary, fixture_server):
|
||||
url = fixture_server + PAGE
|
||||
on = read(firefox_binary, url)
|
||||
assert on["interface"] == "function", on
|
||||
assert on["method"] == "function", on
|
||||
|
||||
# Control: the pref false takes the method away, so the read above depends on the declaration and not on the page.
|
||||
off = read(firefox_binary, url, extra_prefs={PREF: False})
|
||||
assert off["interface"] == "function", off
|
||||
assert off["method"] == "undefined", off
|
||||
assert off["method"] != on["method"]
|
||||
@@ -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"
|
||||
Reference in new issue
Block a user