Compare commits
17
Commits
No files matched your search
@@ -0,0 +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": 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."}
|
||||
]
|
||||
+1
-1
@@ -118,7 +118,7 @@ dependencies = [
|
||||
|
||||
[project.optional-dependencies]
|
||||
remote = ["websockets>=13"]
|
||||
dev = ["websockets>=13", "pytest>=7", "build>=1", "ruff>=0.6", "pytest-rerunfailures>=14", "pytest-timeout>=2", "pytest-xdist>=3", "playwright==1.61.0", "cryptography>=41"]
|
||||
dev = ["websockets>=13", "aioquic>=1.2", "pytest>=7", "build>=1", "ruff>=0.6", "pytest-rerunfailures>=14", "pytest-timeout>=2", "pytest-xdist>=3", "playwright==1.61.0", "cryptography>=41", "h2>=4,<5"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
markers = [
|
||||
|
||||
+19
-34
@@ -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}"
|
||||
|
||||
@@ -0,0 +1,501 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CI verdict - the one judge of the mandatory test suites (stdlib only).
|
||||
|
||||
`ci/required-suites.json` lists the suites a round must run, per operating system, with the number of tests each must
|
||||
collect. A test that is skipped, deselected or never collected is a hole nobody sees, so this script reads the junit
|
||||
pytest wrote and fails on every one of them.
|
||||
|
||||
ci_verdict.py args --required ci/required-suites.json --suite wrapper.e2e.udp --os linux [--with-marker]
|
||||
prints, one per line, the pytest arguments of the suite (files and node ids); with --with-marker, `-m` and the
|
||||
suite's marker come first. An error (exit 2) if the suite does not run on that OS or the list is malformed.
|
||||
|
||||
ci_verdict.py judge --required ci/required-suites.json --suite wrapper.e2e.udp --os linux
|
||||
--junit junit.xml --binary PATH [--commit SHA] [--seal gate.seal.json]
|
||||
[--out result/wrapper.e2e.udp.linux.json]
|
||||
[--main-required PATH | --main-required PATH --main-has-no-list]
|
||||
reads the junit, writes the result json (with `verdict`: "green" or "red") and exits 1, printing EVERY problem
|
||||
with its reason, one per line, when: the junit or the row is missing; the junit is not xunit2 (a testcase with
|
||||
no `classname`); a test failed, errored or was skipped; fewer tests were collected than `min_tests`, or, when
|
||||
the row is `exact`, any number other than `min_tests` (a deselected test is not in the junit: `min_tests` goes
|
||||
up by hand when a test is added, never silently); a required file or node id did not pass; the binary is
|
||||
missing (--binary is mandatory: without it exit 2) or the commit cannot be known; the --seal is unreadable.
|
||||
With --main-required (the list of main) the list only grows: a suite of main is gone, its minimum went down,
|
||||
its `exact` went from true to false, its os or tests lost an element, or its marker changed is red.
|
||||
What the file of main is can be said only by the gate, which checks main out (a failed download is not
|
||||
"main has no list"): the file exists -> it is compared; it does not exist and the gate passed
|
||||
--main-has-no-list (main was checked out and has no such file) -> passed, declared; it does not exist
|
||||
without --main-has-no-list -> RED, "it is not known what main has".
|
||||
The commit is --commit SHA or `git rev-parse HEAD` in the current directory (the checkout of the wrapper),
|
||||
NEVER GITHUB_SHA (in a called workflow it is the commit of the engine's repository). --seal reads the seal of
|
||||
the gate: the seal that `python -m invisible_core seal` writes, and the release seal, carry NO sha256 of the
|
||||
engine binary (an asset's `sha256` is the one of the archive, `omni_sha256` the one of omni.ja), so there is
|
||||
nothing to compare it with: the summary says so and the result records `seal_binary_hash: "absent"`.
|
||||
|
||||
ci_verdict.py complete --required ci/required-suites.json --results DIR
|
||||
DIR holds the result json files `judge` wrote (also in subfolders: one artifact `result-<suite>-<os>` each).
|
||||
Exit 1, one problem per line, when: a (suite, os) of the list has no result; a result is not green; a result
|
||||
is of a (suite, os) that is not in the list, or twice; the commit is not the same in every result, or the
|
||||
binary sha256 is not the same in every result of one OS (or missing).
|
||||
|
||||
The list is validated by all three commands (a malformed one is exit 2, with the reason, never green): ids unique; per
|
||||
row `os` a non-empty subset of {linux, windows}, `tests` a non-empty list of unique strings, `min_tests` an integer > 0,
|
||||
`exact` a bool, `marker` a string, `needs_root` a bool or a list of the row's OSes.
|
||||
|
||||
A required entry of "tests" is a file (at least one test of it must exist and EVERY one collected must pass) or a node
|
||||
id `tests/x.py::name` (that test must pass; a parametrized test is matched on the name before `[`, and every one of its
|
||||
parameters must pass).
|
||||
|
||||
What the gate must do (it is not done here):
|
||||
* run pytest as `env -u PYTEST_ADDOPTS python -m pytest ... -p no:rerunfailures -o junit_family=xunit2
|
||||
--junitxml=junit.xml` (no addopts from outside, no rerun that turns a failure green, a junit that keeps `classname`;
|
||||
a junit with no `classname`, or with `file`/`line`, is red);
|
||||
* on the Linux leg of the DoH suite, export INVPW_REQUIRE_TRAP=1 (the resolver trap must run, never be skipped);
|
||||
* pass --commit or run in the checkout of the wrapper, pass --binary, and check out main before --main-required.
|
||||
|
||||
Exit 0 on a green verdict, 1 on a red one, 2 on a wrong use or a malformed list.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
|
||||
OSES = ("linux", "windows")
|
||||
|
||||
|
||||
class Usage(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class BadList(Usage):
|
||||
"""The required list itself is malformed (exit 2)."""
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------- the required list
|
||||
def _is_int(value):
|
||||
return isinstance(value, int) and not isinstance(value, bool)
|
||||
|
||||
|
||||
def validate_list(data):
|
||||
"""-> the list of reasons why `data` is not a well-formed required list (empty if it is)."""
|
||||
if not isinstance(data, list):
|
||||
return ["the required list must be a JSON list of suites"]
|
||||
if not data:
|
||||
return ["the required list is empty"]
|
||||
problems, seen = [], set()
|
||||
for i, row in enumerate(data):
|
||||
if not isinstance(row, dict):
|
||||
problems.append("row %d is not an object" % i)
|
||||
continue
|
||||
sid = row.get("id")
|
||||
where = "row %d" % i
|
||||
if not isinstance(sid, str) or not sid.strip():
|
||||
problems.append("%s has no id (a non-empty string)" % where)
|
||||
else:
|
||||
where = "row %d (%s)" % (i, sid)
|
||||
if sid in seen:
|
||||
problems.append("%s: the id appears more than once" % where)
|
||||
seen.add(sid)
|
||||
oses = row.get("os")
|
||||
oses_ok = (isinstance(oses, list) and oses and all(isinstance(o, str) for o in oses)
|
||||
and set(oses) <= set(OSES) and len(set(oses)) == len(oses))
|
||||
if not oses_ok:
|
||||
problems.append("%s: os must be a non-empty list of distinct values among %s, not %r"
|
||||
% (where, "/".join(OSES), oses))
|
||||
tests = row.get("tests")
|
||||
if not (isinstance(tests, list) and tests and all(isinstance(t, str) and t.strip() for t in tests)):
|
||||
problems.append("%s: tests must be a non-empty list of non-empty strings" % where)
|
||||
elif len(set(tests)) != len(tests):
|
||||
problems.append("%s: tests has duplicates: %s"
|
||||
% (where, ", ".join(sorted({t for t in tests if tests.count(t) > 1}))))
|
||||
if not _is_int(row.get("min_tests")) or row.get("min_tests") <= 0:
|
||||
problems.append("%s: min_tests must be an integer > 0, not %r" % (where, row.get("min_tests")))
|
||||
if not isinstance(row.get("exact"), bool):
|
||||
problems.append("%s: exact must be true or false, not %r" % (where, row.get("exact")))
|
||||
if not isinstance(row.get("marker"), str) or not row.get("marker").strip():
|
||||
problems.append("%s: marker must be a non-empty string, not %r" % (where, row.get("marker")))
|
||||
root = row.get("needs_root", False)
|
||||
if not isinstance(root, bool):
|
||||
if not (isinstance(root, list) and all(isinstance(o, str) for o in root) and set(root) <= set(OSES)
|
||||
and (not oses_ok or set(root) <= set(oses))):
|
||||
problems.append("%s: needs_root must be a bool or a list of the OSes of the row, not %r" % (where, root))
|
||||
return problems
|
||||
|
||||
|
||||
def _read_json_list(path):
|
||||
try:
|
||||
return json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as exc:
|
||||
raise Usage("cannot read the required list %s: %s" % (path, exc))
|
||||
|
||||
|
||||
def load_required(path):
|
||||
data = _read_json_list(path)
|
||||
problems = validate_list(data)
|
||||
if problems:
|
||||
raise BadList("the required list %s is malformed:\n %s" % (path, "\n ".join(problems)))
|
||||
return data
|
||||
|
||||
|
||||
def find_suite(suites, suite_id, os_name):
|
||||
if os_name not in OSES:
|
||||
raise Usage("--os must be one of %s, not %r" % (", ".join(OSES), os_name))
|
||||
rows = [s for s in suites if isinstance(s, dict) and s.get("id") == suite_id]
|
||||
if not rows:
|
||||
raise Usage("no suite %r in the required list" % suite_id)
|
||||
if len(rows) > 1:
|
||||
raise Usage("the suite %r appears %d times in the required list" % (suite_id, len(rows)))
|
||||
row = rows[0]
|
||||
if os_name not in row.get("os", []):
|
||||
raise Usage("the suite %r does not run on %s (it runs on: %s)"
|
||||
% (suite_id, os_name, ", ".join(row.get("os", [])) or "nowhere"))
|
||||
return row
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------- the junit
|
||||
def node_id(classname, name):
|
||||
"""`tests.test_x` + `test_y[p]` -> `tests/test_x.py::test_y[p]`; a class segment (capitalised) goes after the file."""
|
||||
parts = [p for p in (classname or "").split(".") if p]
|
||||
module, klass = [], []
|
||||
for i, part in enumerate(parts):
|
||||
if part[:1].isupper() and module:
|
||||
klass = parts[i:]
|
||||
break
|
||||
module.append(part)
|
||||
if not module:
|
||||
return name or ""
|
||||
return "::".join(["/".join(module) + ".py"] + klass + [name or ""])
|
||||
|
||||
|
||||
def parse_junit(path):
|
||||
"""-> (list of (node id, outcome) with outcome in passed|failed|errors|skipped, names of the testcases that are not
|
||||
xunit2). Only xunit2 is accepted: a testcase with no `classname` cannot be told which file it is in, and the extra
|
||||
`file`/`line` attributes are what junit_family=xunit1 writes (pytest 9: it keeps the classname AND adds them)."""
|
||||
root = ET.parse(path).getroot()
|
||||
out, no_class = [], []
|
||||
for case in root.iter("testcase"):
|
||||
if not (case.get("classname") or "").strip() or case.get("file") is not None or case.get("line") is not None:
|
||||
no_class.append(case.get("name") or "?")
|
||||
nid = node_id(case.get("classname"), case.get("name"))
|
||||
tags = {child.tag for child in case}
|
||||
if "error" in tags:
|
||||
outcome = "errors"
|
||||
elif "failure" in tags:
|
||||
outcome = "failed"
|
||||
elif "skipped" in tags:
|
||||
outcome = "skipped"
|
||||
else:
|
||||
outcome = "passed"
|
||||
out.append((nid, outcome))
|
||||
return out, no_class
|
||||
|
||||
|
||||
def read_junit(path):
|
||||
return parse_junit(path)[0]
|
||||
|
||||
|
||||
def _base(nid):
|
||||
"""The node id without the parameters of its last segment."""
|
||||
return nid.split("[", 1)[0]
|
||||
|
||||
|
||||
def required_status(entry, cases):
|
||||
"""-> None if the required entry is satisfied, else why not. EVERY collected test of the entry must have passed."""
|
||||
if "::" in entry:
|
||||
mine = [o for n, o in cases if n == entry or _base(n) == entry]
|
||||
what = "node id"
|
||||
else:
|
||||
mine = [o for n, o in cases if n.split("::", 1)[0] == entry]
|
||||
what = "file"
|
||||
if not mine:
|
||||
return "the %s %s did not run (it is not in the junit)" % (what, entry)
|
||||
bad = sorted({o for o in mine if o != "passed"})
|
||||
if bad:
|
||||
return "the %s %s has tests that did not pass (%s)" % (what, entry, ", ".join(bad))
|
||||
return None
|
||||
|
||||
|
||||
def sha256_of(path):
|
||||
if not path or not os.path.isfile(path):
|
||||
return None
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as fh:
|
||||
for chunk in iter(lambda: fh.read(1 << 20), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def commit_sha(explicit):
|
||||
"""--commit, else `git rev-parse HEAD` in the current directory. Never GITHUB_SHA (in a called workflow it is the
|
||||
commit of the engine's repository, not of the wrapper)."""
|
||||
if explicit:
|
||||
return explicit.strip() or None
|
||||
try:
|
||||
sha = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, timeout=30,
|
||||
check=True).stdout.strip()
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return None
|
||||
return sha or None
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ against main
|
||||
def _int(value):
|
||||
return value if _is_int(value) else 0
|
||||
|
||||
|
||||
def against_main(current, main):
|
||||
"""The list only grows: every suite of main is still here, with no lower minimum, no exact turned off, no lost
|
||||
test or OS and the same marker. `main` is read leniently (it may be older than the current format)."""
|
||||
problems = []
|
||||
if not isinstance(main, list):
|
||||
return ["the list of main is not a JSON list: it cannot be compared"]
|
||||
by_id = {s.get("id"): s for s in current if isinstance(s, dict)}
|
||||
for old in main:
|
||||
if not isinstance(old, dict):
|
||||
continue
|
||||
sid = old.get("id")
|
||||
new = by_id.get(sid)
|
||||
if new is None:
|
||||
problems.append("the suite %s of main is gone from the list" % sid)
|
||||
continue
|
||||
if _int(new.get("min_tests")) < _int(old.get("min_tests")):
|
||||
problems.append("the minimum of %s went down: %s on main, %s here"
|
||||
% (sid, old.get("min_tests"), new.get("min_tests")))
|
||||
if old.get("exact") is True and new.get("exact") is not True:
|
||||
problems.append("the suite %s is no longer exact, as it is on main" % sid)
|
||||
lost = [t for t in old.get("tests", []) if t not in new.get("tests", [])]
|
||||
if lost:
|
||||
problems.append("the suite %s lost %d required test(s) that main has: %s" % (sid, len(lost), ", ".join(lost)))
|
||||
lost_os = [o for o in old.get("os", []) if o not in new.get("os", [])]
|
||||
if lost_os:
|
||||
problems.append("the suite %s no longer runs on %s, where main runs it" % (sid, ", ".join(lost_os)))
|
||||
if old.get("marker") != new.get("marker"):
|
||||
problems.append("the marker of %s changed: %r on main, %r here" % (sid, old.get("marker"), new.get("marker")))
|
||||
return problems
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ the commands
|
||||
def cmd_args(ns):
|
||||
row = find_suite(load_required(ns.required), ns.suite, ns.os)
|
||||
lines = []
|
||||
if ns.with_marker and row.get("marker"):
|
||||
lines += ["-m", row["marker"]]
|
||||
lines += list(row.get("tests", []))
|
||||
# bytes, so that Windows does not turn the newlines into CRLF (a CR would stay glued to the last argument)
|
||||
sys.stdout.buffer.write("".join(line + "\n" for line in lines).encode("utf-8"))
|
||||
sys.stdout.buffer.flush()
|
||||
return 0
|
||||
|
||||
|
||||
def _seal_problems(path, result):
|
||||
"""The seal of the gate must be readable. It has no sha256 of the binary to compare (see the docstring)."""
|
||||
try:
|
||||
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("not a JSON object")
|
||||
except (OSError, ValueError) as exc:
|
||||
result["seal_binary_hash"] = "unreadable"
|
||||
return ["the seal %s cannot be read: %s" % (path, exc)]
|
||||
result["seal_binary_hash"] = "absent"
|
||||
print("note: the seal %s carries no sha256 of the engine binary (an asset's sha256 is the one of the archive): "
|
||||
"the binary was not compared with it" % path)
|
||||
return []
|
||||
|
||||
|
||||
def cmd_judge(ns):
|
||||
problems = []
|
||||
result = {"suite": ns.suite, "os": ns.os, "commit": commit_sha(ns.commit), "binary_sha256": sha256_of(ns.binary),
|
||||
"collected": 0, "passed": 0, "failed": 0, "skipped": 0, "errors": 0, "missing_tests": [],
|
||||
"problems": problems}
|
||||
code_on_red = 1
|
||||
try:
|
||||
suites = load_required(ns.required)
|
||||
row = find_suite(suites, ns.suite, ns.os)
|
||||
except BadList as exc:
|
||||
problems.append(str(exc))
|
||||
return _finish(ns, result, 2)
|
||||
except Usage as exc:
|
||||
problems.append("no result for this row: %s" % exc)
|
||||
return _finish(ns, result, code_on_red)
|
||||
|
||||
if result["commit"] is None:
|
||||
problems.append("the commit of the wrapper is not known (no --commit and `git rev-parse HEAD` failed here)")
|
||||
if result["binary_sha256"] is None:
|
||||
problems.append("the binary %s does not exist: a result with no hash of the engine is not a result" % ns.binary)
|
||||
if ns.seal:
|
||||
problems += _seal_problems(ns.seal, result)
|
||||
|
||||
counts = {"passed": 0, "failed": 0, "skipped": 0, "errors": 0}
|
||||
cases = []
|
||||
if not os.path.isfile(ns.junit):
|
||||
problems.append("the junit %s is missing: the suite %s did not report on %s" % (ns.junit, ns.suite, ns.os))
|
||||
else:
|
||||
try:
|
||||
cases, no_class = parse_junit(ns.junit)
|
||||
if no_class:
|
||||
problems.append("the junit is not xunit2: %d testcase(s) have no classname or carry file/line (e.g. %s); the gate must run "
|
||||
"pytest with -o junit_family=xunit2" % (len(no_class), no_class[0]))
|
||||
except (ET.ParseError, OSError) as exc:
|
||||
problems.append("the junit %s cannot be read: %s" % (ns.junit, exc))
|
||||
for _n, outcome in cases:
|
||||
counts[outcome] += 1
|
||||
collected = len(cases)
|
||||
|
||||
if counts["failed"]:
|
||||
problems.append("%d test(s) failed" % counts["failed"])
|
||||
if counts["errors"]:
|
||||
problems.append("%d test(s) ended in error" % counts["errors"])
|
||||
if counts["skipped"]:
|
||||
problems.append("%d test(s) were skipped: a required suite allows no skip" % counts["skipped"])
|
||||
minimum = row.get("min_tests")
|
||||
if collected < minimum:
|
||||
problems.append("collected %d test(s), fewer than the minimum %s" % (collected, minimum))
|
||||
elif row.get("exact") and collected != minimum:
|
||||
problems.append("collected %d test(s), but the suite is exact: %s, not more (a test was added: raise min_tests "
|
||||
"by hand)" % (collected, minimum))
|
||||
missing = []
|
||||
for entry in row.get("tests", []):
|
||||
why = required_status(entry, cases)
|
||||
if why:
|
||||
missing.append(entry)
|
||||
problems.append(why)
|
||||
|
||||
if ns.main_has_no_list and not ns.main_required:
|
||||
problems.append("--main-has-no-list without --main-required: it says nothing")
|
||||
elif ns.main_required:
|
||||
exists = os.path.isfile(ns.main_required)
|
||||
if exists and ns.main_has_no_list:
|
||||
problems.append("the list of main %s exists, but --main-has-no-list says main has none" % ns.main_required)
|
||||
elif exists:
|
||||
try:
|
||||
problems += against_main(suites, _read_json_list(ns.main_required))
|
||||
except Usage as exc:
|
||||
problems.append(str(exc))
|
||||
elif ns.main_has_no_list:
|
||||
print("the list of main %s does not exist and the gate declares that main was checked out and has none: "
|
||||
"nothing to compare" % ns.main_required)
|
||||
else:
|
||||
problems.append("the list of main %s does not exist and main was not declared to have none "
|
||||
"(--main-has-no-list): it is not known what main has, so the list cannot be compared"
|
||||
% ns.main_required)
|
||||
|
||||
result.update(counts, collected=collected, missing_tests=missing)
|
||||
return _finish(ns, result, code_on_red)
|
||||
|
||||
|
||||
def _finish(ns, result, code_on_red):
|
||||
problems = result["problems"]
|
||||
result["verdict"] = "red" if problems else "green"
|
||||
if ns.out:
|
||||
out = Path(ns.out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
if problems:
|
||||
for p in problems:
|
||||
print("VERDICT RED %s/%s: %s" % (ns.suite, ns.os, p))
|
||||
return code_on_red
|
||||
print("VERDICT GREEN %s/%s: %d collected, %d passed" % (ns.suite, ns.os, result["collected"], result["passed"]))
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_complete(ns):
|
||||
suites = load_required(ns.required)
|
||||
expected = {(s["id"], o) for s in suites for o in s["os"]}
|
||||
problems = []
|
||||
folder = Path(ns.results)
|
||||
if not folder.is_dir():
|
||||
problems.append("the results folder %s does not exist: no suite reported" % ns.results)
|
||||
found = {} # (suite, os) -> (path, data)
|
||||
for path in sorted(folder.rglob("*.json")) if folder.is_dir() else []:
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as exc:
|
||||
problems.append("%s cannot be read as a result: %s" % (path, exc))
|
||||
continue
|
||||
if not (isinstance(data, dict) and isinstance(data.get("suite"), str) and isinstance(data.get("os"), str)):
|
||||
problems.append("%s is not a result of judge (no suite and os)" % path)
|
||||
continue
|
||||
key = (data["suite"], data["os"])
|
||||
if key not in expected:
|
||||
problems.append("%s is the result of %s/%s, which is not in the required list" % (path, key[0], key[1]))
|
||||
continue
|
||||
if key in found:
|
||||
problems.append("%s/%s has two results: %s and %s" % (key[0], key[1], found[key][0], path))
|
||||
continue
|
||||
found[key] = (path, data)
|
||||
for suite, os_name in sorted(expected - set(found)):
|
||||
problems.append("%s/%s has no result: the leg did not report" % (suite, os_name))
|
||||
for key, (path, data) in sorted(found.items()):
|
||||
if data.get("verdict") != "green":
|
||||
why = data.get("problems") or ["no verdict in the result"]
|
||||
problems.append("%s/%s is not green (%s): %s" % (key[0], key[1], data.get("verdict"), "; ".join(map(str, why))))
|
||||
elif data.get("problems"):
|
||||
problems.append("%s/%s says green but lists problems: %s" % (key[0], key[1], "; ".join(map(str, data["problems"]))))
|
||||
commits = {}
|
||||
shas = {}
|
||||
for key, (_path, data) in found.items():
|
||||
commits.setdefault(data.get("commit"), []).append("%s/%s" % key)
|
||||
shas.setdefault(key[1], {}).setdefault(data.get("binary_sha256"), []).append("%s/%s" % key)
|
||||
if None in commits:
|
||||
problems.append("no commit in the result of: %s" % ", ".join(sorted(commits[None])))
|
||||
if len([c for c in commits if c]) > 1:
|
||||
problems.append("the legs ran at different commits: %s"
|
||||
% "; ".join("%s: %s" % (c, ", ".join(sorted(v))) for c, v in sorted(commits.items(), key=str)))
|
||||
for os_name, by_sha in sorted(shas.items()):
|
||||
if None in by_sha:
|
||||
problems.append("no binary sha256 in the result of: %s" % ", ".join(sorted(by_sha[None])))
|
||||
if len([s for s in by_sha if s]) > 1:
|
||||
problems.append("the %s legs ran with different binaries: %s" % (
|
||||
os_name, "; ".join("%s: %s" % (s, ", ".join(sorted(v))) for s, v in sorted(by_sha.items(), key=str))))
|
||||
if problems:
|
||||
for p in problems:
|
||||
print("COMPLETE RED: %s" % p)
|
||||
return 1
|
||||
print("COMPLETE GREEN: %d result(s), all green, one commit, one binary per OS" % len(found))
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
a = sub.add_parser("args", help="print the pytest arguments of a suite")
|
||||
a.add_argument("--required", required=True)
|
||||
a.add_argument("--suite", required=True)
|
||||
a.add_argument("--os", required=True)
|
||||
a.add_argument("--with-marker", action="store_true", help="print -m and the marker of the suite first")
|
||||
j = sub.add_parser("judge", help="judge the junit of a suite")
|
||||
j.add_argument("--required", required=True)
|
||||
j.add_argument("--suite", required=True)
|
||||
j.add_argument("--os", required=True)
|
||||
j.add_argument("--junit", required=True)
|
||||
j.add_argument("--binary")
|
||||
j.add_argument("--commit")
|
||||
j.add_argument("--seal")
|
||||
j.add_argument("--out")
|
||||
j.add_argument("--main-required")
|
||||
j.add_argument("--main-has-no-list", action="store_true",
|
||||
help="the gate checked main out and the list is not there (a failed checkout is not this)")
|
||||
c = sub.add_parser("complete", help="check that every (suite, os) reported green at one commit")
|
||||
c.add_argument("--required", required=True)
|
||||
c.add_argument("--results", required=True)
|
||||
ns = ap.parse_args(argv)
|
||||
try:
|
||||
if ns.cmd == "judge":
|
||||
if not ns.binary:
|
||||
raise Usage("judge needs --binary (the engine the suite ran against: its hash goes in the result)")
|
||||
return cmd_judge(ns)
|
||||
if ns.cmd == "complete":
|
||||
return cmd_complete(ns)
|
||||
return cmd_args(ns)
|
||||
except Usage as exc:
|
||||
print("ci_verdict: %s" % exc, file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -713,7 +713,7 @@ def _launch_params(session: Any, *, virtual_display: bool, headless: bool,
|
||||
"""`InvisiblePlaywright.__enter__` up to the launch, as protocol params.
|
||||
|
||||
The same calls in the same order, so the served browser is the one the
|
||||
wrapper would have launched: geo (egress, timezone, locale, srflx), the
|
||||
wrapper would have launched: geo (egress, timezone, locale), the
|
||||
hidden display, the prefs, the proxy, the session token and the env."""
|
||||
from invisible_core import configure_proxy, prepare_session_geo
|
||||
from invisible_core import make_virtual_display
|
||||
@@ -725,7 +725,6 @@ def _launch_params(session: Any, *, virtual_display: bool, headless: bool,
|
||||
session._timezone = geo.timezone
|
||||
session._locale = geo.locale
|
||||
session._webrtc_egress_ip = geo.egress_ip
|
||||
session._srflx_declared = geo.srflx_to_declare()
|
||||
executable = resolve_executable(session._binary_path)
|
||||
pw_headless = bool(headless)
|
||||
if not headless and virtual_display:
|
||||
@@ -789,7 +788,7 @@ def launch_server(host: str = DEFAULT_HOST, port: int = 0, *,
|
||||
pin fingerprint fields forced (see docs/pinning.md).
|
||||
proxy `{"server", "username", "password"}`, fixed after the
|
||||
launch; the egress (exit IP -> timezone, locale
|
||||
"auto", srflx/WebRTC; the GeoIP database offline from
|
||||
"auto"; the GeoIP database offline from
|
||||
STEALTHFOX_GEOIP_MMDB) is measured here through it.
|
||||
headless True = true headless; False = headed.
|
||||
virtual_display with headless=False: a private virtual display (Xvfb
|
||||
|
||||
@@ -295,7 +295,7 @@ def session_for_launch(prefs: Dict, executable: str, proxy: Optional[Dict] = Non
|
||||
|
||||
`proxy` is the launch's own (`launch(proxy=...)`): the session is composed
|
||||
through it as `InvisiblePlaywright(proxy=...)` composes, so the egress it
|
||||
measures there is the address WebRTC declares (STEALTHFOX_WEBRTC_PUBLIC_IP),
|
||||
measures there (timezone, locale) and the network it declares are the proxy's,
|
||||
not this machine's. The engine is told the proxy by `op_launch`, as before.
|
||||
"""
|
||||
if COMPOSED_PREF in prefs:
|
||||
@@ -2477,7 +2477,21 @@ class RouteDispatcher(Dispatcher):
|
||||
# session they came back "Handler for does not implement method", the
|
||||
# held request was never released and the page hung on its first
|
||||
# request. Every route that ever reached a handler failed this way.
|
||||
result = self.request.page.send(command, params)
|
||||
# ⛔ THE ANSWER TO A REQUEST THE BROWSER HAS ALREADY CLOSED IS NOT AN ERROR. The page cancels requests while a route is
|
||||
# deciding (a fetch aborted, an image replaced, an iframe removed, a beacon with its document): the engine takes
|
||||
# the request out of its held set at once, and the late `continue`/`abort`/`fulfill` meets "Cannot find request".
|
||||
# Stock Playwright sends these commands as may-fail and tells the client nothing (`sendMayFail`). Ours passed the
|
||||
# error up; the client kept it as the error of the whole connection and raised it on the NEXT route command,
|
||||
# which was never sent: its request stayed held in the engine, its handler failed too, and so on down the page
|
||||
# (measured on a real news page: six held requests in a row, one a beacon, networkidle never).
|
||||
try:
|
||||
result = self.request.page.send(command, params)
|
||||
except juggler.ProtocolError as exc:
|
||||
if "Cannot find request" not in str(exc):
|
||||
raise
|
||||
result = None
|
||||
except juggler.TargetClosedError:
|
||||
result = None # the page went away: nothing is held any more
|
||||
self.dispose()
|
||||
return result
|
||||
|
||||
@@ -5351,8 +5365,8 @@ class BrowserTypeDispatcher(Dispatcher):
|
||||
# ⛔ THE PROXY IS SET BY THE CORE'S `launch`, before any page exists,
|
||||
# and a proxy the engine refuses closes the browser there: the driver
|
||||
# once accepted `proxy=` and dropped it, and a page went out on the
|
||||
# host address while the session's timezone, locale and WebRTC
|
||||
# candidate had been resolved THROUGH the proxy (2026-08-30). Until
|
||||
# host address while the session's timezone and locale
|
||||
# had been resolved THROUGH the proxy (2026-08-30). Until
|
||||
# 0.34.0 this method sent the command itself, as Selenium's and
|
||||
# Puppeteer's launch did, each with the same fixed 10 s.
|
||||
conn = juggler.launch(executable, profile,
|
||||
|
||||
@@ -86,11 +86,18 @@ def default_session(executable: Optional[str] = None,
|
||||
geo = session_geo(session._timezone, session._proxy, session._locale_requested)
|
||||
session._timezone, session._locale = geo.timezone, geo.locale
|
||||
prefs = session._build_prefs()
|
||||
env = build_env(srflx_declared=geo.srflx_to_declare(), profile=session._profile,
|
||||
env = build_env(network_declared=declared_network(session), profile=session._profile,
|
||||
executable=executable, base_env={})
|
||||
return prefs, env
|
||||
|
||||
|
||||
def declared_network(session: Any) -> str:
|
||||
"""The host network this session declares to the engine (the value of
|
||||
STEALTHFOX_WEBRTC_NETWORK), drawn from its seed, with or without a proxy."""
|
||||
from invisible_core import network_to_declare
|
||||
return network_to_declare(session.seed)
|
||||
|
||||
|
||||
def true_headless_requested(env: Optional[Dict[str, str]] = None) -> bool:
|
||||
return (env if env is not None else os.environ).get(TRUE_HEADLESS_ENV) == "1"
|
||||
|
||||
@@ -99,13 +106,9 @@ def true_headless_requested(env: Optional[Dict[str, str]] = None) -> bool:
|
||||
#: lives. It was duplicated here byte-for-byte - ten entries, including the
|
||||
def build_env(
|
||||
*,
|
||||
#: The address to DECLARE as srflx, or None to declare nothing and let the
|
||||
#: real one through. ⛔ This is NOT the egress IP: it is a DECISION the
|
||||
#: core makes in a single place, looking at the capabilities of the egress
|
||||
#: (`SessionGeo.srflx_to_declare`). The old name, `egress_ip`, said
|
||||
#: something else and made the rule look like "there's a proxy -> declare
|
||||
#: it", which is the wrong question.
|
||||
srflx_declared: Optional[str],
|
||||
#: The host network the engine reads (STEALTHFOX_WEBRTC_NETWORK), drawn from
|
||||
#: the session seed (`declared_network`); None declares nothing.
|
||||
network_declared: Optional[str],
|
||||
profile: Any = None,
|
||||
executable: Optional[str] = None,
|
||||
base_env: Optional[Dict[str, str]] = None,
|
||||
@@ -166,7 +169,7 @@ def build_env(
|
||||
f"(e.g. {missing[:3]}). Engine: {executable}. The metrics "
|
||||
f"would describe fonts that are not there.")
|
||||
manifest_path = cached_font_manifest_path(manifest)
|
||||
return build_launch_env({}, srflx_declared=srflx_declared,
|
||||
return build_launch_env({}, network_declared=network_declared,
|
||||
manifest_path=manifest_path, base_env=base_env,
|
||||
display_env=display_env)
|
||||
|
||||
@@ -279,16 +282,14 @@ class ProxyEgressDrifted(RuntimeError):
|
||||
This is not a condition the product can recover from, and it is deliberate
|
||||
that it is an error instead of a silent update.
|
||||
|
||||
The IP we declare to the engine for the WebRTC srflx candidate is
|
||||
discovered ONCE, at launch. If the egress changes afterwards, the page
|
||||
exits from one address and WebRTC announces another: it is exactly the
|
||||
comparison detectors make ("WebRTC IP doesn't match your Remote IP"), and
|
||||
no Firefox on a real connection produces it.
|
||||
The timezone and the locale are decided ONCE, at launch, from the egress
|
||||
country. If the egress moves afterwards, the page exits from one place
|
||||
while the timezone and the language still describe another: a mismatch no
|
||||
real connection produces.
|
||||
|
||||
Updating the value on the fly would be worse, not better: the site would
|
||||
see the WebRTC IP change before its own eyes mid-session, which is just as
|
||||
unnatural a signal. If the egress does not hold for the duration of the
|
||||
session, that proxy is not sticky and is not usable for this purpose.
|
||||
Updating them on the fly would be just as unnatural (the site would see
|
||||
them change mid-session). If the egress does not hold for the duration of
|
||||
the session, that proxy is not sticky and is not usable for this purpose.
|
||||
|
||||
Measured on 2026-08-25: the two providers tried both declare sessions
|
||||
sticky by TIME (60 minutes at most for one, a sliding timeout for the
|
||||
@@ -384,7 +385,7 @@ class CommonLaunch:
|
||||
`_cursor_engine`, `_extra_prefs`, `_headless`, `_humanize`,
|
||||
`_lifetime_guard`, `_locale` (the core's SessionLocale, None until
|
||||
`__enter__` decides it), `_profile`, `_session_token`, `_show_cursor`,
|
||||
`_srflx_declared`, `_timezone` and `_virtual_display` in their own
|
||||
`_network_declared`, `_timezone` and `_virtual_display` in their own
|
||||
`__init__`. They already did, identically, which is why this works at all.
|
||||
"""
|
||||
|
||||
@@ -449,7 +450,7 @@ class CommonLaunch:
|
||||
"""Env for the Firefox subprocess, then stamped with this session's token.
|
||||
|
||||
The body is `build_env`, shared with the async class - it was
|
||||
written twice, identically, and the WebRTC pair is a contract with the
|
||||
written twice, identically, and the WebRTC declaration is a contract with the
|
||||
binary, so two landing sites meant two chances to miss a change.
|
||||
|
||||
The token stamp stays here because it is the only genuinely per-session
|
||||
@@ -458,7 +459,7 @@ class CommonLaunch:
|
||||
"""
|
||||
vd = self._virtual_display
|
||||
return self._session_token.stamp(
|
||||
build_env(srflx_declared=self._srflx_declared,
|
||||
build_env(network_declared=self._network_declared,
|
||||
profile=self._profile,
|
||||
executable=resolve_executable(self._binary_path),
|
||||
display_env=vd.launch_env() if vd is not None else None))
|
||||
|
||||
@@ -88,13 +88,11 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
# otherwise. Nothing was red because no test enters this context manager.
|
||||
self._session_token = SessionToken()
|
||||
self._lifetime_guard = guard_for()
|
||||
# Proxy egress IP (WebRTC srflx override); discovered in __aenter__.
|
||||
# Proxy egress IP, discovered in __aenter__: the guard against drift
|
||||
# compares it with the egress now. None without a proxy.
|
||||
self._webrtc_egress_ip: Optional[str] = None
|
||||
#: The DECISION about the srflx, distinct from the fact above.
|
||||
#: Starts as None like it: `_build_env` can be called before
|
||||
#: the geo path has resolved, and in that case nothing is
|
||||
#: declared.
|
||||
self._srflx_declared: Optional[str] = None
|
||||
#: The host network the engine reads, drawn from the seed.
|
||||
self._network_declared: str = _session.declared_network(self)
|
||||
#: See the twin in `launcher.py`: starts at 0 because the first
|
||||
#: context must be able to check right away.
|
||||
self._ultimo_controllo_uscita: float = 0.0
|
||||
@@ -116,17 +114,6 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
self._timezone = _geo.timezone
|
||||
self._locale = _geo.locale
|
||||
self._webrtc_egress_ip = _geo.egress_ip
|
||||
# ⛔ TWO DIFFERENT THINGS, and they used to be a single field.
|
||||
# `_webrtc_egress_ip` is the FACT: where we exit from. It feeds
|
||||
# the guard against drift, which compares the current egress
|
||||
# against the one at launch.
|
||||
# `_srflx_declared` is the DECISION: what the engine must
|
||||
# announce. It is None when the egress has proven, consistent
|
||||
# UDP, because there the real srflx is already correct and
|
||||
# declaring one would add a candidate with no matching
|
||||
# allocation - the signal a detector running its own TURN reads.
|
||||
# The core takes it in a single spot.
|
||||
self._srflx_declared = _geo.srflx_to_declare()
|
||||
# binary_path= never reaches ensure_binary(), so the engine check lives
|
||||
# on the resolved executable rather than inside the fetcher.
|
||||
executable = resolve_executable(self._binary_path)
|
||||
@@ -191,7 +178,7 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
#: session gets rejected. One alone would be too strict - a timeout
|
||||
#: happens - but unlimited would be declared blindness: after three
|
||||
#: silent checks at 120 s each, that is six minutes in which nothing
|
||||
#: is confirming the address the engine announces on every page.
|
||||
#: is confirming that the timezone and the locale still match the egress.
|
||||
_MAX_USCITE_NON_MISURABILI = 3
|
||||
|
||||
async def _assert_uscita_invariata(self) -> None:
|
||||
@@ -210,19 +197,19 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
if outcome == _session.USCITA_DERIVATA:
|
||||
raise _session.ProxyEgressDrifted(
|
||||
"the proxy's egress IP changed during the session: "
|
||||
"at launch it was %s, now it is %s. The WebRTC srflx "
|
||||
"candidate still declares the first one, so from this "
|
||||
"moment the page exits from one address and WebRTC "
|
||||
"announces another - the disagreement detectors look "
|
||||
"for. This proxy does not hold the session sticky for "
|
||||
"at launch it was %s, now it is %s. The timezone and the "
|
||||
"locale still describe the first one, so from this moment "
|
||||
"the page exits from one place and they say another. "
|
||||
"This proxy does not hold the session sticky for "
|
||||
"the required duration: use one that guarantees it, or "
|
||||
"shorten the session."
|
||||
% (self._webrtc_egress_ip, current))
|
||||
if outcome == _session.USCITA_NON_MISURABILE:
|
||||
# This is NOT "holds", which is why there are three outcomes. A
|
||||
# probe that fails ONCE is the network; one that always fails is
|
||||
# blindness: from that moment the engine keeps declaring an
|
||||
# address on every page that nobody is confirming anymore. It is
|
||||
# blindness: from that moment the timezone and the locale stay
|
||||
# declared on every page with nobody confirming them against the
|
||||
# egress anymore. It is
|
||||
# counted, instead of ignored, and rejected only if it repeats.
|
||||
self._uscite_non_misurabili += 1
|
||||
if self._uscite_non_misurabili >= self._MAX_USCITE_NON_MISURABILI:
|
||||
@@ -230,8 +217,8 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
"the egress IP could not be verified for %d checks in "
|
||||
"a row. It is not drift - the probe did not respond at "
|
||||
"all - but it is not agreement either: from here on "
|
||||
"the engine would be declaring an address on every "
|
||||
"page that nobody confirms anymore. Check that the "
|
||||
"the timezone and the locale go unconfirmed on every "
|
||||
"page. Check that the "
|
||||
"proxy is reachable, then relaunch the session."
|
||||
% self._uscite_non_misurabili)
|
||||
return
|
||||
|
||||
@@ -235,14 +235,11 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
# before __enter__ has got anywhere - always finds them.
|
||||
self._session_token = SessionToken()
|
||||
self._lifetime_guard = guard_for()
|
||||
# Proxy egress IP, discovered at launch (see __enter__). Feeds the
|
||||
# WebRTC srflx override so the candidate matches the proxy IP, not the
|
||||
# real host IP. None when no proxy is set.
|
||||
# Proxy egress IP, discovered at launch (see __enter__): the guard
|
||||
# against drift compares it with the egress now. None without a proxy.
|
||||
self._webrtc_egress_ip: Optional[str] = None
|
||||
#: The DECISION about the srflx, distinct from the fact above.
|
||||
#: Starts at None like it: `_build_env` can be called before the
|
||||
#: geo path has resolved, and in that case nothing is declared.
|
||||
self._srflx_declared: Optional[str] = None
|
||||
#: The host network the engine reads, drawn from the seed.
|
||||
self._network_declared: str = _session.declared_network(self)
|
||||
#: When the egress was last rechecked. Starts at 0 rather than at
|
||||
#: `time.monotonic()`: the first context must be able to check
|
||||
#: right away, because time may already have passed between launch
|
||||
@@ -264,17 +261,6 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
self._timezone = _geo.timezone
|
||||
self._locale = _geo.locale
|
||||
self._webrtc_egress_ip = _geo.egress_ip
|
||||
# ⛔ TWO DIFFERENT THINGS, and before they were a single field.
|
||||
# `_webrtc_egress_ip` is the FACT: where we exit from. It serves the
|
||||
# guard against drift, which compares now's egress against the one
|
||||
# at launch.
|
||||
# `_srflx_declared` is the DECISION: what the engine must
|
||||
# announce. It is None when the egress has proven, consistent UDP,
|
||||
# because there the real srflx is already born correct and
|
||||
# declaring one would add a candidate with no matching
|
||||
# allocation - the signal a detector running its own TURN reads.
|
||||
# The core reads it in one place only.
|
||||
self._srflx_declared = _geo.srflx_to_declare()
|
||||
# binary_path= never reaches ensure_binary(), so the engine check lives
|
||||
# on the resolved executable rather than inside the fetcher.
|
||||
executable = resolve_executable(self._binary_path)
|
||||
@@ -409,20 +395,18 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
#: session gets refused. Just one would be too strict - a timeout
|
||||
#: happens - but unlimited would be declared blindness: after three
|
||||
#: silent checks at 120s each, that is six minutes in which nobody is
|
||||
#: confirming the address the engine announces on every page.
|
||||
#: confirming that the timezone and the locale still match the egress.
|
||||
_MAX_USCITE_NON_MISURABILI = 3
|
||||
|
||||
def _assert_uscita_invariata(self) -> None:
|
||||
"""Refuses if the egress IP has changed since launch.
|
||||
|
||||
A change mid-session cannot be recovered from: the IP we declare to
|
||||
the engine for the srflx was photographed at launch, so from that
|
||||
moment the page exits from one address and WebRTC announces
|
||||
another - the disagreement detectors look for. Updating it on the
|
||||
fly would not help: it would make the WebRTC IP change under the
|
||||
site's eyes, which is just as unnatural. If the egress does not
|
||||
hold for the session's duration, that proxy is not sticky and is
|
||||
not fit for this purpose.
|
||||
A change mid-session cannot be recovered from: the timezone and the locale were decided from the egress at launch, so
|
||||
from that moment the page exits from one place while they describe
|
||||
another. Updating them on the fly would not help: the site would see
|
||||
them change, which is just as unnatural. If the egress does not hold
|
||||
for the session's duration, that proxy is not sticky and is not fit
|
||||
for this purpose.
|
||||
"""
|
||||
if not self._proxy or not self._webrtc_egress_ip:
|
||||
return
|
||||
@@ -435,10 +419,9 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
if outcome == _session.USCITA_DERIVATA:
|
||||
raise _session.ProxyEgressDrifted(
|
||||
"the proxy's egress IP changed during the session: "
|
||||
"it was %s at launch, now it is %s. The WebRTC srflx "
|
||||
"candidate still declares the first one, so from this "
|
||||
"moment the page exits from one address and WebRTC "
|
||||
"announces another - the disagreement detectors look for. "
|
||||
"it was %s at launch, now it is %s. The timezone and the "
|
||||
"locale still describe the first one, so from this moment "
|
||||
"the page exits from one place and they say another. "
|
||||
"This proxy does not hold the session sticky for the "
|
||||
"required duration: use one that guarantees it, or "
|
||||
"shorten the session."
|
||||
@@ -446,18 +429,18 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
if outcome == _session.USCITA_NON_MISURABILE:
|
||||
# It is NOT "holding", and that is why there are three outcomes.
|
||||
# A probe that fails ONCE is the network; one that always fails
|
||||
# is blindness: from that moment the engine keeps declaring an
|
||||
# address on every page that nobody is confirming anymore. It
|
||||
# is counted, instead of ignored, and refused only if it
|
||||
# is blindness: from that moment the timezone and the locale
|
||||
# stay declared on every page with nobody confirming them against
|
||||
# the egress anymore. It is counted, instead of ignored, and refused only if it
|
||||
# repeats.
|
||||
self._uscite_non_misurabili += 1
|
||||
if self._uscite_non_misurabili >= self._MAX_USCITE_NON_MISURABILI:
|
||||
raise _session.ProxyEgressNonVerificabile(
|
||||
"the egress IP was not verifiable for %d checks in a "
|
||||
"row. It is not drift - the probe did not respond at "
|
||||
"all - but it is not parity either: from here on the "
|
||||
"engine would keep declaring an address on every page "
|
||||
"that nobody confirms anymore. Check that the proxy is "
|
||||
"all - but it is not parity either: from here on "
|
||||
"the timezone and the locale go unconfirmed on every "
|
||||
"page. Check that the proxy is "
|
||||
"reachable, then relaunch the session."
|
||||
% self._uscite_non_misurabili)
|
||||
return
|
||||
@@ -516,11 +499,9 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
# then on.
|
||||
#
|
||||
# Measured 2026-08-25 in a manual session: at launch the egress
|
||||
# was `82.40.95.144` and that is what landed in the srflx; nine
|
||||
# tabs later the page was exiting from `130.12.17.118`, and the
|
||||
# two showed up together on screen - `PUBLIC IP` against
|
||||
# `WEBRTC CLIENT SIDE IP OFFER`. The guard existed, it was
|
||||
# correct, and it was never asked.
|
||||
# was `203.0.113.10`, which the timezone was decided from; nine
|
||||
# tabs later the page was exiting from `203.0.113.20`. The guard
|
||||
# existed, it was correct, and it was never asked.
|
||||
#
|
||||
# The cost stays the same as before: `_assert_uscita_invariata`
|
||||
# limits itself to one check every `_INTERVALLO_CONTROLLO_USCITA_S`,
|
||||
|
||||
@@ -0,0 +1,609 @@
|
||||
"""A DNS-over-HTTPS server and a SOCKS5 gateway that carries the DoH road, for tests that need a real wire.
|
||||
|
||||
Hermetic: loopback only, no DNS, no internet. Nothing here knows about the product.
|
||||
|
||||
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 ``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
|
||||
(``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.
|
||||
* the DNS codec (:func:`parse_query`, :func:`build_response`), which the resolver trap of ``_leaks`` reuses.
|
||||
|
||||
``via`` answers "by which road did this query arrive": the name of the gateway that carried the CONNECT, or
|
||||
``"direct"`` for a client that connected to the FakeDoh's own port.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import datetime
|
||||
import ipaddress
|
||||
import socket
|
||||
import ssl
|
||||
import struct
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Callable, Dict, List, NamedTuple, Optional, Set, Tuple
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from _socks_servers import EXIT, Gateway, WEB_NAME, WHOAMI4, WHOAMI6
|
||||
|
||||
try: # the HTTP/2 side needs it; a test that wants h2 says pytest.importorskip("h2")
|
||||
import h2.config
|
||||
import h2.connection
|
||||
import h2.events
|
||||
import h2.exceptions
|
||||
H2_AVAILABLE = True
|
||||
except ImportError: # pragma: no cover - depends on the environment
|
||||
H2_AVAILABLE = False
|
||||
|
||||
#: 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)})
|
||||
|
||||
QTYPE_A, QTYPE_AAAA = 1, 28
|
||||
RCODE_OK, RCODE_NXDOMAIN, RCODE_REFUSED = 0, 3, 5
|
||||
DOH_TTL = 30
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------- DNS codec
|
||||
class Query(NamedTuple):
|
||||
ident: int
|
||||
flags: int
|
||||
name: str # lower case, no trailing dot
|
||||
qtype: int
|
||||
qclass: int
|
||||
question: bytes # the question section as it came, to be copied into the answer
|
||||
|
||||
|
||||
def parse_query(msg: bytes) -> Query:
|
||||
"""The first (and only) question of a DNS message. Raises ``ValueError`` on anything that is not one."""
|
||||
try:
|
||||
ident, flags, qdcount, _an, _ns, _ar = struct.unpack("!6H", msg[:12])
|
||||
if qdcount != 1:
|
||||
raise ValueError("expected one question, got %d" % qdcount)
|
||||
i, labels = 12, []
|
||||
while True:
|
||||
length = msg[i]
|
||||
i += 1
|
||||
if length == 0:
|
||||
break
|
||||
if length & 0xC0:
|
||||
raise ValueError("a compressed name in the question")
|
||||
labels.append(msg[i:i + length].decode("ascii"))
|
||||
i += length
|
||||
qtype, qclass = struct.unpack("!HH", msg[i:i + 4]) # struct.error when truncated
|
||||
i += 4
|
||||
except (IndexError, struct.error, UnicodeDecodeError) as exc:
|
||||
raise ValueError("not a DNS query: %s" % exc) from None
|
||||
return Query(ident, flags, ".".join(labels).lower(), qtype, qclass, msg[12:i])
|
||||
|
||||
|
||||
def build_response(query: Query, rcode: int = RCODE_OK, answers: Tuple[Tuple[int, bytes], ...] = ()) -> bytes:
|
||||
"""A response to ``query``: QR+RA, the RD bit copied, ``rcode``, the question copied, one record per
|
||||
``(type, rdata)`` with the name as a pointer to the question and TTL 30."""
|
||||
flags = 0x8000 | (query.flags & 0x0100) | 0x0080 | (rcode & 0xF)
|
||||
out = struct.pack("!6H", query.ident, flags, 1, len(answers), 0, 0) + query.question
|
||||
for rtype, rdata in answers:
|
||||
out += struct.pack("!HHHIH", 0xC00C, rtype, 1, DOH_TTL, len(rdata)) + rdata
|
||||
return out
|
||||
|
||||
|
||||
def encode_query(name: str, qtype: int = QTYPE_A, ident: int = 0) -> bytes:
|
||||
"""A query message (RD set), the way a client builds it."""
|
||||
labels = b"".join(bytes([len(p)]) + p.encode("ascii") for p in name.rstrip(".").split(".") if p)
|
||||
return struct.pack("!6H", ident, 0x0100, 1, 0, 0, 0) + labels + b"\x00" + struct.pack("!HH", qtype, 1)
|
||||
|
||||
|
||||
def answer_for(names: Dict[str, str], query: Query) -> bytes:
|
||||
"""The response a zone made of ``names`` (name -> address) gives: A for an IPv4 value, AAAA for an IPv6 one,
|
||||
NOERROR with no answer for any other type of a known name, NXDOMAIN for an unknown name."""
|
||||
value = names.get(query.name)
|
||||
if value is None:
|
||||
return build_response(query, RCODE_NXDOMAIN)
|
||||
address = ipaddress.ip_address(value)
|
||||
if query.qtype == QTYPE_A and address.version == 4:
|
||||
return build_response(query, RCODE_OK, ((QTYPE_A, address.packed),))
|
||||
if query.qtype == QTYPE_AAAA and address.version == 6:
|
||||
return build_response(query, RCODE_OK, ((QTYPE_AAAA, address.packed),))
|
||||
return build_response(query, RCODE_OK)
|
||||
|
||||
|
||||
def wait_until(predicate: Callable[[], object], timeout: float, step: float = 0.05) -> bool:
|
||||
"""True as soon as ``predicate()`` is truthy, False after ``timeout`` seconds."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
if predicate():
|
||||
return True
|
||||
if time.monotonic() >= deadline:
|
||||
return False
|
||||
time.sleep(step)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------ certificate
|
||||
def make_certificate(directory: Path, dns_names: Tuple[str, ...] = (DOH_HOST,),
|
||||
ip_addresses: Tuple[str, ...] = ("127.0.0.1",)) -> Tuple[Path, Path]:
|
||||
"""A self-signed certificate (EC P-256, 30 days) whose SAN covers ``dns_names`` and ``ip_addresses``.
|
||||
Returns (certificate path, key path), both PEM."""
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import NameOID
|
||||
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, dns_names[0] if dns_names else ip_addresses[0])])
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
san = [x509.DNSName(n) for n in dns_names] + [x509.IPAddress(ipaddress.ip_address(a)) for a in ip_addresses]
|
||||
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number()).not_valid_before(now - datetime.timedelta(days=1))
|
||||
.not_valid_after(now + datetime.timedelta(days=30))
|
||||
.add_extension(x509.SubjectAlternativeName(san), critical=False)
|
||||
.sign(key, hashes.SHA256()))
|
||||
cert_path, key_path = directory / "doh-cert.pem", directory / "doh-key.pem"
|
||||
cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
||||
key_path.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption()))
|
||||
return cert_path, key_path
|
||||
|
||||
|
||||
_REASONS = {200: "OK", 400: "Bad Request", 404: "Not Found", 405: "Method Not Allowed",
|
||||
415: "Unsupported Media Type"}
|
||||
|
||||
|
||||
class DohQuery(NamedTuple):
|
||||
name: str
|
||||
qtype: int
|
||||
via: str
|
||||
|
||||
|
||||
class FakeDoh:
|
||||
"""A DoH server on 127.0.0.1 (its own port, ``via`` ``"direct"``) that also serves any socket a gateway hands it.
|
||||
|
||||
``names`` maps a name to the address it resolves to; it can be changed while the server runs. ``h2=False`` makes
|
||||
it offer HTTP/1.1 only (the way to test that a client falls back), ``h2=True`` is the default when the ``h2``
|
||||
package is importable.
|
||||
"""
|
||||
|
||||
def __init__(self, names: Optional[Dict[str, str]] = None, *, h2: Optional[bool] = None):
|
||||
self.names: Dict[str, str] = {k.lower(): v for k, v in (names or {}).items()}
|
||||
self.offers_h2 = H2_AVAILABLE if h2 is None else (h2 and H2_AVAILABLE)
|
||||
#: Every query, in order.
|
||||
self.queries: List[DohQuery] = []
|
||||
#: Every TLS connection served: (via, negotiated protocol).
|
||||
self.connections: List[Tuple[str, str]] = []
|
||||
#: The TLS handshakes that did not complete (a client that refused the certificate): (via, error).
|
||||
self.tls_failures: List[Tuple[str, str]] = []
|
||||
#: Every HTTP request that was not a well-formed DoH query: (via, method, target, status).
|
||||
self.bad_requests: List[Tuple[str, str, str, int]] = []
|
||||
self._lock = threading.Lock()
|
||||
self._open: List[Tuple[str, ssl.SSLSocket]] = []
|
||||
self._dir = tempfile.TemporaryDirectory()
|
||||
self.certificate_path, self._key_path = make_certificate(Path(self._dir.name))
|
||||
self._context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
self._context.load_cert_chain(str(self.certificate_path), str(self._key_path))
|
||||
self._context.set_alpn_protocols(["h2", "http/1.1"] if self.offers_h2 else ["http/1.1"])
|
||||
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.port: int = self._listener.getsockname()[1]
|
||||
self._closed = False
|
||||
threading.Thread(target=self._accept, daemon=True).start()
|
||||
|
||||
# --- what a test reads ------------------------------------------------------------------------------------
|
||||
def queries_for(self, name: str, qtype: Optional[int] = None) -> List[DohQuery]:
|
||||
name = name.lower().rstrip(".")
|
||||
with self._lock:
|
||||
return [q for q in self.queries if q.name == name and (qtype is None or q.qtype == qtype)]
|
||||
|
||||
def vias_of(self, name: str, qtype: Optional[int] = None) -> Set[str]:
|
||||
"""The set of roads (gateway names) a name was asked by."""
|
||||
return {q.via for q in self.queries_for(name, qtype)}
|
||||
|
||||
def seen_names(self) -> List[str]:
|
||||
with self._lock:
|
||||
return sorted({q.name for q in self.queries})
|
||||
|
||||
def alpn_of(self, via: str) -> Set[str]:
|
||||
with self._lock:
|
||||
return {proto for v, proto in self.connections if v == via}
|
||||
|
||||
# --- serving ----------------------------------------------------------------------------------------------
|
||||
def _accept(self) -> None:
|
||||
while not self._closed:
|
||||
try:
|
||||
conn, _ = self._listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self.serve, args=(conn, "direct"), daemon=True).start()
|
||||
|
||||
def serve(self, sock: socket.socket, via: str) -> None:
|
||||
"""Serve one connection (TLS first) that arrived by ``via``. Blocks until it ends, and closes ``sock``."""
|
||||
try:
|
||||
sock.settimeout(60)
|
||||
tls = self._context.wrap_socket(sock, server_side=True)
|
||||
except (ssl.SSLError, OSError) as exc:
|
||||
with self._lock:
|
||||
self.tls_failures.append((via, "%s: %s" % (type(exc).__name__, exc)))
|
||||
try:
|
||||
sock.close()
|
||||
except OSError:
|
||||
pass
|
||||
return
|
||||
protocol = tls.selected_alpn_protocol() or "http/1.1"
|
||||
with self._lock:
|
||||
self.connections.append((via, protocol))
|
||||
self._open.append((via, tls))
|
||||
try:
|
||||
if protocol == "h2":
|
||||
self._serve_h2(tls, via)
|
||||
else:
|
||||
self._serve_h1(tls, via)
|
||||
except (OSError, ssl.SSLError, ValueError, KeyError):
|
||||
pass
|
||||
except Exception as exc: # noqa: BLE001 - an h2 protocol error ends the connection like a reset
|
||||
if not (H2_AVAILABLE and isinstance(exc, h2.exceptions.H2Error)):
|
||||
raise
|
||||
finally:
|
||||
with self._lock:
|
||||
self._open = [(v, s) for v, s in self._open if s is not tls]
|
||||
try:
|
||||
tls.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def drop(self, via: Optional[str] = None) -> int:
|
||||
"""Close every open connection that arrived by ``via`` (all of them when None). Returns how many."""
|
||||
with self._lock:
|
||||
victims = [s for v, s in self._open if via is None or v == via]
|
||||
for s in victims:
|
||||
for action in (lambda: s.shutdown(socket.SHUT_RDWR), s.close):
|
||||
try:
|
||||
action()
|
||||
except OSError:
|
||||
pass
|
||||
return len(victims)
|
||||
|
||||
def _answer(self, via: str, method: str, target: str, content_type: str,
|
||||
body: bytes) -> Tuple[int, bytes, str]:
|
||||
"""(status, body, content type) of one HTTP request, recording the DNS query it carries."""
|
||||
def bad(status: int) -> Tuple[int, bytes, str]:
|
||||
with self._lock:
|
||||
self.bad_requests.append((via, method, target, status))
|
||||
return status, b"", "text/plain"
|
||||
|
||||
split = urlsplit(target)
|
||||
if split.path != DOH_PATH:
|
||||
return bad(404)
|
||||
if method == "POST":
|
||||
if content_type.split(";")[0].strip().lower() != "application/dns-message":
|
||||
return bad(415)
|
||||
message = body
|
||||
elif method == "GET":
|
||||
values = parse_qs(split.query).get("dns")
|
||||
if not values:
|
||||
return bad(400)
|
||||
try:
|
||||
message = base64.urlsafe_b64decode(values[0] + "=" * (-len(values[0]) % 4))
|
||||
except ValueError:
|
||||
return bad(400)
|
||||
else:
|
||||
return bad(405)
|
||||
try:
|
||||
query = parse_query(message)
|
||||
except ValueError:
|
||||
return bad(400)
|
||||
with self._lock:
|
||||
self.queries.append(DohQuery(query.name, query.qtype, via))
|
||||
names = dict(self.names)
|
||||
return 200, answer_for(names, query), "application/dns-message"
|
||||
|
||||
def _serve_h1(self, tls: ssl.SSLSocket, via: str) -> None:
|
||||
buffer = b""
|
||||
while True:
|
||||
while b"\r\n\r\n" not in buffer:
|
||||
chunk = tls.recv(65536)
|
||||
if not chunk:
|
||||
return
|
||||
buffer += chunk
|
||||
head, _, buffer = buffer.partition(b"\r\n\r\n")
|
||||
lines = head.decode("latin-1").split("\r\n")
|
||||
method, target, _version = lines[0].split(" ", 2)
|
||||
headers = {}
|
||||
for line in lines[1:]:
|
||||
key, _, value = line.partition(":")
|
||||
headers[key.strip().lower()] = value.strip()
|
||||
length = int(headers.get("content-length", "0"))
|
||||
while len(buffer) < length:
|
||||
chunk = tls.recv(65536)
|
||||
if not chunk:
|
||||
return
|
||||
buffer += chunk
|
||||
body, buffer = buffer[:length], buffer[length:]
|
||||
status, payload, content_type = self._answer(via, method, target, headers.get("content-type", ""), body)
|
||||
close = headers.get("connection", "").lower() == "close"
|
||||
tls.sendall(("HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %d\r\nCache-Control: max-age=%d\r\n"
|
||||
"%s\r\n" % (status, _REASONS.get(status, "Status"), content_type, len(payload), DOH_TTL,
|
||||
"Connection: close\r\n" if close else "")).encode("latin-1") + payload)
|
||||
if close:
|
||||
return
|
||||
|
||||
def _serve_h2(self, tls: ssl.SSLSocket, via: str) -> None:
|
||||
connection = h2.connection.H2Connection(
|
||||
config=h2.config.H2Configuration(client_side=False, header_encoding="utf-8"))
|
||||
connection.initiate_connection()
|
||||
tls.sendall(connection.data_to_send())
|
||||
streams: Dict[int, dict] = {}
|
||||
while True:
|
||||
data = tls.recv(65536)
|
||||
if not data:
|
||||
return
|
||||
for event in connection.receive_data(data):
|
||||
if isinstance(event, h2.events.RequestReceived):
|
||||
streams[event.stream_id] = {"headers": dict(event.headers), "body": b""}
|
||||
elif isinstance(event, h2.events.DataReceived):
|
||||
streams[event.stream_id]["body"] += event.data
|
||||
connection.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
|
||||
elif isinstance(event, h2.events.StreamEnded):
|
||||
request = streams.pop(event.stream_id)
|
||||
headers = request["headers"]
|
||||
status, payload, content_type = self._answer(
|
||||
via, headers.get(":method", ""), headers.get(":path", ""),
|
||||
headers.get("content-type", ""), request["body"])
|
||||
connection.send_headers(event.stream_id, [
|
||||
(":status", str(status)), ("content-type", content_type),
|
||||
("content-length", str(len(payload))), ("cache-control", "max-age=%d" % DOH_TTL)])
|
||||
connection.send_data(event.stream_id, payload, end_stream=True)
|
||||
elif isinstance(event, h2.events.StreamReset):
|
||||
streams.pop(event.stream_id, None)
|
||||
elif isinstance(event, h2.events.ConnectionTerminated):
|
||||
return
|
||||
pending = connection.data_to_send()
|
||||
if pending:
|
||||
tls.sendall(pending)
|
||||
|
||||
def close(self) -> None:
|
||||
self._closed = True
|
||||
try:
|
||||
self._listener.close()
|
||||
except OSError:
|
||||
pass
|
||||
self.drop()
|
||||
try:
|
||||
self._dir.cleanup()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def __enter__(self) -> "FakeDoh":
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.close()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------- relaying
|
||||
def pump(source: socket.socket, sink: socket.socket, delay: float = 0.0) -> None:
|
||||
"""Copy bytes from ``source`` to ``sink`` until either ends, then shut both. ``delay`` seconds wait before each
|
||||
chunk is forwarded (a gateway that is far away)."""
|
||||
try:
|
||||
while True:
|
||||
data = source.recv(65536)
|
||||
if not data:
|
||||
break
|
||||
if delay:
|
||||
time.sleep(delay)
|
||||
sink.sendall(data)
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
for s in (source, sink):
|
||||
try:
|
||||
s.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def relay(a: socket.socket, b: socket.socket, delay: float = 0.0) -> None:
|
||||
"""Carry bytes both ways between two connected sockets until one ends. Blocks."""
|
||||
a.settimeout(None)
|
||||
b.settimeout(None)
|
||||
thread = threading.Thread(target=pump, args=(b, a, delay), daemon=True)
|
||||
thread.start()
|
||||
pump(a, b, delay)
|
||||
thread.join(timeout=2)
|
||||
|
||||
|
||||
def is_loopback(host: str) -> bool:
|
||||
"""True for a loopback ADDRESS. A name is never loopback here: nothing in these helpers resolves a name."""
|
||||
try:
|
||||
return ipaddress.ip_address(host).is_loopback
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
class DohGateway(Gateway):
|
||||
"""A SOCKS5 gateway of ``_socks_servers`` that carries the DoH road to a :class:`FakeDoh`.
|
||||
|
||||
* CONNECT to ``DOH_TARGETS`` is served by ``doh`` with ``via=name``;
|
||||
* CONNECT to a loopback address is relayed for real (the pages and the echo servers of a test);
|
||||
* the egress endpoints of the base class (``api.ipify.org:80``) keep working;
|
||||
* any other CONNECT is refused (reply 2 "not allowed", for an address; 4 "host unreachable", for a name) and
|
||||
listed in :attr:`refused`: the gateway never resolves a name and never reaches past the loopback.
|
||||
|
||||
:attr:`connects` (inherited) lists EVERY CONNECT target in order, so ``("page-a.test", 80)`` in it means the
|
||||
browser sent a name where it should have sent an address. :attr:`credentials_seen` lists every
|
||||
username/password offered, ``first_connection_delay`` holds the first accepted connection that many seconds
|
||||
before it is answered (a gateway that is slow to say hello), and :meth:`kill` makes the gateway dead: the port
|
||||
refuses, and every open tunnel is closed.
|
||||
"""
|
||||
|
||||
def __init__(self, name: str, doh: FakeDoh, *, user: Optional[str] = None, password: Optional[str] = None,
|
||||
first_connection_delay: float = 0.0, **gateway: object):
|
||||
# ``gateway`` goes to the base Gateway as it is (``udp="relay"``, ``relay_host``, ``rtt_ms``, ``exit_host``,
|
||||
# ``tcp_exit``, ``udp_exit``, ``tcp_data_delay``): a road with UDP is this same class, not another gateway.
|
||||
# State first: the base constructor starts the accept thread.
|
||||
self.name = name
|
||||
self.doh = doh
|
||||
self.first_connection_delay = first_connection_delay
|
||||
#: Every (username, password) a client offered.
|
||||
self.credentials_seen: List[Tuple[str, str]] = []
|
||||
#: Every CONNECT that was refused: (host, port).
|
||||
self.refused: List[Tuple[str, int]] = []
|
||||
#: How many connections were accepted, and the monotonic time of each.
|
||||
self.accepted_at: List[float] = []
|
||||
self.killed = False
|
||||
self._live: List[socket.socket] = []
|
||||
self._live_lock = threading.Lock()
|
||||
options = dict(udp="refuse", tcp_exit=EXIT, udp_exit=EXIT)
|
||||
options.update(gateway)
|
||||
super().__init__(user=user, password=password, **options)
|
||||
|
||||
# --- accepting, and the slow first hello ---------------------------------------------------------------------
|
||||
def _handle(self, c: socket.socket) -> None:
|
||||
with self._live_lock:
|
||||
self.accepted_at.append(time.monotonic())
|
||||
first = len(self.accepted_at) == 1
|
||||
self._live.append(c)
|
||||
if first and self.first_connection_delay:
|
||||
time.sleep(self.first_connection_delay)
|
||||
super()._handle(c)
|
||||
|
||||
def _greet(self, c: socket.socket) -> bool:
|
||||
"""The base negotiation, recording the credentials a client sent."""
|
||||
ver, n = _recv_exact(c, 2)
|
||||
methods = _recv_exact(c, n)
|
||||
if ver != 5:
|
||||
return False
|
||||
if self.user is not None:
|
||||
if 2 not in methods:
|
||||
self._send(c, b"\x05\xff")
|
||||
return False
|
||||
self._send(c, b"\x05\x02")
|
||||
_recv_exact(c, 1)
|
||||
offered = (_recv_exact(c, _recv_exact(c, 1)[0]).decode("utf-8", "replace"),
|
||||
_recv_exact(c, _recv_exact(c, 1)[0]).decode("utf-8", "replace"))
|
||||
self.credentials_seen.append(offered)
|
||||
ok = offered == (self.user, self.password)
|
||||
self._send(c, b"\x01" + (b"\x00" if ok else b"\x01"))
|
||||
return ok
|
||||
self._send(c, b"\x05\x00" if 0 in methods else b"\x05\x02")
|
||||
if 0 not in methods: # a client that only offers user/password: accept any
|
||||
_recv_exact(c, 1)
|
||||
offered = (_recv_exact(c, _recv_exact(c, 1)[0]).decode("utf-8", "replace"),
|
||||
_recv_exact(c, _recv_exact(c, 1)[0]).decode("utf-8", "replace"))
|
||||
self.credentials_seen.append(offered)
|
||||
self._send(c, b"\x01\x00")
|
||||
return True
|
||||
|
||||
# --- CONNECT ---------------------------------------------------------------------------------------------------
|
||||
def _connect(self, c: socket.socket, host: str, port: int) -> None:
|
||||
if (host, port) in DOH_TARGETS:
|
||||
self.connects.append((host, port))
|
||||
self._send(c, self._reply(0))
|
||||
if self.tcp_data_delay and self.rtt: # a far gateway: every chunk of the tunnel waits half the round trip
|
||||
near, far = socket.socketpair()
|
||||
threading.Thread(target=self.doh.serve, args=(far, self.name), daemon=True).start()
|
||||
try:
|
||||
relay(c, near, self.rtt / 2)
|
||||
finally:
|
||||
near.close()
|
||||
return
|
||||
self.doh.serve(c, self.name)
|
||||
return
|
||||
if (host, port) in (WHOAMI4, WHOAMI6, (WEB_NAME, 80)):
|
||||
super()._connect(c, host, port)
|
||||
return
|
||||
if not is_loopback(host):
|
||||
self.connects.append((host, port))
|
||||
self.refused.append((host, port))
|
||||
self._send(c, self._reply(2 if _is_address(host) else 4))
|
||||
return
|
||||
self.connects.append((host, port))
|
||||
try:
|
||||
upstream = socket.create_connection((host, port), timeout=10)
|
||||
except OSError:
|
||||
self._send(c, self._reply(5))
|
||||
return
|
||||
with self._live_lock:
|
||||
self._live.append(upstream)
|
||||
self._send(c, self._reply(0))
|
||||
try:
|
||||
relay(c, upstream, self.rtt / 2 if self.tcp_data_delay else 0.0)
|
||||
finally:
|
||||
upstream.close()
|
||||
|
||||
# --- the DoH road, by CONNECT target --------------------------------------------------------------------------
|
||||
def doh_connects(self) -> List[Tuple[str, int]]:
|
||||
return [t for t in self.connects if t in DOH_TARGETS]
|
||||
|
||||
def kill(self) -> None:
|
||||
"""Dead proxy: the port refuses new connections and every tunnel that was open is closed."""
|
||||
self.killed = True
|
||||
# shutdown() first: on Linux, close() alone leaves a listening socket open (and accepting) while another
|
||||
# thread is blocked in accept() on it, so the "dead" proxy would still take connections.
|
||||
try:
|
||||
self._listener.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
self.close()
|
||||
self.doh.drop(self.name)
|
||||
with self._live_lock:
|
||||
sockets, self._live = self._live, []
|
||||
for s in sockets:
|
||||
for action in (lambda: s.shutdown(socket.SHUT_RDWR), s.close):
|
||||
try:
|
||||
action()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _is_address(host: str) -> bool:
|
||||
try:
|
||||
ipaddress.ip_address(host)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def _recv_exact(s: socket.socket, n: int) -> bytes:
|
||||
data = b""
|
||||
while len(data) < n:
|
||||
chunk = s.recv(n - len(data))
|
||||
if not chunk:
|
||||
raise ConnectionError("closed")
|
||||
data += chunk
|
||||
return data
|
||||
|
||||
|
||||
__all__ = [
|
||||
"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",
|
||||
]
|
||||
@@ -0,0 +1,158 @@
|
||||
"""A local HTTPS server that speaks HTTP/3 as well, reached by its address.
|
||||
|
||||
The same port answers TCP (TLS, HTTP/1.1, with an `Alt-Svc: h3` header) and UDP (QUIC, HTTP/3, aioquic), with a self-signed
|
||||
certificate for the address it is given. It records, for every QUIC connection, the address the packets came from: a
|
||||
connection that comes from anywhere but the relay of a gateway on this host (127.0.0.1) did not go through the proxy.
|
||||
|
||||
Needs `aioquic` (pip install aioquic); a test that wants it imports it with `pytest.importorskip`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import datetime
|
||||
import http.server
|
||||
import ipaddress
|
||||
import socket
|
||||
import ssl
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
|
||||
def _certificate(address: str, directory: Path):
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import NameOID
|
||||
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, address)])
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number()).not_valid_before(now - datetime.timedelta(days=1))
|
||||
.not_valid_after(now + datetime.timedelta(days=30))
|
||||
.add_extension(x509.SubjectAlternativeName([x509.IPAddress(ipaddress.ip_address(address))]), critical=False)
|
||||
.sign(key, hashes.SHA256()))
|
||||
cert_path, key_path = directory / "cert.pem", directory / "key.pem"
|
||||
cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
||||
key_path.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption()))
|
||||
return cert_path, key_path
|
||||
|
||||
|
||||
class H3Server:
|
||||
"""TCP+TLS and QUIC on one port of `address`."""
|
||||
|
||||
def __init__(self, address: str):
|
||||
from aioquic.asyncio import serve
|
||||
from aioquic.asyncio.protocol import QuicConnectionProtocol
|
||||
from aioquic.h3.connection import H3_ALPN, H3Connection
|
||||
from aioquic.h3.events import HeadersReceived
|
||||
from aioquic.quic.configuration import QuicConfiguration
|
||||
from aioquic.quic.events import ProtocolNegotiated
|
||||
|
||||
self.address = address
|
||||
#: The address each QUIC connection came from.
|
||||
self.quic_peers: List[str] = []
|
||||
#: The paths of the requests that were answered over HTTP/3, and over TCP.
|
||||
self.h3_requests: List[str] = []
|
||||
self.tcp_requests: List[str] = []
|
||||
self._dir = tempfile.TemporaryDirectory()
|
||||
cert, key = _certificate(address, Path(self._dir.name))
|
||||
|
||||
server = self
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
timeout = 5
|
||||
|
||||
def do_GET(self):
|
||||
server.tcp_requests.append(self.path)
|
||||
body = b"tcp ok"
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/plain")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Alt-Svc", 'h3=":%d"; ma=3600' % server.port)
|
||||
self.send_header("Access-Control-Allow-Origin", "*")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
# One port for both: the TCP port first, then the same number for UDP.
|
||||
for _ in range(50):
|
||||
tcp = http.server.ThreadingHTTPServer((address, 0), Handler)
|
||||
port = tcp.server_address[1]
|
||||
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
probe.bind((address, port))
|
||||
probe.close()
|
||||
break
|
||||
except OSError:
|
||||
probe.close()
|
||||
tcp.server_close()
|
||||
else:
|
||||
raise RuntimeError("no port free for both TCP and UDP")
|
||||
self.port = port
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain(str(cert), str(key))
|
||||
context.set_alpn_protocols(["http/1.1"])
|
||||
tcp.socket = context.wrap_socket(tcp.socket, server_side=True)
|
||||
tcp.daemon_threads = True
|
||||
self._tcp = tcp
|
||||
threading.Thread(target=tcp.serve_forever, daemon=True).start()
|
||||
|
||||
class Protocol(QuicConnectionProtocol):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._http = None
|
||||
|
||||
def quic_event_received(self, event):
|
||||
if isinstance(event, ProtocolNegotiated):
|
||||
self._http = H3Connection(self._quic)
|
||||
server.quic_peers.append(self._quic._network_paths[0].addr[0])
|
||||
if self._http is not None:
|
||||
for http_event in self._http.handle_event(event):
|
||||
if isinstance(http_event, HeadersReceived):
|
||||
headers = dict(http_event.headers)
|
||||
server.h3_requests.append(headers.get(b":path", b"").decode())
|
||||
self._http.send_headers(http_event.stream_id, [
|
||||
(b":status", b"200"), (b"content-type", b"text/plain"),
|
||||
(b"access-control-allow-origin", b"*")])
|
||||
self._http.send_data(http_event.stream_id, b"h3 ok", end_stream=True)
|
||||
self.transmit()
|
||||
|
||||
configuration = QuicConfiguration(is_client=False, alpn_protocols=H3_ALPN)
|
||||
configuration.load_cert_chain(str(cert), str(key))
|
||||
self._loop = asyncio.new_event_loop()
|
||||
started = threading.Event()
|
||||
|
||||
def run():
|
||||
asyncio.set_event_loop(self._loop)
|
||||
self._quic = self._loop.run_until_complete(
|
||||
serve(address, port, configuration=configuration, create_protocol=Protocol))
|
||||
started.set()
|
||||
self._loop.run_forever()
|
||||
|
||||
threading.Thread(target=run, daemon=True).start()
|
||||
if not started.wait(10):
|
||||
raise RuntimeError("the QUIC server did not start")
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
return "https://%s:%d/" % (self.address, self.port)
|
||||
|
||||
def close(self) -> None:
|
||||
self._tcp.shutdown()
|
||||
self._tcp.server_close()
|
||||
self._quic.close()
|
||||
self._loop.call_soon_threadsafe(self._loop.stop)
|
||||
self._dir.cleanup()
|
||||
|
||||
def __enter__(self) -> "H3Server":
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.close()
|
||||
@@ -0,0 +1,234 @@
|
||||
"""An HTTP proxy on 127.0.0.1 that asks for credentials, and carries the DoH road to a :class:`FakeDoh`.
|
||||
|
||||
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 (``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
|
||||
travels to the proxy, the proxy is the one that resolves it) is forwarded for real to a loopback address. The
|
||||
proxy "resolves" the name with the zone of the FakeDoh (``doh.names``) and never asks any other resolver; a name
|
||||
that is not in the zone answers ``502``. That is the exit's own resolution, and it is why a page behind an HTTP
|
||||
proxy does NOT make the browser ask DoH for its name: something else must (an ICE server name does);
|
||||
* every request is recorded in :attr:`seen` with the ``Proxy-Authorization`` header it carried and the status given.
|
||||
|
||||
Hermetic: nothing leaves the loopback and no name is resolved by the operating system.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import socket
|
||||
import threading
|
||||
from typing import Dict, List, NamedTuple, Optional, Tuple
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from _doh_servers import DOH_TARGETS, FakeDoh, is_loopback, relay
|
||||
|
||||
_REASONS = {200: "Connection Established", 403: "Forbidden", 405: "Method Not Allowed",
|
||||
407: "Proxy Authentication Required", 502: "Bad Gateway"}
|
||||
|
||||
|
||||
def basic(user: str, password: str) -> str:
|
||||
"""The ``Proxy-Authorization`` value of Basic credentials (UTF-8, RFC 7617)."""
|
||||
return "Basic " + base64.b64encode(("%s:%s" % (user, password)).encode("utf-8")).decode("ascii")
|
||||
|
||||
|
||||
class Seen(NamedTuple):
|
||||
method: str
|
||||
host: str
|
||||
port: int
|
||||
#: The Proxy-Authorization header as it came, None when the request had none.
|
||||
authorization: Optional[str]
|
||||
status: int
|
||||
|
||||
|
||||
class HttpProxy:
|
||||
"""See the module docstring. ``user=None`` means no authentication is asked."""
|
||||
|
||||
def __init__(self, name: str, doh: FakeDoh, *, user: Optional[str] = None, password: Optional[str] = None):
|
||||
self.name = name
|
||||
self.doh = doh
|
||||
self.user, self.password = user, password
|
||||
#: Every request, in order.
|
||||
self.seen: List[Seen] = []
|
||||
self._lock = threading.Lock()
|
||||
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.port: int = self._listener.getsockname()[1]
|
||||
self._closed = False
|
||||
threading.Thread(target=self._accept, daemon=True).start()
|
||||
|
||||
# --- what the test hands to the product ---------------------------------------------------------------------
|
||||
@property
|
||||
def server(self) -> str:
|
||||
return "http://127.0.0.1:%d" % self.port
|
||||
|
||||
@property
|
||||
def proxy(self) -> dict:
|
||||
"""The endpoint dict the core takes: ``{"server": ..., [username, password]}``."""
|
||||
out = {"server": self.server}
|
||||
if self.user is not None:
|
||||
out.update(username=self.user, password=self.password)
|
||||
return out
|
||||
|
||||
@property
|
||||
def expected_authorization(self) -> Optional[str]:
|
||||
return basic(self.user, self.password) if self.user is not None else None
|
||||
|
||||
# --- what the test reads ------------------------------------------------------------------------------------
|
||||
@property
|
||||
def connects(self) -> List[Tuple[str, int]]:
|
||||
"""The targets of the CONNECTs that were accepted, in order."""
|
||||
with self._lock:
|
||||
return [(s.host, s.port) for s in self.seen if s.method == "CONNECT" and s.status == 200]
|
||||
|
||||
@property
|
||||
def refused_for_credentials(self) -> List[Seen]:
|
||||
with self._lock:
|
||||
return [s for s in self.seen if s.status == 407]
|
||||
|
||||
def authorizations_for(self, host: str, port: int) -> List[Optional[str]]:
|
||||
"""The Proxy-Authorization of every CONNECT to ``host:port`` (the DoH address, for instance)."""
|
||||
with self._lock:
|
||||
return [s.authorization for s in self.seen if s.method == "CONNECT" and (s.host, s.port) == (host, port)]
|
||||
|
||||
def doh_authorizations(self) -> List[Optional[str]]:
|
||||
with self._lock:
|
||||
return [s.authorization for s in self.seen if s.method == "CONNECT" and (s.host, s.port) in DOH_TARGETS]
|
||||
|
||||
def doh_connects(self) -> List[Tuple[str, int]]:
|
||||
return [t for t in self.connects if t in DOH_TARGETS]
|
||||
|
||||
# --- serving ------------------------------------------------------------------------------------------------
|
||||
def close(self) -> None:
|
||||
self._closed = True
|
||||
try:
|
||||
self._listener.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def __enter__(self) -> "HttpProxy":
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.close()
|
||||
|
||||
def _accept(self) -> None:
|
||||
while not self._closed:
|
||||
try:
|
||||
conn, _ = self._listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self._handle, args=(conn,), daemon=True).start()
|
||||
|
||||
@staticmethod
|
||||
def _answer(conn: socket.socket, status: int, extra: str = "") -> None:
|
||||
conn.sendall(("HTTP/1.1 %d %s\r\n%sContent-Length: 0\r\n%s\r\n" % (
|
||||
status, _REASONS.get(status, "Status"), extra,
|
||||
"Connection: close\r\n" if status != 200 else "")).encode("latin-1"))
|
||||
|
||||
def _record(self, method: str, host: str, port: int, authorization: Optional[str], status: int) -> None:
|
||||
with self._lock:
|
||||
self.seen.append(Seen(method, host, port, authorization, status))
|
||||
|
||||
def _handle(self, conn: socket.socket) -> None:
|
||||
try:
|
||||
conn.settimeout(30)
|
||||
data = b""
|
||||
while b"\r\n\r\n" not in data:
|
||||
chunk = conn.recv(65536)
|
||||
if not chunk:
|
||||
return
|
||||
data += chunk
|
||||
head, _, rest = data.partition(b"\r\n\r\n")
|
||||
lines = head.decode("latin-1").split("\r\n")
|
||||
method, target, _version = lines[0].split(" ", 2)
|
||||
headers: Dict[str, str] = {}
|
||||
for line in lines[1:]:
|
||||
key, _, value = line.partition(":")
|
||||
headers[key.strip().lower()] = value.strip()
|
||||
authorization = headers.get("proxy-authorization")
|
||||
if method == "CONNECT":
|
||||
host, _, port_text = target.rpartition(":")
|
||||
host, port = host.strip("[]"), int(port_text)
|
||||
else:
|
||||
split = urlsplit(target)
|
||||
host, port = split.hostname or "", split.port or 80
|
||||
if self.user is not None and authorization != self.expected_authorization:
|
||||
self._record(method, host, port, authorization, 407)
|
||||
self._answer(conn, 407, 'Proxy-Authenticate: Basic realm="invisible"\r\n')
|
||||
return
|
||||
if method == "CONNECT":
|
||||
self._connect(conn, host, port, authorization)
|
||||
elif method == "GET":
|
||||
self._forward(conn, host, port, authorization, split, headers, rest)
|
||||
else:
|
||||
self._record(method, host, port, authorization, 405)
|
||||
self._answer(conn, 405)
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
conn.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _connect(self, conn: socket.socket, host: str, port: int, authorization: Optional[str]) -> None:
|
||||
if (host, port) in DOH_TARGETS:
|
||||
self._record("CONNECT", host, port, authorization, 200)
|
||||
self._answer(conn, 200)
|
||||
self.doh.serve(conn, self.name)
|
||||
return
|
||||
if not is_loopback(host):
|
||||
self._record("CONNECT", host, port, authorization, 403)
|
||||
self._answer(conn, 403)
|
||||
return
|
||||
try:
|
||||
upstream = socket.create_connection((host, port), timeout=10)
|
||||
except OSError:
|
||||
self._record("CONNECT", host, port, authorization, 502)
|
||||
self._answer(conn, 502)
|
||||
return
|
||||
self._record("CONNECT", host, port, authorization, 200)
|
||||
self._answer(conn, 200)
|
||||
try:
|
||||
relay(conn, upstream)
|
||||
finally:
|
||||
upstream.close()
|
||||
|
||||
def _forward(self, conn: socket.socket, host: str, port: int, authorization: Optional[str], split,
|
||||
headers: Dict[str, str], rest: bytes) -> None:
|
||||
"""A plain GET, in the absolute form: resolved by the zone of the FakeDoh, then fetched for real."""
|
||||
address = host if is_loopback(host) else self.doh.names.get(host.lower(), "")
|
||||
if not address or not is_loopback(address):
|
||||
self._record("GET", host, port, authorization, 502)
|
||||
self._answer(conn, 502)
|
||||
return
|
||||
try:
|
||||
upstream = socket.create_connection((address, port), timeout=10)
|
||||
except OSError:
|
||||
self._record("GET", host, port, authorization, 502)
|
||||
self._answer(conn, 502)
|
||||
return
|
||||
self._record("GET", host, port, authorization, 200)
|
||||
try:
|
||||
path = (split.path or "/") + ("?" + split.query if split.query else "")
|
||||
passed = "".join("%s: %s\r\n" % (k, v) for k, v in headers.items()
|
||||
if not k.startswith("proxy-") and k not in ("connection", "keep-alive"))
|
||||
upstream.sendall(("GET %s HTTP/1.1\r\n%sConnection: close\r\n\r\n" % (path, passed)).encode("latin-1"))
|
||||
conn.settimeout(None)
|
||||
upstream.settimeout(None)
|
||||
while True:
|
||||
data = upstream.recv(65536)
|
||||
if not data:
|
||||
break
|
||||
conn.sendall(data)
|
||||
finally:
|
||||
upstream.close()
|
||||
|
||||
|
||||
__all__ = ["HttpProxy", "Seen", "basic"]
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
"""Two traps for what a browser does that it should not: a connection that does not go through the gateway, and a
|
||||
question put to the resolver of the machine.
|
||||
|
||||
* :class:`Watcher` samples, from before a launch until it is stopped, the network connections of every process that
|
||||
is a DESCENDANT of this test process and whose executable name contains a given word (``firefox`` by default).
|
||||
An inet connection - TCP in any state, SYN_SENT included, or a connected UDP socket - whose remote address is not
|
||||
loopback is a DIRECT connection: the browser did not go through the proxy (the proxy of a test is on 127.0.0.1).
|
||||
It also lists the names of every descendant it saw, which is how a test shows that no helper process
|
||||
(crash reporter, updater...) was ever started. Descendants of THIS process only, so parallel workers do not see
|
||||
each other's browsers.
|
||||
* :class:`ResolverTrap` listens on 127.0.0.1:53 (UDP and TCP, and ::1 when it can) and points ``/etc/resolv.conf``
|
||||
at it for as long as it runs, restoring the file byte for byte at the end, so every question that reaches the
|
||||
resolver of the machine is counted as ``(name, qtype)``. It needs Linux, root and a writable resolv.conf:
|
||||
``ResolverTrap.available`` says so and ``ResolverTrap.reason`` says why not. The trap answers from ``answers``
|
||||
(name -> IPv4) and REFUSES everything else at once, so nothing waits for it. Anything on the machine that resolves
|
||||
a name while it runs is counted too, the test process included: a test must not resolve names itself.
|
||||
|
||||
``ResolverTrap(port=0, rewrite_resolv_conf=False)`` is the same trap on a free port with no file touched, for the
|
||||
unit tests of the trap itself and for a client that is told where to ask.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import os
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Dict, Iterable, List, NamedTuple, Optional, Set, Tuple
|
||||
|
||||
from _doh_servers import RCODE_REFUSED, DohQuery, answer_for, build_response, parse_query
|
||||
|
||||
RESOLV_CONF = Path("/etc/resolv.conf")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------- Watcher
|
||||
class DirectConnection(NamedTuple):
|
||||
pid: int
|
||||
process: str # the name of the process
|
||||
protocol: str # "tcp" or "udp"
|
||||
local: str
|
||||
remote: str # "ip:port"
|
||||
status: str
|
||||
|
||||
|
||||
def _is_loopback(ip: str) -> bool:
|
||||
try:
|
||||
address = ipaddress.ip_address(ip.split("%")[0])
|
||||
except ValueError:
|
||||
return False
|
||||
if address.version == 6 and address.ipv4_mapped is not None:
|
||||
address = address.ipv4_mapped
|
||||
return address.is_loopback
|
||||
|
||||
|
||||
def _connections_of(process) -> list:
|
||||
getter = getattr(process, "net_connections", None) or process.connections
|
||||
return getter(kind="inet")
|
||||
|
||||
|
||||
class Watcher:
|
||||
"""Samples every ``interval`` seconds. Use as a context manager, or ``start()`` and ``stop()``.
|
||||
|
||||
``match`` is a word (or several) searched, case-insensitively, in the name of a process: only the connections of
|
||||
the descendants whose name contains one of them are judged. Every descendant, matching or not, is listed in
|
||||
:attr:`process_names`.
|
||||
"""
|
||||
|
||||
def __init__(self, *, interval: float = 0.02, match: Iterable[str] | str = "firefox", root_pid: Optional[int] = None):
|
||||
self.interval = interval
|
||||
self.match = tuple(m.lower() for m in ([match] if isinstance(match, str) else match))
|
||||
self.root_pid = root_pid if root_pid is not None else os.getpid()
|
||||
#: Every direct connection seen, once per (pid, remote, status).
|
||||
self.direct: List[DirectConnection] = []
|
||||
#: Names of the descendants seen, in the order they were first seen (one entry per name).
|
||||
self.process_names: List[str] = []
|
||||
#: pids of the matching descendants seen.
|
||||
self.watched_pids: Set[int] = set()
|
||||
self.samples = 0
|
||||
self._seen_keys: Set[tuple] = set()
|
||||
self._stop = threading.Event()
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
|
||||
# --- control -------------------------------------------------------------------------------------------------
|
||||
def start(self) -> "Watcher":
|
||||
if self._thread is None:
|
||||
self._thread = threading.Thread(target=self._run, daemon=True, name="leak-watcher")
|
||||
self._thread.start()
|
||||
return self
|
||||
|
||||
def stop(self) -> "Watcher":
|
||||
self._stop.set()
|
||||
if self._thread is not None:
|
||||
self._thread.join(timeout=5)
|
||||
self._thread = None
|
||||
return self
|
||||
|
||||
def __enter__(self) -> "Watcher":
|
||||
return self.start()
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.stop()
|
||||
|
||||
# --- what a test asks ----------------------------------------------------------------------------------------
|
||||
def describe(self) -> str:
|
||||
return "; ".join("%s(pid %d) %s %s -> %s %s" % (c.process, c.pid, c.protocol, c.local, c.remote, c.status)
|
||||
for c in self.direct) or "nothing"
|
||||
|
||||
def helpers_seen(self, forbidden: Iterable[str]) -> List[str]:
|
||||
"""The process names whose stem (the name without its extension) contains one of ``forbidden``."""
|
||||
words = [w.lower() for w in forbidden]
|
||||
return [n for n in self.process_names if any(w in os.path.splitext(n)[0].lower() for w in words)]
|
||||
|
||||
# --- the sampling --------------------------------------------------------------------------------------------
|
||||
def _run(self) -> None:
|
||||
import psutil
|
||||
|
||||
root = None
|
||||
while not self._stop.is_set():
|
||||
started = time.monotonic()
|
||||
try:
|
||||
root = root or psutil.Process(self.root_pid)
|
||||
children = root.children(recursive=True)
|
||||
except psutil.Error:
|
||||
children = []
|
||||
for child in children:
|
||||
try:
|
||||
name = child.name()
|
||||
except psutil.Error:
|
||||
continue
|
||||
if name not in self.process_names:
|
||||
self.process_names.append(name)
|
||||
if not any(m in name.lower() for m in self.match):
|
||||
continue
|
||||
self.watched_pids.add(child.pid)
|
||||
try:
|
||||
connections = _connections_of(child)
|
||||
except (psutil.Error, OSError):
|
||||
continue
|
||||
for c in connections:
|
||||
if not c.raddr or _is_loopback(c.raddr.ip):
|
||||
continue
|
||||
protocol = "udp" if c.type == socket.SOCK_DGRAM else "tcp"
|
||||
key = (child.pid, protocol, c.raddr.ip, c.raddr.port, c.status)
|
||||
if key in self._seen_keys:
|
||||
continue
|
||||
self._seen_keys.add(key)
|
||||
self.direct.append(DirectConnection(
|
||||
child.pid, name, protocol, "%s:%s" % (c.laddr.ip, c.laddr.port) if c.laddr else "",
|
||||
"%s:%s" % (c.raddr.ip, c.raddr.port), c.status))
|
||||
self.samples += 1
|
||||
self._stop.wait(max(0.0, self.interval - (time.monotonic() - started)))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------- ResolverTrap
|
||||
def _trap_capability() -> Tuple[bool, str]:
|
||||
if not sys.platform.startswith("linux"):
|
||||
return False, "the resolver trap needs Linux (it points /etc/resolv.conf at itself)"
|
||||
if os.geteuid() != 0:
|
||||
return False, "the resolver trap needs root (port 53 and /etc/resolv.conf)"
|
||||
if not os.access(RESOLV_CONF, os.W_OK):
|
||||
return False, "/etc/resolv.conf is not writable"
|
||||
return True, ""
|
||||
|
||||
|
||||
class ResolverTrap:
|
||||
"""A resolver on loopback that counts what it is asked. See the module docstring."""
|
||||
|
||||
available, reason = _trap_capability()
|
||||
|
||||
def __init__(self, answers: Optional[Dict[str, str]] = None, *, port: int = 53,
|
||||
rewrite_resolv_conf: bool = True):
|
||||
self.answers = {k.lower(): v for k, v in (answers or {}).items()}
|
||||
self.port = port
|
||||
self.rewrite_resolv_conf = rewrite_resolv_conf
|
||||
#: Every question: (name, qtype, "udp"|"tcp").
|
||||
self.queries: List[DohQuery] = []
|
||||
self._lock = threading.Lock()
|
||||
self._sockets: List[socket.socket] = []
|
||||
self._original: Optional[bytes] = None
|
||||
self._running = False
|
||||
|
||||
# --- what a test reads ---------------------------------------------------------------------------------------
|
||||
def names(self) -> List[str]:
|
||||
with self._lock:
|
||||
return sorted({q.name for q in self.queries})
|
||||
|
||||
def asked(self, name: str, qtype: Optional[int] = None) -> List[DohQuery]:
|
||||
name = name.lower().rstrip(".")
|
||||
with self._lock:
|
||||
return [q for q in self.queries if q.name == name and (qtype is None or q.qtype == qtype)]
|
||||
|
||||
def describe(self) -> str:
|
||||
with self._lock:
|
||||
return ", ".join("%s/%d (%s)" % q for q in self.queries) or "nothing"
|
||||
|
||||
# --- control -------------------------------------------------------------------------------------------------
|
||||
def __enter__(self) -> "ResolverTrap":
|
||||
if self.rewrite_resolv_conf and not self.available:
|
||||
raise RuntimeError(self.reason)
|
||||
try:
|
||||
self._bind()
|
||||
if self.rewrite_resolv_conf:
|
||||
self._original = RESOLV_CONF.read_bytes()
|
||||
# In place, not by rename: in a container the file is often a bind mount.
|
||||
with open(RESOLV_CONF, "wb") as f:
|
||||
f.write(b"nameserver 127.0.0.1\noptions timeout:1 attempts:1\n")
|
||||
except BaseException:
|
||||
self._restore()
|
||||
raise
|
||||
self._running = True
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self._running = False
|
||||
self._restore()
|
||||
|
||||
def _restore(self) -> None:
|
||||
if self._original is not None:
|
||||
with open(RESOLV_CONF, "wb") as f:
|
||||
f.write(self._original)
|
||||
self._original = None
|
||||
for s in self._sockets:
|
||||
try:
|
||||
s.close()
|
||||
except OSError:
|
||||
pass
|
||||
self._sockets = []
|
||||
|
||||
def _bind(self) -> None:
|
||||
"""UDP and TCP on 127.0.0.1 (required) and on ::1 (when it can): the same port for all of them."""
|
||||
discarded: List[socket.socket] = [] # closed at the end, so a failed attempt's port is not handed out again
|
||||
made: List[socket.socket] = []
|
||||
try:
|
||||
for attempt in range(200):
|
||||
made = self._bind_once(discarded)
|
||||
if made:
|
||||
break
|
||||
if self.port != 0:
|
||||
break
|
||||
if not made:
|
||||
raise OSError("the resolver trap found no port it could bind for TCP and UDP")
|
||||
finally:
|
||||
for s in discarded:
|
||||
s.close()
|
||||
self._sockets += made
|
||||
for s in made:
|
||||
target = self._serve_udp if s.type == socket.SOCK_DGRAM else self._serve_tcp
|
||||
threading.Thread(target=target, args=(s,), daemon=True).start()
|
||||
|
||||
def _bind_once(self, discarded: List[socket.socket]) -> List[socket.socket]:
|
||||
"""One attempt: the sockets bound, or [] after putting what it opened in ``discarded``."""
|
||||
made: List[socket.socket] = []
|
||||
port = self.port
|
||||
for family, host, required in ((socket.AF_INET, "127.0.0.1", True), (socket.AF_INET6, "::1", False)):
|
||||
pair: List[socket.socket] = [] # this family's TCP and UDP, kept or dropped together
|
||||
try:
|
||||
# TCP first: Windows keeps big excluded ranges and hands out ephemeral ports in sequence, so a
|
||||
# UDP-first pick can land in a range TCP may not bind, again and again.
|
||||
tcp = socket.socket(family, socket.SOCK_STREAM)
|
||||
pair.append(tcp)
|
||||
if sys.platform != "win32": # on Windows SO_REUSEADDR is "share the port": it breaks bind
|
||||
tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
tcp.bind((host, port))
|
||||
if port == 0:
|
||||
port = tcp.getsockname()[1]
|
||||
tcp.listen(16)
|
||||
udp = socket.socket(family, socket.SOCK_DGRAM)
|
||||
pair.append(udp)
|
||||
udp.bind((host, port))
|
||||
except OSError:
|
||||
discarded += pair
|
||||
if required:
|
||||
discarded += made
|
||||
return []
|
||||
continue
|
||||
made += pair
|
||||
self.port = port
|
||||
return made
|
||||
|
||||
# --- answering -----------------------------------------------------------------------------------------------
|
||||
def _respond(self, message: bytes, protocol: str) -> Optional[bytes]:
|
||||
try:
|
||||
query = parse_query(message)
|
||||
except ValueError:
|
||||
return None
|
||||
with self._lock:
|
||||
self.queries.append(DohQuery(query.name, query.qtype, protocol))
|
||||
if query.name in self.answers:
|
||||
return answer_for(self.answers, query)
|
||||
return build_response(query, RCODE_REFUSED)
|
||||
|
||||
def _serve_udp(self, sock: socket.socket) -> None:
|
||||
while True:
|
||||
try:
|
||||
data, peer = sock.recvfrom(4096)
|
||||
except OSError:
|
||||
return
|
||||
response = self._respond(data, "udp")
|
||||
if response is not None:
|
||||
try:
|
||||
sock.sendto(response, peer)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _serve_tcp(self, listener: socket.socket) -> None:
|
||||
while True:
|
||||
try:
|
||||
conn, _ = listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self._tcp_conversation, args=(conn,), daemon=True).start()
|
||||
|
||||
def _tcp_conversation(self, conn: socket.socket) -> None:
|
||||
try:
|
||||
conn.settimeout(5)
|
||||
while True:
|
||||
head = conn.recv(2)
|
||||
if len(head) < 2:
|
||||
return
|
||||
size = struct.unpack("!H", head)[0]
|
||||
message = b""
|
||||
while len(message) < size:
|
||||
chunk = conn.recv(size - len(message))
|
||||
if not chunk:
|
||||
return
|
||||
message += chunk
|
||||
response = self._respond(message, "tcp")
|
||||
if response is None:
|
||||
return
|
||||
conn.sendall(struct.pack("!H", len(response)) + response)
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
__all__ = ["DirectConnection", "ResolverTrap", "Watcher"]
|
||||
@@ -0,0 +1,443 @@
|
||||
"""Three local SOCKS5 gateways on 127.0.0.1, for tests that need a real wire.
|
||||
|
||||
Reusable: nothing here knows about the core. A test (or the wrapper's system
|
||||
test) starts one with ``with coherent() as gw:`` and points the product at
|
||||
``gw.server`` (``socks5://127.0.0.1:<port>``), with ``gw.credentials`` when the
|
||||
gateway asks for a user and password.
|
||||
|
||||
The three gateways are the three things a real one can be:
|
||||
|
||||
* :func:`coherent` - TCP CONNECT works, UDP ASSOCIATE is granted, and the relay
|
||||
carries a STUN binding request to a fake STUN server that answers with the
|
||||
SAME address the TCP side reports as the exit. This is the gateway whose UDP
|
||||
can be trusted.
|
||||
* :func:`tcp_only` - TCP CONNECT works, UDP ASSOCIATE is refused with reply code
|
||||
7 ("command not supported"), the way a residential gateway does.
|
||||
* :func:`mismatched` - UDP ASSOCIATE is granted and STUN answers, but with an
|
||||
address DIFFERENT from the TCP exit: the disagreement a detector looks for.
|
||||
|
||||
Everything is on loopback, so the "exit address" is made observable and
|
||||
controllable instead of real: the TCP exit is what the gateway's fake "what is
|
||||
my address" endpoint (``api.ipify.org:80``, the one the product asks) answers,
|
||||
and the UDP exit is what the fake STUN server puts in its XOR-MAPPED-ADDRESS.
|
||||
Both are chosen by the test (``tcp_exit`` and ``udp_exit`` arguments).
|
||||
|
||||
Any other CONNECT is really forwarded, and any other UDP datagram is really
|
||||
forwarded to its destination and the reply wrapped back, so a page, or an echo
|
||||
server on 127.0.0.1, can be reached through the gateway and the test can
|
||||
observe which road its bytes took (:attr:`Gateway.connects`,
|
||||
:attr:`Gateway.datagrams`).
|
||||
|
||||
This is the ONE SOCKS5 gateway of the test suite. A road that needs more than the three above (a TURN server, a resolver,
|
||||
a page, by NAME: ``tests/_turn_chain.py``) subclasses :class:`Gateway` and overrides the small hooks (:meth:`Gateway._route`,
|
||||
:meth:`Gateway._target`, :attr:`Gateway.whoami_names`) instead of re-implementing the greeting, the authentication, the
|
||||
ASSOCIATE, the relay or the round trip.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import socket
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
#: The name the product's STUN probe sends through the relay. The relay maps it
|
||||
#: to the fake STUN server; every other destination is forwarded for real.
|
||||
STUN_NAME = "stun.l.google.com"
|
||||
STUN_PORT = 19302
|
||||
#: The same STUN server by NUMBER. A page cannot resolve a name behind the session (the engine forbids local
|
||||
#: resolution), so the wrapper's system test hands the page this address; like the name it is a documentation
|
||||
#: address (RFC 5737, TEST-NET-2), unroutable: the only road to it is the relay, which maps it to the fake STUN
|
||||
#: server. (A copy of invisible_core's tests/_socks_servers.py with this one addition.)
|
||||
STUN_NUMBER = "198.51.100.5"
|
||||
#: A page the gateway serves itself, for a test that loads one through the proxy (a name nothing else resolves).
|
||||
WEB_NAME = "page.test"
|
||||
#: The echo endpoints the product asks for its TCP exit.
|
||||
WHOAMI4 = ("api.ipify.org", 80)
|
||||
WHOAMI6 = ("api6.ipify.org", 80)
|
||||
|
||||
_MAGIC = b"\x21\x12\xa4\x42"
|
||||
|
||||
|
||||
def _recv_exact(s: socket.socket, n: int) -> bytes:
|
||||
data = b""
|
||||
while len(data) < n:
|
||||
chunk = s.recv(n - len(data))
|
||||
if not chunk:
|
||||
raise ConnectionError("closed")
|
||||
data += chunk
|
||||
return data
|
||||
|
||||
|
||||
class FakeStun:
|
||||
"""A UDP STUN server that answers every binding request with ``mapped_ip``."""
|
||||
|
||||
def __init__(self, mapped_ip: str, mapped_port: int = 40000):
|
||||
self.mapped_ip = mapped_ip
|
||||
self.mapped_port = mapped_port
|
||||
self.requests = 0
|
||||
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self._sock.bind(("127.0.0.1", 0))
|
||||
self.address: Tuple[str, int] = self._sock.getsockname()
|
||||
self._thread = threading.Thread(target=self._serve, daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def _serve(self) -> None:
|
||||
while True:
|
||||
try:
|
||||
data, peer = self._sock.recvfrom(2048)
|
||||
except OSError:
|
||||
return
|
||||
if len(data) < 20 or data[0:2] != b"\x00\x01":
|
||||
continue
|
||||
self.requests += 1
|
||||
txid = data[8:20]
|
||||
xport = struct.pack("!H", self.mapped_port ^ 0x2112)
|
||||
xaddr = bytes(a ^ b for a, b in zip(socket.inet_aton(self.mapped_ip), _MAGIC))
|
||||
attr = struct.pack("!HH", 0x0020, 8) + b"\x00\x01" + xport + xaddr
|
||||
resp = b"\x01\x01" + struct.pack("!H", len(attr)) + _MAGIC + txid + attr
|
||||
try:
|
||||
self._sock.sendto(resp, peer)
|
||||
except OSError:
|
||||
return
|
||||
|
||||
def close(self) -> None:
|
||||
self._sock.close()
|
||||
|
||||
|
||||
class Gateway:
|
||||
"""A SOCKS5 server. ``udp`` is ``"relay"`` or ``"refuse"`` (reply code 7)."""
|
||||
|
||||
def __init__(self, *, udp: str, tcp_exit: str, udp_exit: str,
|
||||
user: Optional[str] = None, password: Optional[str] = None,
|
||||
relay_host: str = "127.0.0.1", rtt_ms: int = 0,
|
||||
exit_host: str = "127.0.0.1", tcp_data_delay: bool = False):
|
||||
assert udp in ("relay", "refuse")
|
||||
self.udp = udp
|
||||
#: The round trip to this gateway, in seconds: every answer on the control connection waits for it, and each
|
||||
#: datagram the relay carries waits half of it each way. A real gateway is not on loopback.
|
||||
self.rtt = rtt_ms / 1000.0
|
||||
#: The address of the UDP relay, the BND.ADDR of the association. A real gateway's is a routable address; the
|
||||
#: loopback default only suits a client whose UDP socket is not bound to an interface (an engine's ICE
|
||||
#: sockets are, and Windows does not send from an interface address to loopback).
|
||||
self.relay_host = relay_host
|
||||
#: The local address the relay's datagrams leave from (the source a server behind the gateway sees). Another
|
||||
#: loopback address makes a client that sent direct (from 127.0.0.1) tell apart from one that used the relay.
|
||||
self.exit_host = exit_host
|
||||
#: Whether each chunk of a forwarded TCP stream also waits half the round trip (a far gateway), as the datagrams do.
|
||||
self.tcp_data_delay = tcp_data_delay
|
||||
self.tcp_exit = tcp_exit
|
||||
self.user, self.password = user, password
|
||||
self.stun = FakeStun(udp_exit)
|
||||
#: Every CONNECT, as (host, port), in order.
|
||||
self.connects: List[Tuple[str, int]] = []
|
||||
#: Every UDP ASSOCIATE request, answered or refused.
|
||||
self.associates = 0
|
||||
#: When the gateway started: the origin of the times below.
|
||||
self.t0 = time.monotonic()
|
||||
#: Every UDP ASSOCIATE that was granted, as [start, end] seconds from t0; end is None until it was answered.
|
||||
self.associations: List[List[Optional[float]]] = []
|
||||
#: Every datagram the relay carried out, as (host as sent, port, address type, seconds from t0).
|
||||
self.datagram_log: List[Tuple[str, int, int, float]] = []
|
||||
#: Every datagram the relay carried out, as (host, port, payload).
|
||||
self.datagrams: List[Tuple[str, int, bytes]] = []
|
||||
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.port: int = self._listener.getsockname()[1]
|
||||
self._closed = False
|
||||
threading.Thread(target=self._accept, daemon=True).start()
|
||||
|
||||
# --- what the test hands to the product ---------------------------------
|
||||
@property
|
||||
def server(self) -> str:
|
||||
return "socks5://127.0.0.1:%d" % self.port
|
||||
|
||||
@property
|
||||
def credentials(self) -> dict:
|
||||
return ({"username": self.user, "password": self.password}
|
||||
if self.user is not None else {})
|
||||
|
||||
@property
|
||||
def proxy(self) -> dict:
|
||||
"""The endpoint dict the core takes: ``{"server": ..., [credentials]}``."""
|
||||
return dict({"server": self.server}, **self.credentials)
|
||||
|
||||
def close(self) -> None:
|
||||
self._closed = True
|
||||
for s in (self._listener,):
|
||||
try:
|
||||
s.close()
|
||||
except OSError:
|
||||
pass
|
||||
self.stun.close()
|
||||
|
||||
def __enter__(self) -> "Gateway":
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.close()
|
||||
|
||||
# --- the TCP side --------------------------------------------------------
|
||||
def _send(self, c: socket.socket, data: bytes) -> None:
|
||||
if self.rtt:
|
||||
time.sleep(self.rtt)
|
||||
c.sendall(data)
|
||||
|
||||
def _accept(self) -> None:
|
||||
while not self._closed:
|
||||
try:
|
||||
conn, _ = self._listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self._handle, args=(conn,), daemon=True).start()
|
||||
|
||||
def _greet(self, c: socket.socket) -> bool:
|
||||
ver, n = _recv_exact(c, 2)
|
||||
methods = _recv_exact(c, n)
|
||||
if ver != 5:
|
||||
return False
|
||||
if self.user is not None:
|
||||
if 2 not in methods:
|
||||
self._send(c, b"\x05\xff")
|
||||
return False
|
||||
self._send(c, b"\x05\x02")
|
||||
_recv_exact(c, 1)
|
||||
u = _recv_exact(c, _recv_exact(c, 1)[0]).decode()
|
||||
p = _recv_exact(c, _recv_exact(c, 1)[0]).decode()
|
||||
ok = (u, p) == (self.user, self.password)
|
||||
self._send(c, b"\x01" + (b"\x00" if ok else b"\x01"))
|
||||
return ok
|
||||
self._send(c, b"\x05\x00" if 0 in methods else b"\x05\x02")
|
||||
if 0 not in methods: # a client that only offers user/password: accept any
|
||||
_recv_exact(c, 1)
|
||||
_recv_exact(c, _recv_exact(c, 1)[0])
|
||||
_recv_exact(c, _recv_exact(c, 1)[0])
|
||||
self._send(c, b"\x01\x00")
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _read_address(c: socket.socket) -> Tuple[str, int]:
|
||||
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]
|
||||
|
||||
@staticmethod
|
||||
def _reply(rep: int, host: str = "0.0.0.0", port: int = 0) -> bytes:
|
||||
return b"\x05" + bytes([rep]) + b"\x00\x01" + socket.inet_aton(host) + struct.pack("!H", port)
|
||||
|
||||
def _handle(self, c: socket.socket) -> None:
|
||||
try:
|
||||
c.settimeout(30)
|
||||
if not self._greet(c):
|
||||
return
|
||||
ver, cmd, _rsv = _recv_exact(c, 3)
|
||||
host, port = self._read_address(c)
|
||||
if cmd == 1:
|
||||
self._connect(c, host, port)
|
||||
elif cmd == 3:
|
||||
self._associate(c)
|
||||
else:
|
||||
self._send(c, self._reply(7))
|
||||
except (OSError, ConnectionError):
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
c.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
#: The names the product asks "what is my address" of (on port 80); each is answered with ``tcp_exit``.
|
||||
whoami_names: Tuple[str, ...] = (WHOAMI4[0],)
|
||||
|
||||
def _target(self, host: str, port: int) -> Tuple[str, int]:
|
||||
"""Where a CONNECT that is not a special one really goes. A subclass maps a name to a local server."""
|
||||
return host, port
|
||||
|
||||
def _connect(self, c: socket.socket, host: str, port: int) -> None:
|
||||
self.connects.append((host, port))
|
||||
if host.lower() in self.whoami_names and port == WHOAMI4[1]:
|
||||
self._send(c, self._reply(0))
|
||||
_ = c.recv(4096)
|
||||
body = self.tcp_exit.encode()
|
||||
self._send(c, b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: %d\r\n"
|
||||
b"Connection: close\r\n\r\n%s" % (len(body), body))
|
||||
return
|
||||
if (host, port) == WHOAMI6:
|
||||
self._send(c, self._reply(4)) # no IPv6 exit
|
||||
return
|
||||
if (host, port) == (WEB_NAME, 80): # a page that only the gateway can reach
|
||||
self._send(c, self._reply(0))
|
||||
_ = c.recv(4096)
|
||||
body = b"<html><body>behind the gateway</body></html>"
|
||||
self._send(c, b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n"
|
||||
b"Connection: close\r\n\r\n%s" % (len(body), body))
|
||||
return
|
||||
try:
|
||||
up = socket.create_connection(self._target(host, port), timeout=10)
|
||||
except OSError:
|
||||
self._send(c, self._reply(5))
|
||||
return
|
||||
self._send(c, self._reply(0))
|
||||
c.settimeout(None)
|
||||
up.settimeout(None)
|
||||
|
||||
def pump(a: socket.socket, b: socket.socket) -> None:
|
||||
try:
|
||||
while True:
|
||||
d = a.recv(65536)
|
||||
if not d:
|
||||
break
|
||||
if self.tcp_data_delay and self.rtt:
|
||||
time.sleep(self.rtt / 2)
|
||||
b.sendall(d)
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
for s in (a, b):
|
||||
try:
|
||||
s.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
t = threading.Thread(target=pump, args=(up, c), daemon=True)
|
||||
t.start()
|
||||
pump(c, up)
|
||||
t.join(timeout=2)
|
||||
up.close()
|
||||
|
||||
# --- the UDP side --------------------------------------------------------
|
||||
def _later(self, fn) -> None:
|
||||
"""Run ``fn`` after half the round trip (at once on loopback), ignoring a socket that is already closed."""
|
||||
def run() -> None:
|
||||
try:
|
||||
fn()
|
||||
except OSError:
|
||||
pass
|
||||
threading.Timer(self.rtt / 2, run).start() if self.rtt else run()
|
||||
|
||||
def _deliver(self, relay: socket.socket, to: Tuple[str, int], host: str, port: int, payload: bytes) -> None:
|
||||
"""Wrap ``payload`` as coming from ``host``:``port`` (an IPv4 literal) and send it back to the client."""
|
||||
data = b"\x00\x00\x00\x01" + socket.inet_aton(host) + struct.pack("!H", port) + payload
|
||||
self._later(lambda: relay.sendto(data, to))
|
||||
|
||||
def _route(self, host: str, dport: int, atyp: int, payload: bytes, out_port: int,
|
||||
answer) -> Optional[Tuple[Tuple[str, int], Optional[Tuple[str, int]]]]:
|
||||
"""Where one datagram of the client goes: ``(target, reported_as)``, or None when it is dropped.
|
||||
|
||||
``target`` is the real address the datagram is sent to from the exit socket (``out_port`` is that socket's port);
|
||||
``reported_as`` is the address the client is told the reply came from (None: the real source). A subclass may also
|
||||
answer by itself with ``answer(host, port, data)``. By default the fake STUN server, by name or by number, is
|
||||
mapped and everything else is forwarded for real."""
|
||||
if (host, dport) in ((STUN_NAME, STUN_PORT), (STUN_NUMBER, STUN_PORT)):
|
||||
# A real server answers from the address it was asked at; the fake STUN server is mapped, so its reply is
|
||||
# reported as from the asked address (only when that was a literal: a name has no address to report).
|
||||
return self.stun.address, ((host, dport) if atyp == 1 else None)
|
||||
return (host, dport), None
|
||||
|
||||
def _associate(self, c: socket.socket) -> None:
|
||||
self.associates += 1
|
||||
if self.udp == "refuse":
|
||||
self._send(c, self._reply(7))
|
||||
return
|
||||
record: List[Optional[float]] = [time.monotonic() - self.t0, None]
|
||||
self.associations.append(record)
|
||||
relay = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
relay.bind((self.relay_host, 0))
|
||||
out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
out.bind((self.exit_host, 0))
|
||||
client: List[Optional[Tuple[str, int]]] = [None]
|
||||
#: Where a mapped destination really is -> the address the client is told it answered from.
|
||||
asked_at: dict = {}
|
||||
self._send(c, self._reply(0, self.relay_host, relay.getsockname()[1]))
|
||||
record[1] = time.monotonic() - self.t0
|
||||
|
||||
def answer(host: str, port: int, data: bytes) -> None:
|
||||
self._deliver(relay, client[0], host, port, data)
|
||||
|
||||
def inbound() -> None: # client -> world
|
||||
while True:
|
||||
try:
|
||||
d, peer = relay.recvfrom(65536)
|
||||
except OSError:
|
||||
return
|
||||
if len(d) < 10 or d[2] != 0:
|
||||
continue
|
||||
client[0] = peer
|
||||
atyp, i = d[3], 4
|
||||
if atyp == 1:
|
||||
host, i = socket.inet_ntoa(d[i:i + 4]), i + 4
|
||||
elif atyp == 3:
|
||||
n = d[i]
|
||||
host, i = d[i + 1:i + 1 + n].decode(), i + 1 + n
|
||||
else:
|
||||
host, i = socket.inet_ntop(socket.AF_INET6, d[i:i + 16]), i + 16
|
||||
dport = struct.unpack("!H", d[i:i + 2])[0]
|
||||
payload = d[i + 2:]
|
||||
self.datagrams.append((host, dport, payload))
|
||||
self.datagram_log.append((host, dport, atyp, time.monotonic() - self.t0))
|
||||
routed = self._route(host, dport, atyp, payload, out.getsockname()[1], answer)
|
||||
if routed is None:
|
||||
continue
|
||||
target, reported = routed
|
||||
if reported is not None:
|
||||
asked_at[target] = reported
|
||||
self._later(lambda p=payload, t=target: out.sendto(p, t))
|
||||
|
||||
def outbound() -> None: # world -> client
|
||||
while True:
|
||||
try:
|
||||
d, src = out.recvfrom(65536)
|
||||
except OSError:
|
||||
return
|
||||
if client[0] is None:
|
||||
continue
|
||||
host, port = asked_at.get(src, src)
|
||||
self._deliver(relay, client[0], host, port, d)
|
||||
|
||||
threading.Thread(target=inbound, daemon=True).start()
|
||||
threading.Thread(target=outbound, daemon=True).start()
|
||||
try: # the association lives as long as the control connection
|
||||
c.settimeout(None)
|
||||
while c.recv(1024):
|
||||
pass
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
relay.close()
|
||||
out.close()
|
||||
|
||||
|
||||
#: Documentation addresses (RFC 5737): never a real host, so nothing in a test
|
||||
#: can be mistaken for the machine's own address.
|
||||
EXIT = "203.0.113.7"
|
||||
OTHER_EXIT = "198.51.100.4"
|
||||
|
||||
|
||||
def coherent(*, exit_ip: str = EXIT, user: Optional[str] = None,
|
||||
password: Optional[str] = None, relay_host: str = "127.0.0.1", rtt_ms: int = 0) -> Gateway:
|
||||
"""TCP and UDP both work, and both leave from ``exit_ip``."""
|
||||
return Gateway(udp="relay", tcp_exit=exit_ip, udp_exit=exit_ip,
|
||||
user=user, password=password, relay_host=relay_host, rtt_ms=rtt_ms)
|
||||
|
||||
|
||||
def tcp_only(*, exit_ip: str = EXIT, user: Optional[str] = None,
|
||||
password: Optional[str] = None) -> Gateway:
|
||||
"""TCP works; UDP ASSOCIATE is refused with reply code 7."""
|
||||
return Gateway(udp="refuse", tcp_exit=exit_ip, udp_exit=exit_ip,
|
||||
user=user, password=password)
|
||||
|
||||
|
||||
def mismatched(*, tcp_exit: str = EXIT, udp_exit: str = OTHER_EXIT,
|
||||
user: Optional[str] = None, password: Optional[str] = None) -> Gateway:
|
||||
"""UDP is granted and STUN answers, with an address that is not the TCP exit."""
|
||||
assert udp_exit != tcp_exit
|
||||
return Gateway(udp="relay", tcp_exit=tcp_exit, udp_exit=udp_exit,
|
||||
user=user, password=password)
|
||||
@@ -0,0 +1,26 @@
|
||||
"""When the resolver trap is mandatory (the gate's Linux leg of the DoH suite) a trap that cannot run is a failure.
|
||||
|
||||
`INVPW_REQUIRE_TRAP=1` is set by the gate on the leg where the trap can run (Linux, root). With it, an unavailable
|
||||
trap or a port 53 that cannot be bound fails the test with the reason, instead of letting the assertions on the
|
||||
machine's resolver be skipped in silence. Without it (a developer's machine) the old behaviour stays.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
ENV = "INVPW_REQUIRE_TRAP"
|
||||
|
||||
|
||||
def required(environ=None) -> bool:
|
||||
return (os.environ if environ is None else environ).get(ENV) == "1"
|
||||
|
||||
|
||||
def failure(environ, available: bool, reason: str = "", bind_error=None):
|
||||
"""-> the message to fail with, or None when the test may go on (with or without a trap)."""
|
||||
if not required(environ):
|
||||
return None
|
||||
if not available:
|
||||
return "%s=1 but the resolver trap cannot run here: %s" % (ENV, reason or "no reason given")
|
||||
if bind_error is not None:
|
||||
return "%s=1 but the resolver trap could not bind its port: %s" % (ENV, bind_error)
|
||||
return None
|
||||
@@ -0,0 +1,333 @@
|
||||
"""A whole, hermetic road for a page that asks for a TURN allocation BY NAME behind a SOCKS5 gateway that carries UDP.
|
||||
|
||||
Nothing here is a real server of anybody: everything is on loopback, and the only way to anything is the gateway.
|
||||
|
||||
The design this road keeps: a browser behind a proxy resolves every name with the DoH of Firefox, THROUGH the proxy
|
||||
(``network.trr.mode`` 3, ``https://mozilla.cloudflare-dns.com/dns-query``, found with no DNS at 162.159.61.4). So the name of the
|
||||
TURN server is a DoH question, carried by a SOCKS5 CONNECT; the answer is an ADDRESS, and the datagrams of the allocation go to
|
||||
that address, by SOCKS5 address type 1, through the UDP relay. The gateway resolves nothing and answers no DNS query.
|
||||
|
||||
* :class:`TurnServer` - a TURN server (RFC 5766, the part a browser uses): Allocate answered 401 with a realm and a nonce, then
|
||||
answered with the relayed and the mapped address under a long-term credential, checked and signed (MESSAGE-INTEGRITY), so
|
||||
the browser's ICE agent accepts it as it accepts a real one. It records the SOURCE it saw for every datagram: that is the
|
||||
address a real TURN server would report as the browser's, and the one the verdict compares with.
|
||||
* :class:`Chain` - the SOCKS5 gateway of the tests (``_socks_servers.Gateway``, with the DoH road of
|
||||
``_doh_servers.DohGateway``: greeting, ASSOCIATE, relay and the round trip of a gateway that is far away, ``rtt_ms``, for the
|
||||
control connection, the datagrams and the TCP tunnels, are all there, not here). Told where this world's roads go: a CONNECT
|
||||
to the DoH goes to the :class:`_doh_servers.FakeDoh` of the chain, whose zone is the TURN name and the page name; a CONNECT
|
||||
to a loopback address (the page, once its name is resolved) is relayed; a datagram to the TURN's documentation address goes
|
||||
to the TURN server; a STUN binding request to anything else is answered with the exit. A datagram that carries a NAME or
|
||||
goes to port 53 is dropped and recorded (the roads the product must not use). Datagrams leave from ``EXIT_HOST`` (another
|
||||
loopback address), so the TURN server sees a source that is not the browser's own: if it sees the browser's, the road was
|
||||
not the gateway's.
|
||||
* :class:`Page` - the page and the verdict, with the shape of a leak test's logic: a tick of 2 seconds after the page starts that
|
||||
marks TIMEOUT, cleared only after a POST made when a server-reflexive candidate arrives; the server compares the address
|
||||
of that candidate with the source the TURN saw.
|
||||
|
||||
The names and the addresses are RFC 2606 / RFC 5737: nothing in a test can be mistaken for a real host.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import socket
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
from _doh_servers import DohGateway, FakeDoh
|
||||
from _socks_servers import WHOAMI4, Gateway
|
||||
|
||||
TURN_NAME = "turn.relay-only.test"
|
||||
PAGE_NAME = "page.relay-only.test"
|
||||
#: RFC 5737 TEST-NET-2: unroutable, so the only road to it is the gateway, which maps it to the TURN server.
|
||||
TURN_IP = "198.51.100.7"
|
||||
TURN_PORT = 3478
|
||||
RELAYED = ("198.51.100.7", 50000)
|
||||
#: Where the gateway's datagrams come from. A browser that sends direct comes from 127.0.0.1.
|
||||
EXIT_HOST = "127.0.0.2"
|
||||
MAGIC = 0x2112A442
|
||||
PASSWORD = "qwerty"
|
||||
REALM = "hermetic"
|
||||
NONCE = "6e6f6e6365"
|
||||
|
||||
|
||||
def this_host_address() -> str:
|
||||
"""The address of this host that a socket bound to an interface can send from: the relay's BND.ADDR (a loopback relay
|
||||
only suits a client whose UDP socket is not bound to an interface, and an engine's ICE sockets are)."""
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
s.connect(("192.0.2.1", 9))
|
||||
return s.getsockname()[0]
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
|
||||
# ── STUN / TURN wire ───────────────────────────────────────────────────────────
|
||||
|
||||
def _attrs(data: bytes) -> Dict[int, bytes]:
|
||||
out: Dict[int, bytes] = {}
|
||||
i = 20
|
||||
while i + 4 <= len(data):
|
||||
t, n = struct.unpack("!HH", data[i:i + 4])
|
||||
out[t] = data[i + 4:i + 4 + n]
|
||||
i += 4 + ((n + 3) & ~3)
|
||||
return out
|
||||
|
||||
|
||||
def _attr(t: int, v: bytes) -> bytes:
|
||||
return struct.pack("!HH", t, len(v)) + v + b"\x00" * (-len(v) % 4)
|
||||
|
||||
|
||||
def _xor_addr(ip: str, port: int) -> bytes:
|
||||
xp = port ^ (MAGIC >> 16)
|
||||
xa = struct.unpack("!I", socket.inet_aton(ip))[0] ^ MAGIC
|
||||
return b"\x00\x01" + struct.pack("!HI", xp, xa)
|
||||
|
||||
|
||||
def _message(mtype: int, tid: bytes, attrs: bytes, key: Optional[bytes] = None) -> bytes:
|
||||
if key is None:
|
||||
return struct.pack("!HHI", mtype, len(attrs), MAGIC) + tid + attrs
|
||||
head = struct.pack("!HHI", mtype, len(attrs) + 24, MAGIC) + tid
|
||||
mac = hmac.new(key, head + attrs, hashlib.sha1).digest()
|
||||
return head + attrs + _attr(0x0008, mac)
|
||||
|
||||
|
||||
class TurnServer:
|
||||
"""UDP TURN server on 127.0.0.1. ``seen`` is every datagram as (source ip, source port, STUN type), in order;
|
||||
``allocations`` the successful Allocates as (source ip, source port, username, time)."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
self.sock.bind(("127.0.0.1", 0))
|
||||
self.address: Tuple[str, int] = self.sock.getsockname()
|
||||
self.seen: List[Tuple[str, int, int]] = []
|
||||
self.allocations: List[Tuple[str, int, str, float]] = []
|
||||
self._closed = False
|
||||
threading.Thread(target=self._serve, daemon=True).start()
|
||||
|
||||
def close(self) -> None:
|
||||
self._closed = True
|
||||
self.sock.close()
|
||||
|
||||
def _serve(self) -> None:
|
||||
while not self._closed:
|
||||
try:
|
||||
data, src = self.sock.recvfrom(65536)
|
||||
except OSError:
|
||||
return
|
||||
if len(data) < 20 or struct.unpack("!I", data[4:8])[0] != MAGIC:
|
||||
continue
|
||||
mtype, tid = struct.unpack("!H", data[:2])[0], data[8:20]
|
||||
self.seen.append((src[0], src[1], mtype))
|
||||
attrs = _attrs(data)
|
||||
if mtype == 0x0003: # Allocate
|
||||
if 0x0008 not in attrs or 0x0006 not in attrs: # no credentials: 401 with a realm and a nonce
|
||||
err = _attr(0x0009, b"\x00\x00\x04\x01Unauthorized") + _attr(0x0014, REALM.encode()) + _attr(0x0015, NONCE.encode())
|
||||
self.sock.sendto(_message(0x0113, tid, err), src)
|
||||
continue
|
||||
user = attrs[0x0006].decode(errors="replace")
|
||||
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode()).digest()
|
||||
body = (_attr(0x0016, _xor_addr(*RELAYED)) + _attr(0x0020, _xor_addr(src[0], src[1])) +
|
||||
_attr(0x000D, struct.pack("!I", 600)))
|
||||
self.allocations.append((src[0], src[1], user, time.monotonic()))
|
||||
self.sock.sendto(_message(0x0103, tid, body, key), src)
|
||||
elif mtype in (0x0004, 0x0008, 0x0009): # Refresh, CreatePermission, ChannelBind
|
||||
user = attrs.get(0x0006, b"").decode(errors="replace")
|
||||
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode()).digest()
|
||||
body = _attr(0x000D, struct.pack("!I", 600)) if mtype == 0x0004 else b""
|
||||
self.sock.sendto(_message(mtype | 0x0100, tid, body, key), src)
|
||||
|
||||
|
||||
# ── the gateway ────────────────────────────────────────────────────────────────
|
||||
|
||||
class Chain(DohGateway):
|
||||
"""The one SOCKS5 gateway of the tests (``_socks_servers.Gateway`` through ``_doh_servers.DohGateway``), with UDP, the
|
||||
DoH, the TURN server and the page behind it. A context manager.
|
||||
|
||||
What it does, and nothing else (it never resolves a name and never answers a DNS query):
|
||||
|
||||
* a CONNECT to the DoH (``162.159.61.4:443`` or ``mozilla.cloudflare-dns.com:443``) is handed to :attr:`doh`, whose zone
|
||||
is the TURN name and the page name; a CONNECT to a loopback ADDRESS (the page, once its name is resolved) is relayed;
|
||||
a CONNECT that carries any other name or address is refused and listed in :attr:`refused`;
|
||||
* a datagram to ``TURN_IP:3478`` (address type 1) goes to the TURN server, which hears it from ``EXIT_HOST``; a STUN
|
||||
binding request to anyone else is answered with the exit; everything else is dropped. A datagram that carries a NAME
|
||||
(address type 3) or goes to port 53 is dropped and recorded: those are roads the product must not use.
|
||||
"""
|
||||
|
||||
#: What the product asks "what is my address" of: answered with the exit.
|
||||
whoami_names = ("api.ipify.org", "ifconfig.me", "icanhazip.com")
|
||||
|
||||
def __init__(self, *, rtt_ms: int = 130, relay_host: Optional[str] = None) -> None:
|
||||
self.turn = TurnServer()
|
||||
self.doh = FakeDoh({TURN_NAME: TURN_IP, PAGE_NAME: "127.0.0.1"})
|
||||
self.page = Page(self)
|
||||
super().__init__("chain", self.doh, udp="relay", tcp_exit=EXIT_HOST, udp_exit=EXIT_HOST,
|
||||
relay_host=relay_host or this_host_address(), rtt_ms=rtt_ms,
|
||||
exit_host=EXIT_HOST, tcp_data_delay=True)
|
||||
|
||||
def close(self) -> None:
|
||||
super().close()
|
||||
self.turn.close()
|
||||
self.doh.close()
|
||||
self.page.close()
|
||||
|
||||
def _connect(self, c, host, port) -> None:
|
||||
if host.lower() in self.whoami_names and port == WHOAMI4[1]:
|
||||
Gateway._connect(self, c, host, port) # the answer of "what is my address"
|
||||
return
|
||||
super()._connect(c, host, port)
|
||||
|
||||
def _route(self, host, dport, atyp, payload, out_port, answer):
|
||||
if atyp == 1 and host == TURN_IP and dport == TURN_PORT:
|
||||
return self.turn.address, (host, dport) # the TURN server answers as from the address it was asked at
|
||||
if (atyp == 1 and dport != 53 and len(payload) >= 20 and payload[:2] == b"\x00\x01"
|
||||
and struct.unpack("!I", payload[4:8])[0] == MAGIC):
|
||||
# a STUN binding request to anyone else: answered by the gateway, with the exit as the mapped address
|
||||
answer(host, dport, _message(0x0101, payload[8:20], _attr(0x0020, _xor_addr(EXIT_HOST, out_port))))
|
||||
return None # a name, port 53, anything else: dropped (and in datagram_log)
|
||||
|
||||
# --- what a failed test says ----------------------------------------------
|
||||
def explain(self, result: dict) -> str:
|
||||
"""The road, as the DoH, the gateway, the TURN server and the page saw it, and the sentence that says where it stopped."""
|
||||
turn_heard = list(self.turn.seen)
|
||||
turn_asked = [q for q in self.doh.queries if q.name == TURN_NAME]
|
||||
names_on_relay = [(h, p) for h, p, a, _t in self.datagram_log if a == 3]
|
||||
dns_on_relay = [(h, p) for h, p, _a, _t in self.datagram_log if p == 53]
|
||||
to_turn = [1 for h, p, a, _t in self.datagram_log if a == 1 and h == TURN_IP and p == TURN_PORT]
|
||||
doh_connects = self.doh_connects()
|
||||
lines = ["", "THE ROAD, as each server saw it:"]
|
||||
lines.append(" DoH (reached only through the gateway): %d connection(s) %s, %d TLS failure(s) %s" % (
|
||||
len(self.doh.connections), self.doh.connections[:4], len(self.doh.tls_failures), self.doh.tls_failures[:2]))
|
||||
lines.append(" DoH queries (name, type, road): %s" % ([tuple(q) for q in self.doh.queries][:12] or "none"))
|
||||
lines.append(" gateway: CONNECTs %s; refused %s; the DoH ones: %d" % (self.connects[:12], self.refused[:6], len(doh_connects)))
|
||||
lines.append(" gateway: %d UDP ASSOCIATE (start -> answered, seconds): %s" % (
|
||||
len(self.associations), ", ".join("%.2f->%s" % (a, "%.2f" % b if b is not None else "-") for a, b in self.associations) or "none"))
|
||||
lines.append(" gateway: datagrams carried: %d (to %s:%d by address: %d; carrying a NAME, dropped: %s; to port 53, dropped: %s)" % (
|
||||
len(self.datagram_log), TURN_IP, TURN_PORT, len(to_turn), names_on_relay[:4] or "none", dns_on_relay[:4] or "none"))
|
||||
lines.append(" TURN server heard %d datagram(s) %s; allocations: %s" % (
|
||||
len(turn_heard), [("%s:%d" % (s[0], s[1]), hex(s[2])) for s in turn_heard][:6],
|
||||
[("%s:%d" % (a[0], a[1])) for a in self.turn.allocations]))
|
||||
lines.append(" page server: asked for %s; verdicts: %s" % (
|
||||
self.page.hits[:4] or "nothing", self.page.verdicts or "none: no server-reflexive candidate came before the tick, or the POST did not finish"))
|
||||
lines.append(" page: %s" % json.dumps({k: result.get(k) for k in ("status", "timeline", "errors", "srflx", "candidates")}, default=str)[:900])
|
||||
if not turn_asked:
|
||||
if names_on_relay or dns_on_relay:
|
||||
why = ("the name %r went along the UDP relay (%s) instead of being asked to the DoH: the gateway resolves nothing, so "
|
||||
"no allocation could be asked for" % (TURN_NAME, names_on_relay or dns_on_relay))
|
||||
elif self.doh.tls_failures:
|
||||
why = "the browser reached the DoH but refused its certificate (%s): the context must accept it (ignore_https_errors)" % (self.doh.tls_failures[:1],)
|
||||
elif not doh_connects:
|
||||
why = ("the browser never asked the DoH: no CONNECT to the DoH reached the gateway (%s), so the name %r was not "
|
||||
"resolved through the proxy and the browser never tried to reach the TURN server; the only "
|
||||
"server-reflexive candidate the page can have is one the engine made up"
|
||||
% (self.connects[:6] or "no CONNECT at all", TURN_NAME))
|
||||
else:
|
||||
why = ("the DoH was reached (%d connection(s)) but never asked for %r (it was asked %s): the lookup of the ICE "
|
||||
"server name did not go to the DoH" % (len(self.doh.connections), TURN_NAME, self.doh.seen_names()))
|
||||
elif "direct" in {q.via for q in turn_asked}:
|
||||
why = "the name %r reached the DoH without the proxy (road 'direct')" % TURN_NAME
|
||||
elif not turn_heard:
|
||||
why = ("the name %r was resolved by the DoH (%s) but no datagram reached the TURN server: %s" % (
|
||||
TURN_NAME, sorted({q.via for q in turn_asked}),
|
||||
("the browser sent none to %s:%d by address through the relay (%d association(s), datagrams %s)" % (
|
||||
TURN_IP, TURN_PORT, len(self.associations), [(h, p, a) for h, p, a, _t in self.datagram_log][:4]))
|
||||
if not to_turn else "the answer did not come back"))
|
||||
elif not self.turn.allocations:
|
||||
why = "the TURN server heard the browser but no Allocate was answered with credentials: the 401 round trip did not finish"
|
||||
elif result.get("status") == "TIMEOUT":
|
||||
ends = [e for _s, e in self.associations if e is not None]
|
||||
why = ("the allocation succeeded but too late for the tick of 2000 ms: the association handshakes alone ended at %s s"
|
||||
% ", ".join("%.2f" % e for e in ends))
|
||||
else:
|
||||
why = "the srflx of the page is not the address the TURN server saw (%s)" % [("%s:%d" % (a[0], a[1])) for a in self.turn.allocations]
|
||||
lines.append("WHY: " + why)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ── the page and the verdict ───────────────────────────────────────────────────
|
||||
|
||||
PAGE_HTML = """<!doctype html><meta charset=utf-8><title>relay-only</title><script>
|
||||
const t0 = performance.now(), mark = (k) => (window.__result.timeline[k] = Math.round(performance.now() - t0));
|
||||
window.__result = {status: 'PENDING', timeline: {}, errors: [], candidates: [], srflx: null};
|
||||
let status = 'PENDING';
|
||||
const finish = (s) => { status = s; window.__result.status = s; window.__done = true; };
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
mark('dom');
|
||||
// the tick of a leak test: 2 seconds after the page starts. It is cleared only after the POST made on a srflx.
|
||||
const tick = setInterval(() => { if (status === 'PENDING') { mark('tick'); finish('TIMEOUT'); } clearInterval(tick); }, 2000);
|
||||
const pc = new RTCPeerConnection({iceServers: [{urls: ['turn:%(turn)s:%(port)d?transport=udp'], username: 'challenge-' + Date.now(), credential: '%(password)s'}]});
|
||||
pc.createDataChannel('x');
|
||||
mark('pc');
|
||||
pc.onicegatheringstatechange = () => mark('gathering_' + pc.iceGatheringState);
|
||||
pc.onicecandidateerror = (e) => window.__result.errors.push([e.errorCode, e.url]);
|
||||
pc.onicecandidate = async (e) => {
|
||||
if (!e.candidate) return;
|
||||
window.__result.candidates.push(e.candidate.candidate);
|
||||
if (e.candidate.candidate.indexOf(' typ srflx ') < 0 || status !== 'PENDING') return;
|
||||
mark('srflx');
|
||||
window.__result.srflx = e.candidate.candidate;
|
||||
const r = await fetch('/verdict', {method: 'POST', body: JSON.stringify({srflx: e.candidate.candidate})});
|
||||
mark('posted');
|
||||
if (status !== 'PENDING') return;
|
||||
clearInterval(tick);
|
||||
finish((await r.json()).ok ? 'DONE' : 'REFUSED');
|
||||
};
|
||||
pc.createOffer().then((o) => pc.setLocalDescription(o));
|
||||
});
|
||||
</script>"""
|
||||
|
||||
|
||||
class Page:
|
||||
"""The page server (the browser asks the DoH for its NAME, then reaches the ADDRESS through the gateway) and the verdict."""
|
||||
|
||||
def __init__(self, chain: "Chain") -> None:
|
||||
outer = self
|
||||
self.verdicts: List[dict] = []
|
||||
#: Every GET the page server answered: the Host header and the path.
|
||||
self.hits: List[Tuple[str, str]] = []
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
timeout = 5
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
outer.hits.append((self.headers.get("Host", ""), self.path))
|
||||
body = (PAGE_HTML % {"turn": TURN_NAME, "port": TURN_PORT, "password": PASSWORD}).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_POST(self):
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
cand = json.loads(self.rfile.read(n) or b"{}").get("srflx", "")
|
||||
parts = cand.split()
|
||||
ip, port = (parts[4], int(parts[5])) if len(parts) > 5 else ("", 0)
|
||||
seen = [(a[0], a[1]) for a in chain.turn.allocations]
|
||||
ok = bool(seen) and (ip, port) in seen and ip == EXIT_HOST
|
||||
outer.verdicts.append({"srflx": "%s:%d" % (ip, port), "seen_by_the_turn": ["%s:%d" % s for s in seen], "ok": ok})
|
||||
body = json.dumps({"ok": ok}).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
self.httpd.daemon_threads = True
|
||||
self.port: int = self.httpd.server_address[1]
|
||||
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
return "http://%s:%d/" % (PAGE_NAME, self.port)
|
||||
|
||||
def close(self) -> None:
|
||||
self.httpd.shutdown()
|
||||
@@ -258,6 +258,13 @@ def engine_at_least():
|
||||
return check
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def the_udp_line(engine_at_least):
|
||||
"""The UDP line (the declared network, the DoH through the proxy, the SOCKS5 UDP layer, HTTP/3 through it) is the engine
|
||||
firefox-63: a test of it skips on an older engine (the published one that main's e2e fetches) and runs on the candidate."""
|
||||
engine_at_least("firefox-63")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Local HTTP fixture server - service workers need a real http(s) origin
|
||||
# (data: and about:blank are opaque-origin, no SW registration possible).
|
||||
|
||||
@@ -24,7 +24,7 @@ import time
|
||||
|
||||
import pytest
|
||||
|
||||
pytest.importorskip("websockets")
|
||||
import websockets # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
from websockets.asyncio.client import connect # noqa: E402
|
||||
|
||||
from _servers import LocalServer # noqa: E402
|
||||
|
||||
@@ -39,8 +39,7 @@ def display(monkeypatch):
|
||||
vd = RecordingDisplay()
|
||||
geo = types.SimpleNamespace(timezone="Europe/Rome",
|
||||
locale=SessionLocale.of("it-IT"),
|
||||
egress_ip=None,
|
||||
srflx_to_declare=lambda: None)
|
||||
egress_ip=None)
|
||||
|
||||
def refuse(**_kw):
|
||||
raise FontManifestMismatch("the engine does not carry these faces")
|
||||
|
||||
@@ -77,7 +77,7 @@ async def _two_contexts(endpoint):
|
||||
def test_every_context_of_a_served_browser_is_the_session(firefox_binary):
|
||||
import asyncio
|
||||
|
||||
pytest.importorskip("websockets")
|
||||
import websockets # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US",
|
||||
@@ -91,12 +91,13 @@ def test_every_context_of_a_served_browser_is_the_session(firefox_binary):
|
||||
assert "Windows NT" in agent and platform == "Win32", seen[0]
|
||||
|
||||
|
||||
def test_a_bare_launch_behind_a_proxy_declares_the_egress_as_its_srflx(firefox_binary, monkeypatch):
|
||||
"""Behind a proxy a page must read, as WebRTC's server-reflexive candidate, the address the session
|
||||
leaves from (STEALTHFOX_WEBRTC_PUBLIC_IP, which the session's environment carries), not none and not
|
||||
this machine's. A bare launch got no session environment, so a page behind the proxy saw no srflx of
|
||||
the egress. The proxy is the local TCP-only SOCKS5 of test_webrtc_realness.py; the egress the session
|
||||
measures through it is answered with a TEST-NET address (RFC 5737), as in those tests."""
|
||||
def test_a_bare_launch_behind_a_proxy_is_composed_through_it(firefox_binary, monkeypatch):
|
||||
"""A bare launch behind a proxy gets a session composed THROUGH that proxy (the egress, the timezone and
|
||||
the locale measured there, the network declared from the seed), and the page's WebRTC gather still
|
||||
completes with mDNS hosts. The declaration (STEALTHFOX_WEBRTC_NETWORK) is read by the new engine only;
|
||||
its value is asserted without a browser in test_the_network_declaration_reaches_the_engine.py. The
|
||||
proxy is the local TCP-only SOCKS5 of test_webrtc_realness.py; the egress the session measures through
|
||||
it is answered with a TEST-NET address (RFC 5737), as in those tests."""
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
import threading
|
||||
|
||||
@@ -104,16 +105,15 @@ def test_a_bare_launch_behind_a_proxy_declares_the_egress_as_its_srflx(firefox_b
|
||||
from invisible_core._geo import SessionGeo
|
||||
from invisible_playwright import _session
|
||||
from invisible_playwright._pw.sync_api import sync_playwright
|
||||
from test_webrtc_realness import _PROBE_JS, _Socks5TcpOnly, candidates, srflx_candidates
|
||||
from test_webrtc_realness import _PROBE_JS, _Socks5TcpOnly, candidates, host_is_mdns
|
||||
|
||||
egress = "203.0.113.7"
|
||||
for name in ("STEALTHFOX_WEBRTC_PUBLIC_IP", "STEALTHFOX_WEBRTC_DISABLE_IPV6"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
monkeypatch.delenv("STEALTHFOX_WEBRTC_NETWORK", raising=False)
|
||||
measured = []
|
||||
|
||||
def through_the_proxy(timezone, proxy, locale):
|
||||
measured.append(proxy)
|
||||
return SessionGeo("America/New_York", egress, srflx_suppressed=False,
|
||||
return SessionGeo("America/New_York", egress,
|
||||
locale=decide_session_locale("en-US"))
|
||||
|
||||
monkeypatch.setattr(_session, "session_geo", through_the_proxy, raising=False) # absent before the fix
|
||||
@@ -146,7 +146,7 @@ def test_a_bare_launch_behind_a_proxy_declares_the_egress_as_its_srflx(firefox_b
|
||||
finally:
|
||||
socks.close()
|
||||
httpd.shutdown()
|
||||
srflx = [c for c in srflx_candidates(candidates(res["candidates"])) if c["address"] == egress]
|
||||
assert srflx, "behind the proxy the page reads no srflx of the egress %s: %s" % (egress, res["candidates"])
|
||||
cands = candidates(res["candidates"])
|
||||
assert cands and host_is_mdns(cands), "behind the proxy the gather is blocked or leaks a host: %s" % res["candidates"]
|
||||
assert measured and measured[0] and measured[0].get("server", "").startswith("socks5://"), (
|
||||
"the session was not composed through the launch's proxy: %r" % measured)
|
||||
@@ -0,0 +1,91 @@
|
||||
"""A page reached over IPv6 still gathers host candidates on a machine declared without IPv6.
|
||||
|
||||
The default address is looked up for the family of the page's server. The real network may reach the page over IPv6 (a
|
||||
site with an AAAA record, here a server on `[::1]`), while the declared machine has IPv4 only (`v6=0`): it has no default
|
||||
address of that family, and the gathering found no address at all - it completed in a few milliseconds with zero
|
||||
candidates, with no error, even without a proxy (measured on the firefox-63 candidate, Windows, direct).
|
||||
|
||||
The machine the persona declares answers with the family it has: one host name (UDP and TCP), ranked 127 (an IPv4-only
|
||||
machine has one address), exactly as with the page served over IPv4. Hermetic: no proxy, no external network.
|
||||
Red on an engine before webrtc/declared-interfaces ddaf867f03 (empty gathering).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import pytest
|
||||
|
||||
from test_webrtc_realness import _e2e_binary, _launch, candidates, host_candidates # noqa: F401
|
||||
|
||||
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
|
||||
|
||||
V4_ONLY = "v4=192.168.31.7;v6=0;p6="
|
||||
UDP_127, TCP_127 = 2122252543, 2105524479
|
||||
|
||||
_GATHER_JS = r"""async () => {
|
||||
const pc = new RTCPeerConnection({iceServers: []});
|
||||
pc.createDataChannel('');
|
||||
const cands = [];
|
||||
pc.addEventListener('icecandidate', e => { if (e.candidate && e.candidate.candidate) cands.push(e.candidate.candidate); });
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
await new Promise(r => setTimeout(r, 2500));
|
||||
try { pc.close(); } catch (e) {}
|
||||
return cands;
|
||||
}"""
|
||||
|
||||
|
||||
class _V6Server(ThreadingHTTPServer):
|
||||
address_family = socket.AF_INET6
|
||||
daemon_threads = True
|
||||
|
||||
|
||||
class _Page(BaseHTTPRequestHandler):
|
||||
timeout = 5
|
||||
|
||||
def do_GET(self):
|
||||
body = b"<!doctype html><title>over ipv6</title><p>page"
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def page_over_ipv6():
|
||||
try:
|
||||
srv = _V6Server(("::1", 0), _Page)
|
||||
except OSError as exc: # the environment has no IPv6 loopback: the test cannot mean anything, so it says so
|
||||
pytest.fail("no IPv6 loopback to serve the page on (%s): the test needs [::1]" % exc, pytrace=False)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
try:
|
||||
yield "http://[::1]:%d/" % srv.server_address[1]
|
||||
finally:
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
def _gather(url, monkeypatch, declaration):
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.fail("no patched binary: set STEALTHFOX_E2E_BINARY", pytrace=False)
|
||||
monkeypatch.setenv("STEALTHFOX_WEBRTC_NETWORK", declaration)
|
||||
with _launch(binary_path=binary, seed=42) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto(url, wait_until="domcontentloaded", timeout=60000)
|
||||
assert page.evaluate("location.hostname") == "[::1]"
|
||||
return host_candidates(candidates(page.evaluate(_GATHER_JS)))
|
||||
|
||||
|
||||
def test_a_page_served_over_ipv6_gets_the_host_candidates_of_an_ipv4_only_machine(page_over_ipv6, monkeypatch):
|
||||
hosts = _gather(page_over_ipv6, monkeypatch, V4_ONLY)
|
||||
assert hosts, "an empty gathering: the declared machine found no default address for the family of the page"
|
||||
by_proto = {proto: sorted((c["priority"] for c in hosts if c["proto"] == proto), reverse=True)
|
||||
for proto in ("UDP", "TCP")}
|
||||
assert by_proto == {"UDP": [UDP_127], "TCP": [TCP_127]}, hosts
|
||||
assert all(c["address"].endswith(".local") for c in hosts), "host candidates are mDNS names, never an address: %r" % hosts
|
||||
@@ -13,7 +13,7 @@ import json
|
||||
|
||||
import pytest
|
||||
|
||||
pytest.importorskip("websockets")
|
||||
import websockets # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
from websockets.asyncio.client import connect # noqa: E402
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
@@ -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"
|
||||
@@ -0,0 +1,572 @@
|
||||
"""scripts/ci_verdict.py is the one judge of the mandatory suites: it must fail on every hole (a skip, a failure, too few
|
||||
tests collected, a required file that never ran, a list that lost a row or a minimum against main) and only then. The
|
||||
junit files here are written by hand in tmp_path; the last tests read the real ci/required-suites.json."""
|
||||
import importlib.util
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
REQUIRED = ROOT / "ci" / "required-suites.json"
|
||||
|
||||
|
||||
def _load():
|
||||
spec = importlib.util.spec_from_file_location("ci_verdict_under_test", ROOT / "scripts" / "ci_verdict.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
verdict = _load()
|
||||
|
||||
FILE_A = "tests/test_a.py"
|
||||
FILE_B = "tests/test_b.py"
|
||||
NODE = "tests/test_c.py::test_one"
|
||||
|
||||
|
||||
def _suite(**over):
|
||||
row = {"id": "s.one", "giro": "G2", "os": ["linux", "windows"], "min_tests": 4,
|
||||
"tests": [FILE_A, FILE_B, NODE], "marker": "unit", "needs_root": False, "exact": True,
|
||||
"note": ""}
|
||||
row.update(over)
|
||||
return row
|
||||
|
||||
|
||||
def _write_required(path, rows):
|
||||
path.write_text("[\n" + ",\n".join(" " + json.dumps(r) for r in rows) + "\n]\n", encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def _case(file, name, tag=None, classname=None):
|
||||
classname = file[:-3].replace("/", ".") if classname is None else classname
|
||||
inner = {None: "", "skipped": '<skipped message="s"/>', "failure": '<failure message="f">x</failure>',
|
||||
"error": '<error message="e">x</error>'}[tag]
|
||||
return '<testcase classname="%s" name="%s" time="0.1">%s</testcase>' % (classname, name, inner)
|
||||
|
||||
|
||||
def _junit(path, cases):
|
||||
path.write_text('<?xml version="1.0" encoding="utf-8"?><testsuites><testsuite name="pytest" tests="%d">%s'
|
||||
"</testsuite></testsuites>" % (len(cases), "".join(cases)), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
GREEN = [_case(FILE_A, "test_x"), _case(FILE_A, "test_y[p1]"), _case(FILE_B, "test_z"), _case("tests/test_c.py", "test_one")]
|
||||
|
||||
|
||||
SHA = "a" * 40
|
||||
|
||||
|
||||
def _judge(tmp_path, cases, rows=None, extra=(), suite="s.one", os_name="linux", with_binary=True, commit=SHA):
|
||||
required = _write_required(tmp_path / "required.json", rows or [_suite()])
|
||||
junit = _junit(tmp_path / "junit.xml", cases) if cases is not None else tmp_path / "absent.xml"
|
||||
binary = tmp_path / "firefox.bin"
|
||||
binary.write_bytes(b"engine")
|
||||
out = tmp_path / "result" / ("%s.%s.json" % (suite, os_name))
|
||||
argv = ["judge", "--required", str(required), "--suite", suite, "--os", os_name, "--junit", str(junit),
|
||||
"--out", str(out), *extra]
|
||||
if with_binary:
|
||||
argv += ["--binary", str(binary)]
|
||||
if commit:
|
||||
argv += ["--commit", commit]
|
||||
code = verdict.main(argv)
|
||||
return code, (json.loads(out.read_text(encoding="utf-8")) if out.exists() else None)
|
||||
|
||||
|
||||
def test_everything_green_exits_0_and_writes_the_result(tmp_path, capsys):
|
||||
code, result = _judge(tmp_path, GREEN)
|
||||
assert code == 0, capsys.readouterr().out
|
||||
assert result["suite"] == "s.one" and result["os"] == "linux" and result["commit"] == SHA
|
||||
assert result["verdict"] == "green"
|
||||
assert (result["collected"], result["passed"], result["failed"], result["skipped"], result["errors"]) == (4, 4, 0, 0, 0)
|
||||
assert result["missing_tests"] == [] and result["problems"] == []
|
||||
|
||||
|
||||
def test_the_binary_hash_is_the_sha256_of_the_file(tmp_path):
|
||||
import hashlib
|
||||
_code, result = _judge(tmp_path, GREEN)
|
||||
assert result["binary_sha256"] == hashlib.sha256(b"engine").hexdigest()
|
||||
|
||||
|
||||
def test_judge_without_binary_is_a_wrong_use(tmp_path, capsys):
|
||||
code, result = _judge(tmp_path, GREEN, with_binary=False)
|
||||
assert code == 2 and result is None
|
||||
assert "--binary" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_a_binary_that_does_not_exist_is_red_never_a_null_hash_green(tmp_path, capsys):
|
||||
required = _write_required(tmp_path / "required.json", [_suite()])
|
||||
junit = _junit(tmp_path / "junit.xml", GREEN)
|
||||
out = tmp_path / "r.json"
|
||||
code = verdict.main(["judge", "--required", str(required), "--suite", "s.one", "--os", "linux", "--junit", str(junit),
|
||||
"--binary", str(tmp_path / "nowhere.bin"), "--commit", SHA, "--out", str(out)])
|
||||
result = json.loads(out.read_text(encoding="utf-8"))
|
||||
assert code == 1 and result["binary_sha256"] is None and result["verdict"] == "red"
|
||||
assert "does not exist" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_skipped_test_is_red(tmp_path, capsys):
|
||||
cases = GREEN[:-1] + [_case("tests/test_c.py", "test_one", "skipped")]
|
||||
code, result = _judge(tmp_path, cases)
|
||||
out = capsys.readouterr().out
|
||||
assert code == 1 and result["skipped"] == 1
|
||||
assert "skipped" in out and NODE in out
|
||||
|
||||
|
||||
def test_a_failed_test_is_red(tmp_path, capsys):
|
||||
cases = GREEN + [_case(FILE_B, "test_bad", "failure")]
|
||||
code, result = _judge(tmp_path, cases)
|
||||
out = capsys.readouterr().out
|
||||
assert code == 1 and result["failed"] == 1
|
||||
assert "failed" in out and FILE_B in out
|
||||
|
||||
|
||||
def test_an_error_is_red(tmp_path):
|
||||
cases = GREEN + [_case(FILE_B, "test_bad", "error")]
|
||||
code, result = _judge(tmp_path, cases)
|
||||
assert code == 1 and result["errors"] == 1
|
||||
|
||||
|
||||
def test_fewer_tests_than_the_minimum_is_red(tmp_path, capsys):
|
||||
code, result = _judge(tmp_path, GREEN, rows=[_suite(min_tests=5)])
|
||||
assert code == 1 and result["collected"] == 4
|
||||
assert "fewer than the minimum 5" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_required_file_that_did_not_run_is_red(tmp_path, capsys):
|
||||
cases = [c for c in GREEN if "test_b" not in c]
|
||||
code, result = _judge(tmp_path, cases, rows=[_suite(min_tests=3)])
|
||||
assert code == 1 and result["missing_tests"] == [FILE_B]
|
||||
assert FILE_B in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_required_node_id_that_did_not_run_is_red(tmp_path):
|
||||
cases = [c for c in GREEN if "test_one" not in c]
|
||||
code, result = _judge(tmp_path, cases, rows=[_suite(min_tests=3)])
|
||||
assert code == 1 and result["missing_tests"] == [NODE]
|
||||
|
||||
|
||||
def test_a_parametrized_node_id_is_matched_without_its_parameters(tmp_path):
|
||||
cases = [_case(FILE_A, "test_x"), _case("tests/test_c.py", "test_one[a]"), _case("tests/test_c.py", "test_one[b]")]
|
||||
rows = [_suite(tests=[FILE_A, NODE], min_tests=3)]
|
||||
assert _judge(tmp_path, cases, rows=rows)[0] == 0
|
||||
cases[2] = _case("tests/test_c.py", "test_one[b]", "failure")
|
||||
assert _judge(tmp_path, cases, rows=rows)[0] == 1
|
||||
|
||||
|
||||
def test_a_missing_junit_is_red(tmp_path, capsys):
|
||||
code, result = _judge(tmp_path, None)
|
||||
assert code == 1 and result["collected"] == 0
|
||||
assert "junit" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_every_problem_is_printed_one_per_line(tmp_path, capsys):
|
||||
cases = [_case(FILE_A, "test_x", "failure"), _case(FILE_A, "test_y", "skipped")]
|
||||
code, _result = _judge(tmp_path, cases)
|
||||
lines = [l for l in capsys.readouterr().out.splitlines() if l.startswith("VERDICT RED")]
|
||||
assert code == 1 and len(lines) >= 5, lines
|
||||
|
||||
|
||||
def test_a_row_the_suite_does_not_have_for_that_os_is_red(tmp_path, capsys):
|
||||
code, _result = _judge(tmp_path, GREEN, rows=[_suite(os=["linux"])], os_name="windows")
|
||||
assert code == 1 and "does not run on windows" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_class_in_the_junit_is_part_of_the_node_id():
|
||||
assert verdict.node_id("tests.test_x.TestThing", "test_y") == "tests/test_x.py::TestThing::test_y"
|
||||
assert verdict.node_id("tests.test_x", "test_y[p]") == "tests/test_x.py::test_y[p]"
|
||||
|
||||
|
||||
# --- against main ------------------------------------------------------------------------------------------------
|
||||
def _main_file(tmp_path, rows):
|
||||
return _write_required(tmp_path / "main.json", rows)
|
||||
|
||||
|
||||
def test_a_list_that_only_grew_is_green(tmp_path):
|
||||
main = _main_file(tmp_path, [_suite(min_tests=3, tests=[FILE_A])])
|
||||
code, _r = _judge(tmp_path, GREEN, rows=[_suite(), _suite(id="s.two")], extra=["--main-required", str(main)])
|
||||
assert code == 0
|
||||
|
||||
|
||||
def test_a_suite_of_main_that_is_gone_is_red(tmp_path, capsys):
|
||||
main = _main_file(tmp_path, [_suite(), _suite(id="s.gone")])
|
||||
code, _r = _judge(tmp_path, GREEN, extra=["--main-required", str(main)])
|
||||
assert code == 1 and "s.gone" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_lost_test_row_against_main_is_red(tmp_path, capsys):
|
||||
main = _main_file(tmp_path, [_suite(tests=[FILE_A, FILE_B, NODE, "tests/test_d.py"])])
|
||||
code, _r = _judge(tmp_path, GREEN, extra=["--main-required", str(main)])
|
||||
assert code == 1 and "tests/test_d.py" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_higher_minimum_on_main_is_red(tmp_path, capsys):
|
||||
main = _main_file(tmp_path, [_suite(min_tests=9)])
|
||||
code, _r = _judge(tmp_path, GREEN, extra=["--main-required", str(main)])
|
||||
assert code == 1 and "went down" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_main_list_that_does_not_exist_is_red_unless_the_gate_declares_main_has_none(tmp_path, capsys):
|
||||
missing = str(tmp_path / "no" / "required.json")
|
||||
code, result = _judge(tmp_path, GREEN, extra=["--main-required", missing])
|
||||
assert code == 1 and result["verdict"] == "red"
|
||||
assert "it is not known what main has" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_main_list_declared_absent_is_said_and_passed(tmp_path, capsys):
|
||||
missing = str(tmp_path / "no" / "required.json")
|
||||
code, _r = _judge(tmp_path, GREEN, extra=["--main-required", missing, "--main-has-no-list"])
|
||||
assert code == 0 and "main was checked out and has none" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_declaring_main_has_none_while_the_file_is_there_is_red(tmp_path, capsys):
|
||||
main = _main_file(tmp_path, [_suite()])
|
||||
code, _r = _judge(tmp_path, GREEN, extra=["--main-required", str(main), "--main-has-no-list"])
|
||||
assert code == 1 and "says main has none" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_main_has_no_list_without_a_main_path_is_red(tmp_path):
|
||||
assert _judge(tmp_path, GREEN, extra=["--main-has-no-list"])[0] == 1
|
||||
|
||||
|
||||
def test_an_exact_turned_off_against_main_is_red(tmp_path, capsys):
|
||||
main = _main_file(tmp_path, [_suite(exact=True)])
|
||||
code, _r = _judge(tmp_path, GREEN, rows=[_suite(exact=False)], extra=["--main-required", str(main)])
|
||||
assert code == 1 and "no longer exact" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_reduced_os_against_main_is_red(tmp_path, capsys):
|
||||
main = _main_file(tmp_path, [_suite()])
|
||||
code, _r = _judge(tmp_path, GREEN, rows=[_suite(os=["linux"])], extra=["--main-required", str(main)])
|
||||
assert code == 1 and "no longer runs on windows" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_changed_marker_against_main_is_red(tmp_path, capsys):
|
||||
main = _main_file(tmp_path, [_suite(marker="e2e")])
|
||||
code, _r = _judge(tmp_path, GREEN, extra=["--main-required", str(main)])
|
||||
assert code == 1 and "marker of s.one changed" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_main_list_older_than_the_format_is_still_compared(tmp_path):
|
||||
old = {k: v for k, v in _suite(min_tests=3, tests=[FILE_A]).items() if k != "exact"}
|
||||
main = _main_file(tmp_path, [old])
|
||||
assert _judge(tmp_path, GREEN, extra=["--main-required", str(main)])[0] == 0
|
||||
|
||||
|
||||
# --- args --------------------------------------------------------------------------------------------------------
|
||||
def test_args_prints_the_files_and_node_ids_one_per_line(tmp_path, capsys):
|
||||
required = _write_required(tmp_path / "required.json", [_suite()])
|
||||
assert verdict.main(["args", "--required", str(required), "--suite", "s.one", "--os", "linux"]) == 0
|
||||
assert capsys.readouterr().out.splitlines() == [FILE_A, FILE_B, NODE]
|
||||
|
||||
|
||||
def test_args_with_the_marker_puts_it_first(tmp_path, capsys):
|
||||
required = _write_required(tmp_path / "required.json", [_suite(marker="e2e")])
|
||||
assert verdict.main(["args", "--required", str(required), "--suite", "s.one", "--os", "windows", "--with-marker"]) == 0
|
||||
assert capsys.readouterr().out.splitlines()[:2] == ["-m", "e2e"]
|
||||
|
||||
|
||||
def test_args_for_windows_of_a_linux_only_suite_is_an_error(tmp_path, capsys):
|
||||
required = _write_required(tmp_path / "required.json", [_suite(os=["linux"])])
|
||||
assert verdict.main(["args", "--required", str(required), "--suite", "s.one", "--os", "windows"]) != 0
|
||||
captured = capsys.readouterr()
|
||||
assert captured.out == "" and "does not run on windows" in captured.err
|
||||
|
||||
|
||||
# --- the commit: the wrapper's, never GITHUB_SHA -------------------------------------------------------------------
|
||||
def test_the_commit_is_not_taken_from_github_sha(tmp_path, monkeypatch, capsys):
|
||||
monkeypatch.setenv("GITHUB_SHA", "e" * 40) # in a called workflow this is the commit of the ENGINE's repository
|
||||
code, result = _judge(tmp_path, GREEN, commit="b" * 40)
|
||||
assert code == 0 and result["commit"] == "b" * 40
|
||||
monkeypatch.chdir(tmp_path) # not a git checkout
|
||||
monkeypatch.setenv("GIT_CEILING_DIRECTORIES", str(tmp_path.parent))
|
||||
code, result = _judge(tmp_path, GREEN, commit=None)
|
||||
assert code == 1 and result["commit"] is None
|
||||
assert "commit of the wrapper is not known" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_without_commit_it_is_git_head_of_the_current_directory(tmp_path, monkeypatch):
|
||||
import subprocess
|
||||
repo = tmp_path / "wrapper"
|
||||
repo.mkdir()
|
||||
git = ["git", "-C", str(repo), "-c", "user.name=t", "-c", "user.email=ci-verdict-test"]
|
||||
subprocess.run(git + ["init", "-q"], check=True)
|
||||
subprocess.run(git + ["commit", "-q", "--allow-empty", "-m", "x"], check=True)
|
||||
head = subprocess.run(git + ["rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip()
|
||||
monkeypatch.setenv("GITHUB_SHA", "e" * 40)
|
||||
monkeypatch.chdir(repo)
|
||||
code, result = _judge(tmp_path, GREEN, commit=None)
|
||||
assert code == 0 and result["commit"] == head
|
||||
|
||||
|
||||
# --- the seal of the gate ------------------------------------------------------------------------------------------
|
||||
def test_a_readable_seal_is_noted_as_having_no_binary_hash(tmp_path, capsys):
|
||||
seal = tmp_path / "gate.seal.json"
|
||||
seal.write_text('{"schema": 2, "tag": "t", "assets": {}, "build_id": "1"}', encoding="utf-8")
|
||||
code, result = _judge(tmp_path, GREEN, extra=["--seal", str(seal)])
|
||||
assert code == 0 and result["seal_binary_hash"] == "absent"
|
||||
assert "carries no sha256 of the engine binary" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_seal_that_cannot_be_read_is_red(tmp_path, capsys):
|
||||
code, _r = _judge(tmp_path, GREEN, extra=["--seal", str(tmp_path / "no.seal.json")])
|
||||
assert code == 1 and "cannot be read" in capsys.readouterr().out
|
||||
|
||||
|
||||
# --- exact, every test of a file, xunit2 ---------------------------------------------------------------------------
|
||||
def test_an_exact_suite_with_more_tests_than_min_tests_is_red(tmp_path, capsys):
|
||||
cases = GREEN + [_case(FILE_B, "test_new")]
|
||||
code, result = _judge(tmp_path, cases)
|
||||
assert code == 1 and result["collected"] == 5
|
||||
assert "exact" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_suite_that_is_not_exact_allows_more_tests(tmp_path):
|
||||
cases = GREEN + [_case(FILE_B, "test_new")]
|
||||
assert _judge(tmp_path, cases, rows=[_suite(exact=False)])[0] == 0
|
||||
|
||||
|
||||
def test_a_deselected_test_is_caught_by_the_exact_count(tmp_path, capsys):
|
||||
cases = [c for c in GREEN if "test_y" not in c] # test_y[p1] deselected: not in the junit at all
|
||||
code, _r = _judge(tmp_path, cases)
|
||||
assert code == 1 and "fewer than the minimum 4" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_file_with_one_test_that_did_not_pass_is_red_even_if_another_passed(tmp_path, capsys):
|
||||
cases = [_case(FILE_A, "test_x"), _case(FILE_A, "test_y[p1]", "skipped"), _case(FILE_B, "test_z"),
|
||||
_case("tests/test_c.py", "test_one")]
|
||||
code, result = _judge(tmp_path, cases)
|
||||
assert code == 1 and result["missing_tests"] == [FILE_A]
|
||||
assert "the file %s has tests that did not pass (skipped)" % FILE_A in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_junit_written_as_xunit1_is_red_even_if_it_keeps_the_classname(tmp_path, capsys):
|
||||
xunit1 = _case(FILE_A, "test_x").replace(' time=', ' file="tests\test_a.py" line="3" time=')
|
||||
code, _r = _judge(tmp_path, [xunit1, *GREEN[1:]])
|
||||
assert code == 1 and "not xunit2" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_junit_without_classname_is_red(tmp_path, capsys):
|
||||
cases = [_case(FILE_A, "test_x", classname=""), *GREEN[1:]] # what junit_family=xunit1 leaves
|
||||
code, _r = _judge(tmp_path, cases)
|
||||
out = capsys.readouterr().out
|
||||
assert code == 1 and "not xunit2" in out and "junit_family=xunit2" in out
|
||||
|
||||
|
||||
# --- the list is validated -----------------------------------------------------------------------------------------
|
||||
@pytest.mark.parametrize("bad, why", [
|
||||
(dict(os=[]), "os must be"), (dict(os=["macos"]), "os must be"), (dict(os="linux"), "os must be"),
|
||||
(dict(os=["linux", "linux"]), "os must be"),
|
||||
(dict(tests=[]), "tests must be"), (dict(tests=[1]), "tests must be"), (dict(tests=[FILE_A, FILE_A]), "duplicates"),
|
||||
(dict(min_tests=0), "min_tests"), (dict(min_tests="4"), "min_tests"), (dict(min_tests=True), "min_tests"),
|
||||
(dict(exact="yes"), "exact"), (dict(marker=""), "marker"), (dict(id=""), "no id"),
|
||||
(dict(needs_root="linux"), "needs_root"), (dict(needs_root=["macos"]), "needs_root"),
|
||||
(dict(os=["linux"], needs_root=["windows"]), "needs_root"),
|
||||
])
|
||||
def test_a_malformed_row_is_exit_2_with_the_reason_in_all_three_commands(tmp_path, capsys, bad, why):
|
||||
required = _write_required(tmp_path / "required.json", [_suite(**bad)])
|
||||
assert verdict.main(["args", "--required", str(required), "--suite", "s.one", "--os", "linux"]) == 2
|
||||
assert why in capsys.readouterr().err
|
||||
code, result = _judge(tmp_path, GREEN, rows=[_suite(**bad)])
|
||||
assert code == 2 and result["verdict"] == "red" and why in capsys.readouterr().out
|
||||
assert verdict.main(["complete", "--required", str(required), "--results", str(tmp_path)]) == 2
|
||||
assert why in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_duplicate_ids_and_a_row_that_is_not_an_object_are_exit_2(tmp_path, capsys):
|
||||
required = _write_required(tmp_path / "required.json", [_suite(), _suite()])
|
||||
assert verdict.main(["args", "--required", str(required), "--suite", "s.one", "--os", "linux"]) == 2
|
||||
assert "more than once" in capsys.readouterr().err
|
||||
required.write_text('[1, "x"]', encoding="utf-8")
|
||||
assert verdict.main(["args", "--required", str(required), "--suite", "s.one", "--os", "linux"]) == 2
|
||||
assert "is not an object" in capsys.readouterr().err
|
||||
|
||||
|
||||
# --- complete ------------------------------------------------------------------------------------------------------
|
||||
def _results(tmp_path, rows):
|
||||
"""Run judge for every (suite, os) of rows into tmp_path/results/<artifact>/, as the gate downloads them."""
|
||||
required = _write_required(tmp_path / "required.json", rows)
|
||||
for row in rows:
|
||||
for os_name in row["os"]:
|
||||
binary = tmp_path / ("engine-%s.bin" % os_name)
|
||||
binary.write_bytes(("engine-" + os_name).encode())
|
||||
junit = _junit(tmp_path / ("j-%s-%s.xml" % (row["id"], os_name)), GREEN)
|
||||
out = tmp_path / "results" / ("result-%s-%s" % (row["id"], os_name)) / ("%s.%s.json" % (row["id"], os_name))
|
||||
code = verdict.main(["judge", "--required", str(required), "--suite", row["id"], "--os", os_name,
|
||||
"--junit", str(junit), "--binary", str(binary), "--commit", SHA, "--out", str(out)])
|
||||
assert code == 0
|
||||
return required, tmp_path / "results"
|
||||
|
||||
|
||||
def _complete(required, results):
|
||||
return verdict.main(["complete", "--required", str(required), "--results", str(results)])
|
||||
|
||||
|
||||
def _edit(results, name, **fields):
|
||||
path = next(results.rglob(name))
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
data.update(fields)
|
||||
path.write_text(json.dumps(data), encoding="utf-8")
|
||||
|
||||
|
||||
ROWS = [_suite(), _suite(id="s.two", os=["linux"])]
|
||||
|
||||
|
||||
def test_complete_is_green_when_every_leg_reported_green_at_one_commit(tmp_path, capsys):
|
||||
required, results = _results(tmp_path, ROWS)
|
||||
capsys.readouterr()
|
||||
assert _complete(required, results) == 0
|
||||
assert "COMPLETE GREEN: 3 result(s)" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_complete_fails_on_a_leg_that_never_reported(tmp_path, capsys):
|
||||
required, results = _results(tmp_path, ROWS)
|
||||
next(results.rglob("s.one.windows.json")).unlink()
|
||||
capsys.readouterr()
|
||||
assert _complete(required, results) == 1
|
||||
assert "s.one/windows has no result" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_complete_fails_on_a_missing_results_folder(tmp_path, capsys):
|
||||
required = _write_required(tmp_path / "required.json", ROWS)
|
||||
assert _complete(required, tmp_path / "nothing") == 1
|
||||
out = capsys.readouterr().out
|
||||
assert "does not exist" in out and "s.two/linux has no result" in out
|
||||
|
||||
|
||||
def test_complete_fails_on_a_red_result(tmp_path, capsys):
|
||||
required, results = _results(tmp_path, ROWS)
|
||||
_edit(results, "s.two.linux.json", verdict="red", problems=["1 test(s) failed"])
|
||||
capsys.readouterr()
|
||||
assert _complete(required, results) == 1
|
||||
assert "s.two/linux is not green" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_complete_fails_on_a_result_with_no_verdict(tmp_path):
|
||||
required, results = _results(tmp_path, ROWS)
|
||||
_edit(results, "s.two.linux.json", verdict=None)
|
||||
assert _complete(required, results) == 1
|
||||
|
||||
|
||||
def test_complete_fails_on_a_result_of_a_suite_that_is_not_in_the_list(tmp_path, capsys):
|
||||
required, results = _results(tmp_path, ROWS)
|
||||
(results / "result-s.ghost-linux").mkdir()
|
||||
(results / "result-s.ghost-linux" / "g.json").write_text(
|
||||
json.dumps({"suite": "s.ghost", "os": "linux", "verdict": "green"}), encoding="utf-8")
|
||||
capsys.readouterr()
|
||||
assert _complete(required, results) == 1
|
||||
assert "s.ghost/linux, which is not in the required list" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_complete_fails_on_a_result_of_an_os_the_suite_does_not_run_on(tmp_path, capsys):
|
||||
required, results = _results(tmp_path, ROWS)
|
||||
(results / "result-s.two-windows").mkdir()
|
||||
(results / "result-s.two-windows" / "w.json").write_text(
|
||||
json.dumps({"suite": "s.two", "os": "windows", "verdict": "green"}), encoding="utf-8")
|
||||
capsys.readouterr()
|
||||
assert _complete(required, results) == 1
|
||||
assert "s.two/windows, which is not in the required list" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_complete_fails_on_the_same_leg_reported_twice(tmp_path, capsys):
|
||||
required, results = _results(tmp_path, ROWS)
|
||||
src = next(results.rglob("s.two.linux.json"))
|
||||
(results / "again").mkdir()
|
||||
(results / "again" / "copy.json").write_text(src.read_text(encoding="utf-8"), encoding="utf-8")
|
||||
capsys.readouterr()
|
||||
assert _complete(required, results) == 1
|
||||
assert "s.two/linux has two results" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_complete_fails_on_legs_at_different_commits(tmp_path, capsys):
|
||||
required, results = _results(tmp_path, ROWS)
|
||||
_edit(results, "s.one.windows.json", commit="c" * 40)
|
||||
capsys.readouterr()
|
||||
assert _complete(required, results) == 1
|
||||
assert "different commits" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_complete_fails_when_two_suites_of_one_os_ran_with_different_binaries(tmp_path, capsys):
|
||||
required, results = _results(tmp_path, ROWS)
|
||||
_edit(results, "s.two.linux.json", binary_sha256="f" * 64)
|
||||
capsys.readouterr()
|
||||
assert _complete(required, results) == 1
|
||||
assert "linux legs ran with different binaries" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_complete_fails_on_a_result_with_no_binary_hash(tmp_path, capsys):
|
||||
required, results = _results(tmp_path, ROWS)
|
||||
_edit(results, "s.two.linux.json", binary_sha256=None)
|
||||
capsys.readouterr()
|
||||
assert _complete(required, results) == 1
|
||||
assert "no binary sha256" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_complete_allows_different_binaries_for_different_os(tmp_path):
|
||||
required, results = _results(tmp_path, ROWS) # engine-linux.bin and engine-windows.bin differ
|
||||
assert _complete(required, results) == 0
|
||||
|
||||
|
||||
def test_complete_fails_on_an_unreadable_json_and_on_a_json_that_is_not_a_result(tmp_path, capsys):
|
||||
required, results = _results(tmp_path, ROWS)
|
||||
(results / "junk.json").write_text("{not json", encoding="utf-8")
|
||||
(results / "other.json").write_text("[1]", encoding="utf-8")
|
||||
capsys.readouterr()
|
||||
assert _complete(required, results) == 1
|
||||
out = capsys.readouterr().out
|
||||
assert "junk.json cannot be read" in out and "other.json is not a result" in out
|
||||
|
||||
|
||||
# --- the real list-----------------------------------------------------------------------------------------------
|
||||
def _real():
|
||||
return json.loads(REQUIRED.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def test_the_real_list_is_well_formed_for_the_judge_and_every_row_is_exact():
|
||||
rows = _real()
|
||||
assert verdict.validate_list(rows) == []
|
||||
assert [r["id"] for r in rows if r["exact"] is not True] == []
|
||||
|
||||
|
||||
def test_the_real_list_has_unique_ids_and_sane_rows():
|
||||
rows = _real()
|
||||
ids = [r["id"] for r in rows]
|
||||
assert rows and len(ids) == len(set(ids)), ids
|
||||
for r in rows:
|
||||
assert set(r["os"]) and set(r["os"]) <= {"linux", "windows"}, r["id"]
|
||||
assert isinstance(r["min_tests"], int) and r["min_tests"] > 0, r["id"]
|
||||
assert r["tests"] and len(r["tests"]) == len(set(r["tests"])), r["id"]
|
||||
assert r["giro"] in {"G1", "G2"}, r["id"]
|
||||
# needs_root is a bool (every OS of the row) or the list of the OSes that need root
|
||||
root = r["needs_root"]
|
||||
assert isinstance(root, bool) or (isinstance(root, list) and set(root) <= set(r["os"])), r["id"]
|
||||
|
||||
|
||||
def test_every_required_file_exists_and_every_node_id_is_defined_in_it():
|
||||
for r in _real():
|
||||
for entry in r["tests"]:
|
||||
path, _sep, name = entry.partition("::")
|
||||
file = ROOT / path
|
||||
assert file.is_file(), "%s: %s does not exist" % (r["id"], path)
|
||||
if name:
|
||||
text = file.read_text(encoding="utf-8")
|
||||
base = name.split("[", 1)[0]
|
||||
assert re.search(r"^\s*(async\s+)?def %s\(" % re.escape(base), text, re.M), \
|
||||
"%s: %s has no def %s" % (r["id"], path, base)
|
||||
|
||||
|
||||
def test_a_required_suite_runs_with_the_marker_it_names():
|
||||
for r in _real():
|
||||
assert r["marker"] in {"unit", "e2e"}, r["id"]
|
||||
if r["marker"] == "unit":
|
||||
for entry in r["tests"]:
|
||||
assert "pytestmark = pytest.mark.unit" in (ROOT / entry.split("::")[0]).read_text(encoding="utf-8") \
|
||||
or "@pytest.mark.unit" in (ROOT / entry.split("::")[0]).read_text(encoding="utf-8"), entry
|
||||
|
||||
|
||||
def test_a_suite_that_needs_root_only_on_linux_still_runs_on_windows():
|
||||
doh = [r for r in _real() if r["id"] == "wrapper.e2e.doh"][0]
|
||||
assert doh["os"] == ["linux", "windows"] and doh["needs_root"] == ["linux"]
|
||||
@@ -0,0 +1,196 @@
|
||||
"""The host network a page sees is the one the session DECLARES, not the one of the machine (red until it is declared).
|
||||
|
||||
Design: ``invisible_WebRTC/notes/declared-interfaces-design.md`` and ``declared-interfaces-proofs.md`` (the private study
|
||||
repository). Behind a
|
||||
proxy the engine must not read the host's interfaces: the core declares one adapter in ``STEALTHFOX_WEBRTC_NETWORK``,
|
||||
``v4=<private address>;v6=<0|1>;p6=<the exit's /64 prefix, empty without IPv6>`` (the IPv6 host is that prefix and a
|
||||
temporary identifier; v6=1 without a prefix is no IPv6), and the engine answers the reads of the host (the interface list,
|
||||
the default route, the address and port a bound socket reports) from it (nr_stealth_network.h). A page
|
||||
then sees what retail Firefox on Windows shows on a machine with that adapter, whatever the machine under the browser has:
|
||||
|
||||
* no IPv6: ONE host name (udp + tcp), ranked 127 (the only address);
|
||||
* IPv6: TWO host names, the IPv6 one ranked 127 above the IPv4 one at 126 (``nrinterfaceprioritizer.cpp:82-85``);
|
||||
* the host ports are those of a Windows machine, chosen by our code: 49152-65535, a consecutive pair per connection
|
||||
(IPv4 N, IPv6 N+1), drawn at random by our code for each connection (not by the kernel, not from the seed: two visits
|
||||
with the same seed must not share ports), the same distribution on every host;
|
||||
* two connections on one page connect to each other in the time retail takes.
|
||||
|
||||
Reference shape (retail 159, measured 2026-11-11, ``captures/retail/firefox-159.0-win/direct-dualstack-stun-candidates``):
|
||||
host udp 2122252543 (IPv6) and 2122187007 (IPv4), host tcp 2105524479 and 2105458943, one name per address.
|
||||
|
||||
Red on an engine without the declared network (before webrtc/declared-interfaces b9bdb3c3ad + 6ca7a8c104): it gathered
|
||||
every filtered address of the OS and let the kernel hand out the ports, so these failed on every machine with more than
|
||||
one interface or a port range that is not Windows's, the IPv6 case everywhere, and the loopback test was slower than
|
||||
retail and died with no usable interface. Hermetic: a local TCP-only SOCKS5 proxy and a local page, no external network.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import statistics
|
||||
|
||||
import pytest
|
||||
|
||||
from test_webrtc_realness import (_FAKE_EGRESS, _e2e_binary, _launch, candidates, decode_priority, host_candidates,
|
||||
is_mdns, local_https_page, socks5_tcp_only) # noqa: F401 (fixtures)
|
||||
|
||||
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
|
||||
|
||||
NETWORK_ENV = "STEALTHFOX_WEBRTC_NETWORK"
|
||||
# retail 159 on Windows. The interface rank is the position in the prioritizer's sort, starting at 127
|
||||
# (nrinterfaceprioritizer.cpp:183-189), so an IPv4-only machine ranks its one host 127, and with IPv6 the IPv6 host
|
||||
# takes 127 and the IPv4 host 126.
|
||||
UDP_127, UDP_126, TCP_127, TCP_126 = 2122252543, 2122187007, 2105524479, 2105458943
|
||||
# The two shapes of the declared adapter: without IPv6, and with the exit's /64 prefix.
|
||||
V4_ONLY = "v4=192.168.31.7;v6=0;p6="
|
||||
DUAL = "v4=192.168.31.7;v6=1;p6=2a01:e0a:1f2:3450::/64"
|
||||
|
||||
_GATHER_JS = r"""async () => {
|
||||
const pc = new RTCPeerConnection({iceServers: []});
|
||||
pc.createDataChannel('');
|
||||
const cands = [];
|
||||
pc.addEventListener('icecandidate', e => { if (e.candidate && e.candidate.candidate) cands.push(e.candidate.candidate); });
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
await new Promise(r => setTimeout(r, 2500));
|
||||
try { pc.close(); } catch (e) {}
|
||||
return cands;
|
||||
}"""
|
||||
|
||||
# Two connections on one page, connected to each other in script (the loopback test many demos use).
|
||||
_LOOPBACK_JS = r"""async () => {
|
||||
const t0 = performance.now();
|
||||
const pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();
|
||||
pc1.onicecandidate = e => { if (e.candidate) pc2.addIceCandidate(e.candidate).catch(() => {}); };
|
||||
pc2.onicecandidate = e => { if (e.candidate) pc1.addIceCandidate(e.candidate).catch(() => {}); };
|
||||
const dc = pc1.createDataChannel('x');
|
||||
let opened = null, echoed = false;
|
||||
dc.onopen = () => { opened = Math.round(performance.now() - t0); dc.send('ping'); };
|
||||
pc2.ondatachannel = ev => { ev.channel.onmessage = m => ev.channel.send('pong:' + m.data); };
|
||||
dc.onmessage = m => { echoed = (m.data === 'pong:ping'); };
|
||||
await pc1.setLocalDescription(await pc1.createOffer());
|
||||
await pc2.setRemoteDescription(pc1.localDescription);
|
||||
await pc2.setLocalDescription(await pc2.createAnswer());
|
||||
await pc1.setRemoteDescription(pc2.localDescription);
|
||||
const deadline = performance.now() + 8000;
|
||||
while (performance.now() < deadline && !(opened !== null && echoed)) await new Promise(r => setTimeout(r, 5));
|
||||
pc1.close(); pc2.close();
|
||||
return {opened, echoed};
|
||||
}"""
|
||||
|
||||
# Retail 159 on Windows, 12 cold launches (``captures/mdns-loopback/retail-159-win-12``): 37-52 ms in ten of twelve, two
|
||||
# slow ones at about 110, median 41.5. Without mDNS retail takes about 20 ms (``retail-159-win-nomdns``): the other 20 ms are
|
||||
# the multicast round trip of the responder. The engine makes that round trip too, on the loopback (the responder joins and
|
||||
# speaks on 127.0.0.1; a name of ours answers with the loopback of its family), so the window is the retail one: 30-55 ms on
|
||||
# the MEDIAN of five cold launches. It keeps out "dead" (no usable interface), "slower than retail" and "faster than retail"
|
||||
# (an answer that skips the round trip).
|
||||
RETAIL_MEDIAN_WINDOW_MS = (30, 55)
|
||||
|
||||
|
||||
def _session(declaration, socks, page_url, monkeypatch, seed, script):
|
||||
"""One proxied launch with the declaration in the environment; runs ``script`` on the page and returns the result."""
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
monkeypatch.setenv("STEALTHFOX_WEBRTC_PUBLIC_IP", _FAKE_EGRESS)
|
||||
monkeypatch.delenv("STEALTHFOX_WEBRTC_DISABLE_IPV6", raising=False) # the declaration replaces it
|
||||
monkeypatch.setenv(NETWORK_ENV, declaration)
|
||||
prefs = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": ""}
|
||||
proxy = {"server": "socks5://127.0.0.1:%d" % socks.port}
|
||||
with _launch(binary_path=binary, proxy=proxy, extra_prefs=prefs, seed=seed) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto(page_url, wait_until="domcontentloaded", timeout=60000)
|
||||
return script(page)
|
||||
|
||||
|
||||
def _host_shape(declaration, socks, page_url, monkeypatch, seed=42):
|
||||
return host_candidates(candidates(
|
||||
_session(declaration, socks, page_url, monkeypatch, seed, lambda page: page.evaluate(_GATHER_JS))))
|
||||
|
||||
|
||||
def _by_protocol(hosts):
|
||||
return {proto: sorted((c["priority"] for c in hosts if c["proto"] == proto), reverse=True)
|
||||
for proto in ("UDP", "TCP")}
|
||||
|
||||
|
||||
def _udp_ports_by_rank(hosts):
|
||||
return {decode_priority(c["priority"])["iface_pref"]: c["port"] for c in hosts if c["proto"] == "UDP"}
|
||||
|
||||
|
||||
def test_without_a_declared_ipv6_the_page_sees_one_host_name(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""One adapter, no IPv6: a udp and a tcp host candidate on ONE mDNS name, ranked 127 as the only address.
|
||||
|
||||
The shape is a function of the declaration alone, so this must hold on every machine: run it on a host with three
|
||||
IPv4 adapters (the engine gathers all three today), in a container with two interfaces (``docker network connect``
|
||||
before ``docker start``), and in a container with one."""
|
||||
hosts = _host_shape(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch)
|
||||
assert all(is_mdns(c["address"]) for c in hosts), [c["address"] for c in hosts]
|
||||
assert len({c["address"] for c in hosts}) == 1, "host names: %r" % sorted({c["address"] for c in hosts})
|
||||
assert _by_protocol(hosts) == {"UDP": [UDP_127], "TCP": [TCP_127]}, _by_protocol(hosts)
|
||||
|
||||
|
||||
def test_a_declared_ipv6_gives_two_host_names_ranked_127_and_126(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""One adapter with IPv6: two names; the IPv6 host ranks one above the IPv4 one, as on the retail capture."""
|
||||
hosts = _host_shape(DUAL, socks5_tcp_only, local_https_page, monkeypatch)
|
||||
assert all(is_mdns(c["address"]) for c in hosts), [c["address"] for c in hosts]
|
||||
assert len({c["address"] for c in hosts}) == 2, "host names: %r" % sorted({c["address"] for c in hosts})
|
||||
assert _by_protocol(hosts) == {"UDP": [UDP_127, UDP_126], "TCP": [TCP_127, TCP_126]}, _by_protocol(hosts)
|
||||
assert [decode_priority(p)["iface_pref"] for p in _by_protocol(hosts)["UDP"]] == [127, 126]
|
||||
|
||||
|
||||
def test_ipv6_without_the_exit_prefix_is_no_ipv6(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""v6=1 with an empty prefix: the exit gave the core no /64, so the machine has no IPv6 address, and no fallback
|
||||
invents one. One host name, as without IPv6."""
|
||||
hosts = _host_shape("v4=192.168.31.7;v6=1;p6=", socks5_tcp_only, local_https_page, monkeypatch)
|
||||
assert _by_protocol(hosts) == {"UDP": [UDP_127], "TCP": [TCP_127]}, hosts
|
||||
|
||||
|
||||
def test_the_host_ports_are_those_of_a_windows_machine(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""Retail on Windows (6 of 6 runs, ``captures/retail/firefox-159.0-win/direct-dualstack-srflx-ports``): the UDP host
|
||||
ports are in the dynamic range 49152-65535 and, on one connection, the IPv4 port and the IPv6 port are consecutive
|
||||
(N, N+1). A page reads them. Linux hands out 32768-60999 at random, so on a Linux host this is red today."""
|
||||
hosts = _host_shape(DUAL, socks5_tcp_only, local_https_page, monkeypatch)
|
||||
by_rank = _udp_ports_by_rank(hosts)
|
||||
assert sorted(by_rank) == [126, 127], by_rank
|
||||
assert all(49152 <= port <= 65535 for port in by_rank.values()), by_rank
|
||||
assert by_rank[127] == by_rank[126] + 1, "IPv4 port %d, IPv6 port %d" % (by_rank[126], by_rank[127])
|
||||
|
||||
|
||||
def test_the_host_port_is_in_the_windows_range_without_ipv6_too(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""The one-address case of the range check. On a Linux host it can pass by luck (a kernel port in 49152-60999 falls
|
||||
in the range); the same-seed test above is the one that cannot."""
|
||||
hosts = _host_shape(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch)
|
||||
by_rank = _udp_ports_by_rank(hosts)
|
||||
assert list(by_rank) == [127] and 49152 <= by_rank[127] <= 65535, by_rank
|
||||
|
||||
|
||||
def _ports_of_two_connections(declaration, socks, page_url, monkeypatch, seed):
|
||||
def script(page):
|
||||
first = host_candidates(candidates(page.evaluate(_GATHER_JS)))
|
||||
second = host_candidates(candidates(page.evaluate(_GATHER_JS)))
|
||||
return first, second
|
||||
|
||||
first, second = _session(declaration, socks, page_url, monkeypatch, seed, script)
|
||||
return (sorted(c["port"] for c in first if c["proto"] == "UDP"),
|
||||
sorted(c["port"] for c in second if c["proto"] == "UDP"))
|
||||
|
||||
|
||||
def test_two_connections_on_one_page_get_their_own_port_pair(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""Retail (``captures/retail/firefox-159.0-win/two-pc-port-sequence``, 6 of 6): each connection gets its own pair,
|
||||
consecutive (N, N+1) in the range, and the second pair is unrelated to the first (not increasing)."""
|
||||
first, second = _ports_of_two_connections(DUAL, socks5_tcp_only, local_https_page, monkeypatch, 42)
|
||||
for pair in (first, second):
|
||||
assert len(pair) == 2 and pair[1] == pair[0] + 1 and 49152 <= pair[0] and pair[1] <= 65535, (first, second)
|
||||
assert first != second, (first, second)
|
||||
|
||||
|
||||
def test_two_connections_on_one_page_connect_in_the_time_of_retail(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""The names the browser registered for itself must resolve although the declared address is not the host's, and in
|
||||
the time retail takes: not slower (a responder that cannot hear itself, or an OS list that is empty, kills the test),
|
||||
not faster (an answer that skips the round trip). Five cold launches, median in the retail window."""
|
||||
times = []
|
||||
for n in range(5):
|
||||
res = _session(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch, 100 + n,
|
||||
lambda page: page.evaluate(_LOOPBACK_JS))
|
||||
assert res["echoed"] and res["opened"] is not None, "run %d: the data channel did not open: %r" % (n, res)
|
||||
times.append(res["opened"])
|
||||
low, high = RETAIL_MEDIAN_WINDOW_MS
|
||||
median = statistics.median(times)
|
||||
assert low <= median <= high, "median %s ms of %r, retail window %d-%d ms" % (median, sorted(times), low, high)
|
||||
@@ -0,0 +1,101 @@
|
||||
"""The core declares the PROVIDER of Firefox's DoH for every session; the engine derives the rest from the proxies it receives.
|
||||
|
||||
The contract: with a proxy, every name the browser resolves goes to DoH, and a DoH request is a channel like any other, so it
|
||||
leaves through the proxy of the context of the lookup. What the core writes to make that so is only the provider, with or
|
||||
without a proxy (a DoH state would be two declarations of one fact):
|
||||
|
||||
network.trr.uri = https://mozilla.cloudflare-dns.com/dns-query
|
||||
network.trr.bootstrapAddr = <an IP> the DoH host is found with no DNS at all
|
||||
network.proxy.allow_bypass = False with a proxy: no channel falls back to direct when the proxy stumbles
|
||||
network.parental_controls_cached_state = False declared off, as retail without the service
|
||||
|
||||
and NOT `network.trr.mode`, `network.trr.exclude-etc-hosts` or `network.trr.excluded-domains` (the engine derives the state, the
|
||||
hosts file and the proxy's own name from the proxies Juggler gives it).
|
||||
|
||||
Two doors are checked, because the e2e launches through the second: the core's composer, and the wrapper's own path
|
||||
(`InvisiblePlaywright._build_prefs` and the core's proxy step, what a launch composes). Nothing here starts a browser or the network (the
|
||||
suite's autouse fixture answers the egress lookup).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_core import decide_session_locale
|
||||
from invisible_core._fpforge import generate_profile
|
||||
from invisible_core.prefs import compose_session_prefs
|
||||
|
||||
from invisible_playwright import _session
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
URI = "https://mozilla.cloudflare-dns.com/dns-query"
|
||||
NAMED = {"server": "socks5://gw.example.test:1080"}
|
||||
BY_ADDRESS = {"server": "socks5://203.0.113.9:1080"}
|
||||
HTTP_WITH_CREDENTIALS = {"server": "http://gw.example.test:3128", "username": "u", "password": "p"}
|
||||
HTTP_BY_V6_ADDRESS = {"server": "http://[2001:db8::1]:3128"}
|
||||
|
||||
|
||||
def _core(proxy):
|
||||
return compose_session_prefs(generate_profile(seed=42), locale=decide_session_locale("en-US"),
|
||||
timezone="America/New_York", proxy=proxy).prefs
|
||||
|
||||
|
||||
def _wrapper(proxy):
|
||||
"""What the launcher composes: the session's prefs (`_build_prefs`), then the core's proxy step
|
||||
(`configure_proxy`) on them, exactly as `launcher.__enter__` and `remote.op_launch` do."""
|
||||
from invisible_core import configure_proxy
|
||||
from invisible_playwright.launcher import InvisiblePlaywright
|
||||
|
||||
session = InvisiblePlaywright(seed=42, binary_path="firefox.exe", humanize=False, proxy=proxy or None)
|
||||
geo = _session.session_geo(session._timezone, session._proxy, session._locale_requested)
|
||||
session._timezone, session._locale = geo.timezone, geo.locale
|
||||
prefs = session._build_prefs()
|
||||
configure_proxy(session._proxy, prefs)
|
||||
return prefs
|
||||
|
||||
|
||||
@pytest.fixture(params=[_core, _wrapper], ids=["core", "wrapper"])
|
||||
def compose(request):
|
||||
return request.param
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proxy", [NAMED, BY_ADDRESS, HTTP_WITH_CREDENTIALS, HTTP_BY_V6_ADDRESS],
|
||||
ids=["socks-name", "socks-ip", "http-name", "http-ipv6"])
|
||||
def test_a_proxied_session_declares_the_doh_provider_and_closes_the_bypass(compose, proxy):
|
||||
prefs = compose(proxy)
|
||||
assert prefs["network.trr.uri"] == URI
|
||||
ipaddress.ip_address(prefs["network.trr.bootstrapAddr"]) # raises unless it is an IP literal
|
||||
for derived in ("network.trr.mode", "network.trr.exclude-etc-hosts"):
|
||||
assert derived not in prefs, "%s is derived by the engine from the proxies, not declared by the core" % derived
|
||||
assert prefs["network.proxy.allow_bypass"] is False
|
||||
assert prefs["network.parental_controls_cached_state"] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proxy", [NAMED, HTTP_WITH_CREDENTIALS, BY_ADDRESS, HTTP_BY_V6_ADDRESS],
|
||||
ids=["socks-name", "http-name", "ipv4", "ipv6"])
|
||||
def test_the_core_excludes_no_domain_the_engine_derives_the_proxys_own_name(compose, proxy):
|
||||
assert "network.trr.excluded-domains" not in compose(proxy)
|
||||
|
||||
|
||||
def test_the_bootstrap_address_is_a_public_address_and_not_the_proxy(compose):
|
||||
bootstrap = ipaddress.ip_address(compose(BY_ADDRESS)["network.trr.bootstrapAddr"])
|
||||
assert bootstrap.is_global and str(bootstrap) != "203.0.113.9"
|
||||
|
||||
|
||||
def test_a_session_without_a_proxy_declares_the_provider_and_no_state(compose):
|
||||
prefs = compose(None)
|
||||
assert sorted(k for k in prefs if k.startswith("network.trr.")) == ["network.trr.bootstrapAddr", "network.trr.uri"]
|
||||
assert prefs.get("network.proxy.allow_bypass") is not False, "no proxy, no closed fallback"
|
||||
assert prefs["network.parental_controls_cached_state"] is False, "declared off with or without a proxy"
|
||||
|
||||
|
||||
def test_the_doh_prefs_are_the_same_for_the_same_proxy_whatever_the_seed():
|
||||
"""Nothing about the DoH is drawn from the seed: two sessions behind the same proxy declare the same DoH."""
|
||||
def trr(seed):
|
||||
prefs = compose_session_prefs(generate_profile(seed=seed), locale=decide_session_locale("en-US"),
|
||||
timezone="America/New_York", proxy=NAMED).prefs
|
||||
return {k: v for k, v in prefs.items() if k.startswith("network.trr.")}
|
||||
|
||||
assert trr(1) == trr(2) == trr(970411)
|
||||
@@ -0,0 +1,496 @@
|
||||
"""E2E: behind a proxy every name is resolved by Firefox's DoH THROUGH the proxy, and nothing leaves the host.
|
||||
|
||||
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).
|
||||
Every name the browser resolves - page hosts, ICE server names, HTTP/3 hosts - goes to that DoH; a DoH request is a
|
||||
channel like any other, so it leaves THROUGH the session proxy (a SOCKS5 CONNECT or an HTTP CONNECT to
|
||||
162.159.61.4:443), by the proxy of the context of the lookup; the browser then connects to the resolved ADDRESS (SOCKS5
|
||||
by address, never by name). The session proxy is the first command on the pipe, and every proxied channel waits for
|
||||
it: nothing goes DIRECT. No UDP/53 and no direct TCP leave the browser, and no helper process (crash reporter, default
|
||||
browser agent, maintenance service, updater, pingsender) is started.
|
||||
|
||||
How each test sees it, with nothing but loopback:
|
||||
|
||||
* `FakeDoh` answers the names (`page-a.test`...) and records every query with the gateway it arrived by (`via`);
|
||||
* `DohGateway` / `HttpProxy` are the proxies; a CONNECT to the DoH address is handed to the FakeDoh, every other one to
|
||||
a loopback address is relayed, and every CONNECT is recorded (a CONNECT that carries a NAME is a defect to find);
|
||||
* `Watcher` samples the connections of every browser process from before the launch: one to a non-loopback address is
|
||||
a direct connection;
|
||||
* `ResolverTrap` (Linux, root) points /etc/resolv.conf at a counting resolver: one question is a leak to the resolver
|
||||
of the machine. Where it cannot run, its assertions are skipped, not the test - unless the gate sets
|
||||
INVPW_REQUIRE_TRAP=1: then a trap that cannot run, or whose port 53 cannot be bound, is a failure.
|
||||
|
||||
Pages are served by a local HTTP server on 127.0.0.1 and reached by NAMES only the FakeDoh can resolve. The browser must
|
||||
accept the FakeDoh certificate: the pages are opened in contexts made with `ignore_https_errors=True`, which the engine
|
||||
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, 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
|
||||
ICE resolver's lookup carries the origin attributes of its document; (3) Firefox's TRR accepts HTTP/1.1 as well as h2
|
||||
(the FakeDoh offers both; `doh.alpn_of(...)` says which one was used); (4) the DoH and page connections reach a SOCKS
|
||||
gateway as ADDRESSES; (5) behind an HTTP proxy an `http` page's name goes to the proxy inside the request (it is the
|
||||
proxy that resolves it), so the DoH is triggered there by an ICE server name, which the browser always resolves itself.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import http.server
|
||||
import ipaddress
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_core import SessionGeo, decide_session_locale
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
import _doh_servers as ds
|
||||
import _trap_policy
|
||||
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
|
||||
|
||||
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
|
||||
|
||||
#: The zone of the FakeDoh: every name a test uses, all pointing at the loopback where the page server is.
|
||||
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.
|
||||
#: 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,
|
||||
locale=decide_session_locale("en-US"))
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------- fixtures
|
||||
@pytest.fixture(autouse=True)
|
||||
def _hermetic_session(monkeypatch):
|
||||
"""No egress lookup on the internet, and no egress drift check through the proxy.
|
||||
|
||||
A launch asks "who am I" through the proxy (api.ipify.org by NAME, resolved by the TEST process: a question to the
|
||||
resolver trap and a connection past the loopback), and re-asks at every new context. This test is about the
|
||||
BROWSER's roads, so the answer is declared: the same facts (timezone, locale, position, an exit address) the
|
||||
lookup would have returned.
|
||||
"""
|
||||
monkeypatch.setattr("invisible_playwright.launcher.prepare_session_geo", lambda tz, proxy, locale: GEO)
|
||||
monkeypatch.setattr(InvisiblePlaywright, "_assert_uscita_invariata", lambda self: None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def doh():
|
||||
import h2 # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
server = FakeDoh(ZONE)
|
||||
yield server
|
||||
server.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def gateway(doh):
|
||||
made = []
|
||||
|
||||
def make(name, **kwargs):
|
||||
gw = DohGateway(name, doh, **kwargs)
|
||||
made.append(gw)
|
||||
return gw
|
||||
|
||||
yield make
|
||||
for gw in made:
|
||||
gw.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def trap():
|
||||
"""The resolver trap, counting every question the machine's resolver is asked.
|
||||
|
||||
None only where it cannot run AND the gate does not require it (a developer's machine). With INVPW_REQUIRE_TRAP=1
|
||||
(the gate's Linux leg) a trap that is unavailable or whose port 53 cannot be bound is a failure with its reason."""
|
||||
if not ResolverTrap.available:
|
||||
why = _trap_policy.failure(None, False, ResolverTrap.reason)
|
||||
if why:
|
||||
pytest.fail(why)
|
||||
yield None
|
||||
return
|
||||
resolver = ResolverTrap()
|
||||
try:
|
||||
resolver.__enter__()
|
||||
except OSError as exc: # port 53 taken (another worker holds the trap)
|
||||
why = _trap_policy.failure(None, True, bind_error=exc)
|
||||
if why:
|
||||
pytest.fail(why)
|
||||
yield None
|
||||
return
|
||||
try:
|
||||
yield resolver
|
||||
finally:
|
||||
resolver.__exit__(None, None, None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def watcher(firefox_binary):
|
||||
"""Started BEFORE the test body, so before any launch; stopped by the test or here."""
|
||||
w = Watcher(match=("firefox", Path(firefox_binary).stem.lower())).start()
|
||||
yield w
|
||||
w.stop()
|
||||
|
||||
|
||||
class Pages:
|
||||
"""A local HTTP server: every path answers a page that says which Host it was asked for."""
|
||||
|
||||
def __init__(self):
|
||||
outer = self
|
||||
self.hits = []
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self): # noqa: N802
|
||||
host = self.headers.get("Host", "")
|
||||
outer.hits.append((host, self.path))
|
||||
body = ("<!doctype html><title>page</title><body>HOST=%s</body>" % host).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
self._server = LocalServer(("127.0.0.1", 0), Handler)
|
||||
self.port = self._server.server_address[1]
|
||||
threading.Thread(target=self._server.serve_forever, daemon=True).start()
|
||||
|
||||
def url(self, name):
|
||||
return "http://%s:%d/" % (name, self.port)
|
||||
|
||||
def close(self):
|
||||
self._server.shutdown()
|
||||
self._server.server_close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pages():
|
||||
server = Pages()
|
||||
yield server
|
||||
server.close()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------- helpers
|
||||
def _launch(binary, proxy, **kwargs):
|
||||
return InvisiblePlaywright(seed=42, binary_path=binary, proxy=proxy, extra_prefs=dict(PREFS), **kwargs)
|
||||
|
||||
|
||||
def _page_in(browser, proxy=None):
|
||||
"""A page in a new context, with its own proxy when given and the FakeDoh's certificate accepted."""
|
||||
options = {"ignore_https_errors": True}
|
||||
if proxy is not None:
|
||||
options["proxy"] = proxy
|
||||
context = browser.new_context(**options)
|
||||
return context, context.new_page()
|
||||
|
||||
|
||||
def _text(page):
|
||||
return page.evaluate("() => document.body.innerText")
|
||||
|
||||
|
||||
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 (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):
|
||||
lines.append("%s refused: %s" % (p.name, p.refused))
|
||||
return "\n " + "\n ".join(lines)
|
||||
|
||||
|
||||
def _is_address(host):
|
||||
try:
|
||||
ipaddress.ip_address(host)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
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()
|
||||
if trap is not None:
|
||||
assert trap.queries == [], "the browser asked the resolver of the machine: %s" % trap.describe()
|
||||
|
||||
|
||||
def _create_a_peer_connection_for(page, name):
|
||||
"""An RTCPeerConnection whose ICE server is `stun:<name>:3478`, gathering started: the browser resolves the name."""
|
||||
page.evaluate("""(name) => {
|
||||
const pc = new RTCPeerConnection({iceServers: [{urls: 'stun:' + name + ':3478'}]});
|
||||
window.__pc = pc;
|
||||
pc.createDataChannel('probe');
|
||||
pc.createOffer().then(offer => pc.setLocalDescription(offer));
|
||||
}""", name)
|
||||
|
||||
|
||||
# ============================================================================================================ tests
|
||||
def test_names_resolve_through_doh_by_the_proxy(firefox_binary, doh, pages, gateway, trap, watcher):
|
||||
"""A page name is asked to the DoH, by the proxy, and the page is then reached by ADDRESS."""
|
||||
gw1 = gateway("gw1")
|
||||
with _launch(firefox_binary, gw1.proxy) as browser:
|
||||
context, page = _page_in(browser)
|
||||
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
|
||||
text = _text(page)
|
||||
context.close()
|
||||
watcher.stop()
|
||||
|
||||
assert "HOST=page-a.test:%d" % pages.port in text, "the page did not load through the proxy: %r" % text
|
||||
why = _why(doh, gw1)
|
||||
assert doh.vias_of("page-a.test", QTYPE_A) == {"gw1"}, "page-a.test (A) was not asked by gw1 only" + why
|
||||
assert (DOH_BOOTSTRAP, DOH_PORT) in gw1.connects, "no DoH CONNECT to the bootstrap address" + why
|
||||
assert not [h for h, _p in gw1.connects if h == "page-a.test"], (
|
||||
"the browser sent the NAME page-a.test to the proxy instead of resolving it" + why)
|
||||
assert [h for h, _p in gw1.connects if not _is_address(h) and h != DOH_HOST] == [], (
|
||||
"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, doh, gw1)
|
||||
|
||||
|
||||
def test_an_ice_server_name_resolves_the_same_way(firefox_binary, doh, pages, gateway, trap, watcher):
|
||||
"""A name chosen by the PAGE (a STUN server in iceServers) is resolved by the DoH through the proxy too."""
|
||||
gw1 = gateway("gw1")
|
||||
with _launch(firefox_binary, gw1.proxy) as browser:
|
||||
context, page = _page_in(browser)
|
||||
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
|
||||
_create_a_peer_connection_for(page, "stun-a.test")
|
||||
asked = ds.wait_until(lambda: doh.queries_for("stun-a.test"), 30)
|
||||
page.evaluate("() => window.__pc.close()")
|
||||
context.close()
|
||||
watcher.stop()
|
||||
|
||||
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, doh, gw1)
|
||||
|
||||
|
||||
def test_two_contexts_two_doh_exits(firefox_binary, doh, pages, gateway, trap, watcher):
|
||||
"""Each context resolves by ITS proxy: the browser's for a context with none, its own for context B, each with
|
||||
the credentials of that gateway."""
|
||||
gw1 = gateway("gw1", user="gw1-user", password="gw1-pass")
|
||||
gw2 = gateway("gw2", user="gw2-user", password="gw2-pass")
|
||||
with _launch(firefox_binary, gw1.proxy) as browser:
|
||||
context_a, page_a = _page_in(browser) # no proxy of its own: the browser's, gw1
|
||||
context_b, page_b = _page_in(browser, proxy=gw2.proxy) # its own: gw2
|
||||
page_a.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
|
||||
page_b.goto(pages.url("page-b.test"), wait_until="load", timeout=30000)
|
||||
text_a, text_b = _text(page_a), _text(page_b)
|
||||
context_a.close()
|
||||
context_b.close()
|
||||
watcher.stop()
|
||||
|
||||
why = _why(doh, gw1, gw2)
|
||||
assert "HOST=page-a.test" in text_a and "HOST=page-b.test" in text_b, (text_a, text_b)
|
||||
assert doh.vias_of("page-a.test", QTYPE_A) == {"gw1"}, "page-a.test must be resolved by gw1 only" + why
|
||||
assert doh.vias_of("page-b.test", QTYPE_A) == {"gw2"}, "page-b.test must be resolved by gw2 only" + why
|
||||
assert gw1.doh_connects() and gw2.doh_connects(), "each gateway must have carried a DoH CONNECT" + why
|
||||
assert ("127.0.0.1", pages.port) in gw1.connects and ("127.0.0.1", pages.port) in gw2.connects, (
|
||||
"each page must be reached by address through the gateway of its context" + why)
|
||||
assert gw1.credentials_seen and set(gw1.credentials_seen) == {("gw1-user", "gw1-pass")}, (
|
||||
"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, doh, gw1, gw2)
|
||||
|
||||
|
||||
def test_an_authenticated_http_proxy_resolves(firefox_binary, doh, pages, trap, watcher):
|
||||
"""An http proxy with credentials: the DoH CONNECT carries the PREEMPTIVE `Proxy-Authorization: Basic`, so it
|
||||
never needs a 407 round trip, and the page loads.
|
||||
|
||||
Behind an HTTP proxy an `http` page's NAME goes to the proxy (which resolves it), so the browser's own DoH is
|
||||
triggered here by an ICE server name, which the browser always resolves itself.
|
||||
"""
|
||||
user, password = "ferd_http_user", "pw-é42"
|
||||
proxy = HttpProxy("http1", doh, user=user, password=password)
|
||||
try:
|
||||
with _launch(firefox_binary, proxy.proxy) as browser:
|
||||
context, page = _page_in(browser)
|
||||
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
|
||||
text = _text(page)
|
||||
_create_a_peer_connection_for(page, "stun-a.test")
|
||||
asked = ds.wait_until(lambda: doh.queries_for("stun-a.test"), 30)
|
||||
page.evaluate("() => window.__pc.close()")
|
||||
context.close()
|
||||
watcher.stop()
|
||||
|
||||
expected = "Basic " + base64.b64encode(("%s:%s" % (user, password)).encode("utf-8")).decode("ascii")
|
||||
assert expected == basic(user, password)
|
||||
why = _why(doh, proxy)
|
||||
assert "HOST=page-a.test:%d" % pages.port in text, "the page did not load through the proxy: %r" % text
|
||||
assert asked and doh.vias_of("stun-a.test") == {"http1"}, "the DoH was not reached through the proxy" + why
|
||||
authorizations = proxy.doh_authorizations()
|
||||
assert authorizations, "no DoH CONNECT reached the proxy" + why
|
||||
assert set(authorizations) == {expected}, (
|
||||
"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, doh, proxy)
|
||||
finally:
|
||||
proxy.close()
|
||||
|
||||
|
||||
def test_nothing_leaves_the_host_between_launch_and_the_first_command(firefox_binary, doh, pages, gateway, trap,
|
||||
watcher):
|
||||
"""The watcher runs from before the launch to the first navigation, against a gateway that is slow to say hello
|
||||
(its first accepted connection is answered a second late): the session proxy is the first command on the pipe and
|
||||
every proxied channel is held until then, so nothing may leave meanwhile."""
|
||||
gw1 = gateway("gw1", first_connection_delay=1.0)
|
||||
with _launch(firefox_binary, gw1.proxy) as browser:
|
||||
context, page = _page_in(browser)
|
||||
page.goto(pages.url("page-a.test"), wait_until="load", timeout=45000)
|
||||
text = _text(page)
|
||||
context.close()
|
||||
watcher.stop()
|
||||
|
||||
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, doh, gw1)
|
||||
|
||||
|
||||
def test_no_helper_process_starts(firefox_binary, doh, pages, gateway, trap, watcher):
|
||||
"""No crash reporter client, default browser agent, maintenance service, updater or pingsender is started,
|
||||
through the first five seconds of the session and its teardown (pingsender is the one that starts at exit)."""
|
||||
gw1 = gateway("gw1")
|
||||
with _launch(firefox_binary, gw1.proxy) as browser:
|
||||
context, page = _page_in(browser)
|
||||
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
|
||||
time.sleep(5)
|
||||
context.close()
|
||||
time.sleep(1) # the processes of the exit
|
||||
watcher.stop()
|
||||
|
||||
assert watcher.watched_pids, "the watcher never saw a browser process: %s" % watcher.process_names
|
||||
started = watcher.helpers_seen(HELPERS)
|
||||
assert started == [], "helper processes were started: %s (all processes seen: %s)" % (
|
||||
started, watcher.process_names)
|
||||
|
||||
|
||||
def test_a_dead_proxy_does_not_fall_back(firefox_binary, doh, pages, gateway, trap, watcher):
|
||||
"""When the proxy dies, a navigation fails: it does not go direct and does not reach the resolver of the machine.
|
||||
|
||||
`page-c.test` is not cached anywhere and the FakeDoh would answer it if it were reached.
|
||||
"""
|
||||
gw1 = gateway("gw1")
|
||||
with _launch(firefox_binary, gw1.proxy) as browser:
|
||||
context, page = _page_in(browser)
|
||||
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
|
||||
gw1.kill()
|
||||
with pytest.raises(Exception) as failed:
|
||||
page.goto(pages.url("page-c.test"), wait_until="load", timeout=20000)
|
||||
context.close()
|
||||
watcher.stop()
|
||||
|
||||
why = _why(doh, gw1)
|
||||
assert pages.hits and all(host.startswith("page-a.test") for host, _p in pages.hits), (
|
||||
"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, 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). 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)
|
||||
if why:
|
||||
pytest.fail(why)
|
||||
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
|
||||
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:
|
||||
trap = ResolverTrap({"page-d.test": "127.0.0.1"})
|
||||
trap.__enter__() # port 53 taken by another worker is a failure of the setup, not a reason to skip
|
||||
try:
|
||||
with session as browser:
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
page.goto(pages.url(name), wait_until="load", timeout=30000)
|
||||
text = _text(page)
|
||||
context.close()
|
||||
finally:
|
||||
if trap is not None:
|
||||
trap.__exit__(None, None, None)
|
||||
watcher.stop()
|
||||
|
||||
assert "HOST=%s:%d" % (name, pages.port) in text, "the page did not load through the system resolver: %r" % text
|
||||
if trap is not None:
|
||||
assert trap.asked(name), "the system resolver was never asked for %s: %s" % (name, trap.describe())
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Every route command (continue, abort, fulfill, redirect) leaves through `RouteDispatcher._send`, and `_send` swallows the one
|
||||
error that is not an error: the request the browser has already closed.
|
||||
|
||||
Stock Playwright's server sends the three interception commands as may-fail. Here a new command that talked to the page
|
||||
directly (`self.request.page.send("Network....")`) would bring the old defect back: the client keeps an error for the whole
|
||||
connection and raises it on the next route command, which is then never sent (see
|
||||
`test_networkidle_through_a_served_browser_with_routes_e2e.py`). No browser: the source is read.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import pathlib
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
SERVER = pathlib.Path(__file__).resolve().parents[1] / "src" / "invisible_playwright" / "_juggler" / "server.py"
|
||||
|
||||
|
||||
def _route_dispatcher():
|
||||
tree = ast.parse(SERVER.read_text(encoding="utf-8"))
|
||||
return next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "RouteDispatcher")
|
||||
|
||||
|
||||
def _methods(cls):
|
||||
return {n.name: n for n in cls.body if isinstance(n, ast.FunctionDef)}
|
||||
|
||||
|
||||
def _sends_network_command(fn):
|
||||
"""The `page.send` / `conn.send` / `_send` calls of a function that name a Network.* command string."""
|
||||
out = []
|
||||
for node in ast.walk(fn):
|
||||
if isinstance(node, ast.Call):
|
||||
for arg in node.args[:1]:
|
||||
if isinstance(arg, ast.Constant) and isinstance(arg.value, str) and arg.value.startswith("Network."):
|
||||
out.append((getattr(node.func, "attr", getattr(node.func, "id", "?")), arg.value))
|
||||
return out
|
||||
|
||||
|
||||
def test_every_op_of_a_route_goes_through__send_and_nothing_else_talks_to_the_page():
|
||||
methods = _methods(_route_dispatcher())
|
||||
ops = {name: fn for name, fn in methods.items() if name.startswith("op_")}
|
||||
assert set(ops) >= {"op_abort", "op_continue", "op_fulfill", "op_redirect"}, sorted(ops)
|
||||
for name, fn in ops.items():
|
||||
sends = _sends_network_command(fn)
|
||||
assert sends, "%s sends no Network command at all: update this guard if it is a new kind" % name
|
||||
for via, command in sends:
|
||||
assert via == "_send", "%s sends %s through %s, not through RouteDispatcher._send" % (name, command, via)
|
||||
# and the only direct talk to the page in the class is _send's
|
||||
for name, fn in methods.items():
|
||||
if name in ops or name == "_send":
|
||||
continue
|
||||
assert not _sends_network_command(fn), "%s sends a Network command by itself" % name
|
||||
|
||||
|
||||
def test__send_swallows_a_request_the_browser_already_closed_and_nothing_else():
|
||||
send = _methods(_route_dispatcher())["_send"]
|
||||
handlers = [n for n in ast.walk(send) if isinstance(n, ast.ExceptHandler)]
|
||||
caught = {ast.unparse(h.type) for h in handlers if h.type is not None}
|
||||
assert caught == {"juggler.ProtocolError", "juggler.TargetClosedError"}, caught
|
||||
source = ast.get_source_segment(SERVER.read_text(encoding="utf-8"), send)
|
||||
assert '"Cannot find request" not in str(exc)' in source and "raise" in source, \
|
||||
"a ProtocolError other than 'Cannot find request' must still reach the client"
|
||||
assert source.index("self.dispose()") > source.index("except juggler.TargetClosedError"), \
|
||||
"the route is disposed after a swallowed error too"
|
||||
|
||||
|
||||
def test_the_stock_client_the_networkidle_e2e_drives_the_server_with_is_a_pinned_dev_dependency():
|
||||
"""That e2e fails (not skips) without the stock Playwright client, so CI must install it: the `dev` extra pins it to the
|
||||
version of scripts/playwright_pin.txt."""
|
||||
import tomllib
|
||||
|
||||
root = SERVER.parents[3]
|
||||
dev = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))["project"]["optional-dependencies"]["dev"]
|
||||
pin = (root / "scripts" / "playwright_pin.txt").read_text(encoding="utf-8").strip()
|
||||
assert "playwright==%s" % pin in dev, dev
|
||||
@@ -0,0 +1,90 @@
|
||||
"""HTTP/3 behind a SOCKS5 proxy: the page reads `nextHopProtocol`, and a retail Firefox with no proxy uses h3.
|
||||
|
||||
⛔ THE KNOWN-BAD INPUT: the engine refuses HTTP/3 whenever a proxy is in use (AltSvcCache::UpdateAltServiceMapping, the
|
||||
attempt of DnsAndConnectSocket, HttpBaseChannel), so a page behind a SOCKS5 gateway that relays UDP read `h2` where the
|
||||
same Firefox with no proxy reads `h3`. With a gateway that relays UDP the QUIC connection goes through the ASSOCIATE of the
|
||||
proxy (the server sees the relay, never this host); with one that does not, the QUIC handshake never completes and Firefox
|
||||
falls back to h2 by itself, and nothing UDP leaves this host direct.
|
||||
|
||||
The server is local, reached by its address (an address of this host that is not loopback: a loopback destination goes
|
||||
direct whatever the proxy), with a self-signed certificate (the context ignores certificate errors).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import socket
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
|
||||
|
||||
|
||||
def _binary():
|
||||
cand = os.environ.get("STEALTHFOX_E2E_BINARY") or os.environ.get("INVPW_BINARY_PATH")
|
||||
if not cand or not os.path.exists(cand):
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
return cand
|
||||
|
||||
|
||||
def _address_of_this_host() -> str:
|
||||
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
probe.connect(("192.0.2.1", 9))
|
||||
return probe.getsockname()[0]
|
||||
finally:
|
||||
probe.close()
|
||||
|
||||
|
||||
_FETCH = """async (url) => {
|
||||
const seen = [];
|
||||
for (let i = 0; i < 12; i++) {
|
||||
const r = await fetch(url + '?n=' + i, {cache: 'no-store', mode: 'no-cors'});
|
||||
await r.arrayBuffer();
|
||||
const entry = performance.getEntriesByType('resource').filter(e => e.name.includes('?n=' + i)).pop();
|
||||
seen.push(entry ? entry.nextHopProtocol : '?');
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
}
|
||||
return seen;
|
||||
}"""
|
||||
|
||||
|
||||
def _protocols_behind(gateway, server, monkeypatch):
|
||||
from invisible_core import _geo
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", lambda *_a, **_k: gateway.tcp_exit)
|
||||
with InvisiblePlaywright(headless=True, binary_path=_binary(), timezone="America/New_York",
|
||||
proxy=gateway.proxy) as browser:
|
||||
context = browser.new_context(ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
page.goto(server.url, wait_until="load", timeout=60000) # the answer that carries Alt-Svc: h3
|
||||
page.wait_for_timeout(1500)
|
||||
return page.evaluate(_FETCH, server.url)
|
||||
|
||||
|
||||
def test_a_page_behind_a_gateway_that_relays_udp_reads_h3_and_the_quic_goes_by_the_relay(monkeypatch):
|
||||
import aioquic # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
from _h3_server import H3Server
|
||||
from _socks_servers import coherent
|
||||
|
||||
host = _address_of_this_host()
|
||||
with H3Server(host) as server, coherent(user="alice", password="s3cret", relay_host=host) as gateway:
|
||||
protocols = _protocols_behind(gateway, server, monkeypatch)
|
||||
carried = [(h, p) for h, p, _data in gateway.datagrams if (h, p) == (host, server.port)]
|
||||
assert "h3" in protocols, f"nextHopProtocol of 12 fetches behind a gateway that relays UDP: {protocols}"
|
||||
assert carried, "the QUIC datagrams did not go by the relay of the gateway"
|
||||
assert server.quic_peers and set(server.quic_peers) == {"127.0.0.1"}, (
|
||||
f"the QUIC server saw {server.quic_peers}: only the relay of the gateway (127.0.0.1) may reach it")
|
||||
|
||||
|
||||
def test_a_page_behind_a_gateway_without_udp_falls_back_to_h2_and_nothing_goes_direct(monkeypatch):
|
||||
import aioquic # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
from _h3_server import H3Server
|
||||
from _socks_servers import tcp_only
|
||||
|
||||
host = _address_of_this_host()
|
||||
with H3Server(host) as server, tcp_only(user="alice", password="s3cret") as gateway:
|
||||
protocols = _protocols_behind(gateway, server, monkeypatch)
|
||||
assert "?" not in protocols and "h3" not in protocols, (
|
||||
f"behind a gateway that carries no UDP every fetch is h2 (or http/1.1), never h3: {protocols}")
|
||||
assert not server.quic_peers, f"a QUIC connection reached the server direct, around the proxy: {server.quic_peers}"
|
||||
@@ -56,7 +56,6 @@ _REQUIRED_PREFS_KEYS = (
|
||||
"intl.accept_languages",
|
||||
"intl.locale.requested",
|
||||
"zoom.stealth.fpp.hw_seed",
|
||||
"zoom.stealth.webrtc.host_ip",
|
||||
"zoom.stealth.webgl.renderer",
|
||||
"zoom.stealth.webgl.vendor",
|
||||
"webgl.msaa-samples",
|
||||
@@ -120,7 +119,9 @@ def test_socks5_proxy_mutates_prefs_then_pipeline_still_valid():
|
||||
"network.proxy.socks_username", "network.proxy.socks_password",
|
||||
"network.proxy.http", "network.proxy.ssl"):
|
||||
assert name not in prefs, name
|
||||
assert prefs["zoom.stealth.dns.no_local_resolution"] is True
|
||||
# Names are resolved by Firefox's own DoH, through the session proxy: no gate of ours; the core declares the provider only.
|
||||
assert "zoom.stealth.dns.no_local_resolution" not in prefs
|
||||
assert "network.trr.mode" not in prefs and "network.trr.uri" in prefs # the provider is the core's, the state the engine's
|
||||
|
||||
# Profile-derived keys must still be present after proxy mutation.
|
||||
#
|
||||
@@ -359,7 +360,9 @@ def test_linux_xvfb_workarounds_with_socks_proxy(monkeypatch):
|
||||
# The proxy layer no longer writes any endpoint, and what it does write - the
|
||||
# leak-channel prefs - does not trample the Linux prefs above.
|
||||
assert "network.proxy.type" not in prefs
|
||||
assert prefs["zoom.stealth.dns.no_local_resolution"] is True
|
||||
# Names are resolved by Firefox's own DoH, through the session proxy: no gate of ours; the core declares the provider only.
|
||||
assert "zoom.stealth.dns.no_local_resolution" not in prefs
|
||||
assert "network.trr.mode" not in prefs and "network.trr.uri" in prefs # the provider is the core's, the state the engine's
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -1085,6 +1085,10 @@ def test_the_launch_handler_hands_the_named_environment_to_the_engine(monkeypatc
|
||||
assert env.pop("TEMP") == tmp and env.pop("TMPDIR") == tmp
|
||||
from invisible_playwright import _session
|
||||
_, session_env = _session.default_session("x")
|
||||
# The network is drawn from the seed of each session, and each unmarked
|
||||
# launch is a new session: it is there.
|
||||
assert env.pop("STEALTHFOX_WEBRTC_NETWORK").startswith("v4=")
|
||||
session_env.pop("STEALTHFOX_WEBRTC_NETWORK")
|
||||
assert env == dict(session_env, DISPLAY=":123")
|
||||
assert "WAYLAND_DISPLAY" not in env
|
||||
finally:
|
||||
|
||||
@@ -180,45 +180,23 @@ def test_default_context_with_no_language_asked_is_en_us():
|
||||
assert ip._default_context_kwargs()["locale"] == "en-US"
|
||||
|
||||
|
||||
# ── InvisiblePlaywright._build_env - WebRTC egress auto-derive ─────────
|
||||
# Locks the 2026-06-10 fix: behind a proxy the launcher feeds the discovered
|
||||
# egress IP to nICEr (srflx override) + drops IPv6. Without it, a proxied
|
||||
# session's WebRTC silently fell back to leaking/blocking. Runs in tests.yml.
|
||||
# ── InvisiblePlaywright._build_env - the declared network ─────────────
|
||||
# The session declares its host network (drawn from the seed) in one variable,
|
||||
# with or without a proxy. Runs in tests.yml.
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_build_env_injects_webrtc_egress_when_discovered():
|
||||
ip = InvisiblePlaywright(seed=42)
|
||||
# ⛔ TWO FIELDS, and this test only exercised one. `_webrtc_egress_ip`
|
||||
# is the FACT (where we exit from, read by the guard against drift);
|
||||
# `_srflx_declared` is the DECISION that ends up in the env. Since
|
||||
# 2026-08-25 they do not coincide: when the exit has proven, consistent
|
||||
# UDP the decision is None and nothing gets declared.
|
||||
ip._webrtc_egress_ip = "203.0.113.9" # what __enter__ resolves behind a proxy
|
||||
ip._srflx_declared = "203.0.113.9" # and here the decision coincides with the fact
|
||||
env = ip._build_env({})
|
||||
assert env["STEALTHFOX_WEBRTC_PUBLIC_IP"] == "203.0.113.9"
|
||||
assert env["STEALTHFOX_WEBRTC_DISABLE_IPV6"] == "1"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_build_env_no_webrtc_keys_without_proxy(monkeypatch):
|
||||
monkeypatch.delenv("STEALTHFOX_WEBRTC_PUBLIC_IP", raising=False)
|
||||
ip = InvisiblePlaywright(seed=42)
|
||||
ip._webrtc_egress_ip = None # no proxy → real STUN already truthful
|
||||
env = ip._build_env({})
|
||||
assert "STEALTHFOX_WEBRTC_PUBLIC_IP" not in env
|
||||
assert "STEALTHFOX_WEBRTC_DISABLE_IPV6" not in env
|
||||
def test_build_env_carries_the_declared_network():
|
||||
from invisible_core import network_to_declare
|
||||
env = InvisiblePlaywright(seed=42)._build_env({})
|
||||
assert env["STEALTHFOX_WEBRTC_NETWORK"] == network_to_declare(42)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_build_env_caller_env_override_wins(monkeypatch):
|
||||
monkeypatch.setenv("STEALTHFOX_WEBRTC_PUBLIC_IP", "198.51.100.5")
|
||||
ip = InvisiblePlaywright(seed=42)
|
||||
ip._webrtc_egress_ip = "203.0.113.9" # auto-discovered
|
||||
env = ip._build_env({})
|
||||
assert env["STEALTHFOX_WEBRTC_PUBLIC_IP"] == "198.51.100.5" # caller wins
|
||||
assert env["STEALTHFOX_WEBRTC_DISABLE_IPV6"] == "1"
|
||||
monkeypatch.setenv("STEALTHFOX_WEBRTC_NETWORK", "v4=198.51.100.5;v6=1")
|
||||
env = InvisiblePlaywright(seed=42)._build_env({})
|
||||
assert env["STEALTHFOX_WEBRTC_NETWORK"] == "v4=198.51.100.5;v6=1" # caller wins
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -232,7 +210,7 @@ def test_build_env_drops_the_variables_the_display_names_absent():
|
||||
``None`` value and, worse, keep ``WAYLAND_DISPLAY``."""
|
||||
from invisible_playwright._session import build_env
|
||||
base = {"PATH": "/usr/bin", "WAYLAND_DISPLAY": "wayland-0", "DISPLAY": ":0"}
|
||||
env = build_env(srflx_declared=None, base_env=base,
|
||||
env = build_env(network_declared=None, base_env=base,
|
||||
display_env={"DISPLAY": ":123", "GDK_BACKEND": "x11",
|
||||
"WAYLAND_DISPLAY": None, "PULSE_SERVER": None})
|
||||
assert env["DISPLAY"] == ":123"
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
"""`goto(wait_until="networkidle")` arrives on a served browser whose context routes every request, as a stock Firefox does.
|
||||
|
||||
The shape of a production client: `launch_server()`, a stock Playwright client that connects to it over the WebSocket, a context
|
||||
route on `**/*` that aborts images, fonts and media and continues the rest, and a page that sends a beacon (`sendBeacon`,
|
||||
a POST the page does not wait for) and asks for the same font twice. Measured on real news sites through such a client: the
|
||||
navigation committed, `load` came, and `networkidle` never did (timeout at 30 s on about one fetch in seven, firefox-61 and
|
||||
firefox-62 alike), while a stock Firefox and Chromium reached it on the same addresses.
|
||||
|
||||
Red until the server, the Juggler or the core's lifecycle ends every request a routed page opens.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
|
||||
import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
|
||||
def _stock_client(module):
|
||||
"""The stock Playwright client, as production (tf-fetch) drives the served browser. It is a pinned dev dependency
|
||||
(`playwright==` in the `dev` extra), so its absence is a broken environment, not a reason to skip: a gate that skips
|
||||
in CI checks nothing."""
|
||||
import importlib
|
||||
|
||||
try:
|
||||
return importlib.import_module(module)
|
||||
except ImportError as exc: # pragma: no cover - only in a broken environment
|
||||
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc,
|
||||
pytrace=False)
|
||||
|
||||
PAGE = b"""<!doctype html><html><head><meta charset=utf-8><title>routed</title>
|
||||
<link rel=stylesheet href=/style.css>
|
||||
<link rel=preload as=font type=font/woff2 href=/font.woff2 crossorigin>
|
||||
<style>@font-face{font-family:F2;src:url(/font.woff2) format('woff2')}</style>
|
||||
<script src=/app.js></script>
|
||||
</head><body style="font-family:F,F2"><p>text in the font</p>
|
||||
<img src=/pixel.png><img src=/photo.jpg>
|
||||
<script>
|
||||
addEventListener('load', () => {
|
||||
navigator.sendBeacon('/beacon', JSON.stringify({ev: 'load'}));
|
||||
fetch('/api/data').then(r => r.text());
|
||||
});
|
||||
</script></body></html>"""
|
||||
CSS = b"@font-face{font-family:F;src:url(/font.woff2) format('woff2')} p{color:#333}"
|
||||
JS = b"window.__app = 1;"
|
||||
# The other shapes a news page has: a frame of another site (another process with Fission) with its own routed
|
||||
# resources, a worker that fetches, a script reached through a redirect.
|
||||
EXTRA = {
|
||||
"beacon": b"",
|
||||
"oop_iframe": b"<iframe src='http://localhost:%(port)d/frame'></iframe>",
|
||||
"worker": b"<script>new Worker('/worker.js')</script>",
|
||||
"redirect": b"<script src=/moved.js></script><img src=/moved.png>",
|
||||
# What a slow remote client meets: the page cancels requests while the route is still deciding.
|
||||
"cancel_fetch": b"<script>for(let i=0;i<30;i++){const c=new AbortController();fetch('/api/data?i='+i,{signal:c.signal}).catch(()=>{});setTimeout(()=>c.abort(),i%7)}</script>",
|
||||
"cancel_img": b"<script>for(let i=0;i<30;i++){const m=new Image();m.src='/pixel.png?a='+i;m.src='/pixel.png?b='+i}</script><script src=/slow.js></script>",
|
||||
"cancel_iframe": b"<script>for(let i=0;i<6;i++){const f=document.createElement('iframe');f.src='/frame?i='+i;document.body.appendChild(f);setTimeout(()=>f.remove(),5*i)}</script>",
|
||||
"cancel_navigation": b"<script>history.pushState({},'','/spa');fetch('/api/data');setTimeout(()=>{history.pushState({},'','/spa2');fetch('/api/data?x=1')},10)</script><script src=/slow.js></script>",
|
||||
# Beacons the way ad and analytics scripts send them: to another origin, and while the document is being left.
|
||||
"cross_beacon": b"<script>for(let i=0;i<6;i++)navigator.sendBeacon('http://localhost:%(port)d/beacon?i='+i,JSON.stringify({i}))</script>",
|
||||
"unload_beacon": b"<script>addEventListener('pagehide',()=>{for(let i=0;i<4;i++)navigator.sendBeacon('/beacon?leave='+i,'x')});addEventListener('visibilitychange',()=>navigator.sendBeacon('/beacon?vis','x'))</script>",
|
||||
"keepalive": b"<script>for(let i=0;i<4;i++)fetch('/api/data?k='+i,{method:'POST',keepalive:true,body:'x'}).catch(()=>{})</script>",
|
||||
"many": b"<script>for(let i=0;i<50;i++){fetch('/api/data?i='+i).catch(()=>{});(new Image).src='/pixel.png?i='+i}</script>",
|
||||
}
|
||||
# kinds whose route handler is slow (ms). The sync client runs the handlers one after the other, so the page's 100 requests
|
||||
# of `many` take 100 x (delay + one round trip); an async client (below) answers them all at once, like a Go client does.
|
||||
SLOW_MS = {"cancel_fetch": 120, "cancel_img": 120, "cancel_iframe": 120, "cancel_navigation": 120, "many": 20}
|
||||
FRAME = b"""<!doctype html><title>frame</title><link rel=stylesheet href=/style.css><img src=/ad.png>
|
||||
<script src=/app.js></script><script>addEventListener('load',()=>{navigator.sendBeacon('/beacon','f');fetch('/api/data')})</script>"""
|
||||
WORKER = b"fetch('/api/data').then(r => r.text()); setTimeout(() => fetch('/api/data'), 200);"
|
||||
|
||||
|
||||
class _Handler(BaseHTTPRequestHandler):
|
||||
hits: list = []
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def _send(self, body, ctype, status=200):
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self):
|
||||
path = self.path.split("?")[0]
|
||||
_Handler.hits.append(("GET", path))
|
||||
if path == "/":
|
||||
kind = (self.path.split("kind=")[1].split("&")[0]) if "kind=" in self.path else "beacon"
|
||||
extra = EXTRA[kind] % {b"port": self.server.server_address[1]} if b"%(" in EXTRA[kind] else EXTRA[kind]
|
||||
self._send(PAGE.replace(b"</body>", extra + b"</body>"), "text/html; charset=utf-8")
|
||||
elif path == "/frame":
|
||||
self._send(FRAME, "text/html; charset=utf-8")
|
||||
elif path == "/slow.js":
|
||||
time.sleep(0.15)
|
||||
self._send(JS, "text/javascript")
|
||||
elif path == "/worker.js":
|
||||
self._send(WORKER, "text/javascript")
|
||||
elif path in ("/moved.js", "/moved.png"):
|
||||
self.send_response(302)
|
||||
self.send_header("Location", "/app.js" if path.endswith(".js") else "/pixel.png")
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
elif path == "/style.css":
|
||||
self._send(CSS, "text/css")
|
||||
elif path == "/app.js":
|
||||
self._send(JS, "text/javascript")
|
||||
elif path == "/api/data":
|
||||
self._send(b'{"ok":1}', "application/json")
|
||||
else: # the font and the images: the route aborts them, they must not get here
|
||||
self._send(b"x", "application/octet-stream")
|
||||
|
||||
def do_POST(self):
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
self.rfile.read(n)
|
||||
_Handler.hits.append(("POST", self.path))
|
||||
self._send(b"", "text/plain", 204)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def site():
|
||||
_Handler.hits = []
|
||||
srv = LocalServer(("127.0.0.1", 0), _Handler)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
try:
|
||||
yield "http://127.0.0.1:%d/" % srv.server_address[1]
|
||||
finally:
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
BLOCKED = {"image", "font", "media"}
|
||||
ANSWER_ERRORS: list = []
|
||||
|
||||
|
||||
def _router(delay_s):
|
||||
def route(route):
|
||||
if delay_s:
|
||||
time.sleep(delay_s) # a client far away: the page can cancel the request before the answer arrives
|
||||
try:
|
||||
if route.request.resource_type in BLOCKED:
|
||||
route.abort("blockedbyclient")
|
||||
else:
|
||||
route.continue_()
|
||||
except Exception as e:
|
||||
if "Cannot find request" not in str(e) and "Target" not in str(e):
|
||||
raise
|
||||
ANSWER_ERRORS.append(str(e)[:120])
|
||||
return route
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", sorted(EXTRA))
|
||||
def test_networkidle_arrives_on_a_routed_page_through_a_served_browser(firefox_binary, site, kind):
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
sync_playwright = _stock_client("playwright.sync_api").sync_playwright # a stock client, as production uses
|
||||
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.firefox.connect(server.ws_endpoint)
|
||||
ctx = browser.new_context()
|
||||
ANSWER_ERRORS.clear()
|
||||
ctx.route("**/*", _router(SLOW_MS.get(kind, 0) / 1000.0))
|
||||
page = ctx.new_page()
|
||||
for attempt in range(3): # fresh pages, the way a client fetches one address after another
|
||||
t0 = time.monotonic()
|
||||
page.goto(site + "?kind=%s&n=%d" % (kind, attempt), wait_until="networkidle", timeout=20000)
|
||||
took = time.monotonic() - t0
|
||||
assert took < 15, "networkidle after %.1f s on attempt %d (answers to a closed request: %s)" % (
|
||||
took, attempt, ANSWER_ERRORS[:3])
|
||||
assert page.evaluate("window.__app") == 1
|
||||
assert ("POST", "/beacon") in _Handler.hits, _Handler.hits
|
||||
assert not any(path in ("/font.woff2", "/pixel.png", "/photo.jpg", "/ad.png") for _, path in _Handler.hits), _Handler.hits
|
||||
ctx.close()
|
||||
browser.close()
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["many", "cancel_fetch", "cancel_img", "cancel_iframe", "cancel_navigation"])
|
||||
def test_networkidle_arrives_when_the_client_answers_all_requests_concurrently_and_slowly(firefox_binary, site, kind):
|
||||
"""An async client (the way a Go client answers: every route handler in its own task) that takes 300 ms to decide, so the
|
||||
page cancels, replaces or removes a request while its answer is still on the way."""
|
||||
import asyncio
|
||||
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
|
||||
async_playwright = _stock_client("playwright.async_api").async_playwright
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
|
||||
errors = []
|
||||
|
||||
async def run():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.firefox.connect(server.ws_endpoint)
|
||||
ctx = await browser.new_context()
|
||||
|
||||
async def route(r):
|
||||
await asyncio.sleep(0.3)
|
||||
try:
|
||||
if r.request.resource_type in BLOCKED:
|
||||
await r.abort("blockedbyclient")
|
||||
else:
|
||||
await r.continue_()
|
||||
except Exception as e:
|
||||
errors.append(str(e)[:140])
|
||||
|
||||
await ctx.route("**/*", route)
|
||||
page = await ctx.new_page()
|
||||
for attempt in range(3):
|
||||
t0 = time.monotonic()
|
||||
await page.goto(site + "?kind=%s&n=%d" % (kind, attempt), wait_until="networkidle", timeout=25000)
|
||||
assert time.monotonic() - t0 < 20, "networkidle after %.1f s on attempt %d" % (time.monotonic() - t0, attempt)
|
||||
await ctx.close()
|
||||
await browser.close()
|
||||
|
||||
try:
|
||||
asyncio.run(run())
|
||||
finally:
|
||||
server.close()
|
||||
# an answer to a request the browser had already closed is allowed to fail, but it must not leave the page waiting
|
||||
print("answers to a closed request:", errors[:3])
|
||||
|
||||
|
||||
def test_one_page_reused_for_many_addresses_reaches_networkidle_every_time(firefox_binary, site):
|
||||
"""tf-fetch's shape: ONE page for dozens of fetches. A request whose end never reaches the client (a beacon the
|
||||
page closes with its document, a request the browser cancelled while the route was deciding) must not hold the
|
||||
addresses that follow: the lifecycle's memory of requests in flight is per document, keyed by request id."""
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
|
||||
sync_playwright = _stock_client("playwright.sync_api").sync_playwright
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.firefox.connect(server.ws_endpoint)
|
||||
ctx = browser.new_context()
|
||||
ctx.route("**/*", _router(0.05))
|
||||
page = ctx.new_page()
|
||||
kinds = ["cancel_fetch", "cancel_img", "cancel_iframe", "beacon", "cancel_navigation", "oop_iframe"] * 2
|
||||
for n, kind in enumerate(kinds):
|
||||
t0 = time.monotonic()
|
||||
page.goto(site + "?kind=%s&n=%d" % (kind, n), wait_until="networkidle", timeout=20000)
|
||||
assert time.monotonic() - t0 < 15, "address %d (%s) reached networkidle after %.1f s" % (n, kind, time.monotonic() - t0)
|
||||
ctx.close()
|
||||
browser.close()
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["cancel_fetch", "cancel_img", "cancel_iframe"])
|
||||
def test_a_plain_route_handler_is_not_poisoned_by_a_request_the_page_cancelled(firefox_binary, site, kind):
|
||||
"""The handler of a tf-fetch-like client is a plain function: continue_ or abort, no try. The page cancels requests
|
||||
while the (slow) route is deciding; the browser has already closed them, and the engine answers the late command with
|
||||
`Cannot find request`. Stock Playwright's server sends those commands as may-fail and tells the client nothing; ours
|
||||
passed the error up, the client kept it as the error of the connection and raised it on the NEXT route command, which
|
||||
was then never sent: the request stayed held in the engine, its handler failed too, and so on down the page (measured
|
||||
on a real news page: six held requests in a row, one a beacon, and networkidle never)."""
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
|
||||
sync_playwright = _stock_client("playwright.sync_api").sync_playwright
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.firefox.connect(server.ws_endpoint)
|
||||
ctx = browser.new_context()
|
||||
|
||||
def plain(route): # no try: the way a client is written
|
||||
time.sleep(0.12)
|
||||
if route.request.resource_type in BLOCKED:
|
||||
route.abort("blockedbyclient")
|
||||
else:
|
||||
route.continue_()
|
||||
|
||||
ctx.route("**/*", plain)
|
||||
page = ctx.new_page()
|
||||
for attempt in range(3):
|
||||
t0 = time.monotonic()
|
||||
page.goto(site + "?kind=%s&n=%d" % (kind, attempt), wait_until="networkidle", timeout=25000)
|
||||
assert time.monotonic() - t0 < 20, "attempt %d: networkidle after %.1f s" % (attempt, time.monotonic() - t0)
|
||||
ctx.close()
|
||||
browser.close()
|
||||
finally:
|
||||
server.close()
|
||||
@@ -38,16 +38,41 @@ def test_the_gate_is_importable_from_the_pinned_core():
|
||||
assert hasattr(release, "resolve_project_identity")
|
||||
|
||||
|
||||
def _own_distribution_name() -> str:
|
||||
"""The name this project declares in ITS pyproject, read here independently of the gate."""
|
||||
import tomllib
|
||||
|
||||
with (_REPO / "pyproject.toml").open("rb") as fh:
|
||||
return tomllib.load(fh)["project"]["name"]
|
||||
|
||||
|
||||
def test_the_gate_recognises_THIS_project_and_not_the_core():
|
||||
"""One gate, several projects: the identity comes from our pyproject.
|
||||
Reading the core's would gate the wrong package and pass every time."""
|
||||
Reading the core's would gate the wrong package and pass every time.
|
||||
|
||||
The name is compared with what OUR pyproject declares, not with the name of the folder the checkout sits in:
|
||||
a worktree (``wrapper-p6``, ``wt/foo``) is the same project, and the folder name is nothing the gate reads."""
|
||||
from invisible_core.release import resolve_project_identity
|
||||
|
||||
dist, pkg = resolve_project_identity(_REPO)
|
||||
assert dist.replace("-", "_") == _REPO.name
|
||||
assert dist == _own_distribution_name()
|
||||
assert dist.replace("-", "_") != "invisible_core", "the gate read the core's identity"
|
||||
assert (_REPO / "src" / pkg).is_dir()
|
||||
|
||||
|
||||
def test_the_identity_does_not_depend_on_the_name_of_the_folder(tmp_path):
|
||||
"""The same project under another folder name (what any worktree is) resolves to the same identity."""
|
||||
import shutil
|
||||
|
||||
from invisible_core.release import resolve_project_identity
|
||||
|
||||
moved = tmp_path / "some-worktree-with-another-name"
|
||||
moved.mkdir()
|
||||
shutil.copy(_REPO / "pyproject.toml", moved / "pyproject.toml")
|
||||
assert resolve_project_identity(moved) == resolve_project_identity(_REPO)
|
||||
assert moved.name != _own_distribution_name().replace("-", "_")
|
||||
|
||||
|
||||
@pytest.mark.skipif(not _HOOK.exists(), reason="not a source checkout")
|
||||
def test_the_pre_push_hook_gates_release_tags():
|
||||
"""Driven, not read.
|
||||
|
||||
@@ -74,9 +74,9 @@ _LEAKS = ("PYTHONPATH", "PYTHONHOME", "VIRTUAL_ENV",
|
||||
"INVISIBLE_DOWNLOAD_DEADLINE", "STEALTHFOX_GITHUB_TOKEN", "GITHUB_TOKEN",
|
||||
"INVISIBLE_SEAL_FILE", "INVISIBLE_CORE_PIN", "INVISIBLE_CORE_AUTOFIX",
|
||||
"INVISIBLE_CORE_AUTOFIX_TIMEOUT", "UV", "STEALTHFOX_GEOIP_MMDB",
|
||||
"STEALTHFOX_FONT_MANIFEST", "STEALTHFOX_WEBRTC_PUBLIC_IP",
|
||||
"STEALTHFOX_FONT_MANIFEST", "STEALTHFOX_WEBRTC_NETWORK",
|
||||
"INVPW_CURSOR_TIMER", "INVISIBLE_CORE_AUTOFIX_ATTEMPTED",
|
||||
"INVPW_SESSION_TOKEN", "INVPW_DESKTOP", "STEALTHFOX_WEBRTC_DISABLE_IPV6")
|
||||
"INVPW_SESSION_TOKEN", "INVPW_DESKTOP")
|
||||
|
||||
|
||||
def _clean_env(base=None):
|
||||
|
||||
@@ -0,0 +1,435 @@
|
||||
"""The helpers of the DoH e2e (`_doh_servers.py`) do what the e2e relies on, tested with plain Python clients.
|
||||
|
||||
The e2e tests of `test_doh_through_the_proxy_e2e.py` are written against a contract no engine in this tree has yet, so
|
||||
what can be proven now is that the TOOLS are right: the DNS codec, the DoH server over HTTP/1.1 and over h2, and the
|
||||
SOCKS5 gateway that hands a CONNECT to the DoH address to the DoH server, tagged with its own name. A helper that
|
||||
answers wrongly would turn the e2e red or green for no reason, and nobody would know which.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import socket
|
||||
import ssl
|
||||
import struct
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
import _doh_servers as ds
|
||||
from _doh_servers import (DOH_BOOTSTRAP, DOH_HOST, DOH_PATH, DohGateway, FakeDoh, QTYPE_A, QTYPE_AAAA,
|
||||
encode_query, parse_query)
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
NAMES = {"page-a.test": "127.0.0.1", "other.test": "127.0.0.2"}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ a tiny parser, independent of the server's
|
||||
def read_response(message: bytes):
|
||||
"""(id, flags, rcode, question name, [(type, ttl, rdata)]) read the way a client reads it."""
|
||||
ident, flags, qd, an, ns, ar = struct.unpack("!6H", message[:12])
|
||||
assert (qd, ns, ar) == (1, 0, 0), (qd, ns, ar)
|
||||
i, labels = 12, []
|
||||
while message[i]:
|
||||
labels.append(message[i + 1:i + 1 + message[i]].decode())
|
||||
i += 1 + message[i]
|
||||
i += 1 + 4 # the root label, QTYPE, QCLASS
|
||||
answers = []
|
||||
for _ in range(an):
|
||||
assert message[i:i + 2] == b"\xc0\x0c", "the owner name is a pointer to the question"
|
||||
rtype, rclass, ttl, rdlength = struct.unpack("!HHIH", message[i + 2:i + 12])
|
||||
assert rclass == 1
|
||||
answers.append((rtype, ttl, message[i + 12:i + 12 + rdlength]))
|
||||
i += 12 + rdlength
|
||||
assert i == len(message), "no trailing bytes"
|
||||
return ident, flags, flags & 0xF, ".".join(labels), answers
|
||||
|
||||
|
||||
def _tls(host_port, *, alpn):
|
||||
context = ssl.create_default_context()
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(alpn)
|
||||
raw = socket.create_connection(host_port, timeout=10)
|
||||
return context.wrap_socket(raw, server_hostname=DOH_HOST)
|
||||
|
||||
|
||||
def _h1_request(tls, method, target, body=b"", content_type=None, close=False):
|
||||
head = "%s %s HTTP/1.1\r\nHost: %s\r\nAccept: application/dns-message\r\n" % (method, target, DOH_HOST)
|
||||
if content_type:
|
||||
head += "Content-Type: %s\r\n" % content_type
|
||||
if method == "POST":
|
||||
head += "Content-Length: %d\r\n" % len(body)
|
||||
if close:
|
||||
head += "Connection: close\r\n"
|
||||
tls.sendall(head.encode() + b"\r\n" + body)
|
||||
data = b""
|
||||
while b"\r\n\r\n" not in data:
|
||||
chunk = tls.recv(65536)
|
||||
assert chunk, "the server closed without answering"
|
||||
data += chunk
|
||||
header, _, rest = data.partition(b"\r\n\r\n")
|
||||
lines = header.decode().split("\r\n")
|
||||
status = int(lines[0].split()[1])
|
||||
headers = {k.strip().lower(): v.strip() for k, _, v in (l.partition(":") for l in lines[1:])}
|
||||
length = int(headers["content-length"])
|
||||
while len(rest) < length:
|
||||
rest += tls.recv(65536)
|
||||
return status, headers, rest
|
||||
|
||||
|
||||
def _get_target(message):
|
||||
return "%s?dns=%s" % (DOH_PATH, base64.urlsafe_b64encode(message).rstrip(b"=").decode())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def doh():
|
||||
with FakeDoh(NAMES) as server:
|
||||
yield server
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def doh_h1_only():
|
||||
with FakeDoh(NAMES, h2=False) as server:
|
||||
yield server
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------------------------------- the codec
|
||||
def test_a_query_is_parsed_from_its_labels():
|
||||
q = parse_query(encode_query("Page-A.test.", QTYPE_AAAA, ident=7))
|
||||
assert (q.ident, q.name, q.qtype, q.qclass) == (7, "page-a.test", QTYPE_AAAA, 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("junk", [b"", b"\x00" * 5, b"\x00" * 12, encode_query("a.test")[:-2],
|
||||
encode_query("a.test")[:12] + b"\xc0\x0c" + b"\x00\x01\x00\x01"])
|
||||
def test_a_message_that_is_not_a_query_is_refused(junk):
|
||||
with pytest.raises(ValueError):
|
||||
parse_query(junk)
|
||||
|
||||
|
||||
def test_the_response_codec_round_trips_through_the_independent_parser():
|
||||
q = parse_query(encode_query("page-a.test", QTYPE_A, ident=9))
|
||||
ident, flags, rcode, name, answers = read_response(ds.answer_for(NAMES, q))
|
||||
assert (ident, rcode, name) == (9, 0, "page-a.test")
|
||||
assert flags & 0x8000 and flags & 0x0100, "QR set, RD copied"
|
||||
assert answers == [(QTYPE_A, ds.DOH_TTL, socket.inet_aton("127.0.0.1"))]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------- HTTP/1.1, POST and GET
|
||||
@pytest.mark.parametrize("how", ["POST", "GET"])
|
||||
def test_an_a_query_for_a_known_name_is_answered_over_http1(doh_h1_only, how):
|
||||
tls = _tls(("127.0.0.1", doh_h1_only.port), alpn=["http/1.1"])
|
||||
try:
|
||||
message = encode_query("page-a.test", QTYPE_A, ident=0)
|
||||
if how == "POST":
|
||||
status, headers, body = _h1_request(tls, "POST", DOH_PATH, message, "application/dns-message")
|
||||
else:
|
||||
status, headers, body = _h1_request(tls, "GET", _get_target(message))
|
||||
assert status == 200 and headers["content-type"] == "application/dns-message"
|
||||
_ident, _flags, rcode, name, answers = read_response(body)
|
||||
assert (rcode, name) == (0, "page-a.test")
|
||||
assert answers == [(QTYPE_A, 30, bytes([127, 0, 0, 1]))]
|
||||
finally:
|
||||
tls.close()
|
||||
assert [(q.name, q.qtype, q.via) for q in doh_h1_only.queries] == [("page-a.test", QTYPE_A, "direct")]
|
||||
assert doh_h1_only.alpn_of("direct") == {"http/1.1"}
|
||||
|
||||
|
||||
def test_an_unknown_name_is_nxdomain_over_http1(doh_h1_only):
|
||||
tls = _tls(("127.0.0.1", doh_h1_only.port), alpn=["http/1.1"])
|
||||
try:
|
||||
status, _h, body = _h1_request(tls, "POST", DOH_PATH, encode_query("nobody.test"), "application/dns-message")
|
||||
finally:
|
||||
tls.close()
|
||||
assert status == 200, "a name that does not exist is a DNS answer, not an HTTP error"
|
||||
_i, _f, rcode, name, answers = read_response(body)
|
||||
assert (rcode, name, answers) == (3, "nobody.test", [])
|
||||
assert doh_h1_only.queries_for("nobody.test"), "the miss is recorded too"
|
||||
|
||||
|
||||
def test_an_aaaa_query_for_a_known_name_is_empty_noerror_over_http1(doh_h1_only):
|
||||
tls = _tls(("127.0.0.1", doh_h1_only.port), alpn=["http/1.1"])
|
||||
try:
|
||||
_s, _h, body = _h1_request(tls, "POST", DOH_PATH, encode_query("page-a.test", QTYPE_AAAA),
|
||||
"application/dns-message")
|
||||
finally:
|
||||
tls.close()
|
||||
_i, _f, rcode, _n, answers = read_response(body)
|
||||
assert (rcode, answers) == (0, [])
|
||||
|
||||
|
||||
def test_http1_keeps_the_connection_for_the_next_query(doh_h1_only):
|
||||
tls = _tls(("127.0.0.1", doh_h1_only.port), alpn=["http/1.1"])
|
||||
try:
|
||||
for name in ("page-a.test", "other.test"):
|
||||
status, _h, body = _h1_request(tls, "POST", DOH_PATH, encode_query(name), "application/dns-message")
|
||||
assert status == 200 and read_response(body)[4]
|
||||
finally:
|
||||
tls.close()
|
||||
assert len(doh_h1_only.connections) == 1 and len(doh_h1_only.queries) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("request_, status", [
|
||||
(("POST", DOH_PATH, b"junk", "application/dns-message"), 400),
|
||||
(("POST", DOH_PATH, b"", "text/plain"), 415),
|
||||
(("GET", DOH_PATH, b"", None), 400),
|
||||
(("GET", "/elsewhere", b"", None), 404),
|
||||
(("PUT", DOH_PATH, b"", None), 405),
|
||||
])
|
||||
def test_what_is_not_a_doh_query_is_an_http_error_and_not_a_query(doh_h1_only, request_, status):
|
||||
method, target, body, content_type = request_
|
||||
tls = _tls(("127.0.0.1", doh_h1_only.port), alpn=["http/1.1"])
|
||||
try:
|
||||
got, _h, _b = _h1_request(tls, method, target, body, content_type, close=True)
|
||||
finally:
|
||||
tls.close()
|
||||
assert got == status
|
||||
assert doh_h1_only.queries == []
|
||||
assert doh_h1_only.bad_requests[-1][3] == status
|
||||
|
||||
|
||||
def test_the_certificate_covers_the_doh_host_and_loopback(doh):
|
||||
"""A client that VERIFIES (trusting the certificate file) accepts both names the DoH may be reached by."""
|
||||
for server_name in (DOH_HOST, "127.0.0.1"):
|
||||
context = ssl.create_default_context(cafile=str(doh.certificate_path))
|
||||
raw = socket.create_connection(("127.0.0.1", doh.port), timeout=10)
|
||||
tls = context.wrap_socket(raw, server_hostname=server_name)
|
||||
tls.close()
|
||||
context = ssl.create_default_context(cafile=str(doh.certificate_path))
|
||||
raw = socket.create_connection(("127.0.0.1", doh.port), timeout=10)
|
||||
with pytest.raises(ssl.SSLCertVerificationError):
|
||||
context.wrap_socket(raw, server_hostname="some-other-host.test")
|
||||
raw.close()
|
||||
|
||||
|
||||
def test_a_client_that_refuses_the_certificate_is_listed_as_a_tls_failure(doh):
|
||||
context = ssl.create_default_context() # verifies, and does not trust the self-signed certificate
|
||||
raw = socket.create_connection(("127.0.0.1", doh.port), timeout=10)
|
||||
with pytest.raises(ssl.SSLError):
|
||||
context.wrap_socket(raw, server_hostname=DOH_HOST)
|
||||
raw.close()
|
||||
assert ds.wait_until(lambda: doh.tls_failures, 5), "the failed handshake is recorded"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------- h2
|
||||
def _h2_query(doh, method, message, raw=None):
|
||||
"""One DoH query over h2, on `raw` (a connected socket, e.g. a tunnel) or straight to the server."""
|
||||
h2_config = pytest.importorskip("h2.config")
|
||||
h2_connection = pytest.importorskip("h2.connection")
|
||||
h2_events = pytest.importorskip("h2.events")
|
||||
if raw is None:
|
||||
tls = _tls(("127.0.0.1", doh.port), alpn=["h2", "http/1.1"])
|
||||
else:
|
||||
context = ssl.create_default_context()
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(["h2", "http/1.1"])
|
||||
tls = context.wrap_socket(raw, server_hostname=DOH_HOST)
|
||||
assert tls.selected_alpn_protocol() == "h2"
|
||||
conn = h2_connection.H2Connection(config=h2_config.H2Configuration(client_side=True, header_encoding="utf-8"))
|
||||
conn.initiate_connection()
|
||||
headers = [(":method", method), (":scheme", "https"), (":authority", DOH_HOST),
|
||||
(":path", DOH_PATH if method == "POST" else _get_target(message)), ("accept", "application/dns-message")]
|
||||
if method == "POST":
|
||||
headers += [("content-type", "application/dns-message"), ("content-length", str(len(message)))]
|
||||
conn.send_headers(1, headers)
|
||||
conn.send_data(1, message, end_stream=True)
|
||||
else:
|
||||
conn.send_headers(1, headers, end_stream=True)
|
||||
tls.sendall(conn.data_to_send())
|
||||
status, body, ended = None, b"", False
|
||||
while not ended:
|
||||
data = tls.recv(65536)
|
||||
assert data, "the server closed without answering"
|
||||
for event in conn.receive_data(data):
|
||||
if isinstance(event, h2_events.ResponseReceived):
|
||||
status = dict(event.headers)[":status"]
|
||||
elif isinstance(event, h2_events.DataReceived):
|
||||
body += event.data
|
||||
conn.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
|
||||
elif isinstance(event, h2_events.StreamEnded):
|
||||
ended = True
|
||||
tls.sendall(conn.data_to_send())
|
||||
tls.close()
|
||||
return status, body
|
||||
|
||||
|
||||
@pytest.mark.parametrize("how", ["POST", "GET"])
|
||||
def test_an_a_query_is_answered_over_h2(doh, how):
|
||||
status, body = _h2_query(doh, how, encode_query("page-a.test", QTYPE_A))
|
||||
assert status == "200"
|
||||
_i, _f, rcode, name, answers = read_response(body)
|
||||
assert (rcode, name, answers) == (0, "page-a.test", [(QTYPE_A, 30, bytes([127, 0, 0, 1]))])
|
||||
assert doh.alpn_of("direct") == {"h2"}
|
||||
|
||||
|
||||
def test_a_miss_and_an_aaaa_are_answered_over_h2(doh):
|
||||
_s, body = _h2_query(doh, "POST", encode_query("nobody.test"))
|
||||
assert read_response(body)[2:] == (3, "nobody.test", [])
|
||||
_s, body = _h2_query(doh, "GET", encode_query("page-a.test", QTYPE_AAAA))
|
||||
assert (read_response(body)[2], read_response(body)[4]) == (0, [])
|
||||
assert [(q.name, q.qtype) for q in doh.queries] == [("nobody.test", 1), ("page-a.test", QTYPE_AAAA)]
|
||||
|
||||
|
||||
def test_a_server_that_does_not_offer_h2_selects_http1_for_a_client_that_asks_for_both(doh_h1_only):
|
||||
tls = _tls(("127.0.0.1", doh_h1_only.port), alpn=["h2", "http/1.1"])
|
||||
try:
|
||||
assert tls.selected_alpn_protocol() == "http/1.1"
|
||||
finally:
|
||||
tls.close()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------- the gateway (H2)
|
||||
def _socks_connect(gateway_port, host, port, *, credentials=None, by_name=False):
|
||||
"""A plain SOCKS5 client: returns (socket, reply code)."""
|
||||
s = socket.create_connection(("127.0.0.1", gateway_port), timeout=10)
|
||||
if credentials:
|
||||
s.sendall(b"\x05\x01\x02")
|
||||
assert s.recv(2) == b"\x05\x02"
|
||||
u, p = (c.encode() for c in credentials)
|
||||
s.sendall(b"\x01" + bytes([len(u)]) + u + bytes([len(p)]) + p)
|
||||
assert s.recv(2) == b"\x01\x00"
|
||||
else:
|
||||
s.sendall(b"\x05\x01\x00")
|
||||
assert s.recv(2) == b"\x05\x00"
|
||||
if by_name:
|
||||
target = b"\x03" + bytes([len(host)]) + host.encode()
|
||||
else:
|
||||
target = b"\x01" + socket.inet_aton(host)
|
||||
s.sendall(b"\x05\x01\x00" + target + struct.pack("!H", port))
|
||||
reply = b""
|
||||
while len(reply) < 10:
|
||||
chunk = s.recv(10 - len(reply))
|
||||
if not chunk:
|
||||
break
|
||||
reply += chunk
|
||||
return s, (reply[1] if len(reply) > 1 else None)
|
||||
|
||||
|
||||
def _query_through(sock, name, qtype=QTYPE_A):
|
||||
context = ssl.create_default_context()
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(["http/1.1"])
|
||||
tls = context.wrap_socket(sock, server_hostname=DOH_HOST)
|
||||
try:
|
||||
status, _h, body = _h1_request(tls, "POST", DOH_PATH, encode_query(name, qtype), "application/dns-message",
|
||||
close=True)
|
||||
finally:
|
||||
tls.close()
|
||||
return status, body
|
||||
|
||||
|
||||
@pytest.mark.parametrize("by_name", [False, True])
|
||||
def test_a_connect_to_the_doh_address_reaches_the_doh_and_is_tagged_with_the_gateway(doh, by_name):
|
||||
with DohGateway("gw1", doh) as gw:
|
||||
target = DOH_HOST if by_name else DOH_BOOTSTRAP
|
||||
s, code = _socks_connect(gw.port, target, 443, by_name=by_name)
|
||||
assert code == 0
|
||||
status, body = _query_through(s, "page-a.test")
|
||||
assert status == 200 and read_response(body)[4][0][0] == QTYPE_A
|
||||
assert gw.connects == [(target, 443)]
|
||||
assert gw.doh_connects() == [(target, 443)]
|
||||
assert [(q.name, q.qtype, q.via) for q in doh.queries] == [("page-a.test", QTYPE_A, "gw1")]
|
||||
assert doh.vias_of("page-a.test") == {"gw1"}
|
||||
|
||||
|
||||
def test_two_gateways_tag_their_own_queries(doh):
|
||||
with DohGateway("gw1", doh) as one, DohGateway("gw2", doh) as two:
|
||||
for gateway, name in ((one, "page-a.test"), (two, "other.test")):
|
||||
s, code = _socks_connect(gateway.port, DOH_BOOTSTRAP, 443)
|
||||
assert code == 0
|
||||
assert _query_through(s, name)[0] == 200
|
||||
assert doh.vias_of("page-a.test") == {"gw1"}
|
||||
assert doh.vias_of("other.test") == {"gw2"}
|
||||
|
||||
|
||||
def test_the_doh_road_works_over_h2_through_the_gateway(doh):
|
||||
import h2 # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
with DohGateway("gw1", doh) as gw:
|
||||
s, code = _socks_connect(gw.port, DOH_BOOTSTRAP, 443)
|
||||
assert code == 0
|
||||
status, body = _h2_query(doh, "POST", encode_query("page-a.test"), raw=s)
|
||||
assert status == "200" and read_response(body)[4]
|
||||
assert doh.alpn_of("gw1") == {"h2"}
|
||||
assert doh.vias_of("page-a.test") == {"gw1"}
|
||||
|
||||
|
||||
def test_a_gateway_with_credentials_records_what_it_was_offered_and_serves_only_the_right_ones(doh):
|
||||
with DohGateway("gw1", doh, user="alice", password="pw-1") as gw:
|
||||
try:
|
||||
_socks_connect(gw.port, DOH_BOOTSTRAP, 443, credentials=("alice", "bad"))
|
||||
except AssertionError:
|
||||
pass # the refusal of the auth reply is what the client helper asserts on
|
||||
s, code = _socks_connect(gw.port, DOH_BOOTSTRAP, 443, credentials=("alice", "pw-1"))
|
||||
assert code == 0
|
||||
assert _query_through(s, "page-a.test")[0] == 200
|
||||
assert gw.credentials_seen == [("alice", "bad"), ("alice", "pw-1")]
|
||||
assert doh.vias_of("page-a.test") == {"gw1"}
|
||||
|
||||
|
||||
def test_a_connect_to_a_loopback_address_is_relayed_for_real_and_recorded(doh):
|
||||
echo = socket.socket()
|
||||
echo.bind(("127.0.0.1", 0))
|
||||
echo.listen(1)
|
||||
|
||||
def serve():
|
||||
c, _ = echo.accept()
|
||||
c.sendall(c.recv(100).upper())
|
||||
c.close()
|
||||
|
||||
threading.Thread(target=serve, daemon=True).start()
|
||||
with DohGateway("gw1", doh) as gw:
|
||||
s, code = _socks_connect(gw.port, "127.0.0.1", echo.getsockname()[1])
|
||||
assert code == 0
|
||||
s.sendall(b"ping")
|
||||
assert s.recv(10) == b"PING"
|
||||
s.close()
|
||||
assert gw.connects == [("127.0.0.1", echo.getsockname()[1])]
|
||||
echo.close()
|
||||
assert doh.queries == []
|
||||
|
||||
|
||||
def test_a_connect_that_would_leave_the_loopback_is_refused_and_never_resolved(doh):
|
||||
with DohGateway("gw1", doh) as gw:
|
||||
s, code = _socks_connect(gw.port, "198.51.100.77", 80)
|
||||
assert code == 2
|
||||
s.close()
|
||||
s, code = _socks_connect(gw.port, "page-a.test", 80, by_name=True)
|
||||
assert code == 4, "a name is refused, not looked up"
|
||||
s.close()
|
||||
assert gw.refused == [("198.51.100.77", 80), ("page-a.test", 80)]
|
||||
assert ("page-a.test", 80) in gw.connects, "a CONNECT by name is visible to a test that forbids it"
|
||||
|
||||
|
||||
def test_the_first_connection_can_be_answered_late(doh):
|
||||
import time
|
||||
with DohGateway("gw1", doh, first_connection_delay=0.6) as gw:
|
||||
started = time.monotonic()
|
||||
s, code = _socks_connect(gw.port, DOH_BOOTSTRAP, 443)
|
||||
assert code == 0 and time.monotonic() - started >= 0.55
|
||||
s.close()
|
||||
started = time.monotonic()
|
||||
s, code = _socks_connect(gw.port, DOH_BOOTSTRAP, 443)
|
||||
assert code == 0 and time.monotonic() - started < 0.5, "only the first one is late"
|
||||
s.close()
|
||||
|
||||
|
||||
def test_a_killed_gateway_refuses_and_drops_its_open_tunnels(doh):
|
||||
gw = DohGateway("gw1", doh)
|
||||
port = gw.port
|
||||
s, code = _socks_connect(port, DOH_BOOTSTRAP, 443)
|
||||
assert code == 0
|
||||
context = ssl.create_default_context()
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(["http/1.1"])
|
||||
tls = context.wrap_socket(s, server_hostname=DOH_HOST)
|
||||
assert _h1_request(tls, "POST", DOH_PATH, encode_query("page-a.test"), "application/dns-message")[0] == 200
|
||||
gw.kill()
|
||||
with pytest.raises((OSError, AssertionError)):
|
||||
_h1_request(tls, "POST", DOH_PATH, encode_query("other.test"), "application/dns-message")
|
||||
tls.close()
|
||||
with pytest.raises(OSError):
|
||||
socket.create_connection(("127.0.0.1", port), timeout=2)
|
||||
assert gw.killed and doh.vias_of("other.test") == set()
|
||||
@@ -0,0 +1,179 @@
|
||||
"""The HTTP proxy of the DoH e2e (`_http_proxy.py`) refuses without credentials, serves with them, and records headers.
|
||||
|
||||
Tested with raw sockets and `http.client`: the e2e asserts on what this proxy recorded (the preemptive
|
||||
`Proxy-Authorization` of the DoH CONNECT), so what it records has to be what the wire carried.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import http.client
|
||||
import socket
|
||||
import ssl
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from _doh_servers import DOH_BOOTSTRAP, DOH_HOST, DOH_PATH, FakeDoh, QTYPE_A, encode_query, wait_until
|
||||
from _http_proxy import HttpProxy, basic
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
USER, PASSWORD = "ferd:user", "pässword" # a colon in the name and a non-ASCII password: UTF-8, as RFC 7617 says
|
||||
NAMES = {"page-a.test": "127.0.0.1"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def doh():
|
||||
with FakeDoh(NAMES) as server:
|
||||
yield server
|
||||
|
||||
|
||||
def _connect_raw(proxy, target, authorization=None):
|
||||
"""CONNECT on a raw socket: (socket, status line, headers)."""
|
||||
s = socket.create_connection(("127.0.0.1", proxy.port), timeout=10)
|
||||
head = "CONNECT %s HTTP/1.1\r\nHost: %s\r\n" % (target, target)
|
||||
if authorization:
|
||||
head += "Proxy-Authorization: %s\r\n" % authorization
|
||||
s.sendall((head + "\r\n").encode())
|
||||
data = b""
|
||||
while b"\r\n\r\n" not in data:
|
||||
chunk = s.recv(4096)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
lines = data.split(b"\r\n\r\n")[0].decode().split("\r\n")
|
||||
headers = {k.strip().lower(): v.strip() for k, _, v in (l.partition(":") for l in lines[1:])}
|
||||
return s, lines[0], headers
|
||||
|
||||
|
||||
def test_basic_is_base64_of_utf8_user_colon_password():
|
||||
assert basic(USER, PASSWORD) == "Basic " + base64.b64encode("ferd:user:pässword".encode("utf-8")).decode()
|
||||
|
||||
|
||||
def test_a_connect_without_credentials_gets_407_with_a_basic_challenge(doh):
|
||||
with HttpProxy("http1", doh, user=USER, password=PASSWORD) as proxy:
|
||||
s, status, headers = _connect_raw(proxy, "%s:443" % DOH_BOOTSTRAP)
|
||||
s.close()
|
||||
assert status.split()[1] == "407"
|
||||
assert headers["proxy-authenticate"].lower().startswith("basic")
|
||||
assert proxy.connects == []
|
||||
assert [(r.method, r.authorization, r.status) for r in proxy.refused_for_credentials] == [("CONNECT", None, 407)]
|
||||
|
||||
|
||||
def test_a_connect_with_the_wrong_credentials_gets_407_and_the_header_is_recorded(doh):
|
||||
with HttpProxy("http1", doh, user=USER, password=PASSWORD) as proxy:
|
||||
wrong = basic(USER, "not-it")
|
||||
s, status, _h = _connect_raw(proxy, "%s:443" % DOH_BOOTSTRAP, wrong)
|
||||
s.close()
|
||||
assert status.split()[1] == "407"
|
||||
assert proxy.authorizations_for(DOH_BOOTSTRAP, 443) == [wrong]
|
||||
|
||||
|
||||
def test_a_connect_with_the_right_credentials_is_accepted_and_the_header_is_recorded(doh):
|
||||
with HttpProxy("http1", doh, user=USER, password=PASSWORD) as proxy:
|
||||
s, status, _h = _connect_raw(proxy, "%s:443" % DOH_BOOTSTRAP, basic(USER, PASSWORD))
|
||||
assert status.split()[1] == "200"
|
||||
context = ssl.create_default_context()
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(["http/1.1"])
|
||||
tls = context.wrap_socket(s, server_hostname=DOH_HOST)
|
||||
message = encode_query("page-a.test", QTYPE_A)
|
||||
tls.sendall(("POST %s HTTP/1.1\r\nHost: %s\r\nContent-Type: application/dns-message\r\n"
|
||||
"Content-Length: %d\r\nConnection: close\r\n\r\n" % (DOH_PATH, DOH_HOST, len(message))).encode()
|
||||
+ message)
|
||||
reply = b""
|
||||
while True:
|
||||
chunk = tls.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
reply += chunk
|
||||
tls.close()
|
||||
assert reply.startswith(b"HTTP/1.1 200")
|
||||
assert proxy.doh_authorizations() == [basic(USER, PASSWORD)]
|
||||
assert proxy.doh_connects() == [(DOH_BOOTSTRAP, 443)]
|
||||
assert doh.vias_of("page-a.test") == {"http1"}
|
||||
|
||||
|
||||
def test_a_proxy_without_credentials_asks_for_none(doh):
|
||||
with HttpProxy("http1", doh) as proxy:
|
||||
s, status, _h = _connect_raw(proxy, "%s:443" % DOH_HOST)
|
||||
s.close()
|
||||
assert status.split()[1] == "200"
|
||||
assert proxy.doh_authorizations() == [None]
|
||||
assert proxy.proxy == {"server": proxy.server}
|
||||
|
||||
|
||||
def test_the_endpoint_dict_carries_the_credentials(doh):
|
||||
with HttpProxy("http1", doh, user=USER, password=PASSWORD) as proxy:
|
||||
assert proxy.proxy == {"server": "http://127.0.0.1:%d" % proxy.port, "username": USER, "password": PASSWORD}
|
||||
|
||||
|
||||
def test_a_connect_to_loopback_is_relayed_and_one_that_would_leave_it_is_refused(doh):
|
||||
listener = socket.socket()
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen(1)
|
||||
|
||||
def serve():
|
||||
c, _ = listener.accept()
|
||||
c.sendall(b"hello")
|
||||
c.close()
|
||||
|
||||
threading.Thread(target=serve, daemon=True).start()
|
||||
with HttpProxy("http1", doh) as proxy:
|
||||
s, status, _h = _connect_raw(proxy, "127.0.0.1:%d" % listener.getsockname()[1])
|
||||
assert status.split()[1] == "200"
|
||||
assert s.recv(10) == b"hello"
|
||||
s.close()
|
||||
s, status, _h = _connect_raw(proxy, "198.51.100.77:443")
|
||||
s.close()
|
||||
assert status.split()[1] == "403"
|
||||
s, status, _h = _connect_raw(proxy, "page-a.test:443")
|
||||
s.close()
|
||||
assert status.split()[1] == "403", "a name is refused, not resolved"
|
||||
assert wait_until(lambda: len(proxy.seen) == 3, 5)
|
||||
listener.close()
|
||||
|
||||
|
||||
def test_a_plain_get_in_the_absolute_form_is_forwarded_by_the_zone_of_the_doh(doh):
|
||||
"""The form a browser sends to an HTTP proxy for an http page: the name travels to the proxy, which resolves it."""
|
||||
import http.server
|
||||
|
||||
class Page(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self): # noqa: N802
|
||||
body = ("host=%s path=%s via=%s" % (self.headers["Host"], self.path,
|
||||
self.headers.get("Proxy-Authorization"))).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
server = http.server.HTTPServer(("127.0.0.1", 0), Page)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
port = server.server_address[1]
|
||||
try:
|
||||
with HttpProxy("http1", doh, user=USER, password=PASSWORD) as proxy:
|
||||
conn = http.client.HTTPConnection("127.0.0.1", proxy.port, timeout=10)
|
||||
conn.request("GET", "http://page-a.test:%d/x?y=1" % port, headers={"Host": "page-a.test:%d" % port})
|
||||
assert conn.getresponse().status == 407
|
||||
conn.close()
|
||||
conn = http.client.HTTPConnection("127.0.0.1", proxy.port, timeout=10)
|
||||
conn.request("GET", "http://page-a.test:%d/x?y=1" % port,
|
||||
headers={"Host": "page-a.test:%d" % port, "Proxy-Authorization": basic(USER, PASSWORD)})
|
||||
response = conn.getresponse()
|
||||
body = response.read().decode()
|
||||
conn.close()
|
||||
assert response.status == 200
|
||||
assert body == "host=page-a.test:%d path=/x?y=1 via=None" % port, "the proxy's header is not passed on"
|
||||
conn = http.client.HTTPConnection("127.0.0.1", proxy.port, timeout=10)
|
||||
conn.request("GET", "http://not-in-the-zone.test:%d/" % port,
|
||||
headers={"Proxy-Authorization": basic(USER, PASSWORD)})
|
||||
assert conn.getresponse().status == 502
|
||||
conn.close()
|
||||
assert [s.status for s in proxy.seen] == [407, 200, 502]
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
@@ -0,0 +1,174 @@
|
||||
"""The traps of the DoH e2e (`_leaks.py`): the connection watcher and the resolver trap, tested on what they promise.
|
||||
|
||||
A trap that cannot see is worse than none: the e2e asserts "nothing left the host", and an empty Watcher reads the
|
||||
same whether nothing left or the Watcher was blind. So the Watcher is shown a connection that does leave (a connect in
|
||||
flight to a blackholed documentation address, from a child process) and shown that it ignores loopback. The resolver
|
||||
trap is shown on a free port without touching any file; the rewrite of /etc/resolv.conf is tested only where it can
|
||||
run (Linux, root).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import errno
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
import _doh_servers as ds
|
||||
from _leaks import ResolverTrap, Watcher
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
#: RFC 5737 TEST-NET-3: never routed, so a SYN to it stays in flight (or is refused at once on a host with no route).
|
||||
BLACKHOLE = ("203.0.113.1", 9)
|
||||
|
||||
_IN_FLIGHT = {errno.EINPROGRESS, errno.EWOULDBLOCK, getattr(errno, "WSAEWOULDBLOCK", errno.EWOULDBLOCK), 10035}
|
||||
|
||||
CHILD_SYN = """
|
||||
import errno, socket, sys, time
|
||||
s = socket.socket()
|
||||
s.setblocking(False)
|
||||
code = s.connect_ex(("%s", %d))
|
||||
print("in-flight" if code in (%s) else "failed:%%d" %% code, flush=True)
|
||||
time.sleep(float(sys.argv[1]))
|
||||
""" % (BLACKHOLE[0], BLACKHOLE[1], ", ".join(str(c) for c in sorted(_IN_FLIGHT)))
|
||||
|
||||
|
||||
def _child(code, *args):
|
||||
return subprocess.Popen([sys.executable, "-c", code, *map(str, args)], stdout=subprocess.PIPE, text=True)
|
||||
|
||||
|
||||
def test_the_watcher_flags_a_connection_in_flight_to_a_non_loopback_address():
|
||||
with Watcher(match="python") as watcher:
|
||||
child = _child(CHILD_SYN, 4)
|
||||
try:
|
||||
state = child.stdout.readline().strip()
|
||||
if state != "in-flight":
|
||||
pytest.skip("this host refuses a connect to %s:%d at once (%s): a SYN_SENT cannot be observed here"
|
||||
% (BLACKHOLE + (state,)))
|
||||
seen = ds.wait_until(lambda: any(c.remote == "%s:%d" % BLACKHOLE for c in watcher.direct), 3)
|
||||
finally:
|
||||
child.kill()
|
||||
child.wait()
|
||||
if not seen and sys.platform != "win32" and not watcher.watched_pids:
|
||||
pytest.skip("the child process was never listed as a descendant")
|
||||
assert seen, "a connect in flight to %s:%d was not reported; the watcher saw: %s (processes: %s)" % (
|
||||
BLACKHOLE + (watcher.describe(), watcher.process_names))
|
||||
first = [c for c in watcher.direct if c.remote == "%s:%d" % BLACKHOLE][0]
|
||||
assert first.protocol == "tcp" and first.pid in watcher.watched_pids
|
||||
|
||||
|
||||
def test_the_watcher_ignores_loopback_connections_tcp_and_udp():
|
||||
listener = socket.socket()
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen(4)
|
||||
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
udp.bind(("127.0.0.1", 0))
|
||||
code = """
|
||||
import socket, sys, time
|
||||
s = socket.create_connection(("127.0.0.1", %d))
|
||||
u = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
u.connect(("127.0.0.1", %d))
|
||||
print("up", flush=True)
|
||||
time.sleep(1.5)
|
||||
""" % (listener.getsockname()[1], udp.getsockname()[1])
|
||||
with Watcher(match="python") as watcher:
|
||||
child = _child(code)
|
||||
try:
|
||||
assert child.stdout.readline().strip() == "up"
|
||||
time.sleep(0.8)
|
||||
finally:
|
||||
child.kill()
|
||||
child.wait()
|
||||
listener.close()
|
||||
udp.close()
|
||||
assert watcher.direct == [], watcher.describe()
|
||||
assert watcher.samples > 5
|
||||
|
||||
|
||||
def test_the_watcher_lists_the_names_of_the_descendants():
|
||||
with Watcher(match="no-such-process-name") as watcher:
|
||||
child = _child("import time; print('x', flush=True); time.sleep(2)")
|
||||
try:
|
||||
child.stdout.readline()
|
||||
assert ds.wait_until(lambda: watcher.process_names, 3)
|
||||
finally:
|
||||
child.kill()
|
||||
child.wait()
|
||||
assert any("python" in n.lower() for n in watcher.process_names), watcher.process_names
|
||||
assert watcher.direct == [] and not watcher.watched_pids, "an unmatched name is listed but not judged"
|
||||
|
||||
|
||||
def test_helpers_are_matched_on_the_stem_case_insensitively():
|
||||
watcher = Watcher()
|
||||
watcher.process_names[:] = ["firefox.exe", "CrashReporter.exe", "default-browser-agent.exe", "updater",
|
||||
"python3", "Updater.EXE", "pingsender"]
|
||||
assert watcher.helpers_seen(["crashreporter", "default-browser-agent", "maintenanceservice", "updater",
|
||||
"pingsender"]) == ["CrashReporter.exe", "default-browser-agent.exe", "updater",
|
||||
"Updater.EXE", "pingsender"]
|
||||
assert watcher.helpers_seen(["exe"]) == [], "the extension is not part of the stem"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- the resolver trap
|
||||
def _udp_ask(port, name, qtype=ds.QTYPE_A):
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s.settimeout(5)
|
||||
s.sendto(ds.encode_query(name, qtype, ident=77), ("127.0.0.1", port))
|
||||
data, _ = s.recvfrom(4096)
|
||||
s.close()
|
||||
return data
|
||||
|
||||
|
||||
def _tcp_ask(port, name):
|
||||
import struct
|
||||
s = socket.create_connection(("127.0.0.1", port), timeout=5)
|
||||
message = ds.encode_query(name, ds.QTYPE_A, ident=78)
|
||||
s.sendall(struct.pack("!H", len(message)) + message)
|
||||
size = struct.unpack("!H", s.recv(2))[0]
|
||||
data = b""
|
||||
while len(data) < size:
|
||||
data += s.recv(size - len(data))
|
||||
s.close()
|
||||
return data
|
||||
|
||||
|
||||
def test_the_trap_counts_a_query_it_is_sent_and_refuses_what_it_cannot_answer():
|
||||
with ResolverTrap(port=0, rewrite_resolv_conf=False) as trap:
|
||||
assert trap.port > 0
|
||||
refused = _udp_ask(trap.port, "leak.test")
|
||||
assert refused[0:2] == b"\x00\x4d" and refused[3] & 0xF == ds.RCODE_REFUSED
|
||||
_tcp_ask(trap.port, "leak-tcp.test")
|
||||
assert ds.wait_until(lambda: len(trap.queries) == 2, 3)
|
||||
assert [(q.name, q.qtype, q.via) for q in trap.queries] == [
|
||||
("leak.test", ds.QTYPE_A, "udp"), ("leak-tcp.test", ds.QTYPE_A, "tcp")]
|
||||
assert trap.asked("LEAK.test.") and trap.names() == ["leak-tcp.test", "leak.test"]
|
||||
|
||||
|
||||
def test_the_trap_answers_the_names_it_is_given_over_udp_and_tcp():
|
||||
with ResolverTrap({"page-d.test": "127.0.0.1"}, port=0, rewrite_resolv_conf=False) as trap:
|
||||
for data in (_udp_ask(trap.port, "page-d.test"), _tcp_ask(trap.port, "page-d.test")):
|
||||
assert data[3] & 0xF == 0 and data[6:8] == b"\x00\x01", "NOERROR with one answer"
|
||||
assert data.endswith(socket.inet_aton("127.0.0.1"))
|
||||
aaaa = _udp_ask(trap.port, "page-d.test", ds.QTYPE_AAAA)
|
||||
assert aaaa[3] & 0xF == 0 and aaaa[6:8] == b"\x00\x00", "empty NOERROR for AAAA"
|
||||
|
||||
|
||||
# A test that does not apply to a host is not collected there, never skipped (ci/required-suites.json: no skip is
|
||||
# allowed in a required suite). Exactly one of the two below exists on every host, so the count is the same everywhere.
|
||||
if ResolverTrap.available:
|
||||
def test_the_trap_points_resolv_conf_at_itself_and_restores_it_byte_for_byte():
|
||||
from pathlib import Path
|
||||
original = Path("/etc/resolv.conf").read_bytes()
|
||||
with ResolverTrap({"page-d.test": "127.0.0.1"}) as trap:
|
||||
assert b"nameserver 127.0.0.1" in Path("/etc/resolv.conf").read_bytes()
|
||||
assert socket.gethostbyname("page-d.test") == "127.0.0.1"
|
||||
assert trap.asked("page-d.test")
|
||||
assert Path("/etc/resolv.conf").read_bytes() == original
|
||||
else:
|
||||
def test_a_trap_that_cannot_rewrite_resolv_conf_says_why_and_does_not_start():
|
||||
assert ResolverTrap.reason
|
||||
with pytest.raises(RuntimeError):
|
||||
ResolverTrap().__enter__()
|
||||
@@ -0,0 +1,74 @@
|
||||
"""The session declares the host network to the engine from its seed.
|
||||
|
||||
One variable, STEALTHFOX_WEBRTC_NETWORK, drawn by the core from the session seed
|
||||
and written with or without a proxy. Nothing here launches a browser.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
|
||||
import pytest
|
||||
from invisible_core import network_to_declare
|
||||
|
||||
from invisible_playwright._session import build_env
|
||||
|
||||
NETWORK = "STEALTHFOX_WEBRTC_NETWORK"
|
||||
SRC = pathlib.Path(__file__).resolve().parent.parent / "src" / "invisible_playwright"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("seed", [1, 42, 123456])
|
||||
def test_build_env_carries_the_seed_declaration(seed):
|
||||
env = build_env(network_declared=network_to_declare(seed), base_env={})
|
||||
assert env[NETWORK] == network_to_declare(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(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)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("proxy", [None, {"server": "socks5://127.0.0.1:1"}])
|
||||
def test_the_server_default_session_declares_the_network_of_its_seed(monkeypatch, proxy):
|
||||
"""`default_session` (what a launch naming no session gets) declares the
|
||||
network of ITS seed, with or without a proxy."""
|
||||
from invisible_core import decide_session_locale
|
||||
from invisible_core._geo import SessionGeo
|
||||
from invisible_playwright import _session
|
||||
from invisible_playwright.launcher import InvisiblePlaywright
|
||||
|
||||
seeds = []
|
||||
real_init = InvisiblePlaywright.__init__
|
||||
|
||||
def spy(self, *a, **k):
|
||||
real_init(self, *a, **k)
|
||||
seeds.append(self.seed)
|
||||
|
||||
monkeypatch.setattr(InvisiblePlaywright, "__init__", spy)
|
||||
monkeypatch.setattr(_session, "session_geo", lambda tz, px, loc: SessionGeo(
|
||||
"America/New_York", None, locale=decide_session_locale("en-US")))
|
||||
_prefs, env = _session.default_session(None, proxy)
|
||||
assert env[NETWORK] == network_to_declare(seeds[0])
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_library_adds_no_other_webrtc_variable():
|
||||
env = build_env(network_declared=network_to_declare(42), base_env={})
|
||||
assert "STEALTHFOX_WEBRTC_PUBLIC_IP" not in env
|
||||
assert "STEALTHFOX_WEBRTC_DISABLE_IPV6" not in env
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_no_source_file_spells_the_removed_names():
|
||||
removed = ("srflx_declared", "srflx_to_declare", "WEBRTC_PUBLIC_IP", "WEBRTC_DISABLE_IPV6")
|
||||
hits = [(p.name, w) for p in SRC.rglob("*.py")
|
||||
for w in removed if w in p.read_text(encoding="utf-8")]
|
||||
assert not hits, hits
|
||||
@@ -15,7 +15,7 @@ import json
|
||||
|
||||
import pytest
|
||||
|
||||
pytest.importorskip("websockets")
|
||||
import websockets # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
|
||||
from websockets.asyncio.client import connect # noqa: E402
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ import time
|
||||
|
||||
import pytest
|
||||
|
||||
pytest.importorskip("websockets")
|
||||
import websockets # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
|
||||
from websockets.asyncio.client import connect # noqa: E402
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ from urllib.parse import quote
|
||||
|
||||
import pytest
|
||||
|
||||
pytest.importorskip("websockets")
|
||||
import websockets # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
|
||||
from websockets.asyncio.client import connect # noqa: E402
|
||||
from websockets.exceptions import ConnectionClosed, InvalidStatus # noqa: E402
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""With INVPW_REQUIRE_TRAP=1 (set by the gate on its Linux leg) a resolver trap that cannot run, or whose port 53 cannot
|
||||
be bound, FAILS the DoH tests with the reason; without it the assertions on the machine's resolver are skipped as they
|
||||
always were (a developer's machine). The fixture and the "no proxy" test of the e2e file are run here for real, with
|
||||
the trap forced unavailable, so the old code (which yielded None) fails these tests."""
|
||||
import importlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
import _trap_policy
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
def _e2e():
|
||||
here = str(Path(__file__).resolve().parent)
|
||||
if here not in sys.path:
|
||||
sys.path.insert(0, here)
|
||||
return importlib.import_module("test_doh_through_the_proxy_e2e")
|
||||
|
||||
|
||||
def _fixture_body(module):
|
||||
fixture = module.trap
|
||||
return getattr(fixture, "_get_wrapped_function", lambda: getattr(fixture, "__wrapped__"))()
|
||||
|
||||
|
||||
def test_the_policy_is_off_unless_the_gate_sets_it():
|
||||
assert _trap_policy.failure({}, False, "no root") is None
|
||||
assert _trap_policy.failure({"INVPW_REQUIRE_TRAP": "0"}, False, "no root") is None
|
||||
assert _trap_policy.failure({"INVPW_REQUIRE_TRAP": ""}, True, bind_error=OSError("busy")) is None
|
||||
|
||||
|
||||
def test_the_policy_names_the_reason_when_the_gate_requires_the_trap():
|
||||
env = {"INVPW_REQUIRE_TRAP": "1"}
|
||||
assert "needs root" in _trap_policy.failure(env, False, "the resolver trap needs root")
|
||||
assert "Address already in use" in _trap_policy.failure(env, True, bind_error=OSError("Address already in use"))
|
||||
assert _trap_policy.failure(env, True) is None
|
||||
|
||||
|
||||
def test_the_trap_fixture_fails_when_the_gate_requires_it_and_it_cannot_run(monkeypatch):
|
||||
module = _e2e()
|
||||
monkeypatch.setenv("INVPW_REQUIRE_TRAP", "1")
|
||||
monkeypatch.setattr(module.ResolverTrap, "available", False)
|
||||
monkeypatch.setattr(module.ResolverTrap, "reason", "no root here")
|
||||
with pytest.raises(pytest.fail.Exception, match="no root here"):
|
||||
next(_fixture_body(module)())
|
||||
|
||||
|
||||
def test_the_trap_fixture_fails_when_the_gate_requires_it_and_port_53_is_taken(monkeypatch):
|
||||
module = _e2e()
|
||||
monkeypatch.setenv("INVPW_REQUIRE_TRAP", "1")
|
||||
monkeypatch.setattr(module.ResolverTrap, "available", True)
|
||||
|
||||
def busy(self):
|
||||
raise OSError("Address already in use")
|
||||
|
||||
monkeypatch.setattr(module.ResolverTrap, "__enter__", busy)
|
||||
with pytest.raises(pytest.fail.Exception, match="Address already in use"):
|
||||
next(_fixture_body(module)())
|
||||
|
||||
|
||||
def test_the_trap_fixture_yields_none_without_the_variable(monkeypatch):
|
||||
module = _e2e()
|
||||
monkeypatch.delenv("INVPW_REQUIRE_TRAP", raising=False)
|
||||
monkeypatch.setattr(module.ResolverTrap, "available", False)
|
||||
assert next(_fixture_body(module)()) is None
|
||||
|
||||
|
||||
def test_the_no_proxy_test_fails_when_the_gate_requires_the_trap_and_it_cannot_run(monkeypatch):
|
||||
module = _e2e()
|
||||
monkeypatch.setenv("INVPW_REQUIRE_TRAP", "1")
|
||||
monkeypatch.setattr(module.ResolverTrap, "available", False)
|
||||
monkeypatch.setattr(module.ResolverTrap, "reason", "no root here")
|
||||
test = module.test_a_session_without_a_proxy_resolves_with_the_system_resolver
|
||||
with pytest.raises(pytest.fail.Exception, match="no root here"):
|
||||
test("unused-binary", None, None)
|
||||
@@ -26,7 +26,7 @@ import json
|
||||
|
||||
import pytest
|
||||
|
||||
pytest.importorskip("websockets")
|
||||
import websockets # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
from websockets.asyncio.client import connect # noqa: E402
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
"""The hermetic road of test_the_whole_udp_chain_by_name_e2e is itself a working road: a plain client walks it by hand
|
||||
(no browser), the way a browser behind a proxy must: SOCKS5 UDP ASSOCIATE, the NAME of the TURN server asked of the DoH
|
||||
through a SOCKS5 CONNECT (the answer is an address), then an Allocate sent to that ADDRESS through the relay, answered 401
|
||||
and, with the credentials, with an answer signed as a real TURN server signs it, and the source the TURN server saw is the
|
||||
gateway's exit and not the client. A name sent along the relay (address type 3) or a DNS query to port 53 gets no answer, and
|
||||
a CONNECT that carries the page's name is refused. If this helper were wrong, the e2e could never go green; this says it can."""
|
||||
import hashlib
|
||||
import hmac
|
||||
import socket
|
||||
import ssl
|
||||
import struct
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
import _turn_chain as c
|
||||
from _doh_servers import DOH_BOOTSTRAP, DOH_HOST, DOH_PATH, DOH_PORT, QTYPE_A, QTYPE_AAAA, encode_query
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
def _socks_hello(chain):
|
||||
t = socket.create_connection(("127.0.0.1", chain.port), timeout=5)
|
||||
t.sendall(b"\x05\x01\x00")
|
||||
assert t.recv(2) == b"\x05\x00"
|
||||
return t
|
||||
|
||||
|
||||
def _socks_associate(chain):
|
||||
t = _socks_hello(chain)
|
||||
t.sendall(b"\x05\x03\x00\x01\x00\x00\x00\x00\x00\x00")
|
||||
rep = t.recv(10)
|
||||
assert rep[1] == 0
|
||||
return t, (socket.inet_ntoa(rep[4:8]), struct.unpack("!H", rep[8:10])[0])
|
||||
|
||||
|
||||
def _socks_connect(chain, host, port, by_name=False):
|
||||
"""(socket, reply code) of a CONNECT by address, or by name (address type 3)."""
|
||||
t = _socks_hello(chain)
|
||||
target = (b"\x03" + bytes([len(host)]) + host.encode()) if by_name else (b"\x01" + socket.inet_aton(host))
|
||||
t.sendall(b"\x05\x01\x00" + target + struct.pack("!H", port))
|
||||
rep = b""
|
||||
while len(rep) < 10:
|
||||
chunk = t.recv(10 - len(rep))
|
||||
if not chunk:
|
||||
break
|
||||
rep += chunk
|
||||
return t, (rep[1] if len(rep) > 1 else None)
|
||||
|
||||
|
||||
def _via(relay_sock, relay, host_ip, port, payload):
|
||||
relay_sock.sendto(b"\x00\x00\x00\x01" + socket.inet_aton(host_ip) + struct.pack("!H", port) + payload, relay)
|
||||
data, _ = relay_sock.recvfrom(65536)
|
||||
return data[10:]
|
||||
|
||||
|
||||
def _http_over_tls(sock, chain, method, target, body=b"", content_type=None, host=DOH_HOST):
|
||||
"""One HTTP/1.1 request over TLS on a tunnel, trusting the certificate of the chain's DoH."""
|
||||
context = ssl.create_default_context(cafile=str(chain.doh.certificate_path))
|
||||
context.set_alpn_protocols(["http/1.1"])
|
||||
tls = context.wrap_socket(sock, server_hostname=host)
|
||||
head = "%s %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\nContent-Length: %d\r\n" % (method, target, host, len(body))
|
||||
if content_type:
|
||||
head += "Content-Type: %s\r\n" % content_type
|
||||
tls.sendall(head.encode() + b"\r\n" + body)
|
||||
data = b""
|
||||
while True:
|
||||
chunk = tls.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
tls.close()
|
||||
head, _, payload = data.partition(b"\r\n\r\n")
|
||||
return int(head.split(b" ", 2)[1]), payload
|
||||
|
||||
|
||||
def _resolve_through_doh(chain, name, qtype=QTYPE_A, target=DOH_BOOTSTRAP):
|
||||
"""What a browser does for a name: a CONNECT to the DoH through the gateway, then the query (RFC 8484 POST)."""
|
||||
t, code = _socks_connect(chain, target, DOH_PORT, by_name=target == DOH_HOST)
|
||||
assert code == 0
|
||||
status, payload = _http_over_tls(t, chain, "POST", DOH_PATH, encode_query(name, qtype), "application/dns-message")
|
||||
assert status == 200
|
||||
return payload
|
||||
|
||||
|
||||
def test_a_client_walks_the_whole_road_and_the_turn_server_sees_the_gateways_exit():
|
||||
with c.Chain(rtt_ms=20, relay_host="127.0.0.1") as chain:
|
||||
# the name of the TURN server is asked of the DoH, through a CONNECT: the answer is an address
|
||||
answer = _resolve_through_doh(chain, c.TURN_NAME)
|
||||
assert socket.inet_ntoa(answer[-4:]) == c.TURN_IP
|
||||
assert [(q.name, q.qtype, q.via) for q in chain.doh.queries] == [(c.TURN_NAME, QTYPE_A, "chain")]
|
||||
assert chain.doh_connects() == [(DOH_BOOTSTRAP, DOH_PORT)]
|
||||
# the UDP relay of the gateway, and an Allocate to the ADDRESS the DoH gave
|
||||
t, relay = _socks_associate(chain)
|
||||
u = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
u.settimeout(5)
|
||||
# an Allocate without credentials: 401 with a realm and a nonce
|
||||
tid = b"\x01" * 12
|
||||
alloc = struct.pack("!HHI", 0x0003, 8, c.MAGIC) + tid + struct.pack("!HH", 0x0019, 4) + b"\x11\x00\x00\x00"
|
||||
r1 = _via(u, relay, c.TURN_IP, c.TURN_PORT, alloc)
|
||||
assert struct.unpack("!H", r1[:2])[0] == 0x0113
|
||||
attrs = c._attrs(r1)
|
||||
assert attrs[0x0014] == c.REALM.encode() and attrs[0x0015] == c.NONCE.encode()
|
||||
# with the credentials: a success signed with the long-term key
|
||||
user = b"challenge-1"
|
||||
key = hashlib.md5(b"challenge-1:" + c.REALM.encode() + b":" + c.PASSWORD.encode()).digest()
|
||||
body = (c._attr(0x0019, b"\x11\x00\x00\x00") + c._attr(0x0006, user) + c._attr(0x0014, c.REALM.encode()) +
|
||||
c._attr(0x0015, c.NONCE.encode()))
|
||||
req = c._message(0x0003, b"\x02" * 12, body, key)
|
||||
r2 = _via(u, relay, c.TURN_IP, c.TURN_PORT, req)
|
||||
assert struct.unpack("!H", r2[:2])[0] == 0x0103
|
||||
# the signature of the answer is the one a client with the same credentials computes
|
||||
mi_at = r2.index(struct.pack("!HH", 0x0008, 20))
|
||||
head = struct.pack("!H", 0x0103) + struct.pack("!H", mi_at - 20 + 24) + r2[4:20]
|
||||
assert hmac.new(key, head + r2[20:mi_at], hashlib.sha1).digest() == r2[mi_at + 4:mi_at + 24]
|
||||
mapped = c._attrs(r2)[0x0020]
|
||||
port = struct.unpack("!H", mapped[2:4])[0] ^ (c.MAGIC >> 16)
|
||||
ip = socket.inet_ntoa(struct.pack("!I", struct.unpack("!I", mapped[4:8])[0] ^ c.MAGIC))
|
||||
# the XOR-MAPPED-ADDRESS is the source the TURN server saw: the gateway's exit, not this client
|
||||
assert ip == c.EXIT_HOST and (ip, port) in [(a[0], a[1]) for a in chain.turn.allocations]
|
||||
assert {s[0] for s in chain.turn.seen} == {c.EXIT_HOST}
|
||||
# nothing was carried by name or to port 53: the only datagrams are the two Allocates, by address
|
||||
assert [(h, p, a) for h, p, a, _t in chain.datagram_log] == [(c.TURN_IP, c.TURN_PORT, 1)] * 2
|
||||
assert chain.refused == []
|
||||
u.close()
|
||||
t.close()
|
||||
|
||||
|
||||
def test_the_page_name_is_asked_of_the_doh_and_the_page_is_reached_by_its_address():
|
||||
with c.Chain(rtt_ms=20, relay_host="127.0.0.1") as chain:
|
||||
answer = _resolve_through_doh(chain, c.PAGE_NAME, target=DOH_HOST) # the DoH host may be sent by name too
|
||||
assert socket.inet_ntoa(answer[-4:]) == "127.0.0.1"
|
||||
# an AAAA question for a known name: the name exists, nothing of that type
|
||||
assert _resolve_through_doh(chain, c.PAGE_NAME, QTYPE_AAAA)[6:8] == b"\x00\x00"
|
||||
t, code = _socks_connect(chain, "127.0.0.1", chain.page.port)
|
||||
assert code == 0
|
||||
# the page is plain HTTP: ask it for itself, with the Host a browser sends
|
||||
t.sendall(("GET / HTTP/1.1\r\nHost: %s:%d\r\nConnection: close\r\n\r\n" % (c.PAGE_NAME, chain.page.port)).encode())
|
||||
data = b""
|
||||
while True:
|
||||
chunk = t.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
t.close()
|
||||
assert b"RTCPeerConnection" in data and chain.page.hits == [("%s:%d" % (c.PAGE_NAME, chain.page.port), "/")]
|
||||
assert ("127.0.0.1", chain.page.port) in chain.connects
|
||||
assert chain.doh.vias_of(c.PAGE_NAME) == {"chain"}
|
||||
|
||||
|
||||
def test_the_gateway_resolves_nothing_a_name_on_the_relay_a_query_to_port_53_and_a_connect_by_name_get_no_answer():
|
||||
with c.Chain(rtt_ms=0, relay_host="127.0.0.1") as chain:
|
||||
t, relay = _socks_associate(chain)
|
||||
u = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
u.settimeout(0.6)
|
||||
alloc = struct.pack("!HHI", 0x0003, 8, c.MAGIC) + b"\x03" * 12 + struct.pack("!HH", 0x0019, 4) + b"\x11\x00\x00\x00"
|
||||
name = c.TURN_NAME.encode()
|
||||
# the TURN server written as a NAME (address type 3) is not resolved by the gateway
|
||||
u.sendto(b"\x00\x00\x00\x03" + bytes([len(name)]) + name + struct.pack("!H", c.TURN_PORT) + alloc, relay)
|
||||
# nor a DNS query to port 53, by address
|
||||
question = b"\x12\x34\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00" + b"".join(
|
||||
bytes([len(p)]) + p.encode() for p in c.TURN_NAME.split(".")) + b"\x00\x00\x01\x00\x01"
|
||||
u.sendto(b"\x00\x00\x00\x01" + socket.inet_aton("192.0.2.53") + struct.pack("!H", 53) + question, relay)
|
||||
with pytest.raises(socket.timeout):
|
||||
u.recvfrom(65536)
|
||||
# a CONNECT that carries the page's name is refused, not resolved, and listed
|
||||
s, code = _socks_connect(chain, c.PAGE_NAME, chain.page.port, by_name=True)
|
||||
s.close()
|
||||
assert code == 4
|
||||
u.close()
|
||||
t.close()
|
||||
time.sleep(0.1)
|
||||
assert chain.turn.seen == [] and chain.doh.queries == []
|
||||
assert [(h, p, a) for h, p, a, _t in chain.datagram_log] == [(c.TURN_NAME, c.TURN_PORT, 3), ("192.0.2.53", 53, 1)]
|
||||
assert chain.refused == [(c.PAGE_NAME, chain.page.port)]
|
||||
# and the explanation says why the allocation could not have been asked for
|
||||
why = chain.explain({"status": "TIMEOUT"}).splitlines()[-1]
|
||||
assert "went along the UDP relay" in why and c.TURN_NAME in why
|
||||
|
||||
|
||||
def test_a_silent_browser_is_explained_by_what_each_server_saw():
|
||||
with c.Chain(rtt_ms=0, relay_host="127.0.0.1") as chain:
|
||||
text = chain.explain({"status": "TIMEOUT"})
|
||||
assert "never asked the DoH" in text.splitlines()[-1]
|
||||
for server in ("DoH queries", "gateway: CONNECTs", "TURN server heard 0", "page server"):
|
||||
assert server in text
|
||||
_resolve_through_doh(chain, c.TURN_NAME)
|
||||
assert "no datagram reached the TURN server" in chain.explain({"status": "TIMEOUT"}).splitlines()[-1]
|
||||
|
||||
|
||||
def test_every_step_of_the_gateway_costs_its_round_trip():
|
||||
with c.Chain(rtt_ms=130, relay_host="127.0.0.1") as chain:
|
||||
began = time.monotonic()
|
||||
t, _relay = _socks_associate(chain)
|
||||
took = time.monotonic() - began
|
||||
t.close()
|
||||
assert 0.25 <= took < 1.5, took # the greeting and the request each wait one round trip
|
||||
assert chain.associations and chain.associations[0][1] is not None
|
||||
|
||||
|
||||
def test_the_doh_road_is_as_far_as_the_gateway():
|
||||
with c.Chain(rtt_ms=130, relay_host="127.0.0.1") as chain:
|
||||
began = time.monotonic()
|
||||
_resolve_through_doh(chain, c.TURN_NAME)
|
||||
took = time.monotonic() - began
|
||||
# greeting + CONNECT (2 round trips) and at least the TLS flights and the query, each chunk waiting half a round trip
|
||||
assert took >= 0.5, took
|
||||
@@ -0,0 +1,76 @@
|
||||
"""The whole chain a leak test walks, by NAME, behind a SOCKS5 gateway that carries UDP, all on loopback (hermetic).
|
||||
|
||||
A page asks for a TURN allocation at a server written as a NAME (`turn:turn.relay-only.test:3478`), as the real leak-test pages
|
||||
do: no STUN, so a server-reflexive candidate can only be born from a successful allocation. Its logic is the logic of such a page:
|
||||
a tick of 2 seconds from the start of the page that marks TIMEOUT, cleared only after a POST made when the srflx arrives; the
|
||||
server compares the address of that srflx with the source the TURN server saw for the allocation.
|
||||
|
||||
The only road to anything is a gateway at 130 ms of round trip (every step of its control connection, every datagram, every
|
||||
chunk of a tunnel): the TURN server is at an unroutable documentation address that only the gateway maps to it; the names (the
|
||||
TURN's and the page's) are known only to a DoH server (a `FakeDoh`, with a certificate for `mozilla.cloudflare-dns.com`) that
|
||||
only the gateway reaches, by a CONNECT; and the gateway's datagrams leave from 127.0.0.2 so that a TURN server hearing 127.0.0.1
|
||||
proves the browser went around the gateway. The gateway resolves nothing: it answers no DNS query and no name sent as SOCKS5
|
||||
address type 3, on the relay or in a CONNECT.
|
||||
|
||||
What the product must do, to be what a retail Firefox is with no proxy at all (the same candidates, in the same time):
|
||||
* the name of the ICE server is resolved by the DoH of Firefox (`network.trr.mode` 3, found with no DNS at 162.159.61.4),
|
||||
whose request leaves THROUGH the proxy of the context: a SOCKS5 CONNECT to 162.159.61.4:443; no local resolution;
|
||||
* the UDP to the address the DoH gave leaves through the gateway's relay (address type 1);
|
||||
* and all of it, with the DoH and the handshakes of the associations the browser needs, fits in the tick of the page.
|
||||
|
||||
It fails on an engine that does not keep this (the one of the wrong candidate), and says WHY: the explanation lists what the
|
||||
DoH, the gateway, the TURN server and the page each saw. The engine refuses to resolve a name that is not a literal behind a
|
||||
proxy, so the DoH is never asked (no CONNECT to it reaches the gateway) and the browser never reaches the TURN server; then
|
||||
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), 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
|
||||
|
||||
EXIT = "203.0.113.7" # what the product's own probe of the egress is told: RFC 5737 TEST-NET-3
|
||||
#: Loopback goes through the proxy too (as in test_doh_through_the_proxy_e2e.py), so the road of the page is observable.
|
||||
PREFS = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": ""}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def gateway(monkeypatch):
|
||||
# The probes of the core that ask for the egress go nowhere: the world has no network but the gateway.
|
||||
for module, name in (("invisible_core._geo", "discover_egress_ip"),):
|
||||
try:
|
||||
mod = __import__(module, fromlist=[name])
|
||||
monkeypatch.setattr(mod, name, lambda *a, **k: EXIT, raising=False)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
try:
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
monkeypatch.setattr(InvisiblePlaywright, "_assert_uscita_invariata", lambda self: None, raising=False)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
with chain_mod.Chain(rtt_ms=130) as chain:
|
||||
yield chain
|
||||
|
||||
|
||||
def test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick(gateway, firefox_binary, engine_at_least):
|
||||
import h2 # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
engine_at_least("firefox-63")
|
||||
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={**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:
|
||||
page.wait_for_function("window.__done === true", timeout=9000)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
result = page.evaluate("window.__result")
|
||||
ok = result.get("status") == "DONE" and gateway.page.verdicts and gateway.page.verdicts[-1]["ok"]
|
||||
assert ok, "the page did not get a server-reflexive candidate that the TURN server saw, before its tick of 2 s:" + gateway.explain(result)
|
||||
@@ -68,9 +68,9 @@ _LEAKS = ("PYTHONPATH", "PYTHONHOME", "VIRTUAL_ENV",
|
||||
"INVISIBLE_DOWNLOAD_DEADLINE", "STEALTHFOX_GITHUB_TOKEN", "GITHUB_TOKEN",
|
||||
"INVISIBLE_SEAL_FILE", "INVISIBLE_CORE_PIN", "INVISIBLE_CORE_AUTOFIX",
|
||||
"INVISIBLE_CORE_AUTOFIX_TIMEOUT", "UV", "STEALTHFOX_GEOIP_MMDB",
|
||||
"STEALTHFOX_FONT_MANIFEST", "STEALTHFOX_WEBRTC_PUBLIC_IP",
|
||||
"STEALTHFOX_FONT_MANIFEST", "STEALTHFOX_WEBRTC_NETWORK",
|
||||
"INVPW_CURSOR_TIMER", "INVISIBLE_CORE_AUTOFIX_ATTEMPTED",
|
||||
"INVPW_SESSION_TOKEN", "INVPW_DESKTOP", "STEALTHFOX_WEBRTC_DISABLE_IPV6")
|
||||
"INVPW_SESSION_TOKEN", "INVPW_DESKTOP")
|
||||
|
||||
|
||||
def _clean_env(base=None):
|
||||
|
||||
+299
-80
@@ -4,15 +4,13 @@ Two layers, both runnable on GitHub CI:
|
||||
|
||||
* **unit** (`@pytest.mark.unit`) - pure SDP/candidate assertions against golden
|
||||
samples. No browser, no proxy, no network. These lock in every rule we found
|
||||
on 2026-06-06: host must be mDNS ``.local``; the synthetic srflx must carry the
|
||||
egress IP with a GENUINE nICEr priority (never ``local_pref == 0xFFFF``) and a
|
||||
on 2026-06-06: host must be mDNS ``.local``; an srflx must carry a
|
||||
GENUINE nICEr priority (never ``local_pref == 0xFFFF``) and a
|
||||
stable, distinct foundation; CreepJS's resolver must return the egress, and a
|
||||
host-only SDP must read as "blocked". They run in the standard ``tests.yml``.
|
||||
|
||||
* **e2e** (`@pytest.mark.e2e`) - launch the patched binary and verify the live
|
||||
ICE gather. "Being behind a proxy" is faked WITHOUT any external proxy provider:
|
||||
- the egress IP is injected via ``STEALTHFOX_WEBRTC_PUBLIC_IP`` (RFC 5737
|
||||
TEST-NET, so it never collides with a real IP);
|
||||
- the "behind a TCP-only SOCKS proxy" condition is reproduced by a tiny
|
||||
in-process SOCKS5 server that relays TCP CONNECT but refuses UDP ASSOCIATE
|
||||
(exactly a residential TCP-only proxy → WebRTC's default-route UDP probe
|
||||
@@ -240,27 +238,14 @@ def test_shipped_webrtc_baseline_is_the_validated_config():
|
||||
# without a proxy the pref did.
|
||||
assert "zoom.stealth.webrtc.disable_ipv6" not in prefs
|
||||
assert "media.peerconnection.ice.disableIPv6" not in prefs
|
||||
# The single source is the environment, and it turns on ONLY behind a proxy.
|
||||
#
|
||||
# Measured on 2026-08-25 against the installed retail Firefox, same
|
||||
# connection (dual-stack, no VPN): retail emits 6 candidates - host UDP x2
|
||||
# and host TCP x2 obfuscated mDNS, plus srflx v4 and **srflx v6 with the
|
||||
# real global address IN THE CLEAR** (mDNS only covers the hosts). We
|
||||
# emitted 3, because we always filtered IPv6: we looked like an IPv4-only
|
||||
# machine where the reference is dual-stack.
|
||||
#
|
||||
# Behind an IPv4 proxy the filter is genuinely useful (that IPv6 would be a
|
||||
# leak and an inconsistency with the HTTP IP); without a proxy it protects
|
||||
# nothing and only costs realism.
|
||||
# The single source is the environment (STEALTHFOX_WEBRTC_NETWORK, drawn from
|
||||
# the seed), declared with or without a proxy.
|
||||
from invisible_core import network_to_declare
|
||||
from invisible_core.launch import build_launch_env
|
||||
from invisible_playwright._session import build_env
|
||||
for build_fn in (lambda **k: build_launch_env({}, **k), build_env):
|
||||
env_with = build_fn(srflx_declared="203.0.113.77", base_env={})
|
||||
assert env_with["STEALTHFOX_WEBRTC_DISABLE_IPV6"] == "1"
|
||||
assert env_with["STEALTHFOX_WEBRTC_PUBLIC_IP"] == "203.0.113.77"
|
||||
env_without = build_fn(srflx_declared=None, base_env={})
|
||||
assert "STEALTHFOX_WEBRTC_DISABLE_IPV6" not in env_without
|
||||
assert "STEALTHFOX_WEBRTC_PUBLIC_IP" not in env_without
|
||||
env = build_fn(network_declared=network_to_declare(42), base_env={})
|
||||
assert env["STEALTHFOX_WEBRTC_NETWORK"] == network_to_declare(42)
|
||||
# peerconnection stays ON (a disabled WebRTC is itself a tell).
|
||||
assert prefs["media.peerconnection.enabled"] is True
|
||||
|
||||
@@ -459,14 +444,13 @@ def _launch(**extra):
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_srflx_is_real_and_resolvable(local_https_page):
|
||||
"""No proxy needed: the egress is faked via the env. Asserts the live srflx
|
||||
is genuine (Fix A/B) and that CreepJS's resolver returns it (not blocked)."""
|
||||
def test_the_gather_is_real_without_a_proxy(local_https_page):
|
||||
"""No proxy: the engine keeps the real network. The gather completes, the
|
||||
host is mDNS, and an srflx, when one is born, is genuine (Fix A/B) and
|
||||
resolvable by the resolver of a studied system (not blocked)."""
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
os.environ["STEALTHFOX_WEBRTC_PUBLIC_IP"] = _FAKE_EGRESS
|
||||
os.environ["STEALTHFOX_WEBRTC_DISABLE_IPV6"] = "1"
|
||||
with _launch(binary_path=binary) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto(local_https_page, wait_until="domcontentloaded", timeout=60000)
|
||||
@@ -474,97 +458,332 @@ def test_srflx_is_real_and_resolvable(local_https_page):
|
||||
cands = candidates(res["candidates"])
|
||||
assert cands, "ICE produced ZERO candidates (blocked)"
|
||||
assert host_is_mdns(cands), [c["address"] for c in host_candidates(cands)]
|
||||
srflx = [c for c in srflx_candidates(cands) if c["address"] == _FAKE_EGRESS]
|
||||
assert srflx, f"no synthetic srflx with {_FAKE_EGRESS}: {res['candidates']}"
|
||||
ok, reasons = srflx_realness(srflx[0], expected_ip=_FAKE_EGRESS)
|
||||
assert ok, reasons
|
||||
srflx = srflx_candidates(cands)
|
||||
for c in srflx:
|
||||
ok, reasons = srflx_realness(c, expected_ip=c["address"])
|
||||
assert ok, reasons
|
||||
# Two srflx for the same base must share ONE stable foundation (Fix B).
|
||||
assert len({c["foundation"] for c in srflx}) == 1
|
||||
assert creep_get_ipaddress(res["sdp"]) == _FAKE_EGRESS
|
||||
assert len({c["foundation"] for c in srflx}) <= 1
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_not_blocked_behind_tcp_only_socks(socks5_tcp_only):
|
||||
"""Fix C sentinel: behind a TCP-only SOCKS proxy on a remote origin, ICE
|
||||
must still complete (host .local + synthetic srflx), not return zero
|
||||
candidates. Without Fix C this page is fully 'blocked'."""
|
||||
"""Behind a TCP-only SOCKS proxy on a remote origin, ICE must still complete
|
||||
(host .local candidates), not return zero candidates: a fully blocked
|
||||
WebRTC is itself a tell. The session declares its network from the seed
|
||||
(STEALTHFOX_WEBRTC_NETWORK); that variable is read by the new engine only."""
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
os.environ["STEALTHFOX_WEBRTC_PUBLIC_IP"] = _FAKE_EGRESS
|
||||
os.environ["STEALTHFOX_WEBRTC_DISABLE_IPV6"] = "1"
|
||||
proxy = {"server": f"socks5://127.0.0.1:{socks5_tcp_only.port}"}
|
||||
try:
|
||||
with _launch(binary_path=binary, proxy=proxy) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
# remote origin loaded THROUGH the local SOCKS proxy (not localhost,
|
||||
# so no proxy-bypass) → WebRTC proxy config active → Fix C path.
|
||||
# so no proxy-bypass) -> WebRTC proxy config active.
|
||||
page.goto("https://example.com/", wait_until="domcontentloaded", timeout=70000)
|
||||
res = page.evaluate(_PROBE_JS)
|
||||
except Exception as exc: # network/proxy unavailable in this environment
|
||||
pytest.skip(f"proxy/network path unavailable: {exc!r}")
|
||||
cands = candidates(res["candidates"])
|
||||
# Hard regression check: ZERO candidates means WebRTC is fully blocked behind
|
||||
# the SOCKS proxy - that's the Fix C regression this sentinel exists to catch.
|
||||
assert cands, "behind SOCKS the gather returned ZERO candidates - Fix C regressed (blocked)"
|
||||
assert cands, "behind SOCKS the gather returned ZERO candidates (blocked)"
|
||||
assert host_is_mdns(cands)
|
||||
# A missing synthetic srflx used to be a skip, blamed on "a datacenter CI
|
||||
# box". That was wrong, and the skip hid a real defect on every Linux run:
|
||||
# behind a SOCKS proxy with remote DNS the document channel reports
|
||||
# 0.0.0.0 as the server address, and Firefox hands that wildcard to nICEr's
|
||||
# default-route probe. Windows refuses a UDP connect() to 0.0.0.0, so Fix C
|
||||
# fires and the synthetic srflx is born; Linux accepts it and answers
|
||||
# 127.0.0.1, so Fix C never fired, no srflx was born, and real sites saw
|
||||
# WebRTC as blocked. firefox-35 rejects a wildcard target in nICEr itself,
|
||||
# so Linux takes the Windows path. From that engine on, a missing srflx is
|
||||
# the defect this sentinel exists for, on every platform, and it FAILS.
|
||||
# Only an engine older than firefox-35 still skips, naming the known defect.
|
||||
srflx = [c for c in srflx_candidates(cands) if c["address"] == _FAKE_EGRESS]
|
||||
if not srflx:
|
||||
revision = _engine_revision()
|
||||
if revision is not None and revision < 35:
|
||||
pytest.skip(f"engine firefox-{revision} predates the nICEr wildcard "
|
||||
"fix: behind SOCKS on Linux no synthetic srflx is born "
|
||||
"(known defect B236, fixed in firefox-35)")
|
||||
pytest.fail("behind SOCKS the gather has no synthetic srflx with "
|
||||
f"{_FAKE_EGRESS} on engine {_engine_tag()}: real sites see "
|
||||
f"WebRTC as blocked (B236). Candidates: {res['candidates']}")
|
||||
assert creep_get_ipaddress(res["sdp"]) == _FAKE_EGRESS
|
||||
|
||||
|
||||
def _engine_tag() -> str:
|
||||
"""The release tag of the engine just launched. The launch refuses a binary
|
||||
the active seal does not describe (`verify_engine`), so after a launch the
|
||||
active seal's tag IS the binary's revision."""
|
||||
from invisible_core.seal import active_seal
|
||||
return active_seal().tag
|
||||
# The gather the next tests read: one STUN server, by number, and everything the engine says about it.
|
||||
_RELAY_PROBE_JS = r"""async (stun) => {
|
||||
const t0 = performance.now();
|
||||
const pc = new RTCPeerConnection({iceServers: [{urls: [stun]}]});
|
||||
pc.createDataChannel('');
|
||||
const cands = [], errors = [], at = {};
|
||||
pc.addEventListener('icecandidate', e => {
|
||||
if (e.candidate && e.candidate.candidate) {
|
||||
cands.push(e.candidate.candidate);
|
||||
const typ = (e.candidate.candidate.match(/ typ (\w+)/) || [])[1];
|
||||
if (typ && !(typ in at)) at[typ] = Math.round(performance.now() - t0);
|
||||
}
|
||||
});
|
||||
pc.addEventListener('icecandidateerror', e => { errors.push({code: e.errorCode, text: e.errorText, url: e.url}); at.error = Math.round(performance.now() - t0); });
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
await new Promise(resolve => {
|
||||
const timer = setTimeout(resolve, 25000);
|
||||
pc.addEventListener('icegatheringstatechange', () => {
|
||||
if (pc.iceGatheringState === 'complete') { at.complete = Math.round(performance.now() - t0); clearTimeout(timer); resolve(); }
|
||||
});
|
||||
});
|
||||
const sdp = (pc.localDescription && pc.localDescription.sdp) || '';
|
||||
try { pc.close(); } catch (e) {}
|
||||
return {candidates: cands, errors, sdp, at_ms: at};
|
||||
}"""
|
||||
|
||||
|
||||
def _address_of_this_host() -> str:
|
||||
"""The IPv4 address the host sends from (a routable one, as a real gateway's relay is). No packet is sent."""
|
||||
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
probe.connect(("192.0.2.1", 9))
|
||||
return probe.getsockname()[0]
|
||||
finally:
|
||||
probe.close()
|
||||
|
||||
|
||||
_ICE_PREFS = [
|
||||
{}, # the engine's default: ICE in the socket process
|
||||
{"media.peerconnection.mtransport_process": False}, # ICE in the process of the page
|
||||
]
|
||||
_ICE_IDS = ["ice_in_the_socket_process", "ice_in_the_content_process"]
|
||||
|
||||
|
||||
def _gather_behind_a_coherent_gateway(monkeypatch, credentials, ice_prefs, rtt_ms, page_first_ms=None):
|
||||
"""Launch the default engine behind a local gateway with coherent UDP, `rtt_ms` away, gather with a STUN server only
|
||||
its relay reaches, and say whether the page's request took the relay and what the gather looked like."""
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
from invisible_core import _geo
|
||||
|
||||
from _socks_servers import STUN_NUMBER, STUN_PORT, coherent
|
||||
stun = f"stun:{STUN_NUMBER}:{STUN_PORT}"
|
||||
user, password = credentials or (None, None)
|
||||
# The relay sits on the address of this host, as a real gateway's does: the engine's ICE sockets are bound to an
|
||||
# interface address, and on Windows such a socket cannot send to a relay on loopback.
|
||||
with coherent(user=user, password=password, relay_host=_address_of_this_host(), rtt_ms=rtt_ms) as gateway:
|
||||
exit_ip = gateway.tcp_exit
|
||||
# The session asks the gateway for its TCP exit over HTTPS, which no local gateway can answer as itself: the
|
||||
# answer is the gateway's. The UDP probe that follows is NOT replaced: it runs through the relay, for real.
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", lambda *_a, **_k: exit_ip)
|
||||
extra_prefs = {"media.peerconnection.ice.obfuscate_host_addresses": True, **ice_prefs}
|
||||
with _launch(binary_path=binary, proxy=gateway.proxy, extra_prefs=extra_prefs) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
if page_first_ms is None:
|
||||
page.goto("about:blank")
|
||||
else:
|
||||
# A page that is loaded through the gateway, and a while later asks for WebRTC.
|
||||
page.goto("http://page.test/")
|
||||
page.wait_for_timeout(page_first_ms)
|
||||
res = page.evaluate(_RELAY_PROBE_JS, stun)
|
||||
carried = [(host, port) for host, port, _payload in gateway.datagrams]
|
||||
stun_requests = gateway.stun.requests
|
||||
associates = gateway.associates
|
||||
srflx = [c for c in srflx_candidates(candidates(res["candidates"])) if c["address"] == exit_ip]
|
||||
verdict = (f"srflx with the gateway's exit {exit_ip}: {srflx}; candidates: {res['candidates']}; "
|
||||
f"ICE errors: {res['errors']}; gather timings (ms from the offer): {res['at_ms']}; "
|
||||
f"datagrams the relay carried: {carried}; STUN requests the server answered: {stun_requests}; "
|
||||
f"UDP ASSOCIATEs the gateway saw: {associates}; round trip to the gateway: {rtt_ms} ms")
|
||||
return bool(srflx) and (STUN_NUMBER, STUN_PORT) in carried, verdict, res["at_ms"]
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.parametrize("credentials", [None, ("alice", "s3cret"), ("user~tcp-windows-65535", "not-a-real-password")],
|
||||
ids=["no_auth", "user_and_password", "user_with_a_tilde"])
|
||||
@pytest.mark.parametrize("ice_prefs", _ICE_PREFS, ids=_ICE_IDS)
|
||||
@pytest.mark.usefixtures("the_udp_line")
|
||||
def test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay(monkeypatch, credentials, ice_prefs):
|
||||
"""The default engine, a SOCKS5 gateway that relays UDP and whose UDP exit is its TCP exit: the page's STUN request
|
||||
goes THROUGH the relay and the srflx it gets is the gateway's exit.
|
||||
|
||||
The two places ICE can run are both held: in the socket process (the engine's default, `media.peerconnection.
|
||||
mtransport_process`; the sockets are NrSocket's) and in the process of the page (UDPSocketParent's sockets), each
|
||||
with a gateway that wants no credentials and with one that does. A request that does not take the relay ends in
|
||||
an ICE error 701 and no srflx; the failure message says what the gateway saw.
|
||||
|
||||
The gateway is local (tests/_socks_servers.py): the TCP exit and the UDP exit it reports are documentation addresses,
|
||||
and the STUN server the page is given is a documentation address too, so the only road to it is the relay. The page
|
||||
reaches the proxy by the session the Juggler holds, as every page does; nothing here sets a pref of the engine."""
|
||||
took_the_relay, verdict, _timings = _gather_behind_a_coherent_gateway(monkeypatch, credentials, ice_prefs, rtt_ms=0)
|
||||
assert took_the_relay, "the page's STUN request did not take the relay. " + verdict
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.usefixtures("the_udp_line")
|
||||
def test_a_host_with_ipv6_addresses_gathers_through_an_ipv4_relay(monkeypatch):
|
||||
"""The ICE sockets are opened with the family of the host candidate they carry (NrSocket::create, PR_OpenUDPSocket
|
||||
with the address's family): an IPv6 host gets AF_INET6 sockets next to its AF_INET ones, while the relay of the
|
||||
gateway is IPv4. With the host addresses in the clear, the IPv4 STUN server must still be answered through the relay."""
|
||||
took_the_relay, verdict, _timings = _gather_behind_a_coherent_gateway(
|
||||
monkeypatch, ("alice", "s3cret"), {"media.peerconnection.ice.obfuscate_host_addresses": False}, 0)
|
||||
print("[families] " + verdict)
|
||||
assert took_the_relay, "the page's STUN request did not take the relay. " + verdict
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.parametrize("rtt_ms", [80, 150, 250])
|
||||
@pytest.mark.parametrize("ice_prefs", _ICE_PREFS, ids=_ICE_IDS)
|
||||
@pytest.mark.usefixtures("the_udp_line")
|
||||
def test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_its_relay(monkeypatch, ice_prefs, rtt_ms):
|
||||
"""The same gather with a gateway that is not on loopback: every answer on the control connection waits `rtt_ms`
|
||||
and the relay adds half of it each way. The layer opens one association per ICE socket, one after the other, each
|
||||
with a connect, a greeting, an authentication and the ASSOCIATE; a gather must not be over before they are done."""
|
||||
took_the_relay, verdict, _timings = _gather_behind_a_coherent_gateway(
|
||||
monkeypatch, ("alice", "s3cret"), ice_prefs, rtt_ms)
|
||||
print(f"[gather] rtt {rtt_ms} ms, {_ICE_IDS[_ICE_PREFS.index(ice_prefs)]}: {_timings}")
|
||||
assert took_the_relay, "the page's STUN request did not take the relay. " + verdict
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.parametrize("ice_prefs", _ICE_PREFS, ids=_ICE_IDS)
|
||||
@pytest.mark.usefixtures("the_udp_line")
|
||||
def test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far_away(monkeypatch, ice_prefs):
|
||||
"""⛔ THE KNOWN-BAD INPUT: a gateway 250 ms away. The layer made its associations one after the other on the thread of
|
||||
the ICE sockets, a connect, a greeting, an authentication and the ASSOCIATE each, so the first candidate of the page
|
||||
came out after about twelve round trips (host candidate at 2.3 s on Linux and 3.0 s on Windows, against well under a
|
||||
second next to the gateway), and a page that times `icecandidate` reads it. A candidate does not wait for the proxy:
|
||||
the host candidate of the far gather comes within a round trip and a quarter of a second of the near one, and the
|
||||
srflx within the handshake (four round trips) and a STUN request (one) of its host candidate."""
|
||||
rtt_ms = 250
|
||||
near_ok, near_verdict, near = _gather_behind_a_coherent_gateway(monkeypatch, ("alice", "s3cret"), ice_prefs, 0)
|
||||
far_ok, far_verdict, far = _gather_behind_a_coherent_gateway(monkeypatch, ("alice", "s3cret"), ice_prefs, rtt_ms)
|
||||
print(f"[first candidate] near {near}, {rtt_ms} ms away {far}")
|
||||
assert near_ok, near_verdict
|
||||
assert far_ok, far_verdict
|
||||
assert far["host"] - near["host"] <= rtt_ms + 250, (
|
||||
f"the first candidate waited for the gateway: host candidate at {far['host']} ms behind a gateway {rtt_ms} ms away, "
|
||||
f"{near['host']} ms next to it. {far_verdict}")
|
||||
assert far["srflx"] - far["host"] <= 5 * rtt_ms + 250, (
|
||||
f"the srflx came {far['srflx'] - far['host']} ms after the host candidate. {far_verdict}")
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.usefixtures("the_udp_line")
|
||||
def test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server(monkeypatch):
|
||||
"""⛔ THE KNOWN-BAD INPUT: a gateway 250 ms away, a page loaded through it, and two seconds later the page asks for
|
||||
WebRTC. Next to a gateway the srflx comes at once; behind this one it may come later by the road itself, the round
|
||||
trip of the relay to the STUN server and back, and by nothing else: the connect, the greeting, the authentication and
|
||||
the ASSOCIATE of each socket (about 0.56 s against the real driver) are made before the page asks, when the proxy
|
||||
of the context is first used, not after. A target without the proxy has no such cost to show."""
|
||||
rtt_ms = 250
|
||||
near_ok, near_verdict, near = _gather_behind_a_coherent_gateway(
|
||||
monkeypatch, ("alice", "s3cret"), {}, 0, page_first_ms=2000)
|
||||
far_ok, far_verdict, far = _gather_behind_a_coherent_gateway(
|
||||
monkeypatch, ("alice", "s3cret"), {}, rtt_ms, page_first_ms=2500)
|
||||
print(f"[page first] near {near}, {rtt_ms} ms away {far}")
|
||||
assert near_ok, near_verdict
|
||||
assert far_ok, far_verdict
|
||||
assert far["host"] - near["host"] <= 100, f"the host candidate waited: {far_verdict}"
|
||||
assert far["srflx"] - near["srflx"] <= rtt_ms + 250, (
|
||||
f"the srflx came {far['srflx']} ms after the offer behind a gateway {rtt_ms} ms away, {near['srflx']} ms next to "
|
||||
f"it: more than the road to the server ({rtt_ms} ms). {far_verdict}")
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.usefixtures("the_udp_line")
|
||||
def test_two_contexts_with_two_proxies_each_gets_the_srflx_of_its_own(monkeypatch):
|
||||
"""⛔ THE KNOWN-BAD INPUT: a session whose proxy is one gateway and a context whose proxy is another. The proxy a
|
||||
page's traffic takes is the one of its context, UDP included: the srflx of each context is the exit of its own
|
||||
gateway. (The engine took one proxy for the whole session and handed over nothing when two differed.)"""
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
from invisible_core import _geo
|
||||
|
||||
from _socks_servers import STUN_NUMBER, STUN_PORT, coherent
|
||||
stun = f"stun:{STUN_NUMBER}:{STUN_PORT}"
|
||||
host = _address_of_this_host()
|
||||
with coherent(exit_ip="203.0.113.7", user="alice", password="s3cret", relay_host=host) as first, coherent(exit_ip="198.51.100.77", user="bob", password="hunter2", relay_host=host) as second:
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", lambda *_a, **_k: first.tcp_exit)
|
||||
extra_prefs = {"media.peerconnection.ice.obfuscate_host_addresses": True}
|
||||
with _launch(binary_path=binary, proxy=first.proxy, extra_prefs=extra_prefs) as browser:
|
||||
of_the_session = browser.new_context().new_page()
|
||||
of_its_own = browser.new_context(proxy=second.proxy).new_page()
|
||||
res_session = of_the_session.evaluate(_RELAY_PROBE_JS, stun)
|
||||
res_own = of_its_own.evaluate(_RELAY_PROBE_JS, stun)
|
||||
|
||||
def exits(res):
|
||||
return sorted(c["address"] for c in srflx_candidates(candidates(res["candidates"])))
|
||||
|
||||
assert exits(res_session) == [first.tcp_exit], f"the context of the session: {res_session}"
|
||||
assert exits(res_own) == [second.tcp_exit], f"the context with a proxy of its own: {res_own}"
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.usefixtures("the_udp_line")
|
||||
def test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context(monkeypatch):
|
||||
"""⛔ THE KNOWN-BAD INPUT: the proxy lookup of the TCP socket of a TURN server was made with a channel of the system
|
||||
principal, so the filter of the session answered for context 0 and a SOCKS5 proxy of the context was not the one the
|
||||
TURN connection took. The page below sits in a context with a proxy of its own and asks for a TURN server over TCP:
|
||||
the CONNECT must reach the gateway of that context and not the one of the session."""
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
from invisible_core import _geo
|
||||
|
||||
from _socks_servers import coherent
|
||||
host = _address_of_this_host()
|
||||
turn_host, turn_port = "198.51.100.9", 3478
|
||||
with coherent(exit_ip="203.0.113.7", user="alice", password="s3cret", relay_host=host) as session, coherent(exit_ip="198.51.100.77", user="bob", password="hunter2", relay_host=host) as context:
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", lambda *_a, **_k: session.tcp_exit)
|
||||
extra_prefs = {"media.peerconnection.ice.obfuscate_host_addresses": True}
|
||||
with _launch(binary_path=binary, proxy=session.proxy, extra_prefs=extra_prefs) as browser:
|
||||
page = browser.new_context(proxy=context.proxy).new_page()
|
||||
page.goto("about:blank")
|
||||
page.evaluate("""async (turn) => {
|
||||
const pc = new RTCPeerConnection({iceServers: [{urls: [turn], username: 'u', credential: 'p'}]});
|
||||
pc.createDataChannel('');
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
await new Promise(r => setTimeout(r, 6000));
|
||||
pc.close();
|
||||
}""", f"turn:{turn_host}:{turn_port}?transport=tcp")
|
||||
in_context = [c for c in context.connects if c == (turn_host, turn_port)]
|
||||
in_session = [c for c in session.connects if c == (turn_host, turn_port)]
|
||||
assert in_context and not in_session, (
|
||||
f"the TURN connection of the context: by the gateway of the context {context.connects}, "
|
||||
f"by the gateway of the session {session.connects}")
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.usefixtures("the_udp_line")
|
||||
def test_a_proxy_that_does_not_relay_udp_gives_no_srflx_at_all(monkeypatch):
|
||||
"""⛔ THE KNOWN-BAD INPUT: a gateway that refuses UDP ASSOCIATE. The target is a retail Windows at home on a network
|
||||
that blocks UDP: the host candidates are there, the UDP datagrams leave nowhere and nothing answers (no error, no
|
||||
direct send), so the STUN request retransmits and ends in 701 in nICEr's own time, and the page gets no srflx: the
|
||||
session does not invent one (a candidate with the exit of TCP and no allocation behind it, raddr 0.0.0.0, is a value
|
||||
no browser makes). The time of that 701 on a retail with UDP blocked is still to be measured."""
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
from invisible_core import _geo
|
||||
|
||||
from _socks_servers import STUN_NUMBER, STUN_PORT, tcp_only
|
||||
stun = f"stun:{STUN_NUMBER}:{STUN_PORT}"
|
||||
with tcp_only(user="alice", password="s3cret") as gateway:
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", lambda *_a, **_k: gateway.tcp_exit)
|
||||
extra_prefs = {"media.peerconnection.ice.obfuscate_host_addresses": True}
|
||||
with _launch(binary_path=binary, proxy=gateway.proxy, extra_prefs=extra_prefs) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto("about:blank")
|
||||
res = page.evaluate(_RELAY_PROBE_JS, stun)
|
||||
typ = [c["typ"] for c in candidates(res["candidates"])]
|
||||
assert "srflx" not in typ and "relay" not in typ, f"a candidate that nothing allocated: {res['candidates']}"
|
||||
assert "host" in typ, f"no host candidate at all: {res['candidates']}"
|
||||
assert [e["code"] for e in res["errors"]] == [701], f"a network that blocks UDP ends the STUN request in 701: {res['errors']}"
|
||||
# The shape of a retail Firefox on a network that drops UDP (notes/retail-udp-blocked-reference.md): udp and tcp host
|
||||
# candidates, and the 701 of the UDP request at nICEr's own time, 11.1-11.3 s, together with the end of the gather: never
|
||||
# an immediate error, never a candidate that nothing allocated.
|
||||
protocols = sorted({c["proto"].upper() for c in candidates(res["candidates"]) if c["typ"] == "host"})
|
||||
assert protocols == ["TCP", "UDP"], f"host candidates of a retail on a network that drops UDP: {res['candidates']}"
|
||||
assert 10_000 <= res["at_ms"]["error"] <= 13_000, (
|
||||
f"the 701 of the UDP request came at {res['at_ms']['error']} ms; nICEr's time on a network that drops UDP is 11.1-11.3 s")
|
||||
|
||||
|
||||
def _engine_revision():
|
||||
"""N for a `firefox-N` tag (a local seal may append to it, as in
|
||||
`firefox-34-prfix`), or None when the tag says no revision. None never
|
||||
buys a skip: an engine that cannot say it is old is judged as a new one."""
|
||||
m = re.match(r"firefox-(\d+)", _engine_tag())
|
||||
return int(m.group(1)) if m else None
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
# The egress IP must not change MID-SESSION.
|
||||
#
|
||||
# Measured on 2026-08-25 on browserleaks, behind a residential proxy: the
|
||||
# page exited from 216.131.76.63 while the WebRTC srflx candidate announced
|
||||
# page exited from 203.0.113.30 while a second reading of the exit said
|
||||
# 216.131.76.64, and the site says so plainly ("WebRTC IP doesn't match your
|
||||
# Remote IP"). It was not a regression in the binary - interleaved A/B between
|
||||
# the release binary and the new one: 4 runs out of 4 consistent on both.
|
||||
#
|
||||
# The cause is that the IP declared to the engine is photographed ONCE, at
|
||||
# launch, and residential proxies do not promise to keep it: the docs of the
|
||||
# The cause is that the egress behind the timezone and the locale is photographed
|
||||
# ONCE, at launch, and residential proxies do not promise to keep it: the docs of the
|
||||
# two providers tried declare TIME-based sticky sessions (60 minutes max for
|
||||
# one; a sliding timeout for the other, which also expires early if the peer
|
||||
# disconnects). On a long session the drift is a certainty, not a risk - which
|
||||
# is why short probes never saw it.
|
||||
#
|
||||
# Owner's decision, 2026-08-25: it is not updated on the fly. A WebRTC IP that
|
||||
# Owner's decision, 2026-08-25: it is not updated on the fly. A timezone that
|
||||
# changes in front of the site's own eyes is as unnatural as the mismatch
|
||||
# itself. A proxy that does not hold the session is not fit for purpose, and
|
||||
# the product must SAY SO instead of carrying on.
|
||||
|
||||
Reference in new issue
Block a user