Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07018c00b7 | ||
|
|
98da306330 | ||
|
|
c3295c5b12 | ||
|
|
66e5b75cb6 | ||
|
|
3f372e4675 | ||
|
|
6b67a514e5 |
No files matched your search
@@ -1,110 +0,0 @@
|
||||
"""A popup opened the way a page opens one, and what it reads of its own window.
|
||||
|
||||
Shared by `test_popup_geometry_is_the_declared_frame_e2e.py` and by the inner-size test of
|
||||
`test_fingerprint_surface.py`: both need a popup (`window.open` with features, from a click) whose document may carry an
|
||||
iframe of another site (so, under Fission, in another process), and both read the window geometry from inside it.
|
||||
|
||||
The popup is read with a CONDITION, not a pause: the reading is repeated (with the client's events being read between two
|
||||
looks) until the caller's `ready` holds or 30 s have passed, and the last reading is returned either way, so the caller's
|
||||
assertion names what was read when it never settled.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from typing import Any, Callable, Dict, Optional
|
||||
|
||||
from _fission_frames import Sites, wait_frame
|
||||
from _waits import wait_until
|
||||
|
||||
#: The scale at which the declared window frame is the one of `WINDOW_FRAME_BY_DPR[1.0]`: border 8, popup UI 72, default
|
||||
#: position 4 (device pixels, and CSS pixels at 1.0). The screen is the one the other surface tests pin.
|
||||
PIN = {"screen.width": 1920, "screen.height": 1080, "screen.dpr": 1.0}
|
||||
|
||||
#: A second declared window frame that no runner has: a border of 6, a popup UI of 53 above the content, a default position of 9. The declared frame at scale 1.0
|
||||
#: (8, 72, 4) is the frame of a retail Windows window, so a Windows runner's own popup has it too (outer - inner = 16 x 80) and a launch with the engine off
|
||||
#: cannot tell the declaration from the host there; a launch declared with ANOTHER frame can (the prefs are applied last, over the core's declaration).
|
||||
OTHER_FRAME = {"zoom.stealth.screen.frame_border": 6, "zoom.stealth.screen.popup_ui": 53, "zoom.stealth.screen.popup_position": 9}
|
||||
OTHER_BORDER, OTHER_POPUP_UI, OTHER_POSITION = 6, 53, 9
|
||||
|
||||
READ = """() => ({iw: innerWidth, ih: innerHeight, ow: outerWidth, oh: outerHeight,
|
||||
sx: screenX, sy: screenY, mx: mozInnerScreenX, my: mozInnerScreenY})"""
|
||||
|
||||
|
||||
def in_a_thread_of_its_own(fn: Callable[[], Any], timeout: float = 300) -> Any:
|
||||
"""Runs `fn` in a thread with no asyncio loop and gives back its result or raises its error.
|
||||
|
||||
For a module whose own fixture keeps a sync client open for the whole module: an open sync client leaves its loop marked as
|
||||
running in its thread, and a second sync client started in that thread refuses with "Playwright Sync API inside the asyncio
|
||||
loop". The second browser needs a thread of its own.
|
||||
"""
|
||||
box: Dict[str, Any] = {}
|
||||
|
||||
def run() -> None:
|
||||
try:
|
||||
box["value"] = fn()
|
||||
except BaseException as exc: # handed back to the test's thread below
|
||||
box["error"] = exc
|
||||
|
||||
worker = threading.Thread(target=run, name="second-sync-client", daemon=True)
|
||||
worker.start()
|
||||
worker.join(timeout)
|
||||
if worker.is_alive():
|
||||
raise AssertionError("the browser of the test did not end within %d s" % timeout)
|
||||
if "error" in box:
|
||||
raise box["error"]
|
||||
return box.get("value")
|
||||
|
||||
|
||||
def frame_of_the_declaration():
|
||||
"""The window frame the core declares at scale 1.0: what the engine adds to a popup's inner size."""
|
||||
from invisible_core.constants import WINDOW_FRAME_BY_DPR
|
||||
|
||||
return WINDOW_FRAME_BY_DPR[1.0]
|
||||
|
||||
|
||||
def frame_extra(border: int, popup_ui: int):
|
||||
"""What a popup adds to its inner size: (outer - inner) wide and high, for a border and a popup UI."""
|
||||
return (2 * border, popup_ui + border)
|
||||
|
||||
|
||||
def _plausible(reading: Dict[str, Any]) -> bool:
|
||||
"""Every size of every window read is above 0: the window (and its frame, if any) has been laid out."""
|
||||
return all(r["iw"] > 0 and r["ih"] > 0 and r["ow"] > 0 and r["oh"] > 0
|
||||
for r in (reading["popup"], reading["frame"]) if r is not None)
|
||||
|
||||
|
||||
def read_popup(binary: str, extra_prefs: Optional[Dict[str, Any]] = None, iframe: bool = False,
|
||||
ready: Optional[Callable[[Dict[str, Any]], bool]] = None,
|
||||
features: str = "width=500,height=400") -> Dict[str, Any]:
|
||||
"""Open `window.open(url, 'p', features)` (default `width=500,height=400`) from a click and read it.
|
||||
|
||||
Returns `{"popup": {...}, "frame": {...} or None}` with `iw ih ow oh sx sy mx my` (innerWidth, innerHeight,
|
||||
outerWidth, outerHeight, screenX, screenY, mozInnerScreenX, mozInnerScreenY) of the popup and, with `iframe`, of its
|
||||
iframe (another site, 200x150). `ready(reading)` says when the reading has settled (default: every size above 0).
|
||||
"""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with Sites() as s:
|
||||
s.route("A", "/main", "<!doctype html><title>main</title><button id='open' onclick=\"window.open('%s', 'p', "
|
||||
"'%s')\">open</button>" % (s.url("A", "/popup"), features))
|
||||
frame_html = ("<iframe id='f' src='%s' style='position:absolute;left:0;top:0;width:200px;height:150px;border:0'>"
|
||||
"</iframe>" % s.url("B", "/frame")) if iframe else ""
|
||||
s.route("A", "/popup", "<!doctype html><title>popup</title>" + frame_html)
|
||||
s.route("B", "/frame", "<!doctype html><title>frame</title>")
|
||||
with InvisiblePlaywright(seed=42, pin=PIN, binary_path=binary, headless=True, humanize=False,
|
||||
extra_prefs=extra_prefs) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(s.url("A", "/main"), wait_until="load", timeout=30000)
|
||||
with page.expect_popup(timeout=30000) as info:
|
||||
page.click("#open", timeout=30000)
|
||||
popup = info.value
|
||||
popup.wait_for_load_state("load", timeout=30000)
|
||||
frame = wait_frame(popup, s.origin["B"], "/frame", seconds=30) if iframe else None
|
||||
seen: Dict[str, Any] = {}
|
||||
|
||||
def settled() -> bool:
|
||||
seen["now"] = {"popup": popup.evaluate(READ), "frame": frame.evaluate(READ) if frame else None}
|
||||
return _plausible(seen["now"]) and (ready is None or bool(ready(seen["now"])))
|
||||
|
||||
wait_until(settled, 30, lambda: popup.wait_for_timeout(100))
|
||||
return seen["now"]
|
||||
@@ -1,93 +0,0 @@
|
||||
"""A real click inside an iframe: `screenX - clientX` is the iframe's own `mozInnerScreenX`.
|
||||
|
||||
What it fixes: the relation a page checks with one subtraction on every mouse event, `event.screenX - event.clientX ==
|
||||
window.mozInnerScreenX` (and the same on Y), INSIDE an iframe placed at (220, 150) of the page. The defect of 2026-08-10:
|
||||
`mozInnerScreenX/Y` answered the origin of the top-level content to every window, so the iframe read (top origin) while
|
||||
its events still carried the iframe's offset, and `screenX - clientX` was 220 against a `mozInnerScreenX` of 0.
|
||||
|
||||
Engine hook: `fingerprint/screen-window/geometry` of the engine series: `nsGlobalWindowOuter::GetMozInnerScreenX/Y` and
|
||||
`Event::GetScreenCoords` both add the ONE content origin shift (`nsGlobalWindowOuter::StealthContentOriginShift`, declared
|
||||
window against real one) to the window's OWN real rectangle, so the offset between frames stays true at every depth.
|
||||
|
||||
Control, in the same test: the top window's `mozInnerScreenX/Y` is a different number (the iframe sits 220 and 150 CSS
|
||||
pixels off it). The test asserts the iframe's `mozInnerScreenX/Y` is the top's plus the iframe's rectangle, and that what
|
||||
the events carry (`screenX - clientX`) is NOT the top's origin: a window that answered the top origin to every frame fails
|
||||
both.
|
||||
|
||||
The click is a real one (`page.mouse.click` at a point inside the iframe, the pointer events the engine makes), not a
|
||||
dispatched event. The page and the iframe are one site, so the page may read the iframe's `mozInnerScreenX`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from _fission_frames import Sites
|
||||
from _waits import wait_until
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
LEFT, TOP = 220, 150
|
||||
|
||||
PARENT = """<!doctype html><meta charset=utf-8><title>parent</title>
|
||||
<style>html,body{margin:0;padding:0;height:100%%}
|
||||
#f{position:absolute;left:%dpx;top:%dpx;width:360px;height:220px;border:0}</style>
|
||||
<body><iframe id=f src="/child"></iframe>
|
||||
<script>
|
||||
window.__geom = () => {
|
||||
const w = document.getElementById('f').contentWindow;
|
||||
const r = document.getElementById('f').getBoundingClientRect();
|
||||
return {top_x: window.mozInnerScreenX, top_y: window.mozInnerScreenY,
|
||||
ifr_x: w.mozInnerScreenX, ifr_y: w.mozInnerScreenY, rect_x: r.x, rect_y: r.y};
|
||||
};
|
||||
</script>""" % (LEFT, TOP)
|
||||
|
||||
CHILD = """<!doctype html><meta charset=utf-8><title>child</title>
|
||||
<style>html,body{margin:0;padding:0;height:100%}
|
||||
#g{position:absolute;left:30px;top:40px;width:220px;height:130px;background:#06c}</style>
|
||||
<body><div id=g>y</div>
|
||||
<script>
|
||||
window.__ev = [];
|
||||
for (const t of ['mousemove', 'mousedown', 'mouseup', 'click']) {
|
||||
window.addEventListener(t, e => {
|
||||
window.__ev.push({t: t, cx: e.clientX, cy: e.clientY, sx: e.screenX, sy: e.screenY});
|
||||
}, true);
|
||||
}
|
||||
window.__inner = () => [window.mozInnerScreenX, window.mozInnerScreenY];
|
||||
</script>"""
|
||||
|
||||
|
||||
def test_a_real_click_in_an_iframe_has_the_screen_origin_of_the_iframe(firefox_binary):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with Sites() as s:
|
||||
s.route("A", "/parent", PARENT)
|
||||
s.route("A", "/child", CHILD)
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, humanize=False) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(s.url("A", "/parent"), wait_until="load", timeout=30000)
|
||||
geom = page.evaluate("() => window.__geom()")
|
||||
frame = page.frames[1]
|
||||
frame.evaluate("() => { window.__ev = []; }")
|
||||
# a point inside the blue square of the iframe, in the coordinates of the page
|
||||
page.mouse.click(LEFT + 30 + 100, TOP + 40 + 60)
|
||||
kinds = {"mousedown", "mouseup", "click"}
|
||||
assert wait_until(lambda: kinds <= {e["t"] for e in frame.evaluate("() => window.__ev")}, 30,
|
||||
lambda: page.wait_for_timeout(100)), (
|
||||
"the iframe heard %r of the click" % [e["t"] for e in frame.evaluate("() => window.__ev")])
|
||||
events = frame.evaluate("() => window.__ev")
|
||||
inner = frame.evaluate("() => window.__inner()")
|
||||
|
||||
# the iframe is where it was put, and answers its OWN origin: the top's plus the iframe's rectangle
|
||||
assert (geom["rect_x"], geom["rect_y"]) == (LEFT, TOP)
|
||||
assert (geom["ifr_x"], geom["ifr_y"]) == (geom["top_x"] + geom["rect_x"], geom["top_y"] + geom["rect_y"]), (
|
||||
"the iframe reads mozInnerScreen (%r, %r), the page's is (%r, %r) and the iframe sits at (%d, %d)"
|
||||
% (geom["ifr_x"], geom["ifr_y"], geom["top_x"], geom["top_y"], LEFT, TOP))
|
||||
assert (inner[0], inner[1]) != (geom["top_x"], geom["top_y"]), "the iframe answers the origin of the top-level content"
|
||||
clicks = [e for e in events if e["t"] == "click"]
|
||||
assert clicks, "no click event in the iframe: %r" % events
|
||||
for e in events:
|
||||
assert e["sx"] - e["cx"] == inner[0], (
|
||||
"%s in the iframe: screenX - clientX = %r against mozInnerScreenX = %r" % (e["t"], e["sx"] - e["cx"], inner[0]))
|
||||
assert e["sy"] - e["cy"] == inner[1], (
|
||||
"%s in the iframe: screenY - clientY = %r against mozInnerScreenY = %r" % (e["t"], e["sy"] - e["cy"], inner[1]))
|
||||
# the control: the top window's origin is NOT what the events carry
|
||||
assert (e["sx"] - e["cx"], e["sy"] - e["cy"]) != (geom["top_x"], geom["top_y"])
|
||||
@@ -1,136 +0,0 @@
|
||||
"""The size and pointer media queries answer the declaration, not the host.
|
||||
|
||||
What it fixes, from the page's side (`matchMedia`):
|
||||
|
||||
* `(device-width: Wpx)` / `(device-height: Hpx)` are the declared screen (`zoom.stealth.screen.width/height`), not the
|
||||
host's monitor.
|
||||
* `(pointer: ...)` / `(any-pointer: ...)` / `(hover: ...)` are the declared pointer capabilities
|
||||
(`zoom.stealth.pointer.primary` / `.all`, the bitmask Coarse 1, Fine 2, Hover 4), not the host's (a Windows machine
|
||||
with a digitizer adds Coarse by itself).
|
||||
* A context made with `has_touch=True` (Juggler's touch override) still reads a COARSE pointer when a fine one is
|
||||
declared: the override of the context decides before the declaration does.
|
||||
|
||||
Engine hook: `fingerprint/screen-window/css-media` of the engine series (`layout/style/nsMediaFeatures.cpp`:
|
||||
`GetDeviceSize`, `GetPointerCapabilities`; the declarations in `StealthMediaFeatures.h`).
|
||||
|
||||
Negative controls, in the same test: the device size is read on a launch declared with ANOTHER screen (2623x1411): the
|
||||
wrapper hands the declared screen to the browser by two roads (the screen prefs and the screen of the context, which Juggler
|
||||
emulates), so a launch with the prefs at 0 still reads the pinned screen; the queries must follow each declaration. The
|
||||
pointer is read with the engine off (`hw_seed` 0, stock Firefox: an active engine refuses a declaration cleared with -1), the
|
||||
host's answer; and has_touch is read in a context without it, on the same launch.
|
||||
|
||||
Linux and Windows run the same assertions: the declared values are the ones no runner has (a 2731x1537 screen; a coarse
|
||||
primary pointer on a machine with a mouse).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
#: A screen no runner has.
|
||||
SCREEN = {"screen.width": 2731, "screen.height": 1537, "screen.dpr": 1.0}
|
||||
|
||||
#: Another screen no runner has: the control of the device size is a launch declared with this one.
|
||||
OTHER_SCREEN = {"screen.width": 2623, "screen.height": 1411, "screen.dpr": 1.0}
|
||||
|
||||
#: The engine off (stock Firefox): the control of the pointer. The engine refuses an active launch with a declaration cleared.
|
||||
ENGINE_OFF = {"zoom.stealth.fpp.hw_seed": 0}
|
||||
|
||||
COARSE, FINE, HOVER = 1, 2, 4
|
||||
|
||||
QUERIES = {name: "matchMedia('%s').matches" % query for name, query in {
|
||||
"pointer_coarse": "(pointer: coarse)", "pointer_fine": "(pointer: fine)",
|
||||
"any_coarse": "(any-pointer: coarse)", "any_fine": "(any-pointer: fine)",
|
||||
"hover_none": "(hover: none)", "any_hover_none": "(any-hover: none)"}.items()}
|
||||
|
||||
READ_POINTER = "() => ({%s})" % ", ".join("%s: %s" % (k, v) for k, v in QUERIES.items())
|
||||
|
||||
|
||||
def _launch(binary, pin=None, extra_prefs=None):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
return InvisiblePlaywright(seed=42, pin=pin, binary_path=binary, headless=True, humanize=False,
|
||||
extra_prefs=extra_prefs)
|
||||
|
||||
|
||||
def _read_pointer(binary, primary=None, every=None):
|
||||
"""Declared pointer prefs, or (both None) the engine off."""
|
||||
prefs = ENGINE_OFF if primary is None else {"zoom.stealth.pointer.primary": primary, "zoom.stealth.pointer.all": every}
|
||||
with _launch(binary, extra_prefs=prefs) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank", timeout=30000)
|
||||
return page.evaluate(READ_POINTER)
|
||||
|
||||
|
||||
def test_a_declared_pointer_is_what_the_media_queries_read(firefox_binary):
|
||||
declared = _read_pointer(firefox_binary, COARSE, COARSE)
|
||||
assert declared == {"pointer_coarse": True, "pointer_fine": False, "any_coarse": True, "any_fine": False,
|
||||
"hover_none": True, "any_hover_none": True}, (
|
||||
"a coarse pointer without hover is declared and the page reads %r" % declared)
|
||||
|
||||
# The control: the engine off is not that machine. A fine pointer with hover is the declaration of a desktop; the host
|
||||
# with no declaration answers its own, and it is not a coarse one without hover.
|
||||
undeclared = _read_pointer(firefox_binary)
|
||||
assert undeclared != declared, "with no pointer declared the page reads the same as with a coarse one: %r" % undeclared
|
||||
assert undeclared["pointer_coarse"] is False and undeclared["any_coarse"] is False, (
|
||||
"with no pointer declared the page reads %r" % undeclared)
|
||||
|
||||
fine = _read_pointer(firefox_binary, FINE | HOVER, FINE | HOVER)
|
||||
assert fine == {"pointer_coarse": False, "pointer_fine": True, "any_coarse": False, "any_fine": True,
|
||||
"hover_none": False, "any_hover_none": False}, (
|
||||
"a fine pointer with hover is declared and the page reads %r" % fine)
|
||||
|
||||
|
||||
def test_has_touch_reads_a_coarse_pointer_even_when_a_fine_one_is_declared(firefox_binary):
|
||||
with _launch(firefox_binary, extra_prefs={"zoom.stealth.pointer.primary": FINE | HOVER,
|
||||
"zoom.stealth.pointer.all": FINE | HOVER}) as browser:
|
||||
plain = browser.new_context().new_page()
|
||||
plain.goto("about:blank", timeout=30000)
|
||||
touch = browser.new_context(has_touch=True).new_page()
|
||||
touch.goto("about:blank", timeout=30000)
|
||||
without = plain.evaluate(READ_POINTER)
|
||||
with_touch = touch.evaluate(READ_POINTER)
|
||||
# the control: the same launch, a context without the override, reads the declared fine pointer
|
||||
assert without["pointer_fine"] is True and without["pointer_coarse"] is False, (
|
||||
"a context without has_touch reads %r under a declared fine pointer" % without)
|
||||
assert with_touch["pointer_coarse"] is True and with_touch["pointer_fine"] is False, (
|
||||
"a context with has_touch reads %r under a declared fine pointer: the touch override must win" % with_touch)
|
||||
assert with_touch["any_coarse"] is True, "any-pointer in a has_touch context reads %r" % with_touch
|
||||
|
||||
|
||||
def _read_device_size(binary, pin, ask):
|
||||
"""The page of a launch pinned to ``pin``, asked for the device size ``ask`` (width, height) and for its own."""
|
||||
with _launch(binary, pin=pin) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank", timeout=30000)
|
||||
return page.evaluate("""([w, h]) => ({
|
||||
screen_w: screen.width, screen_h: screen.height,
|
||||
device_width: matchMedia('(device-width: ' + w + 'px)').matches,
|
||||
device_height: matchMedia('(device-height: ' + h + 'px)').matches,
|
||||
own_width: matchMedia('(device-width: ' + screen.width + 'px)').matches,
|
||||
own_height: matchMedia('(device-height: ' + screen.height + 'px)').matches})""", list(ask))
|
||||
|
||||
|
||||
def test_the_device_size_media_queries_read_the_declared_screen(firefox_binary):
|
||||
first = (SCREEN["screen.width"], SCREEN["screen.height"])
|
||||
second = (OTHER_SCREEN["screen.width"], OTHER_SCREEN["screen.height"])
|
||||
|
||||
declared = _read_device_size(firefox_binary, SCREEN, first)
|
||||
assert declared["device_width"] is True and declared["device_height"] is True, (
|
||||
"(device-width: 2731px) and (device-height: 1537px) do not match under a declared 2731x1537 screen: %r" % declared)
|
||||
assert (declared["screen_w"], declared["screen_h"]) == first
|
||||
assert declared["own_width"] is True and declared["own_height"] is True, (
|
||||
"the device size the media queries read is not the screen the page reads: %r" % declared)
|
||||
|
||||
# The control: the wrapper hands the declared screen to the browser by two roads (the prefs, and the screen of the context
|
||||
# that Juggler emulates), so the absent declaration is not a control. A launch with ANOTHER declared screen is: the same
|
||||
# query for the first size does not match there, and the queries follow that declaration.
|
||||
other = _read_device_size(firefox_binary, OTHER_SCREEN, first)
|
||||
assert (other["screen_w"], other["screen_h"]) == second, other
|
||||
assert other["device_width"] is False and other["device_height"] is False, (
|
||||
"(device-width: 2731px) matches under a declared %dx%d screen: the media queries do not follow the declaration, %r"
|
||||
% (second + (other,)))
|
||||
assert other["own_width"] is True and other["own_height"] is True, (
|
||||
"the device size the media queries read is not the screen the page reads: %r" % other)
|
||||
assert second != first and other != declared
|
||||
@@ -313,105 +313,3 @@ def test_webgl_readpixels_no_masking_signature(page):
|
||||
f"WebGL readPixels shows {res['spikes']} high-frequency noise spikes "
|
||||
f"(pixelscan-maskable); the stealth noise must be a smooth gamma remap."
|
||||
)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# The declared screen, and the inner size of the top level (characterisation of
|
||||
# the engine hooks fingerprint/screen-window/screen: nsScreen.cpp, nsPresContext.cpp)
|
||||
# ===========================================================================
|
||||
|
||||
#: A screen no runner has: 2731x1537, a 41 px taskbar, 30-bit colour, at scale 1.0.
|
||||
_DECLARED_SCREEN = {"screen.width": 2731, "screen.height": 1537, "screen.taskbar_px": 41,
|
||||
"screen.color_depth": 30, "screen.dpr": 1.0}
|
||||
|
||||
#: Another screen no runner has, for the control: the wrapper hands the declared screen to the browser by two roads (the prefs and
|
||||
#: the screen of the context that Juggler emulates), so a launch with the prefs at 0 still reads the pinned screen.
|
||||
_OTHER_SCREEN = {"screen.width": 2623, "screen.height": 1411, "screen.taskbar_px": 37,
|
||||
"screen.color_depth": 24, "screen.dpr": 1.0}
|
||||
|
||||
_READ_SCREEN = """() => ({width: screen.width, height: screen.height, availWidth: screen.availWidth,
|
||||
availHeight: screen.availHeight, pixelDepth: screen.pixelDepth,
|
||||
colorDepth: screen.colorDepth})"""
|
||||
|
||||
|
||||
def _read_screen(firefox_binary, pin=_DECLARED_SCREEN):
|
||||
with InvisiblePlaywright(seed=42, pin=pin, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank", timeout=30_000)
|
||||
return page.evaluate(_READ_SCREEN)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_declared_screen_that_no_runner_has_is_what_the_page_reads(firefox_binary):
|
||||
"""The page reads the screen the core declares (nsScreen::GetRect, GetAvailRect, PixelDepth), not the host's.
|
||||
|
||||
The available height is the declared height less the declared taskbar (2731x1537, taskbar 41, depth 30 -> availWidth
|
||||
2731, availHeight 1496). The control is a launch declared with ANOTHER screen (2623x1411, taskbar 37, depth 24: the wrapper
|
||||
hands the declared screen to the browser by two roads, so the absent declaration is not a control): the page reads that one, and
|
||||
none of the first declaration's numbers.
|
||||
"""
|
||||
from _popup_geometry import in_a_thread_of_its_own
|
||||
|
||||
# The module's `page` fixture keeps a sync client open in this thread: a second browser needs a thread of its own.
|
||||
declared = in_a_thread_of_its_own(lambda: _read_screen(firefox_binary))
|
||||
assert declared == {"width": 2731, "height": 1537, "availWidth": 2731, "availHeight": 1537 - 41,
|
||||
"pixelDepth": 30, "colorDepth": 30}, "the page reads %r under a declared 2731x1537 screen" % declared
|
||||
|
||||
host = in_a_thread_of_its_own(lambda: _read_screen(firefox_binary, _OTHER_SCREEN))
|
||||
assert host == {"width": 2623, "height": 1411, "availWidth": 2623, "availHeight": 1411 - 37,
|
||||
"pixelDepth": 24, "colorDepth": 24}, "the page reads %r under another declared screen" % host
|
||||
for key in ("width", "height", "availWidth", "availHeight", "pixelDepth"):
|
||||
assert host[key] != declared[key], (
|
||||
"under another declared screen screen.%s reads %r, the first declared value: the control reads the first declaration "
|
||||
"(%r)" % (key, host[key], host))
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_the_inner_size_of_the_top_is_synced_with_the_engine_active_and_not_without(firefox_binary):
|
||||
"""A popup's iframe reads the top level's inner size (nsPresContext::UpdateInnerSizeSpoofedForRFP).
|
||||
|
||||
With the engine active the top-level inner size is synced to every process of the browsing context, so an iframe of
|
||||
another site in a popup (200x150, in its own process) answers the outer size of the POPUP: the top's inner size plus the
|
||||
declared frame, 2 * border wide and popup UI + border high, and not the size of its own 200x150. The popup itself
|
||||
answers the same. The control is the same page in a launch declared with a SECOND frame that no runner has (border 6, popup
|
||||
UI 53): the iframe then answers the top's inner size plus THAT frame, and none of the first declaration's. The engine off is
|
||||
not the control: the declared frame is the one of a retail Windows window at scale 1.0, so a Windows runner's own popup
|
||||
reads it with the engine off too (measured: 516x480 for a 500x400 popup) and the test could not fail there.
|
||||
"""
|
||||
from _popup_geometry import (OTHER_BORDER, OTHER_FRAME, OTHER_POPUP_UI, frame_extra, frame_of_the_declaration,
|
||||
in_a_thread_of_its_own, read_popup)
|
||||
|
||||
frame = frame_of_the_declaration()
|
||||
extra = frame_extra(frame.border, frame.popup_ui)
|
||||
other_extra = frame_extra(OTHER_BORDER, OTHER_POPUP_UI)
|
||||
assert other_extra != extra
|
||||
|
||||
def synced_to(wanted):
|
||||
def synced(reading):
|
||||
top = reading["popup"]
|
||||
return (reading["frame"]["ow"], reading["frame"]["oh"]) == (top["iw"] + wanted[0], top["ih"] + wanted[1])
|
||||
return synced
|
||||
|
||||
# The module's `page` fixture keeps a sync client open in this thread: a second browser needs a thread of its own.
|
||||
on = in_a_thread_of_its_own(lambda: read_popup(firefox_binary, iframe=True, ready=synced_to(extra)))
|
||||
top, inner = on["popup"], on["frame"]
|
||||
assert (top["ow"], top["oh"]) == (top["iw"] + extra[0], top["ih"] + extra[1]), (
|
||||
"the popup reads outer %dx%d for inner %dx%d, the declared frame adds %r" % (top["ow"], top["oh"], top["iw"],
|
||||
top["ih"], extra))
|
||||
assert (inner["ow"], inner["oh"]) == (top["iw"] + extra[0], top["ih"] + extra[1]), (
|
||||
"the iframe of the popup reads outer %dx%d, the top level's inner %dx%d plus the declared frame %r is %dx%d (the "
|
||||
"iframe's own inner size is %dx%d)" % (inner["ow"], inner["oh"], top["iw"], top["ih"], extra,
|
||||
top["iw"] + extra[0], top["ih"] + extra[1], inner["iw"], inner["ih"]))
|
||||
assert (inner["iw"], inner["ih"]) != (top["iw"], top["ih"]), "the iframe has the size of the popup: the read proves nothing"
|
||||
|
||||
other = in_a_thread_of_its_own(lambda: read_popup(firefox_binary, extra_prefs=OTHER_FRAME, iframe=True, ready=synced_to(other_extra)))
|
||||
other_top, other_inner = other["popup"], other["frame"]
|
||||
assert (other_inner["ow"], other_inner["oh"]) == (other_top["iw"] + other_extra[0], other_top["ih"] + other_extra[1]), (
|
||||
"declared with another frame the iframe of a popup reads outer %dx%d, the top's inner %dx%d plus the second declared frame %r is %dx%d: %r"
|
||||
% (other_inner["ow"], other_inner["oh"], other_top["iw"], other_top["ih"], other_extra,
|
||||
other_top["iw"] + other_extra[0], other_top["ih"] + other_extra[1], other))
|
||||
assert (other_top["ow"], other_top["oh"]) == (other_top["iw"] + other_extra[0], other_top["ih"] + other_extra[1]), (
|
||||
"declared with another frame the popup reads outer %dx%d for inner %dx%d, the second declared frame adds %r"
|
||||
% (other_top["ow"], other_top["oh"], other_top["iw"], other_top["ih"], other_extra))
|
||||
assert (other_inner["ow"] - other_top["iw"], other_inner["oh"] - other_top["ih"]) != (inner["ow"] - top["iw"], inner["oh"] - top["ih"]), (
|
||||
"the iframe reads the same frame under two declarations: it does not follow the declaration: %r vs %r" % (other, on))
|
||||
@@ -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,)
|
||||
@@ -1,120 +0,0 @@
|
||||
"""A popup reads the window frame the core declares, not the one of the host.
|
||||
|
||||
What it fixes: the geometry of a window a page opens with `window.open(url, 'p', 'width=500,height=400')`, read from
|
||||
inside the popup. A popup is its real inner size plus the declared frame (retail Windows Firefox, measured by the core at
|
||||
scale 1.0: a border of 8 on the left, right and bottom, the popup UI of 72 above the content, and a default position of
|
||||
4,4 when the page names no left/top):
|
||||
|
||||
* `outerWidth == innerWidth + 2 * border`
|
||||
* `outerHeight == innerHeight + popup_ui + border`
|
||||
* `screenX == screenY ==` the declared default position (the page named none)
|
||||
* `mozInnerScreenX == screenX + border`, `mozInnerScreenY == screenY + popup_ui`
|
||||
|
||||
Engine hook: `fingerprint/screen-window/geometry` of the engine series (`nsGlobalWindowOuter::GetOuterSize`,
|
||||
`GetScreenXY`, `GetMozInnerScreenX/Y`, with the content origin shift of `StealthScreenCoords`) and
|
||||
`fingerprint/screen-window/popup-position` (`nsWindowWatcher`, the default position of a popup).
|
||||
|
||||
Negative control, in the same test: the same page in a launch declared with a SECOND frame that no runner has (border 6,
|
||||
popup UI 53, default position 9). The popup reads that one (outer - inner = 12 x 59, screen 9, mozInnerScreen 15 x 62) and
|
||||
none of the first declaration's numbers, and the two readings DIFFER. The engine off is not the control: the declared frame
|
||||
is the one of a retail Windows window at scale 1.0, so on a Windows runner the host's own popup has the very same frame
|
||||
(measured: 16 x 80 with the engine off) and the test could not tell a hook that answers from one that does not.
|
||||
|
||||
A popup that names ONLY `left` (`window.open(url, 'p', 'width=500,height=400,left=137')`, `test_a_popup_naming_only_left_..`): the
|
||||
hook (`StealthPlacePopupAtDefault`, `fingerprint/screen-window/popup-position`) fills in only the coordinate the page did not give, so
|
||||
`screenX` is the 137 the page asked for (the opener's CSS-to-desktop scale is 1.0 here, no second conversion) and `screenY` is the
|
||||
declared default position, 4 (9 under the second frame); the frame relations are the same as for a popup with no position at all.
|
||||
|
||||
Why a page reads it: `outerWidth - innerWidth`, `screenX` and `mozInnerScreenX/Y` are one line each, and a popup whose
|
||||
frame is not a Windows frame is a browser that does not run on Windows. Linux and Windows run the same assertions: the
|
||||
declaration, not the host, is what is read.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from _popup_geometry import (OTHER_BORDER, OTHER_FRAME, OTHER_POPUP_UI, OTHER_POSITION, frame_extra, frame_of_the_declaration,
|
||||
read_popup)
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
|
||||
def test_a_popup_is_its_inner_size_plus_the_declared_frame(firefox_binary):
|
||||
frame = frame_of_the_declaration()
|
||||
declared = (2 * frame.border, frame.popup_ui + frame.border)
|
||||
|
||||
def has_the_frame(reading):
|
||||
p = reading["popup"]
|
||||
return (p["ow"] - p["iw"], p["oh"] - p["ih"]) == declared
|
||||
|
||||
on = read_popup(firefox_binary, ready=has_the_frame)["popup"]
|
||||
assert (on["ow"] - on["iw"], on["oh"] - on["ih"]) == declared, (
|
||||
"the popup reads outer %dx%d for inner %dx%d: the frame is %r, the declaration is %r"
|
||||
% (on["ow"], on["oh"], on["iw"], on["ih"], (on["ow"] - on["iw"], on["oh"] - on["ih"]), declared))
|
||||
assert (on["sx"], on["sy"]) == (frame.popup_position, frame.popup_position), (
|
||||
"a popup that names no position reads screen %r, the declared default is %d" % ((on["sx"], on["sy"]),
|
||||
frame.popup_position))
|
||||
assert on["mx"] == pytest.approx(on["sx"] + frame.border, abs=0.01), (
|
||||
"mozInnerScreenX %r is not screenX %r plus the border %d" % (on["mx"], on["sx"], frame.border))
|
||||
assert on["my"] == pytest.approx(on["sy"] + frame.popup_ui, abs=0.01), (
|
||||
"mozInnerScreenY %r is not screenY %r plus the popup UI %d" % (on["my"], on["sy"], frame.popup_ui))
|
||||
|
||||
# The control: a launch declared with another frame reads that one, and none of the first declaration's relations.
|
||||
other_declared = frame_extra(OTHER_BORDER, OTHER_POPUP_UI)
|
||||
assert other_declared != declared
|
||||
|
||||
def has_the_other_frame(reading):
|
||||
p = reading["popup"]
|
||||
return (p["ow"] - p["iw"], p["oh"] - p["ih"]) == other_declared
|
||||
|
||||
other = read_popup(firefox_binary, extra_prefs=OTHER_FRAME, ready=has_the_other_frame)["popup"]
|
||||
assert (other["ow"] - other["iw"], other["oh"] - other["ih"]) == other_declared, (
|
||||
"declared with another frame the popup reads outer %dx%d for inner %dx%d: the frame is %r, the second declaration is %r"
|
||||
% (other["ow"], other["oh"], other["iw"], other["ih"], (other["ow"] - other["iw"], other["oh"] - other["ih"]), other_declared))
|
||||
assert (other["sx"], other["sy"]) == (OTHER_POSITION, OTHER_POSITION), (
|
||||
"declared with another default position the popup reads screen %r, the second declaration is %d" % ((other["sx"], other["sy"]), OTHER_POSITION))
|
||||
assert other["mx"] == pytest.approx(other["sx"] + OTHER_BORDER, abs=0.01)
|
||||
assert other["my"] == pytest.approx(other["sy"] + OTHER_POPUP_UI, abs=0.01)
|
||||
assert (other["ow"] - other["iw"], other["oh"] - other["ih"]) != (on["ow"] - on["iw"], on["oh"] - on["ih"]), (
|
||||
"the two declared frames read the same frame: the declaration decides nothing")
|
||||
assert (other["sx"], other["sy"]) != (on["sx"], on["sy"]) and other["my"] - other["sy"] != on["my"] - on["sy"], (
|
||||
"the two declared frames read the same position or content origin: %r vs %r" % (other, on))
|
||||
|
||||
|
||||
LEFT = 137
|
||||
|
||||
|
||||
def test_a_popup_naming_only_left_reads_that_x_and_the_declared_default_y(firefox_binary):
|
||||
frame = frame_of_the_declaration()
|
||||
features = "width=500,height=400,left=%d" % LEFT
|
||||
declared = (2 * frame.border, frame.popup_ui + frame.border)
|
||||
|
||||
def has_the_frame(reading):
|
||||
p = reading["popup"]
|
||||
return (p["ow"] - p["iw"], p["oh"] - p["ih"]) == declared
|
||||
|
||||
on = read_popup(firefox_binary, ready=has_the_frame, features=features)["popup"]
|
||||
assert (on["ow"] - on["iw"], on["oh"] - on["ih"]) == declared, (
|
||||
"the popup reads outer %dx%d for inner %dx%d: the frame is %r, the declaration is %r"
|
||||
% (on["ow"], on["oh"], on["iw"], on["ih"], (on["ow"] - on["iw"], on["oh"] - on["ih"]), declared))
|
||||
assert on["sx"] == LEFT, "a popup that names left=%d reads screenX %r: the page's own x is lost" % (LEFT, on["sx"])
|
||||
assert on["sy"] == frame.popup_position, (
|
||||
"a popup that names no top reads screenY %r, the declared default is %d" % (on["sy"], frame.popup_position))
|
||||
assert on["mx"] == pytest.approx(on["sx"] + frame.border, abs=0.01)
|
||||
assert on["my"] == pytest.approx(on["sy"] + frame.popup_ui, abs=0.01)
|
||||
|
||||
# The control: a launch declared with a second frame keeps the page's x and reads the second default for y.
|
||||
other_declared = frame_extra(OTHER_BORDER, OTHER_POPUP_UI)
|
||||
|
||||
def has_the_other_frame(reading):
|
||||
p = reading["popup"]
|
||||
return (p["ow"] - p["iw"], p["oh"] - p["ih"]) == other_declared
|
||||
|
||||
other = read_popup(firefox_binary, extra_prefs=OTHER_FRAME, ready=has_the_other_frame, features=features)["popup"]
|
||||
assert (other["ow"] - other["iw"], other["oh"] - other["ih"]) == other_declared
|
||||
assert other["sx"] == LEFT, "declared with another frame the popup reads screenX %r, the page asked for %d" % (other["sx"], LEFT)
|
||||
assert other["sy"] == OTHER_POSITION, (
|
||||
"declared with another default position the popup reads screenY %r, the second declaration is %d" % (other["sy"], OTHER_POSITION))
|
||||
assert other["mx"] == pytest.approx(LEFT + OTHER_BORDER, abs=0.01)
|
||||
assert other["my"] == pytest.approx(OTHER_POSITION + OTHER_POPUP_UI, abs=0.01)
|
||||
assert other["sy"] != on["sy"] and other["sx"] == on["sx"], (
|
||||
"the declaration decides y alone when the page names x: %r vs %r" % (other, on))
|
||||
@@ -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"]
|
||||
Reference in new issue
Block a user