Compare commits

..
8 changed files with 467 additions and 911 deletions

No files matched your search

@@ -1,179 +0,0 @@
"""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,163 +0,0 @@
"""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
@@ -1,256 +0,0 @@
"""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"]
@@ -1,126 +0,0 @@
"""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()
+361
View File
@@ -0,0 +1,361 @@
"""A WebGL context tells the page what the session DECLARES, never what the host's GL says.
Characterises, on the published engine (firefox-68), the hooks of the series folder
``fingerprint/webgl/parameters`` in ``dom/canvas`` (``StealthWebGLParams.cpp`` and the hooks in
``ClientWebGLContext.cpp``, ``WebGLContextValidate.cpp``): the numeric ``getParameter`` answers
(``zoom.stealth.webgl.int_params`` / ``int2_params`` / ``float_params``), the renderer and the
vendor strings (``zoom.stealth.webgl.renderer`` / ``vendor``), ``getShaderPrecisionFormat``
(``zoom.stealth.webgl.shader_precisions``), the extension list the page reads
(``zoom.stealth.webgl.extensions`` / ``zoom.stealth.webgl2.extensions``) and the stencil masks a
fresh context starts with. A page reads every one of them with a handful of lines, and they are
the biggest part of a WebGL fingerprint, so a value that came from the host's GPU or driver (a
Mesa llvmpipe on a Linux runner, a WARP adapter on a Windows one) is a value that tells the
machine apart from the Windows the session claims to be.
Each test declares a value no runner has (a ``MAX_TEXTURE_SIZE`` of 12345, a precision of
7:11:13, a Radeon HD 5850, an extension list in a deliberately wrong order) and reads it back
where a page reads it. The negative control is in the same test: the same page, the same
engine, with the declaration of that value empty, reads the host's own answer, and the test
asserts the two DIFFER, so it fails if the declaration is not what the page reads.
The renderer and the vendor have no empty control: an engine that is on refuses to start
without them (the declaration gate), and an engine that is off draws on the host's GL, which a
runner without a GPU may not give at all. The control there is the session's own persona (the
product default), which the page must NOT read once the declaration says otherwise.
The stencil masks have no pref at all: the engine starts them at all ones, as ANGLE does, where
the driver's own start is the stencil bits (Mesa: 255). The control is the same read after the
page writes 255 itself, which proves the read is live and that 255 is what the masks were
before the engine.
The test reads the engine through ``extra_prefs`` (applied last by the core), RFP stays off.
"""
from __future__ import annotations
import pytest
pytestmark = pytest.mark.e2e
SEED = 4246
#: gl.INVALID_ENUM
INVALID_ENUM = 1280
# -- numeric parameters ----------------------------------------------------------------------
#: A value no runner has for each (the host's are 16384 / 2048 / 32767 on a GL or ANGLE).
DECLARED_INT = "3379|12345,34024|23456,34076|9001,32883|4321,35071|777"
DECLARED_INT2 = "3386|12345:23456"
DECLARED_FLOAT = "33901|1:7777,33902|3:5"
EMPTY_NUMERIC = {
"zoom.stealth.webgl.int_params": "",
"zoom.stealth.webgl.int2_params": "",
"zoom.stealth.webgl.float_params": "",
}
DECLARED_NUMERIC = {
"zoom.stealth.webgl.int_params": DECLARED_INT,
"zoom.stealth.webgl.int2_params": DECLARED_INT2,
"zoom.stealth.webgl.float_params": DECLARED_FLOAT,
}
NUMERIC_JS = """() => {
const NAMES = {
MAX_TEXTURE_SIZE: 0x0D33, MAX_RENDERBUFFER_SIZE: 0x84E8, MAX_CUBE_MAP_TEXTURE_SIZE: 0x851C,
MAX_VIEWPORT_DIMS: 0x0D3A, ALIASED_POINT_SIZE_RANGE: 0x846D, ALIASED_LINE_WIDTH_RANGE: 0x846E,
MAX_3D_TEXTURE_SIZE: 0x8073, MAX_ARRAY_TEXTURE_LAYERS: 0x88FF,
};
const out = {};
for (const kind of ["webgl", "webgl2"]) {
const gl = document.createElement("canvas").getContext(kind);
if (!gl) { out[kind] = null; continue; }
gl.getError();
const r = {};
for (const [name, pname] of Object.entries(NAMES)) {
const v = gl.getParameter(pname);
const error = gl.getError();
const view = v !== null && ArrayBuffer.isView(v);
r[name] = {value: view ? Array.from(v) : v,
type: v === null ? "null" : (view ? v.constructor.name : typeof v), error};
}
out[kind] = r;
}
return out;
}"""
# -- renderer and vendor ---------------------------------------------------------------------
#: A device no runner has. ``SanitizeRenderer`` keeps the device of this Direct3D string as it
#: is (a "Radeon HD 5850" is its own bucket) and rewrites what comes after the suffix, so the
#: page reads this prefix whether the string is sanitized or not.
RENDERER = "ANGLE (AMD, Radeon HD 5850 Direct3D11 vs_5_0 ps_5_0, D3D11)"
RENDERER_READ_PREFIX = "ANGLE (AMD, Radeon HD 5850 Direct3D11 vs_5_0 ps_5_0"
VENDOR = "Google Inc. (AMD)"
RENDERER_JS = """() => {
const out = {};
for (const kind of ["webgl", "webgl2"]) {
const gl = document.createElement("canvas").getContext(kind);
if (!gl) { out[kind] = null; continue; }
gl.getError();
// UNMASKED_RENDERER_WEBGL before the extension is enabled: Mozilla's own error.
const before = gl.getParameter(0x9246);
const before_error = gl.getError();
const ext = gl.getExtension("WEBGL_debug_renderer_info");
out[kind] = {
renderer: gl.getParameter(gl.RENDERER),
vendor: gl.getParameter(gl.VENDOR),
unmasked_before_extension: before,
unmasked_before_extension_error: before_error,
has_extension: !!ext,
unmasked_renderer: ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : null,
unmasked_vendor: ext ? gl.getParameter(ext.UNMASKED_VENDOR_WEBGL) : null,
error: gl.getError(),
};
}
return out;
}"""
# -- shader precision ------------------------------------------------------------------------
#: VERTEX_SHADER*LOW_FLOAT -> 7:11:13 and FRAGMENT_SHADER*HIGH_INT -> 3:5:2. No GPU has either.
DECLARED_PRECISION = "35633*36336|7:11:13,35632*36341|3:5:2"
PRECISION_JS = """() => {
const out = {};
for (const kind of ["webgl", "webgl2"]) {
const gl = document.createElement("canvas").getContext(kind);
if (!gl) { out[kind] = null; continue; }
gl.getError();
const read = (shader, precision) => {
const f = gl.getShaderPrecisionFormat(shader, precision);
const error = gl.getError();
return {format: f === null ? null : [f.rangeMin, f.rangeMax, f.precision], error};
};
out[kind] = {
vertex_low_float: read(gl.VERTEX_SHADER, gl.LOW_FLOAT),
fragment_high_int: read(gl.FRAGMENT_SHADER, gl.HIGH_INT),
vertex_high_float: read(gl.VERTEX_SHADER, gl.HIGH_FLOAT),
bad_precision_type: read(gl.VERTEX_SHADER, 0x1234),
bad_shader_type: read(gl.TEXTURE_2D, gl.LOW_FLOAT),
};
}
return out;
}"""
# -- extension list --------------------------------------------------------------------------
#: ``WebGLExtensionID`` of ``dom/canvas/WebGLTypes.h``, in declaration order (``MOZ_debug`` is
#: never listed to a page): the one order a page ever reads, the retail one.
ENUM_ORDER = [
"ANGLE_instanced_arrays", "EXT_blend_minmax", "EXT_clip_control", "EXT_color_buffer_float",
"EXT_color_buffer_half_float", "EXT_depth_clamp", "EXT_disjoint_timer_query", "EXT_float_blend",
"EXT_frag_depth", "EXT_polygon_offset_clamp", "EXT_shader_texture_lod", "EXT_sRGB",
"EXT_texture_compression_bptc", "EXT_texture_compression_rgtc",
"EXT_texture_filter_anisotropic", "EXT_texture_mirror_clamp_to_edge", "EXT_texture_norm16",
"OES_draw_buffers_indexed", "OES_element_index_uint", "OES_fbo_render_mipmap",
"OES_standard_derivatives", "OES_texture_float", "OES_texture_float_linear",
"OES_texture_half_float", "OES_texture_half_float_linear", "OES_vertex_array_object",
"OVR_multiview2", "WEBGL_color_buffer_float", "WEBGL_compressed_texture_astc",
"WEBGL_compressed_texture_etc", "WEBGL_compressed_texture_etc1",
"WEBGL_compressed_texture_pvrtc", "WEBGL_compressed_texture_s3tc",
"WEBGL_compressed_texture_s3tc_srgb", "WEBGL_debug_renderer_info", "WEBGL_debug_shaders",
"WEBGL_depth_texture", "WEBGL_draw_buffers", "WEBGL_explicit_present", "WEBGL_lose_context",
"WEBGL_provoking_vertex",
]
#: Declared in an order that is NOT the enum's: the page must read them in the enum's.
DECLARED_EXTENSIONS_1 = ["WEBGL_lose_context", "OES_texture_float", "EXT_blend_minmax",
"OES_vertex_array_object", "ANGLE_instanced_arrays"]
DECLARED_EXTENSIONS_2 = ["WEBGL_lose_context", "EXT_texture_filter_anisotropic",
"EXT_color_buffer_float", "OES_texture_float_linear"]
EXTENSIONS_JS = """() => {
const out = {};
for (const kind of ["webgl", "webgl2"]) {
const gl = document.createElement("canvas").getContext(kind);
if (!gl) { out[kind] = null; continue; }
out[kind] = {list: gl.getSupportedExtensions(),
depth_texture: gl.getExtension("WEBGL_depth_texture") === null ? null : "object"};
}
return out;
}"""
# -- stencil masks ---------------------------------------------------------------------------
STENCIL_JS = """() => {
const PNAMES = {STENCIL_VALUE_MASK: 0x0B93, STENCIL_WRITEMASK: 0x0B98,
STENCIL_BACK_VALUE_MASK: 0x8CA4, STENCIL_BACK_WRITEMASK: 0x8CA5};
const read = gl => {
const r = {};
for (const [name, pname] of Object.entries(PNAMES)) r[name] = gl.getParameter(pname);
return r;
};
const out = {};
for (const kind of ["webgl", "webgl2"]) {
for (const stencil of [false, true]) {
const key = kind + (stencil ? "+stencil" : "");
const gl = document.createElement("canvas").getContext(kind, {stencil});
if (!gl) { out[key] = null; continue; }
const fresh = read(gl);
// The control: the page writes 255 itself and reads it back.
gl.stencilMask(255);
gl.stencilMaskSeparate(gl.BACK, 255);
gl.stencilFunc(gl.ALWAYS, 0, 255);
gl.stencilFuncSeparate(gl.BACK, gl.ALWAYS, 0, 255);
out[key] = {fresh, written: read(gl)};
}
}
return out;
}"""
def _read(firefox_binary, prefs, js):
"""One short-lived product session with ``prefs`` overlaid, and what the page answers to ``js``."""
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=SEED, binary_path=firefox_binary, headless=True,
extra_prefs=dict(prefs)) as browser:
page = browser.new_page()
page.goto("about:blank")
return page.evaluate(js)
def _contexts(got, label):
for kind in ("webgl", "webgl2"):
assert got[kind] is not None, "%s: no %s context at all" % (label, kind)
def test_declared_numeric_parameters_replace_the_hosts_and_webgl2_only_names_stay_null_on_webgl1(
firefox_binary):
declared = _read(firefox_binary, DECLARED_NUMERIC, NUMERIC_JS)
control = _read(firefox_binary, EMPTY_NUMERIC, NUMERIC_JS)
_contexts(declared, "declared")
_contexts(control, "control")
want = {
"MAX_TEXTURE_SIZE": (12345, "number"),
"MAX_RENDERBUFFER_SIZE": (23456, "number"),
"MAX_CUBE_MAP_TEXTURE_SIZE": (9001, "number"),
"MAX_VIEWPORT_DIMS": ([12345, 23456], "Int32Array"),
"ALIASED_POINT_SIZE_RANGE": ([1, 7777], "Float32Array"),
"ALIASED_LINE_WIDTH_RANGE": ([3, 5], "Float32Array"),
}
want_webgl2_only = {"MAX_3D_TEXTURE_SIZE": 4321, "MAX_ARRAY_TEXTURE_LAYERS": 777}
for kind in ("webgl", "webgl2"):
for name, (value, type_) in want.items():
got = declared[kind][name]
assert got == {"value": value, "type": type_, "error": 0}, (kind, name, got)
# The control: the same page with the declaration empty reads the host's answer.
assert control[kind][name]["value"] != value, (
"%s %s: the host's own answer is the declared one, so this test cannot tell "
"the declaration from the host: %r" % (kind, name, control[kind][name]))
assert control[kind][name]["error"] == 0, (kind, name, control[kind][name])
# WebGL 2 only: the declared number is read on a WebGL 2 context ...
for name, value in want_webgl2_only.items():
got = declared["webgl2"][name]
assert got == {"value": value, "type": "number", "error": 0}, (name, got)
assert control["webgl2"][name]["value"] != value, (name, control["webgl2"][name])
# ... and on a WebGL 1 context the name does not exist: null and INVALID_ENUM, declared
# or not (the declaration cannot make a name appear that the context does not have).
for label, run in (("declared", declared), ("control", control)):
got = run["webgl"][name]
assert got == {"value": None, "type": "null", "error": INVALID_ENUM}, (
label, name, got)
def test_declared_renderer_and_vendor_are_read_in_every_form(firefox_binary):
declared = _read(firefox_binary, {"zoom.stealth.webgl.renderer": RENDERER,
"zoom.stealth.webgl.vendor": VENDOR}, RENDERER_JS)
# The control: the session's own persona, the product default (the declaration gate refuses
# an empty pair on a running engine).
control = _read(firefox_binary, {}, RENDERER_JS)
_contexts(declared, "declared")
_contexts(control, "control")
for kind in ("webgl", "webgl2"):
got = declared[kind]
# Every form of the renderer: the masked constant, and the unmasked one through the
# extension the page enables.
assert got["renderer"].startswith(RENDERER_READ_PREFIX), (kind, got)
assert got["has_extension"], (kind, got)
assert got["unmasked_renderer"].startswith(RENDERER_READ_PREFIX), (kind, got)
assert got["unmasked_vendor"] == VENDOR, (kind, got)
# The masked vendor is Firefox's own constant, whatever is declared.
assert got["vendor"] == "Mozilla", (kind, got)
# Without the extension the unmasked constants are not a thing: Mozilla's error.
assert got["unmasked_before_extension"] is None, (kind, got)
assert got["unmasked_before_extension_error"] == INVALID_ENUM, (kind, got)
assert got["error"] == 0, (kind, got)
base = control[kind]
assert base["has_extension"], (kind, base)
assert not base["renderer"].startswith(RENDERER_READ_PREFIX), (kind, base)
assert not base["unmasked_renderer"].startswith(RENDERER_READ_PREFIX), (kind, base)
assert base["unmasked_vendor"] != VENDOR, (kind, base)
assert base["vendor"] == "Mozilla", (kind, base)
assert base["unmasked_before_extension"] is None, (kind, base)
assert base["unmasked_before_extension_error"] == INVALID_ENUM, (kind, base)
def test_declared_shader_precision_replaces_the_hosts_and_a_bad_pair_still_errors(
firefox_binary):
declared = _read(firefox_binary,
{"zoom.stealth.webgl.shader_precisions": DECLARED_PRECISION}, PRECISION_JS)
control = _read(firefox_binary, {"zoom.stealth.webgl.shader_precisions": ""}, PRECISION_JS)
_contexts(declared, "declared")
_contexts(control, "control")
for kind in ("webgl", "webgl2"):
got, base = declared[kind], control[kind]
assert got["vertex_low_float"] == {"format": [7, 11, 13], "error": 0}, (kind, got)
assert got["fragment_high_int"] == {"format": [3, 5, 2], "error": 0}, (kind, got)
# The control: with the declaration empty the page reads the host's formats.
assert base["vertex_low_float"]["format"] not in (None, [7, 11, 13]), (kind, base)
assert base["fragment_high_int"]["format"] not in (None, [3, 5, 2]), (kind, base)
assert base["vertex_low_float"]["error"] == 0, (kind, base)
# A pair nothing declares is the host's, untouched by the declarations next to it.
assert got["vertex_high_float"] == base["vertex_high_float"], (kind, got, base)
assert got["vertex_high_float"]["format"] is not None, (kind, got)
# A bad pair is Mozilla's error with or without a declaration in the pref.
for name in ("bad_precision_type", "bad_shader_type"):
for label, run in (("declared", got), ("control", base)):
assert run[name] == {"format": None, "error": INVALID_ENUM}, (kind, label, name, run)
def test_the_declared_extension_list_is_read_in_firefoxs_order(firefox_binary):
declared = _read(firefox_binary, {
"zoom.stealth.webgl.extensions": ",".join(DECLARED_EXTENSIONS_1),
"zoom.stealth.webgl2.extensions": ",".join(DECLARED_EXTENSIONS_2),
}, EXTENSIONS_JS)
control = _read(firefox_binary, {"zoom.stealth.webgl.extensions": "",
"zoom.stealth.webgl2.extensions": ""}, EXTENSIONS_JS)
_contexts(declared, "declared")
_contexts(control, "control")
for kind, names in (("webgl", DECLARED_EXTENSIONS_1), ("webgl2", DECLARED_EXTENSIONS_2)):
assert names != sorted(names, key=ENUM_ORDER.index), "the declared order must be wrong"
want = [e for e in ENUM_ORDER if e in names]
assert declared[kind]["list"] == want, (kind, declared[kind]["list"])
# The control: with the declaration empty the page reads the host's own list.
assert control[kind]["list"] != want, (kind, control[kind]["list"])
assert control[kind]["list"], (kind, "the host list is empty")
# Only what is declared is served: the host has WEBGL_depth_texture, the declaration lacks it.
assert declared["webgl"]["depth_texture"] is None, declared["webgl"]
def test_the_stencil_masks_start_at_all_ones(firefox_binary):
got = _read(firefox_binary, {}, STENCIL_JS)
all_ones = 4294967295
names = ("STENCIL_VALUE_MASK", "STENCIL_WRITEMASK",
"STENCIL_BACK_VALUE_MASK", "STENCIL_BACK_WRITEMASK")
for key in ("webgl", "webgl+stencil", "webgl2", "webgl2+stencil"):
run = got[key]
assert run is not None, "%s: no context at all" % key
# A fresh context, on any OS: all ones, as ANGLE starts them.
assert run["fresh"] == {n: all_ones for n in names}, (key, run["fresh"])
# The control: what the masks were before the engine on a driver GL is the stencil
# bits (255 on Mesa), and a page that writes 255 reads 255 back, so the read is live and
# all ones is not a constant of the page's reading.
assert run["written"] == {n: 255 for n in names}, (key, run["written"])
+106
View File
@@ -0,0 +1,106 @@
"""``getTranslatedShaderSource`` answers in the DECLARED shader language, not the host's.
Characterises, on the published engine (firefox-68), the hooks of the series folder
``fingerprint/webgl/shader-language`` in ``dom/canvas`` (``StealthWebGLShaderLanguage.cpp``;
hooks in ``WebGLShader.cpp``, ``WebGLShaderValidator.cpp``, ``WebGLContext.cpp``): with
``zoom.stealth.webgl.shader_output_language`` set to ``essl`` the page that asks
``WEBGL_debug_shaders`` for the translated source of a shader reads ANGLE's translation to ESSL,
the language a Windows Firefox (ANGLE, a GLES context) always answers in; the driver keeps
receiving its own.
Why a page reads it: the session declares a Windows ANGLE renderer, and on a host whose GL
context is not GLES (Linux through GLX) the same translator emits desktop GLSL, so the page
would read ``#version 450`` from a browser whose RENDERER says ANGLE: a contradiction inside
one page, with no need to know the OS.
The negative control is in the same test: the same engine, the same shaders, with the
declaration empty. It is adapted to the OS, as the engine is. On Linux the host's language is
desktop GLSL, so the declared and the undeclared sources DIFFER (the WebGL 2 shaders lose their
``#version 300 es`` line). On Windows the context already goes through ANGLE and is already
ESSL, so the two are EQUAL (and the declared one is the Windows one). On both, the driver still
compiles and links the shader: the page sees one language, the pixels do not move.
"""
from __future__ import annotations
import sys
import pytest
pytestmark = pytest.mark.e2e
SEED = 4246
TRANSLATE_JS = """() => {
const VS1 = 'attribute vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }';
const FS1 = 'precision mediump float; void main(){ gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); }';
const VS2 = '#version 300 es\\nin vec2 p;\\nvoid main(){ gl_Position = vec4(p, 0.0, 1.0); }';
const FS2 = '#version 300 es\\nprecision mediump float;\\nout vec4 o;\\n'
+ 'void main(){ o = vec4(1.0, 0.0, 0.0, 1.0); }';
const out = {};
for (const [kind, vs, fs] of [["webgl", VS1, FS1], ["webgl2", VS2, FS2]]) {
const gl = document.createElement("canvas").getContext(kind);
if (!gl) { out[kind] = null; continue; }
const dbg = gl.getExtension("WEBGL_debug_shaders");
const v = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(v, vs); gl.compileShader(v);
const f = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(f, fs); gl.compileShader(f);
const prog = gl.createProgram(); gl.attachShader(prog, v); gl.attachShader(prog, f);
gl.linkProgram(prog);
out[kind] = {
has_extension: !!dbg,
vertex: dbg ? dbg.getTranslatedShaderSource(v) : null,
fragment: dbg ? dbg.getTranslatedShaderSource(f) : null,
compiled: gl.getShaderParameter(v, gl.COMPILE_STATUS) && gl.getShaderParameter(f, gl.COMPILE_STATUS),
linked: gl.getProgramParameter(prog, gl.LINK_STATUS),
};
}
return out;
}"""
def _read(firefox_binary, language):
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(
seed=SEED, binary_path=firefox_binary, headless=True,
extra_prefs={"zoom.stealth.webgl.shader_output_language": language}) as browser:
page = browser.new_page()
page.goto("about:blank")
return page.evaluate(TRANSLATE_JS)
def test_get_translated_shader_source_is_in_the_declared_language_and_the_driver_still_compiles(
firefox_binary):
declared = _read(firefox_binary, "essl")
control = _read(firefox_binary, "")
for kind in ("webgl", "webgl2"):
for label, run in (("declared", declared), ("control", control)):
got = run[kind]
assert got is not None, "%s: no %s context at all" % (label, kind)
assert got["has_extension"], (label, kind)
# The driver is not touched by what the page is shown: it compiles and links.
assert got["compiled"] is True and got["linked"] is True, (label, kind, got)
assert got["vertex"] and got["fragment"], (label, kind, got)
# Declared: ESSL, on every OS. A WebGL 1 shader has no #version line in ESSL 1.00 and a
# WebGL 2 one keeps its "#version 300 es".
assert "#version" not in declared["webgl"]["vertex"], declared["webgl"]
assert "#version" not in declared["webgl"]["fragment"], declared["webgl"]
assert declared["webgl2"]["vertex"].lstrip().startswith("#version 300 es"), declared["webgl2"]
assert declared["webgl2"]["fragment"].lstrip().startswith("#version 300 es"), declared["webgl2"]
if sys.platform.startswith("linux"):
# The host's context is desktop GL: without the declaration the page reads desktop GLSL.
# The declaration is what makes the two differ (as a pair of stages: a one-line vertex
# shader may translate to the same text in both languages).
for kind in ("webgl", "webgl2"):
assert (control[kind]["vertex"], control[kind]["fragment"]) != (
declared[kind]["vertex"], declared[kind]["fragment"]), (kind, control[kind])
assert not control["webgl2"]["vertex"].lstrip().startswith("#version 300 es"), control["webgl2"]
assert not control["webgl2"]["fragment"].lstrip().startswith("#version 300 es"), control["webgl2"]
else:
# Windows (ANGLE, a GLES context): the host's language is already ESSL, nothing to
# translate twice, and the declaration changes nothing.
for kind in ("webgl", "webgl2"):
for stage in ("vertex", "fragment"):
assert control[kind][stage] == declared[kind][stage], (kind, stage, control[kind])
@@ -1,141 +0,0 @@
"""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
@@ -1,46 +0,0 @@
"""`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"]