Compare commits

...
Author SHA1 Message Date
feder-cr 4161449bee ci: the drive gate launches through the core (the engine waits for the session's road; bare Playwright never sends it); the declaration test does not resolve an engine 2026-11-12 03:19:43 +01:00
feder-crandClaude Sonnet 5.5 fd564c38f4 tests: the chain by name declares the FakeDoh's own provider (doh.gateway.test): the DoH of Mozilla is HSTS-preloaded and takes no override
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:07:23 +01:00
feder-crandClaude Sonnet 5.5 d84f24b6e5 tests: the fake DoH of the e2e uses a name that is not HSTS-preloaded (doh.gateway.test at 192.0.2.53), declared through extra_prefs
Firefox refuses certificate overrides for HSTS-preloaded/pinned hosts, so a self-signed fake for
mozilla.cloudflare-dns.com could never be accepted. The test now declares its own provider
(network.trr.uri, network.trr.bootstrapAddr) and counts every connection of the browser, including
the background traffic of the default context whose TLS fails by design, at the gateways.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:04:44 +01:00
9 changed files with 177 additions and 119 deletions

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
[
{"id": "wrapper.e2e.udp", "giro": "G2", "os": ["linux", "windows"], "min_tests": 51, "exact": true, "tests": ["tests/test_the_whole_udp_chain_by_name_e2e.py", "tests/test_declared_host_network_e2e.py", "tests/test_http3_through_the_proxy_e2e.py", "tests/test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_e2e.py", "tests/test_networkidle_through_a_served_browser_with_routes_e2e.py", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_webrtc_realness.py::test_a_host_with_ipv6_addresses_gathers_through_an_ipv4_relay", "tests/test_webrtc_realness.py::test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_its_relay", "tests/test_webrtc_realness.py::test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far_away", "tests/test_webrtc_realness.py::test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server", "tests/test_webrtc_realness.py::test_two_contexts_with_two_proxies_each_gets_the_srflx_of_its_own", "tests/test_webrtc_realness.py::test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context", "tests/test_webrtc_realness.py::test_a_proxy_that_does_not_relay_udp_gives_no_srflx_at_all"], "marker": "e2e", "needs_root": false, "note": "Needs the candidate binary (STEALTHFOX_E2E_BINARY) and the engine that carries the UDP line. 51 = 1+7+2+1+21 from the five files + 19 from the 8 UDP-line tests of test_webrtc_realness.py (parametrized)."},
{"id": "wrapper.e2e.doh", "giro": "G2", "os": ["linux", "windows"], "min_tests": 8, "exact": true, "tests": ["tests/test_doh_through_the_proxy_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux needs root: the resolver trap of the file (ResolverTrap) points /etc/resolv.conf at a counting resolver on port 53. Su Windows il resolver trap non gira: l'asserzione sul resolver di sistema è l'unica omessa. Run it without xdist (port 53 is one per host). On the Linux leg the gate exports INVPW_REQUIRE_TRAP=1: a trap that cannot run or bind port 53 is a failure, not a skipped assertion."},
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 92, "exact": true, "tests": ["tests/test_the_udp_chain_helper.py", "tests/test_the_fake_doh_answers.py", "tests/test_doh_session_prefs_unit.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added."}
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 95, "exact": true, "tests": ["tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_fake_doh_answers.py", "tests/test_doh_session_prefs_unit.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added."}
]
+19 -34
View File
@@ -3,8 +3,20 @@
A raw `firefox --screenshot` proves nothing about automation: a juggler-less
binary renders a screenshot just fine and ships broken (firefox-8 did exactly
that). This DRIVES the binary the way users will - Playwright launches it over
the juggler pipe and exercises real paths.
that). This DRIVES the binary the way users will - the wrapper (and the core under
it) launches it over the juggler pipe and exercises real paths.
⛔ THROUGH THE CORE, NOT THROUGH BARE PLAYWRIGHT. Since firefox-63 the engine holds
every channel that asks the proxy service until the client has said how the
session leaves the host (`Browser.setBrowserProxy`, or the explicit
`Browser.setNoBrowserProxy` of a session without a proxy): nothing may leave the
host before that. Stock Playwright sends the first only when it is given a proxy,
so a bare `p.firefox.launch_persistent_context(executable_path=...)` navigates
nowhere: run 43134774602, `Page.goto: Timeout 30000ms` on every leg, three
attempts. The core's launch sends the decision FIRST, and declares the first run
(terms of use, pre-onboarding) that this script used to copy into user.js, so
the copy is gone with it. The job installs the core under test (core_ref, from
git) and the wrapper, and seals the binary, before this script runs.
Three levels (see `--click` / `--full`):
@@ -60,31 +72,9 @@ Exit 0 + "DRIVE GATE OK ..." on success; non-zero with a reason on failure.
from __future__ import annotations
import http.server
import json
import shutil
import socketserver
import sys
import tempfile
import threading
from pathlib import Path
# ⛔ THE FIRST RUN IS DECLARED HERE, A COPY OF THE CORE'S, written into the
# profile's user.js. Since firefox-55 the engine leaves Mozilla's first-run
# lines and invisible_core declares the state (terms of use accepted long ago,
# pre-onboarding off). This job installs only Playwright, so nothing declared
# it: measured 2026-11-02 on run 41388672849, Windows showed the terms-of-use
# modal ("the page did not handle mouse event") and Linux opened
# https://www.mozilla.org/en-US/privacy/firefox/ in a second tab (the legacy
# data-reporting flow) ("Unexpected number of tabs in the new window: 2").
# Upstream Playwright sends its own defaults in Browser.enable, which this
# engine refuses, so a raw launch runs on Mozilla's lines alone. With these
# three in user.js, both legs drive. tests/test_ci_drive_gate_first_run.py
# ties the copy to the core.
FIRST_RUN = {
"browser.preonboarding.enabled": False,
"termsofuse.acceptedVersion": 4,
"termsofuse.acceptedDate": "1785573000000",
}
HTML = (
"<!doctype html><html><head><title>dt</title></head><body>"
@@ -155,16 +145,12 @@ def _drive(exe: str, url: str, level: str) -> str:
"""One run. `level` is "smoke", "click" or "full". Returns the UA."""
interacts = level in ("click", "full")
full = level == "full"
from playwright.sync_api import sync_playwright
from invisible_playwright import InvisiblePlaywright
# A user.js is read at startup, before the window that would carry the
# modal; a persistent context is the only way to hand Playwright a profile.
profile_dir = Path(tempfile.mkdtemp(prefix="ci-drive-gate-"))
(profile_dir / "user.js").write_bytes(
"".join("user_pref(%s, %s);\n" % (json.dumps(k), json.dumps(v))
for k, v in sorted(FIRST_RUN.items())).encode("utf-8"))
with sync_playwright() as p:
ctx = p.firefox.launch_persistent_context(str(profile_dir), executable_path=exe, headless=True)
# The core declares the first run and sends the session's road before anything else; the seal of the binary is
# INVISIBLE_SEAL_FILE (the job sets it), and `binary_path` is the binary under test.
with InvisiblePlaywright(seed=42, binary_path=exe, headless=True, humanize=False) as browser:
ctx = browser.new_context()
try:
page = ctx.new_page()
resp = page.goto(url, wait_until="load")
@@ -192,7 +178,6 @@ def _drive(exe: str, url: str, level: str) -> str:
inter["plugins"] = page.evaluate("() => navigator.plugins instanceof PluginArray")
finally:
ctx.close()
shutil.rmtree(profile_dir, ignore_errors=True)
# SMOKE asserts (always).
assert "Firefox" in ua, f"unexpected UA (binary not driving correctly): {ua!r}"
+21 -10
View File
@@ -2,18 +2,23 @@
Hermetic: loopback only, no DNS, no internet. Nothing here knows about the product.
What a proxied session declares (core-19) is that every name the browser resolves goes to the DoH of Firefox
(``network.trr.mode`` 3), at ``https://mozilla.cloudflare-dns.com/dns-query``, found with no DNS at the address
``network.trr.bootstrapAddr`` (162.159.61.4), and that the DoH request is a channel like any other, so it leaves
THROUGH the proxy of the context of the lookup. A test of that needs three things this file builds:
What the core declares (core-19), for every session, is the DoH of Firefox at
``https://mozilla.cloudflare-dns.com/dns-query``, found with no DNS at the address ``network.trr.bootstrapAddr``
(162.159.61.4). A test does NOT impersonate that host: Firefox refuses a certificate override for an HSTS-preloaded or
pinned host (``mozilla.cloudflare-dns.com`` is one), so a self-signed certificate for it can never be accepted, whatever
``ignore_https_errors`` says. The test declares its own provider instead, through the core's ``extra_prefs`` overlay:
``network.trr.uri`` = ``https://doh.gateway.test/dns-query`` (a ``.test`` name, never preloaded) and
``network.trr.bootstrapAddr`` = ``192.0.2.53`` (TEST-NET-1, so nothing real is addressed). With a proxy the engine turns it on (``network.trr.mode`` 3, derived from the proxies it receives, never
written by the core), so every name the browser resolves goes to it; the DoH request is a channel like any other, so it
leaves THROUGH the proxy of the context of the lookup. A test of that needs three things this file builds:
* :class:`FakeDoh` - the DoH server. RFC 8484 (POST ``application/dns-message`` and GET ``?dns=base64url``) over TLS
with a certificate for ``mozilla.cloudflare-dns.com`` and ``127.0.0.1``, written by hand: the question is parsed from
with a certificate for ``doh.gateway.test`` and ``127.0.0.1``, written by hand: the question is parsed from
its labels and the answer is built byte by byte (header, the question copied, one A record, TTL 30). It answers
HTTP/2 when the ``h2`` package is importable and ALPN selects it (Firefox's TRR speaks h2), HTTP/1.1 otherwise.
Every query is recorded as ``(name, qtype, via)``.
* :class:`DohGateway` - a SOCKS5 gateway (the ``Gateway`` of ``_socks_servers``) whose CONNECT to the DoH address
(``162.159.61.4:443``, or ``mozilla.cloudflare-dns.com:443`` by name) is handed to the FakeDoh of the test, with the
(``192.0.2.53:443``, or ``doh.gateway.test:443`` by name) is handed to the FakeDoh of the test, with the
gateway's name as ``via``; every other CONNECT to a loopback address is relayed for real. It never resolves a name
itself and never reaches a non-loopback address: a CONNECT that asks for one is refused and recorded, so a test run
cannot leak anything and cannot be mistaken for leaking.
@@ -48,11 +53,17 @@ try: # the HTTP/2 side needs it; a test that wants h2 says pytest.importorskip(
except ImportError: # pragma: no cover - depends on the environment
H2_AVAILABLE = False
#: The host name of the DoH the session declares, and the address it is found at without DNS.
DOH_HOST = "mozilla.cloudflare-dns.com"
DOH_BOOTSTRAP = "162.159.61.4"
#: The host name of the DoH the TEST declares (``network.trr.uri``) and the address it is found at without DNS
#: (``network.trr.bootstrapAddr``). Not the core's default provider: that host is HSTS-preloaded/pinned, so Firefox
#: refuses any certificate override for it and a fake could never be accepted. A ``.test`` name is on no preload list;
#: 192.0.2.0/24 is TEST-NET-1 (RFC 5737), reserved for documentation, so the address cannot reach anything real.
DOH_HOST = "doh.gateway.test"
DOH_BOOTSTRAP = "192.0.2.53"
DOH_PORT = 443
DOH_PATH = "/dns-query"
#: The two prefs that make a session use the FakeDoh as its provider (applied with ``extra_prefs``).
DOH_PROVIDER_PREFS = {"network.trr.uri": "https://%s%s" % (DOH_HOST, DOH_PATH),
"network.trr.bootstrapAddr": DOH_BOOTSTRAP}
#: Every CONNECT target the gateways hand to the FakeDoh.
DOH_TARGETS = frozenset({(DOH_BOOTSTRAP, DOH_PORT), (DOH_HOST, DOH_PORT)})
@@ -591,7 +602,7 @@ def _recv_exact(s: socket.socket, n: int) -> bytes:
__all__ = [
"DOH_BOOTSTRAP", "DOH_HOST", "DOH_PATH", "DOH_PORT", "DOH_TARGETS", "DOH_TTL", "H2_AVAILABLE", "QTYPE_A",
"DOH_BOOTSTRAP", "DOH_HOST", "DOH_PATH", "DOH_PORT", "DOH_PROVIDER_PREFS", "DOH_TARGETS", "DOH_TTL", "H2_AVAILABLE", "QTYPE_A",
"QTYPE_AAAA", "RCODE_NXDOMAIN", "RCODE_OK", "RCODE_REFUSED", "DohGateway", "DohQuery", "FakeDoh", "Query",
"answer_for", "build_response", "encode_query", "is_loopback", "make_certificate", "parse_query", "pump",
"relay", "wait_until",
+1 -1
View File
@@ -4,7 +4,7 @@ The counterpart of :class:`_doh_servers.DohGateway` for the ``http`` scheme:
* a request without a valid ``Proxy-Authorization: Basic`` gets ``407`` with ``Proxy-Authenticate: Basic`` (the
connection is closed, as many real proxies do); the right credentials get through;
* ``CONNECT`` to the DoH address (``162.159.61.4:443`` or ``mozilla.cloudflare-dns.com:443``) is answered ``200``
* ``CONNECT`` to the DoH address (``192.0.2.53:443`` or ``doh.gateway.test:443``) is answered ``200``
and handed to the FakeDoh with ``via=name``; ``CONNECT`` to a loopback address is relayed for real; any other
CONNECT is refused (``403``) and recorded;
* a plain ``GET http://host:port/path`` (the form a browser sends to an HTTP proxy for an ``http`` page: the NAME
-47
View File
@@ -1,47 +0,0 @@
"""The drive gate's copy of the first-run declaration must not diverge from the core.
`scripts/ci_drive_gate.py` runs in a job that installs only Playwright, so it
carries FIRST_RUN, a literal copy of what invisible_core declares for the first
run, and writes it into the profile's user.js. Since firefox-55 the engine leaves
Mozilla's first-run lines and the core alone declares that state: without the
copy, run 41388672849 (2026-11-02) showed the terms-of-use modal on Windows
(no mouse event reached the page) and opened Mozilla's privacy page in a second
tab on Linux. This test binds the copy: a first-run pref the core adds, drops or
changes turns it red.
"""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
_GATE = Path(__file__).resolve().parents[1] / "scripts" / "ci_drive_gate.py"
_FIRST_RUN_PREFIXES = ("termsofuse.", "browser.preonboarding.", "datareporting.policy.")
def _first_run_from_gate() -> dict:
"""FIRST_RUN as the gate defines it, without importing Playwright (imported
inside `_drive`)."""
ns: dict = {}
head = _GATE.read_text(encoding="utf-8").split("\nHTML = (")[0]
exec(compile(head, str(_GATE), "exec"), ns) # noqa: S102 - our own file
return ns["FIRST_RUN"]
@pytest.mark.unit
@pytest.mark.parametrize("platform", ["win32", "linux"])
def test_ci_drive_gate_first_run_matches_the_core(monkeypatch, platform):
from invisible_core._fpforge import generate_profile
from invisible_core.prefs import translate_profile_to_prefs
monkeypatch.setattr(sys, "platform", platform)
prefs = translate_profile_to_prefs(generate_profile(970411), timezone="America/New_York")
from_core = {k: v for k, v in prefs.items() if k.startswith(_FIRST_RUN_PREFIXES)}
from_gate = _first_run_from_gate()
assert from_core, "the core declares no first-run state: the engine would show the modal"
assert from_gate == from_core, (
"FIRST_RUN in scripts/ci_drive_gate.py is no longer what invisible_core declares.\n"
" core: %r\n gate: %r" % (from_core, from_gate))
for k, v in from_gate.items():
assert type(v) is type(from_core[k]), k
@@ -0,0 +1,53 @@
"""The drive gate launches the binary through the wrapper and the core, never through bare Playwright.
Since firefox-63 the engine holds every channel that asks the proxy service until the client has said how the session
leaves the host (`Browser.setBrowserProxy`, or `Browser.setNoBrowserProxy` for a session without a proxy). The core's launch
sends that decision first; stock Playwright sends it only when it is given a proxy. A drive gate that launches with
`p.firefox.launch_persistent_context(executable_path=...)` therefore waits for a decision nobody takes: run 43134774602,
`Page.goto: Timeout 30000ms` on every leg, three attempts.
The core also declares the first run (terms of use, pre-onboarding), which the gate used to copy into user.js
(`FIRST_RUN`, tied to the core by a test of its own): with the launch through the core the copy has no reason to exist.
This test reads the script; it launches nothing.
"""
from __future__ import annotations
import ast
from pathlib import Path
import pytest
_GATE = Path(__file__).resolve().parents[1] / "scripts" / "ci_drive_gate.py"
def _tree() -> ast.Module:
return ast.parse(_GATE.read_text(encoding="utf-8"))
@pytest.mark.unit
def test_the_drive_gate_imports_no_playwright_client():
imported = []
for node in ast.walk(_tree()):
if isinstance(node, ast.Import):
imported += [a.name for a in node.names]
elif isinstance(node, ast.ImportFrom):
imported.append(node.module or "")
bare = [m for m in imported if m == "playwright" or m.startswith("playwright.")]
assert not bare, "the drive gate imports %s: a bare Playwright never tells the engine the road of the session" % bare
@pytest.mark.unit
def test_the_drive_gate_launches_with_the_wrapper_on_the_binary_under_test():
calls = [n for n in ast.walk(_tree()) if isinstance(n, ast.Call)
and getattr(n.func, "id", getattr(n.func, "attr", None)) == "InvisiblePlaywright"]
assert len(calls) == 1, "the drive gate must launch with InvisiblePlaywright, once"
keywords = {k.arg: k.value for k in calls[0].keywords}
assert isinstance(keywords.get("binary_path"), ast.Name) and keywords["binary_path"].id == "exe", \
"the binary under test is the gate's argument, handed over as binary_path="
assert isinstance(keywords.get("headless"), ast.Constant) and keywords["headless"].value is True
@pytest.mark.unit
def test_the_drive_gate_keeps_no_copy_of_the_first_run_declaration():
names = {t.id for n in ast.walk(_tree()) if isinstance(n, ast.Assign) for t in n.targets if isinstance(t, ast.Name)}
assert "FIRST_RUN" not in names, "the core declares the first run; a copy in the gate can only drift from it"
+72 -23
View File
@@ -1,11 +1,17 @@
"""E2E: behind a proxy every name is resolved by Firefox's DoH THROUGH the proxy, and nothing leaves the host.
WRITTEN AGAINST THE CONTRACT, BEFORE THE ENGINE THAT KEEPS IT EXISTS. No binary in this tree has the behaviour yet, so
these tests cannot go green here; what is proven now is that the tools they stand on are right
(`test_the_fake_doh_answers.py`, `test_the_http_proxy_helper_asks_for_credentials.py`,
`test_the_leak_watcher_sees_a_direct_connection.py`) and that the session declares what the contract starts from
(`test_doh_session_prefs_unit.py`). Run against an engine that keeps the contract, they are the proof; run against one
that does not, each of them fails on the thing it names.
Hermetic on a real binary. The tools they stand on are proven by `test_the_fake_doh_answers.py`,
`test_the_http_proxy_helper_asks_for_credentials.py` and `test_the_leak_watcher_sees_a_direct_connection.py`, and the
session declaration they start from by `test_doh_session_prefs_unit.py`. Run against an engine that keeps the contract,
they are the proof; run against one that does not, each of them fails on the thing it names.
The fake DoH is NOT `mozilla.cloudflare-dns.com`. That host is HSTS-preloaded/pinned, and Firefox refuses any
certificate override for such a host ("HSTS or pinned host - no overrides allowed", MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT),
so a self-signed fake for it is rejected whatever `ignore_https_errors` says. The test declares its own provider through
the core's `extra_prefs` overlay (applied last, documented for this): `network.trr.uri` = `https://doh.gateway.test/
dns-query` (a `.test` name is on no preload list) and `network.trr.bootstrapAddr` = `192.0.2.53` (TEST-NET-1: the
address of the FakeDoh as a gateway knows it, never a real one). The gateways map a CONNECT to that address (or name) to
the FakeDoh. The core's own default provider is checked by `test_doh_session_prefs_unit.py`, not here.
The contract (core-19 and motore-18): a PROXIED session declares TRR mode 3 (`network.trr.uri` the DoH of Mozilla,
`network.trr.bootstrapAddr` an address so the DoH host is found with no DNS, `network.proxy.allow_bypass` false).
@@ -32,8 +38,11 @@ accept the FakeDoh certificate: the pages are opened in contexts made with `igno
implements per user context (`Browser.setIgnoreHTTPSErrors` -> `nsICertOverrideService`, keyed by the origin attributes
of the TLS socket), and a DoH request of a lookup carries the user context of that lookup
(`StealthApplyTRRContextToChannel`). So the lookups of THESE contexts accept the certificate; a lookup of the default
context (user context 0: the browser's own background resolutions) cannot be made to, and mode 3 does not need it. This
is why a test says "a context with no proxy of its own" where the brief says "the default context".
context (user context 0: the browser's own background resolutions, telemetry and the like) cannot be made to, and mode 3
does not need it: those lookups fail against the FakeDoh BY DESIGN, so no assertion here counts the FakeDoh's TLS
failures or treats a name of the default context as a result; every assertion is about the names and the contexts the
test itself creates. This is why a test says "a context with no proxy of its own" where the brief says "the default
context".
Assumptions that could not be verified without the engine, each one the first place to look if a test fails for no
visible reason: (1) the TRR channel of a lookup in a context honours `ignore_https_errors` of that context; (2) the
@@ -58,7 +67,7 @@ from invisible_playwright import InvisiblePlaywright
import _doh_servers as ds
import _trap_policy
from _doh_servers import DOH_BOOTSTRAP, DOH_HOST, DOH_PORT, QTYPE_A, DohGateway, FakeDoh
from _doh_servers import DOH_BOOTSTRAP, DOH_HOST, DOH_PORT, DOH_PROVIDER_PREFS, QTYPE_A, DohGateway, FakeDoh
from _http_proxy import HttpProxy, basic
from _leaks import ResolverTrap, Watcher
from _servers import LocalServer
@@ -69,7 +78,9 @@ pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
ZONE = {"page-a.test": "127.0.0.1", "page-b.test": "127.0.0.1", "page-c.test": "127.0.0.1",
"stun-a.test": "127.0.0.1"}
#: Loopback targets go through the proxy too (as in test_proxy_socks_auth_e2e.py), so the road of a page is observable.
PREFS = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": ""}
#: The two `network.trr.*` entries replace the core's default provider (a preloaded host whose certificate cannot be
#: overridden) with the FakeDoh's: https://doh.gateway.test/dns-query, found at 192.0.2.53 with no DNS.
PREFS = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": "", **DOH_PROVIDER_PREFS}
#: The helper processes of Firefox that a session behind a proxy must never start (match on the executable's stem).
HELPERS = ("crashreporter", "default-browser-agent", "maintenanceservice", "updater", "pingsender")
GEO = SessionGeo("America/New_York", "203.0.113.7", latitude=40.7128, longitude=-74.0060,
@@ -209,7 +220,7 @@ def _why(doh, *proxies):
"""What every side saw, for the message of a failed assertion."""
lines = ["FakeDoh queries: %s" % [tuple(q) for q in doh.queries],
"FakeDoh connections (via, protocol): %s" % doh.connections,
"FakeDoh TLS failures: %s" % doh.tls_failures]
"FakeDoh TLS failures (the default context's background lookups fail by design): %s" % doh.tls_failures]
for p in proxies:
lines.append("%s CONNECTs: %s" % (p.name, p.connects))
if getattr(p, "refused", None):
@@ -225,8 +236,42 @@ def _is_address(host):
return False
def _assert_stayed_home(watcher, trap=None):
"""Nothing went past the gateway (no direct connection) and nothing asked the machine's resolver."""
def _assert_every_connection_went_through_the_gateway(doh, *proxies):
"""Every connection the browser made, the test's own and the background traffic of the default context, is
accounted for at a gateway, and none reached the FakeDoh by another road.
The background lookups of the default context (telemetry and the like) have no `ignore_https_errors`, so their TLS
handshake with the FakeDoh fails BY DESIGN. That is an expected outcome, counted here, not ignored:
* the FakeDoh served no connection (successful or failed) by `direct`: each one arrived by a named gateway;
* per gateway, the connections the FakeDoh served (completed + failed handshakes) are all tunnels of a DoH CONNECT
that the gateway itself recorded (it records the CONNECT before it hands the socket over), so none is
unaccounted for: served <= recorded DoH CONNECTs;
* no CONNECT of any gateway carries the name of the test's own zone (the browser resolves those with the DoH and
connects by address); a CONNECT to some other non-loopback target is listed by the gateway in `refused`, i.e. it
was attempted THROUGH the gateway and went no further, which is the point.
"""
why = _why(doh, *proxies)
names = {p.name for p in proxies}
served = list(doh.connections) + [(via, "tls-failed") for via, _error in doh.tls_failures]
by_road = {via for via, _what in served}
assert by_road <= names, "the FakeDoh served a connection by a road that is no gateway of the test: %s" % (
sorted(by_road - names)) + why
for proxy in proxies:
mine = [what for via, what in served if via == proxy.name]
recorded = len(proxy.doh_connects())
assert len(mine) <= recorded, (
"%s: the FakeDoh served %d connection(s) (%d failed handshakes) but the gateway recorded only %d DoH "
"CONNECT(s)" % (proxy.name, len(mine), mine.count("tls-failed"), recorded) + why)
zone_names = [h for h, _p in proxy.connects if h.lower() in ZONE]
assert zone_names == [], "%s was sent the NAME %s instead of an address" % (proxy.name, zone_names) + why
def _assert_stayed_home(watcher, trap=None, doh=None, *proxies):
"""Nothing went past the gateway (no direct connection), nothing asked the machine's resolver, and (when the
FakeDoh and the proxies are given) every connection is accounted for at a gateway."""
if doh is not None:
_assert_every_connection_went_through_the_gateway(doh, *proxies)
assert watcher.watched_pids, ("the watcher never saw a browser process (it saw: %s): a watcher that cannot see "
"proves nothing" % watcher.process_names)
assert watcher.direct == [], "the browser connected past the gateway: %s" % watcher.describe()
@@ -265,7 +310,7 @@ def test_names_resolve_through_doh_by_the_proxy(firefox_binary, doh, pages, gate
"a CONNECT carried a name: the browser must resolve with the DoH and connect by address" + why)
assert ("127.0.0.1", pages.port) in gw1.connects, "the page was not reached by address through gw1" + why
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy" + why
_assert_stayed_home(watcher, trap)
_assert_stayed_home(watcher, trap, doh, gw1)
def test_an_ice_server_name_resolves_the_same_way(firefox_binary, doh, pages, gateway, trap, watcher):
@@ -283,7 +328,7 @@ def test_an_ice_server_name_resolves_the_same_way(firefox_binary, doh, pages, ga
why = _why(doh, gw1)
assert asked, "the browser never asked the DoH for the ICE server name" + why
assert doh.vias_of("stun-a.test") == {"gw1"}, "stun-a.test was not asked by gw1 only" + why
_assert_stayed_home(watcher, trap)
_assert_stayed_home(watcher, trap, doh, gw1)
def test_two_contexts_two_doh_exits(firefox_binary, doh, pages, gateway, trap, watcher):
@@ -312,7 +357,7 @@ def test_two_contexts_two_doh_exits(firefox_binary, doh, pages, gateway, trap, w
"gw1 saw: %s" % gw1.credentials_seen)
assert gw2.credentials_seen and set(gw2.credentials_seen) == {("gw2-user", "gw2-pass")}, (
"gw2 saw: %s" % gw2.credentials_seen)
_assert_stayed_home(watcher, trap)
_assert_stayed_home(watcher, trap, doh, gw1, gw2)
def test_an_authenticated_http_proxy_resolves(firefox_binary, doh, pages, trap, watcher):
@@ -346,7 +391,7 @@ def test_an_authenticated_http_proxy_resolves(firefox_binary, doh, pages, trap,
"every DoH CONNECT must carry the preemptive Basic header %r, saw %r" % (expected, authorizations) + why)
assert [s for s in proxy.refused_for_credentials if (s.host, s.port) in ds.DOH_TARGETS] == [], (
"the DoH CONNECT needed a 407 round trip: the header was not preemptive" + why)
_assert_stayed_home(watcher, trap)
_assert_stayed_home(watcher, trap, doh, proxy)
finally:
proxy.close()
@@ -367,7 +412,7 @@ def test_nothing_leaves_the_host_between_launch_and_the_first_command(firefox_bi
why = _why(doh, gw1)
assert "HOST=page-a.test" in text
assert gw1.accepted_at, "the browser never connected to the gateway" + why
_assert_stayed_home(watcher, trap)
_assert_stayed_home(watcher, trap, doh, gw1)
def test_no_helper_process_starts(firefox_binary, doh, pages, gateway, trap, watcher):
@@ -408,13 +453,14 @@ def test_a_dead_proxy_does_not_fall_back(firefox_binary, doh, pages, gateway, tr
"the dead proxy still served a page: %s" % pages.hits + why)
assert doh.queries_for("page-c.test") == [], "page-c.test was resolved after the proxy died" + why
assert gw1.killed and failed.value is not None
_assert_stayed_home(watcher, trap)
_assert_stayed_home(watcher, trap, doh, gw1)
def test_a_session_without_a_proxy_resolves_with_the_system_resolver(firefox_binary, pages, watcher):
"""The negative control: with no proxy the exit is the machine's own network and retail resolves with the system
resolver (mode 0). No `network.trr.*` pref is declared. Where the resolver trap can run (Linux, root) it also sees the
question; where it cannot (Windows) the page is reached by a name the system resolves by itself, and the trap's
resolver (mode 0). The core declares the DoH provider (uri + bootstrapAddr) in every session, but no engine-owned
state (`network.trr.mode` and the other two), so TRR stays off. Where the resolver trap can run (Linux, root) it also sees
the question; where it cannot (Windows) the page is reached by a name the system resolves by itself, and the trap's
assertion is the only one that is not made."""
trapped = ResolverTrap.available
why = _trap_policy.failure(None, trapped, ResolverTrap.reason)
@@ -423,8 +469,11 @@ def test_a_session_without_a_proxy_resolves_with_the_system_resolver(firefox_bin
name = "page-d.test" if trapped else "localhost"
session = InvisiblePlaywright(seed=42, binary_path=firefox_binary, proxy=None)
session._timezone, session._locale = GEO.timezone, GEO.locale
declared = [k for k in session._build_prefs() if k.startswith("network.trr.")]
assert declared == [], "a session without a proxy declared TRR prefs: %s" % declared
prefs = session._build_prefs()
assert prefs.get("network.trr.mode") != 3, "a session without a proxy turned TRR on: %s" % prefs.get("network.trr.mode")
engine_owned = [k for k in ("network.trr.mode", "network.trr.exclude-etc-hosts", "network.trr.excluded-domains")
if k in prefs]
assert engine_owned == [], "a session without a proxy declared engine-owned TRR prefs: %s" % engine_owned
trap = None
if trapped:
@@ -25,8 +25,12 @@ def test_build_env_carries_the_seed_declaration(seed):
@pytest.mark.unit
@pytest.mark.parametrize("proxy", [None, {"server": "socks5://127.0.0.1:1"}])
def test_a_session_declares_its_seed_network_with_or_without_a_proxy(proxy):
def test_a_session_declares_its_seed_network_with_or_without_a_proxy(monkeypatch, proxy):
from invisible_playwright import _session
from invisible_playwright.launcher import InvisiblePlaywright
# Nothing here launches a browser, and the engine is not what is asked about: under a local seal (the gate's, for a
# candidate) there is no engine to download, and resolving one is not this test's business.
monkeypatch.setattr(_session, "resolve_executable", lambda path: pathlib.Path("firefox"))
ip = InvisiblePlaywright(seed=42, proxy=proxy)
assert ip._build_env({})[NETWORK] == network_to_declare(42)
@@ -24,11 +24,14 @@ proxy, so the DoH is never asked (no CONNECT to it reaches the gateway) and the
the handshakes of its associations are serial (each costs round trips of the gateway before a socket is usable).
The browser accepts the certificate of the FakeDoh the way `test_doh_through_the_proxy_e2e.py` does: the page is opened in a
context made with `ignore_https_errors=True` (applied per user context to the DoH request of the lookup of that context).
context made with `ignore_https_errors=True` (applied per user context to the DoH request of the lookup of that context), and
the provider is the FakeDoh's own name (`doh.gateway.test`, declared through `extra_prefs`): the DoH of Mozilla is HSTS-preloaded
and Firefox never accepts an override for it.
"""
import pytest
import _turn_chain as chain_mod
from _doh_servers import DOH_PROVIDER_PREFS
pytestmark = pytest.mark.e2e
@@ -61,7 +64,7 @@ def test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick(gateway,
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(headless=True, binary_path=firefox_binary, timezone="America/New_York", locale="en-US",
proxy=gateway.proxy, extra_prefs=dict(PREFS)) as browser:
proxy=gateway.proxy, extra_prefs={**PREFS, **DOH_PROVIDER_PREFS}) as browser:
page = browser.new_context(ignore_https_errors=True).new_page()
page.goto(gateway.page.url, wait_until="domcontentloaded", timeout=60000)
try: