Compare commits

..
3 changed files with 279 additions and 467 deletions

No files matched your search

+279
View File
@@ -0,0 +1,279 @@
"""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"
-361
View File
@@ -1,361 +0,0 @@
"""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
@@ -1,106 +0,0 @@
"""``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])