Characterization e2e of the media enumeration, voice URIs, eval name, native line endings and branding on firefox-68

This commit is contained in:
feder-cr committed 2026-11-21 20:50:35 +01:00
1 parent 5d84475d98
commit 79b46cc0a2
5 files changed
+347

No files matched your search

@@ -0,0 +1,56 @@
"""Native line endings are Windows' on every host.
On retail Windows Firefox a `Blob` made with `endings: 'native'` converts every
"\n" to "\r\n" (dom/file/BlobSet.cpp, under `XP_WIN`), and the plain-text
serializer used by `getSelection().toString()` puts "\r\n" between blocks
(dom/serializers/nsPlainTextSerializer.cpp, `DetermineLineBreak`); on retail
Linux both stay "\n". A page reads both, so the engine gives the lines of
Windows everywhere, with no pref (hook `fingerprint/js-surface/line-endings`:
`StealthNativeEOL.h`, `StealthPlainTextLineBreak.h`). The test is the same on
Linux and Windows, where the engine's answer is the same.
Control: the conversion is the one of `native`, not a global change of every
line break: the default `endings` (transparent) leaves a Blob's "\n" alone
(size 1), and `innerText` of the same two blocks keeps "\n". The stock
Firefox of the same candidate (1 and "\n" on Linux) cannot be asked from the
candidate: the hook is not behind the engine's gate, as it is not in the
retail.
"""
from __future__ import annotations
import pytest
pytestmark = pytest.mark.e2e
PROBE = """() => {
document.body.innerHTML = '<div>one</div><div>two</div>';
const sel = getSelection();
sel.removeAllRanges();
sel.selectAllChildren(document.body);
return {
native: new Blob(['\n'], {endings: 'native'}).size,
native_text: new Blob(['a\nb'], {endings: 'native'}).size,
transparent: new Blob(['\n'], {endings: 'transparent'}).size,
default: new Blob(['\n']).size,
selection: sel.toString(),
inner_text: document.body.innerText,
};
}"""
def test_native_line_endings_are_windows(firefox_binary):
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True) as browser:
page = browser.new_page()
page.goto("about:blank")
got = page.evaluate(PROBE)
assert got["native"] == 2, got
assert got["native_text"] == 4, got
# The text between two blocks is "\r\n" and nothing is a bare "\n".
assert "\r\n" in got["selection"], got
assert got["selection"].replace("\r\n", "\n") == "one\ntwo", got
assert "\n" not in got["selection"].replace("\r\n", ""), got
# Control: the conversion belongs to `native` and to the serializer.
assert got["transparent"] == 1 and got["default"] == 1, got
assert "\r" not in got["inner_text"], got
@@ -0,0 +1,107 @@
"""A page loads the branding from the archive the core declares, with the
content sandbox on.
`chrome://branding/content/` and `resource://usercontext-content/branding/`
are content-accessible, and what a page reads there tells a build from the
retail one. The core declares where the files are (`zoom.stealth.branding.
archive`, the zip of a set it ships or one of the caller's own, `pin=
{"branding": <archive>}`); the engine serves them as `jar:` at the two places
that resolve those URIs (netwerk/protocol/res, `fingerprint/js-surface/
branding`) and grants the content processes read access to exactly that file
(Windows: `sandboxBroker.cpp`; Linux: `SandboxBrokerPolicyFactory.cpp`), for the
archive lives wherever the package is installed, outside what the sandbox opens.
So a page that loads the files shows both the redirect (the declared files, not
the build's) and the sandbox grant (the load works at all). Both are read here
as the page reads them: the size of the image a page loads, from a page on
127.0.0.1, on Linux and on Windows.
Negative control: the same page with the declaration pointed at another archive
sees that archive's file, and the dimensions differ from the shipped retail
set's, so a launch that ignored the declaration, or whose content process could
not read it, fails here. (An undeclared archive with the engine on is refused
at launch by the declaration gate, which the core's own tests hold: the browser
does not start to be read.) The archive of the caller's own is the shipped
`official` set with `about-logo.png` replaced by a 7x5 image.
"""
from __future__ import annotations
import struct
import zlib
import zipfile
import pytest
pytestmark = pytest.mark.e2e
#: An image no brand has: the declaration, not the build's file.
_MINE = (7, 5)
_FILE = "about-logo.png"
URLS = {
"chrome": "chrome://branding/content/" + _FILE,
"resource": "resource://usercontext-content/branding/" + _FILE,
}
LOAD = """async (urls) => {
const out = {};
for (const [way, url] of Object.entries(urls)) {
out[way] = await new Promise(resolve => {
const img = new Image();
img.onload = () => resolve([img.naturalWidth, img.naturalHeight]);
img.onerror = () => resolve('error');
img.src = url;
});
}
return out;
}"""
def _png(width, height):
def chunk(kind, data):
body = kind + data
return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF)
rows = b"".join(b"\x00" + b"\xff\x00\x00\xff" * width for _ in range(height))
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b""))
def _size_in(archive):
with zipfile.ZipFile(archive) as z:
head = z.read(_FILE)[:24]
return list(struct.unpack(">II", head[16:24]))
def _own_archive(tmp_path):
from invisible_core._fpforge.profile import branding_archive
with zipfile.ZipFile(branding_archive("official")) as z:
entries = {n: z.read(n) for n in z.namelist()}
entries[_FILE] = _png(*_MINE)
path = tmp_path / "mine.zip"
with zipfile.ZipFile(path, "w") as z:
for name, data in entries.items():
z.writestr(name, data)
return path
def _load(firefox_binary, url, pin):
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, pin=pin) as browser:
page = browser.new_page()
page.goto(url)
return page.evaluate(LOAD, URLS)
def test_the_branding_a_page_loads_is_the_declared_archive(firefox_binary, fixture_server, tmp_path):
from invisible_core._fpforge.profile import branding_archive
retail = _size_in(branding_archive("official"))
assert retail != list(_MINE), retail
shipped = _load(firefox_binary, fixture_server + "/from-network", None)
assert shipped == {"chrome": retail, "resource": retail}, (shipped, retail)
# Control: another declared archive is the one a page sees, through both ways.
own = _load(firefox_binary, fixture_server + "/from-network", {"branding": str(_own_archive(tmp_path))})
assert own == {"chrome": list(_MINE), "resource": list(_MINE)}, own
assert own != shipped, (own, shipped)
@@ -108,3 +108,83 @@ def test_the_engine_waits_the_declared_time_and_never_asks_the_host(firefox_bina
declared = generate_profile(_SEED).hardware.media_enumeration_ms
assert text.count("declared wait: %d ms" % declared) == 1, text[-2000:]
assert "host speakers asked: yes" not in text, text[-2000:]
# --- the two ways the declaration is told apart from its absence ------------
# The engine's hook is the pref `zoom.stealth.media.enumeration_ms`: non-zero,
# the speakers are not asked of the host (neither for the list nor for the
# groupId correlation of a camera) and the first list waits the declared time;
# 0, Firefox's own path. 0 is the negative control of both tests below.
#: A time no host has: the declaration, not a coincidence of the machine.
_DECLARED_MS = 777
#: Camera only: the correlation of a camera's groupId with the speakers
#: (MediaManager::EnumerateRawDevices) runs after a video stream was granted.
CAMERA_ONLY = """async () => {
const stream = await navigator.mediaDevices.getUserMedia({video: true});
const list = await navigator.mediaDevices.enumerateDevices();
stream.getTracks().forEach(t => t.stop());
return list.map(d => d.kind).join(',');
}"""
def _engine_log(firefox_binary, tmp_path, monkeypatch, name, script, enumeration_ms):
"""Launch with the enumeration declared as `enumeration_ms` (0 = not
declared), run `script` on a page of 127.0.0.1 and return the text the
engine logged (MOZ_LOG=StealthMediaEnumeration) together with the result."""
from invisible_playwright import InvisiblePlaywright
log = tmp_path / name
monkeypatch.setenv("MOZ_LOG", "sync,StealthMediaEnumeration:4")
monkeypatch.setenv("MOZ_LOG_FILE", str(log))
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Page)
srv.daemon_threads = True
threading.Thread(target=srv.serve_forever, daemon=True).start()
try:
with InvisiblePlaywright(
seed=_SEED, binary_path=firefox_binary, headless=True,
extra_prefs={"zoom.stealth.media.enumeration_ms": enumeration_ms,
# getUserMedia without a prompt, as the fake devices are
# asked for by a page of a test
"media.navigator.permission.disabled": True}) as browser:
page = browser.new_page()
page.goto("http://127.0.0.1:%d/" % srv.server_address[1])
result = page.evaluate(script)
finally:
srv.shutdown()
text = "".join(open(f, encoding="utf-8", errors="replace").read()
for f in glob.glob(str(log) + "*"))
return text, result
def test_the_enumeration_with_no_declaration_does_not_wait_and_asks_the_host(
firefox_binary, tmp_path, monkeypatch):
"""Negative control of the declared wait: the same seed and the same four
calls with the declaration at 0 log no declared wait and ask the host's
speakers; with it declared they log ONE wait and never ask them."""
if _engine_release() < 57:
pytest.skip("the engine logs the enumeration from firefox-57")
declared, _ = _engine_log(firefox_binary, tmp_path, monkeypatch, "on", MEASURE, _DECLARED_MS)
undeclared, rows = _engine_log(firefox_binary, tmp_path, monkeypatch, "off", MEASURE, 0)
assert declared.count("declared wait: %d ms" % _DECLARED_MS) == 1, declared[-2000:]
assert "host speakers asked: yes" not in declared, declared[-2000:]
assert "declared wait" not in undeclared, undeclared[-2000:]
assert "host speakers asked: yes" in undeclared, undeclared[-2000:]
# The list is still a list of the session's devices without the declaration.
assert len(rows) == 4 and all("audioinput" in k and "videoinput" in k for _t, k in rows), rows
def test_the_camera_only_enumeration_never_asks_the_host_speakers(
firefox_binary, tmp_path, monkeypatch):
"""The path of the groupId correlation: a camera granted, then a list. With
the enumeration declared the host's speakers are never asked; at 0 they
are (the negative control: without the declaration the hook is the only
difference)."""
if _engine_release() < 57:
pytest.skip("the engine logs the enumeration from firefox-57")
declared, kinds = _engine_log(firefox_binary, tmp_path, monkeypatch, "on", CAMERA_ONLY, _DECLARED_MS)
undeclared, _ = _engine_log(firefox_binary, tmp_path, monkeypatch, "off", CAMERA_ONLY, 0)
assert "videoinput" in kinds, kinds
assert "host speakers asked: yes" not in declared, declared[-2000:]
assert "host speakers asked: yes" in undeclared, undeclared[-2000:]
@@ -0,0 +1,51 @@
"""The code a client evaluates in the page is not named "debugger eval code".
Juggler's `Runtime.evaluate` runs the client's script through the debugger
(`Debugger.Object.executeInGlobal`), and SpiderMonkey names such a script
"debugger eval code" and gives it the introduction type "debugger eval". A page
reads the name from `new Error().stack` on a call it made inside an evaluation
of the client, and no retail Firefox has a frame with that name. The engine's
hook (js/src/debugger, `fingerprint/js-surface/eval-name`) gives the default
name "eval code" and the type "eval"; a name given by the caller still wins.
Negative control: a script that names itself (`//# sourceURL=`) is read back
with the name it gave, untouched, next to the one the engine gives to a script
that names nothing, so the default is the only name that changed. (A filename
passed to `executeInGlobal` by a caller is not reachable from a page; the
display URL is the name a caller can give.) Runs the same on Linux and Windows.
"""
from __future__ import annotations
import pytest
pytestmark = pytest.mark.e2e
_CALLER_NAME = "caller-named-script.js"
def _stacks(firefox_binary):
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True) as browser:
page = browser.new_page()
page.goto("about:blank")
return {
"expression": page.evaluate("new Error().stack"),
"function": page.evaluate("() => new Error().stack"),
"named": page.evaluate("new Error().stack\n//# sourceURL=%s" % _CALLER_NAME),
}
def test_the_evaluated_code_has_no_debugger_name(firefox_binary):
stacks = _stacks(firefox_binary)
for how in ("expression", "function"):
stack = stacks[how]
assert "debugger eval" not in stack, (how, stack)
# What the engine gives instead: the name retail gives to evaluated code.
assert "eval code" in stack, (how, stack)
# Control: the name the caller gave is the one read, and it replaces the
# default one, which is therefore the only name the hook changes.
assert _CALLER_NAME in stacks["named"], stacks["named"]
assert "debugger eval" not in stacks["named"], stacks["named"]
assert "eval code" not in stacks["named"], stacks["named"]
assert _CALLER_NAME not in stacks["expression"], stacks["expression"]
+53
View File
@@ -46,3 +46,56 @@ def test_the_voices_are_retail_windows_in_its_order_and_none_is_the_default(
page = browser.new_page()
page.goto("about:blank")
assert page.evaluate(READ) == RETAIL
# --- voiceURI: the retail form, and what an empty declaration falls to ------
# Retail Windows Firefox's SAPI backend names a voice `urn:moz-tts:sapi:<name>?<lang>`;
# the engine builds that string from the declared list (the hook of
# dom/media/webspeech/synth: StealthSpeechVoices, StealthSpeechVoice). With the
# pref empty the engine does not answer: Firefox's own path reads the host's
# registry (Windows) or speech-dispatcher (Linux).
READ_URIS = """() => speechSynthesis.getVoices().map(v => [v.name, v.voiceURI])"""
#: A voice no host has: the declaration, not a coincidence of the machine.
_ONLY = "Zaphod Quux - English (United States)"
def _uris(firefox_binary, extra_prefs):
"""The voices a page reads: asked until the list is not empty (the engine's
answer is there at once; the host's comes when the host's service has loaded
and may be empty, so the deadline is the end of the wait, not a failure)."""
from _waits import wait_until
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True,
locale="en-US", timezone="America/New_York",
extra_prefs=extra_prefs) as browser:
page = browser.new_page()
page.goto("about:blank")
def pump():
page.wait_for_timeout(100) # the events of a sync client are delivered while it calls the browser
wait_until(lambda: page.evaluate(READ_URIS), 30, pump)
return page.evaluate(READ_URIS)
def test_the_voice_uri_is_the_retail_form_and_an_empty_list_falls_to_the_registry(
firefox_binary):
declared = _uris(firefox_binary, None)
assert declared == [[name, "urn:moz-tts:sapi:%s?en-US" % name] for name, *_ in RETAIL], declared
assert not any(uri.startswith("stealth") for _n, uri in declared), declared
# The declaration is what answers: a one-voice list is the whole answer.
one = _uris(firefox_binary, {"zoom.stealth.voices.list": "%s|en-US|0|1" % _ONLY})
assert one == [[_ONLY, "urn:moz-tts:sapi:%s?en-US" % _ONLY]], one
# Negative control: the same launch with the list empty is not answered by
# the engine. Whatever the host's registry (Windows) or speech-dispatcher
# (Linux) lists, it is not the declared voice, and no URI is of the engine's
# internal `stealth` form.
empty = _uris(firefox_binary, {"zoom.stealth.voices.list": ""})
assert all(name != _ONLY for name, _uri in empty), empty
assert not any(uri.startswith("stealth") for _n, uri in empty), empty
assert empty != one, (empty, one)