Compare commits

...
6 changed files with 911 additions and 0 deletions

No files matched your search

@@ -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"]
+46
View File
@@ -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"]