Compare commits

..
7 changed files with 911 additions and 279 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,)
-279
View File
@@ -1,279 +0,0 @@
"""An IPv6 literal a page asks for is judged by the declared network, and a destination behind a SOCKS proxy is left to the proxy.
What this fixes in place (characterisation of the published engine firefox-68; the engine hook is `nsSocketTransport::InitiateSocket` in
`netwerk/base/nsSocketTransport2.cpp`, the decision is `StealthConnect` / `StealthConnectError` in `netwerk/base/StealthIPv6Literal.cpp`, series folder
`network/ipv6-literal`):
* The session declares its host network in `STEALTHFOX_WEBRTC_NETWORK` (`v6=0`: no IPv6). A hostname then never resolves to AAAA, but a LITERAL
(`http://[2001:db8::1]/`) is handed to the socket by Firefox without any lookup, and the route table of the machine under the browser would decide.
The engine decides instead: a direct connection to a routable IPv6 literal fails before `connect()` is called, the way a Windows machine that has the
IPv6 stack and no IPv6 route fails it, and nothing is sent. The client reads it as `NS_ERROR_CONNECTION_REFUSED` (a failed `fetch` is a `TypeError`,
and `requestfailed` carries that text). A page reads this: whether `fetch("http://[<global IPv6>]/")` fails at once or hangs, and with which error, is
the first thing that tells a machine with an IPv6 route from one without.
* An IPv4-mapped literal (`::ffff:127.0.0.1`) is refused on every system and whatever the declaration says: Windows refuses `connect()` to a mapped
address on a socket that is IPv6-only (Firefox's are), and a dual-stack Linux socket would connect over IPv4. The listener below never sees it.
* A destination behind a SOCKS proxy is never judged: the proxy reaches it, not this host. The same literal that is refused with no proxy reaches the
proxy as a CONNECT whose destination is that address and port, as an IPv6 address (SOCKS5 address type 4), never as a name. How many times the
browser tries it (Mozilla retries a connection that did not answer at once) is Mozilla's code and is not fixed here: every CONNECT of the
navigation to the documentation destination has that shape, and there is at least one.
Not clocks: "refused by the engine" and "timed out" are told apart by the error (`TypeError` with the failure text `NS_ERROR_CONNECTION_REFUSED`, against a
`TimeoutError` of the 30 s deadline of the fetch), and by the listener having heard nothing; no duration is read anywhere.
Negative controls, in the same test:
* the listener is real: the same address by its IPv4 literal (`127.0.0.1`) reaches it, once, in the launches where the mapped literal does not;
* the mapped literal is refused with IPv6 declared on as well as off (a rule of its own: the declaration decides the other literals, not this one);
* behind the proxy the documentation-prefix literal that is refused direct IS carried: an engine that judged it behind SOCKS (or that always passed
`kDirect`) would make the proxy record no CONNECT, and the fetch would fail; and an engine that handed the proxy the literal in another shape (a
name, an IPv4 address) fails the shape assertion.
What this test cannot tell, by design: with IPv6 declared on, a global IPv6 literal goes to the OS, whose answer depends on the machine (a runner with no
IPv6 route answers `ENETUNREACH`, the same `NS_ERROR_CONNECTION_REFUSED` as the engine's), so the documentation-prefix fetch is judged only in the
declared-off launch and behind the proxy. The port is 80: Firefox bans port 9 (discard) before any connect, so a fetch to it never reaches the gate.
Hermetic: a local listener, a local SOCKS5 gateway of `tests/_socks_servers.py` that maps the documentation address to the listener and forwards
NOTHING else: the browser's own background traffic also arrives at the gateway, and every CONNECT to an address that is not the lab's is refused
(reply 5) and recorded. Every request, refused or carried, is recorded with its time since the launch, its SOCKS5 address type, its destination as received and
its port. The refused list is written, always, under `$RUNNER_TEMP/invpw-evidence/` (the folder the e2e jobs upload), so that a reader sees
what the browser asked for besides the literal.
"""
from __future__ import annotations
import json
import os
import pathlib
import socket
import socketserver
import struct
import threading
import time
import pytest
from _servers import LocalServer
from _socks_servers import EXIT, Gateway, _recv_exact
from _udp_line import egress_by_proxy, measure_servers
from _waits import wait_until
from test_declared_host_network_e2e import DUAL, NETWORK_ENV, V4_ONLY
pytestmark = pytest.mark.e2e
#: A global-unicast-looking address that no host routes (RFC 3849 documentation prefix): the gate answers for it, whatever the machine has.
DOCUMENTATION = "2001:db8::1"
DOCUMENTATION_HTTP = 80
#: What a failed connect of the engine is called by the browser (NSPR's PR_NETWORK_UNREACHABLE_ERROR and PR_ADDRESS_NOT_AVAILABLE_ERROR both end here).
REFUSED = "NS_ERROR_CONNECTION_REFUSED"
#: SOCKS5 address type of an IPv6 address (RFC 1928); 1 is IPv4, 3 a domain name.
ATYP_IPV6 = 4
#: The folder under ``$RUNNER_TEMP`` the e2e workflows upload (``invpw-evidence-*``).
EVIDENCE_FOLDER = "invpw-evidence"
#: The deadline of a fetch that must END (refused, or carried): far beyond a healthy run; what the page reads on a timeout is a `TimeoutError`, never a verdict.
FETCH_SECONDS = 30
_FETCH_JS = """async (url) => {
try {
const response = await fetch(url, {mode: 'no-cors', cache: 'no-store', signal: AbortSignal.timeout(%d)});
return {ok: true, type: response.type};
} catch (e) {
return {ok: false, name: e.name, message: String(e.message)};
}
}""" % (FETCH_SECONDS * 1000)
class _Listener:
"""A local HTTP-ish listener that remembers every connection it accepted and answers each with a tiny 200."""
def __init__(self) -> None:
self.connections: list = []
outer = self
class Handler(socketserver.BaseRequestHandler):
def handle(self) -> None:
outer.connections.append(self.client_address)
self.request.settimeout(FETCH_SECONDS)
try:
self.request.recv(65536)
self.request.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok")
except OSError:
pass
self.server = LocalServer(("127.0.0.1", 0), Handler)
self.port: int = self.server.server_address[1]
threading.Thread(target=self.server.serve_forever, daemon=True).start()
def __enter__(self) -> "_Listener":
return self
def __exit__(self, *exc) -> None:
self.server.shutdown()
self.server.server_close()
class _GatewayToALocalListener(Gateway):
"""The SOCKS5 gateway of the tests (UDP refused) that carries the documentation address to a local listener and forwards nothing else: the destination
it is asked for is what it records in ``connects`` (with its SOCKS5 address type in ``addresses``), what the listener hears is what it carried, and
every CONNECT to an address that is not the lab's is refused and recorded in ``refused``."""
def __init__(self, carried: dict) -> None:
self._carried = dict(carried)
#: Every address of a request the gateway read, as (host, port, address type), in order.
self.addresses: list = []
#: Every CONNECT that was not the lab's and was refused (reply 5, connection refused), as (host, port), in order.
self.refused: list = []
#: Every request, as a dict, for the evidence file: ``t`` (seconds, monotonic, since ``launch_started``), ``atyp`` (SOCKS5 address type: 1 IPv4,
#: 3 domain name, 4 IPv6), ``destination`` (as received: the NAME when the type is 3), ``port``, ``outcome``.
self.records: list = []
self._launch_t0 = time.monotonic()
self._current = threading.local()
super().__init__(udp="refuse", tcp_exit=EXIT, udp_exit=EXIT)
@staticmethod
def _address_of(c: socket.socket):
atyp = _recv_exact(c, 1)[0]
if atyp == 1:
host = socket.inet_ntoa(_recv_exact(c, 4))
elif atyp == 3:
host = _recv_exact(c, _recv_exact(c, 1)[0]).decode()
else:
host = socket.inet_ntop(socket.AF_INET6, _recv_exact(c, 16))
return host, struct.unpack("!H", _recv_exact(c, 2))[0], atyp
def launch_started(self) -> None:
"""Call just before the launch of the browser behind this gateway: the origin of the times of ``records``."""
self._launch_t0 = time.monotonic()
def _read_address(self, c: socket.socket):
host, port, atyp = self._address_of(c)
self.addresses.append((host, port, atyp))
record = {"t": round(time.monotonic() - self._launch_t0, 3), "atyp": atyp, "destination": host, "port": port,
"outcome": "answered by the lab (or not a CONNECT)"}
self.records.append(record)
self._current.record = record
return host, port
def _target(self, host: str, port: int):
return self._carried.get((host, port), (host, port))
def _open_upstream(self, target):
if target not in self._carried.values():
self.refused.append(target)
self._current.record["outcome"] = "refused"
raise OSError("the lab forwards nothing outside the lab: %s:%d" % target)
self._current.record["outcome"] = "carried to the listener of the lab"
return super()._open_upstream(target)
def documentation_connects(self) -> list:
"""Every request of the navigation to the documentation destination, in whatever shape it arrived: the host is told by its digits."""
return [(host, port, atyp) for host, port, atyp in self.addresses if "2001:db8" in host.lower()]
def _write_refused(gateway: "_GatewayToALocalListener") -> None:
"""What the gateway refused, always (a few lines): under ``$RUNNER_TEMP/invpw-evidence/`` the e2e jobs upload. Off a runner nothing is written."""
runner_temp = os.environ.get("RUNNER_TEMP")
if not runner_temp:
return
folder = pathlib.Path(runner_temp) / EVIDENCE_FOLDER / "ipv6-literal-refused-connects" / ("%d-%d" % (os.getpid(), int(time.time() * 1000)))
folder.mkdir(parents=True, exist_ok=True)
(folder / "refused-connects.json").write_text(json.dumps({
"refused": ["%s:%d" % target for target in gateway.refused],
"requests": gateway.records,
}, indent=2), encoding="utf-8")
def _launch(firefox_binary, gateway=None):
from invisible_playwright import InvisiblePlaywright
kw = {"seed": 42, "binary_path": firefox_binary, "headless": True, "timezone": "America/New_York"}
if gateway is not None:
kw.update(proxy=gateway.proxy, udp_stun_servers=measure_servers(gateway))
return InvisiblePlaywright(**kw)
def _try(page, failures, url, needle):
"""One fetch of ``url`` from the page: what the page read, and the failure texts the client reported for the request whose URL holds ``needle``."""
result = page.evaluate(_FETCH_JS, url)
if not result["ok"]:
wait_until(lambda: [text for seen, text in failures if needle in seen], FETCH_SECONDS, lambda: page.wait_for_timeout(50))
return result, [text for seen, text in failures if needle in seen]
def _page_of(browser):
page = browser.new_context().new_page()
failures: list = []
page.on("requestfailed", lambda request: failures.append((request.url, request.failure)))
page.goto("about:blank")
return page, failures
def _direct_launch(firefox_binary, monkeypatch, declaration, listener, with_documentation_prefix):
"""One launch with no proxy and ``declaration``: the IPv4 literal of the listener (control), the mapped literal of the same listener, and, when
asked, the documentation-prefix literal. Returns what was read and the connections the listener heard after each step."""
monkeypatch.setenv(NETWORK_ENV, declaration)
seen = {}
with _launch(firefox_binary) as browser:
page, failures = _page_of(browser)
before = len(listener.connections)
seen["control"] = _try(page, failures, "http://127.0.0.1:%d/" % listener.port, "127.0.0.1")
wait_until(lambda: len(listener.connections) > before, FETCH_SECONDS, lambda: page.wait_for_timeout(50))
seen["after_control"] = len(listener.connections) - before
seen["mapped"] = _try(page, failures, "http://[::ffff:127.0.0.1]:%d/" % listener.port, "[::ffff:")
seen["after_mapped"] = len(listener.connections) - before
if with_documentation_prefix:
seen["documentation"] = _try(page, failures, "http://[%s]:%d/" % (DOCUMENTATION, DOCUMENTATION_HTTP), "[%s]" % DOCUMENTATION)
return seen
def test_a_direct_ipv6_literal_is_refused_and_one_behind_socks_is_left_to_the_proxy(firefox_binary, monkeypatch):
from invisible_core import _geo
with _Listener() as direct, _Listener() as behind:
off = _direct_launch(firefox_binary, monkeypatch, V4_ONLY, direct, with_documentation_prefix=True)
on = _direct_launch(firefox_binary, monkeypatch, DUAL, direct, with_documentation_prefix=False)
# Behind a SOCKS5 gateway, IPv6 declared off as in the first launch: the documentation-prefix literal is the proxy's to reach.
gateway = _GatewayToALocalListener({(DOCUMENTATION, DOCUMENTATION_HTTP): ("127.0.0.1", behind.port)})
try:
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(gateway))
monkeypatch.setenv(NETWORK_ENV, V4_ONLY)
gateway.launch_started()
with _launch(firefox_binary, gateway) as browser:
page, failures = _page_of(browser)
proxied = _try(page, failures, "http://[%s]:%d/" % (DOCUMENTATION, DOCUMENTATION_HTTP), "[%s]" % DOCUMENTATION)
wait_until(lambda: behind.connections, FETCH_SECONDS, lambda: page.wait_for_timeout(50))
documentation = gateway.documentation_connects()
finally:
gateway.close()
_write_refused(gateway)
# The listener is real: its IPv4 literal reaches it, once per launch.
for name, seen in (("declared off", off), ("declared on", on)):
control, _failed = seen["control"]
assert control["ok"], "%s: the IPv4 literal of the local listener was not reached: %s" % (name, seen)
assert seen["after_control"] == 1, "%s: the listener heard %d connections for one fetch of its IPv4 literal: %s" % (name, seen["after_control"], seen)
# An IPv4-mapped literal is refused by the engine, declared off or on, and the listener hears nothing for it.
for name, seen in (("declared off", off), ("declared on", on)):
result, failed = seen["mapped"]
assert result["ok"] is False and result["name"] == "TypeError", (
"%s: the fetch of the mapped literal did not fail as a refused connection (a TimeoutError would be a connect that was attempted): %s" % (name, seen))
assert failed == [REFUSED], "%s: the client reported %r for the mapped literal, not the engine's refusal: %s" % (name, failed, seen)
assert seen["after_mapped"] == seen["after_control"], "%s: the listener heard a connection through the mapped literal: %s" % (name, seen)
# With IPv6 declared off, a direct documentation-prefix literal is refused by the engine: the same failure as a machine with no IPv6 route.
result, failed = off["documentation"]
assert result["ok"] is False and result["name"] == "TypeError", (
"declared off: the direct fetch of %s did not fail as a refused connection (a TimeoutError means a connect was attempted): %s" % (DOCUMENTATION, off))
assert failed == [REFUSED], "declared off: the client reported %r for the direct documentation-prefix literal: %s" % (failed, off)
# The same literal behind the SOCKS5 gateway is carried: every CONNECT of the navigation to the documentation destination is the IPv6 literal and port,
# as an IPv6 address (how many the browser makes is Mozilla's), and the listener behind it answered.
assert proxied[0] == {"ok": True, "type": "opaque"}, (
"the fetch of %s behind the SOCKS5 gateway was not carried (it is refused with no proxy): %s; failures %s; gateway requests %s" % (
DOCUMENTATION, proxied[0], proxied[1], gateway.addresses))
assert documentation, "the gateway was asked for no CONNECT to %s:%d: %s" % (DOCUMENTATION, DOCUMENTATION_HTTP, gateway.addresses)
assert set(documentation) == {(DOCUMENTATION, DOCUMENTATION_HTTP, ATYP_IPV6)}, (
"every CONNECT to the documentation destination should carry the IPv6 literal %s port %d as an IPv6 address (type %d): %s" % (
DOCUMENTATION, DOCUMENTATION_HTTP, ATYP_IPV6, documentation))
assert (DOCUMENTATION, DOCUMENTATION_HTTP) not in gateway.refused, "the gateway refused the destination of the lab: %s" % gateway.refused
assert len(behind.connections) >= 1, "the listener behind the gateway heard nothing"
@@ -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"]