Compare commits
114
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7575a45a42 | ||
|
|
d87492ea9f | ||
|
|
71c3324006 | ||
|
|
302af97575 | ||
|
|
47725170de | ||
|
|
d56ea298b4 | ||
|
|
e88e664a50 | ||
|
|
bacf03ad21 | ||
|
|
9357e790b3 | ||
|
|
1466ac6433 | ||
|
|
bf5c6dabb3 | ||
|
|
e992255d38 | ||
|
|
8049df3c33 | ||
|
|
e4edf5f81f | ||
|
|
7a094c3bbc | ||
|
|
7272ea8f64 | ||
|
|
a70f2fecaf | ||
|
|
65f7580182 | ||
|
|
4933f8cdba | ||
|
|
bfb67e0c2c | ||
|
|
2022ecf32a | ||
|
|
5ae6833299 | ||
|
|
a90dadc204 | ||
|
|
210161d9b6 | ||
|
|
1542fede01 | ||
|
|
5426744bc6 | ||
|
|
973927fdb7 | ||
|
|
071cf8d697 | ||
|
|
7af5b84954 | ||
|
|
a18e967675 | ||
|
|
64dc8d3476 | ||
|
|
bd46760313 | ||
|
|
2283d40198 | ||
|
|
012fc862ef | ||
|
|
8c7e413b68 | ||
|
|
bbf4019940 | ||
|
|
4e1f2ecf40 | ||
|
|
6f9b87c860 | ||
|
|
a072aa22b8 | ||
|
|
328ed0738e | ||
|
|
6200bc29ed | ||
|
|
b05741f538 | ||
|
|
95c7e156ac | ||
|
|
620f969655 | ||
|
|
adf96a2b15 | ||
|
|
2167538130 | ||
|
|
440bbb36e6 | ||
|
|
2f153c76ff | ||
|
|
fbceeafb65 | ||
|
|
b09d620930 | ||
|
|
776c00afe2 | ||
|
|
ba5b51cf91 | ||
|
|
14c24347c5 | ||
|
|
99c7fc93aa | ||
|
|
a61465b2be | ||
|
|
47536b5e64 | ||
|
|
4f95aa3797 | ||
|
|
6a60dcebb7 | ||
|
|
7927e30679 | ||
|
|
bf2a3c33b0 | ||
|
|
03d96a7baa | ||
|
|
7db28e4611 | ||
|
|
f76240893e | ||
|
|
d5c0e410de | ||
|
|
422e675b86 | ||
|
|
1c7bcf9dee | ||
|
|
84fd375562 | ||
|
|
d596ee81c8 | ||
|
|
66d5090a0b | ||
|
|
3a1dc8df9b | ||
|
|
5b87926543 | ||
|
|
b396e055ce | ||
|
|
68bb2b8e8f | ||
|
|
c14f2b1e9a | ||
|
|
bfedd53850 | ||
|
|
e868714339 | ||
|
|
36ecd11e99 | ||
|
|
80672c69a3 | ||
|
|
a21e1decb9 | ||
|
|
ecf384a923 | ||
|
|
a8cc2c842e | ||
|
|
5da874d67f | ||
|
|
f3e3ce164d | ||
|
|
2329dc6c1c | ||
|
|
52e520dd92 | ||
|
|
73c070ebb1 | ||
|
|
1d564f5732 | ||
|
|
6f25adc2e5 | ||
|
|
cd062e2c59 | ||
|
|
5a617dd899 | ||
|
|
793ea3d191 | ||
|
|
154a9de475 | ||
|
|
8c92c764b7 | ||
|
|
000fa7a3ad | ||
|
|
6a5b7e014a | ||
|
|
b78c5bb67c | ||
|
|
228576009b | ||
|
|
bc816cb1ae | ||
|
|
7ef736ca73 | ||
|
|
d6f5c884b4 | ||
|
|
cbd9f5db5b | ||
|
|
183219ce18 | ||
|
|
5c66186464 | ||
|
|
7ddb451af7 | ||
|
|
98d9a799f6 | ||
|
|
f9221ae3c2 | ||
|
|
41f7bec7a7 | ||
|
|
56b33a7740 | ||
|
|
fef0bc5ea7 | ||
|
|
2bc12eb80b | ||
|
|
ff2123ef58 | ||
|
|
5402da4d80 | ||
|
|
c23612e295 | ||
|
|
11b9e08b1a |
No files matched your search
@@ -0,0 +1,132 @@
|
||||
name: cold-pool-hunt (one UDP e2e of the SOCKS5 line, repeated, with the engine's SOCKS logs)
|
||||
|
||||
# test_webrtc_realness.py::test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server was red once in 41 on Windows
|
||||
# in the gate of run 43188313516: the srflx came at 1024 ms, four steps of 250 ms, as if the PeerConnection had opened a new association instead
|
||||
# of taking a ready one. This job repeats THAT test on the engine of that run, in a fresh pytest process each time, with the engine's logs
|
||||
# (MOZ_LOG timestamp,sync,append,SOCKS,SOCKS-UDP,signaling) in one folder per repetition and the wall-clock times of what the test gateway sees
|
||||
# (tests/_hunt_plugin.py), keeps the red repetitions and three green ones as an artifact, and prints red/total and, for each red one, the sequence
|
||||
# with times (scripts/cold_pool_report.py): first SOCKS5 connection, associations OK, PeerConnection, push of the UDP layer, and how many
|
||||
# associations were ready at each push. A hunt, not a gate: it starts on a push that touches this file, and its verdict is the printed numbers.
|
||||
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- '.github/workflows/cold-pool-hunt.yml'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
engine_run_id:
|
||||
description: 'run of feder-cr/firefox_antidetect_patch whose asset-win-x86_64 artifact is the engine'
|
||||
required: false
|
||||
default: ''
|
||||
core_ref:
|
||||
description: 'ref of feder-cr/invisible_core that run built the engine with'
|
||||
required: false
|
||||
default: ''
|
||||
repetitions:
|
||||
description: 'how many times the test runs'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
ENGINE_RUN_ID: ${{ inputs.engine_run_id || '43188313516' }}
|
||||
ENGINE_REPO: feder-cr/firefox_antidetect_patch
|
||||
CORE_REF: ${{ inputs.core_ref || 'candidate/core-63-r5' }}
|
||||
# The wrapper that drives this engine: the tests come from this branch (a branch of udp/wrapper-r5), the package under them from udp/wrapper-r5.
|
||||
WRAPPER_REF: udp/wrapper-r5
|
||||
SEAL_TAG: firefox-63-candidate
|
||||
REPETITIONS: ${{ inputs.repetitions || '150' }}
|
||||
TEST_ID: tests/test_webrtc_realness.py::test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server
|
||||
# The core under test is the one the engine was built with, whatever this wrapper pins.
|
||||
INVISIBLE_CORE_AUTOFIX: 'off'
|
||||
INVISIBLE_CORE_PIN: allow
|
||||
|
||||
jobs:
|
||||
hunt:
|
||||
name: cold-pool hunt (windows-2022, engine of run ${{ inputs.engine_run_id || '43188313516' }})
|
||||
runs-on: windows-2022
|
||||
timeout-minutes: 240
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with: { fetch-depth: 1 }
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: The core of the run, then the wrapper, then the core again over it
|
||||
run: |
|
||||
CORE_GIT="git+https://github.com/feder-cr/invisible_core@$CORE_REF"
|
||||
python -m pip install --quiet --upgrade pip
|
||||
python -m pip install --quiet "$CORE_GIT"
|
||||
python -m pip install --quiet ".[dev]"
|
||||
python -m pip install --quiet --force-reinstall --no-deps "git+https://github.com/feder-cr/invisible_playwright@$WRAPPER_REF"
|
||||
python -m pip install --quiet --force-reinstall "$CORE_GIT"
|
||||
python -c "import importlib.metadata as m; print('installed: invisible-playwright', m.version('invisible-playwright'), '| invisible-core', m.version('invisible-core'))"
|
||||
python - <<'PY'
|
||||
import json, os, subprocess, sys
|
||||
from importlib.metadata import distribution, version
|
||||
ref = os.environ["CORE_REF"]
|
||||
rows = [line.split() for line in subprocess.run(
|
||||
["git", "ls-remote", "https://github.com/feder-cr/invisible_core", ref, ref + "^{}"],
|
||||
capture_output=True, text=True, check=True).stdout.splitlines() if line.strip()]
|
||||
peeled = [s for s, r in rows if r.endswith("^{}")]
|
||||
want = (peeled or [s for s, _ in rows] or [""])[0]
|
||||
import invisible_playwright # noqa: F401 - the import-time pin check runs here, as under pytest
|
||||
raw = distribution("invisible-core").read_text("direct_url.json")
|
||||
got = (json.loads(raw).get("vcs_info") or {}).get("commit_id") if raw else None
|
||||
print("core under test: %s from %s" % (version("invisible-core"), got or "the index"))
|
||||
if not want or got != want:
|
||||
sys.exit("THE CORE UNDER TEST IS NOT CORE_REF %s: installed from %s, the ref is %s" % (ref, got or "the index", want or "unknown"))
|
||||
PY
|
||||
- name: The engine of the run
|
||||
run: |
|
||||
mkdir -p engine
|
||||
gh run download "$ENGINE_RUN_ID" --repo "$ENGINE_REPO" --name asset-win-x86_64 --dir engine/archive
|
||||
ls -la engine/archive
|
||||
python - <<'PY'
|
||||
import glob, zipfile
|
||||
z = glob.glob("engine/archive/*.zip")[0]
|
||||
zipfile.ZipFile(z).extractall("engine/x")
|
||||
print("extracted", z)
|
||||
PY
|
||||
python -m invisible_core seal --binary engine/x/firefox.exe --tag "$SEAL_TAG" -o "$PWD/engine/seal.json"
|
||||
echo "INVPW_BINARY_PATH=$PWD/engine/x/firefox.exe" >> "$GITHUB_ENV"
|
||||
echo "STEALTHFOX_E2E_BINARY=$PWD/engine/x/firefox.exe" >> "$GITHUB_ENV"
|
||||
echo "INVISIBLE_SEAL_FILE=$PWD/engine/seal.json" >> "$GITHUB_ENV"
|
||||
- name: The test once, as the gate runs it (is the machine able to run it at all)
|
||||
run: |
|
||||
python -m pytest "$TEST_ID" -m e2e -p no:cacheprovider -q -rA || echo "the single run was red or skipped, the hunt goes on"
|
||||
- name: The hunt
|
||||
id: hunt
|
||||
run: python scripts/cold_pool_hunt.py --test "$TEST_ID" --repetitions "$REPETITIONS" --out hunt --greens 3 | tee hunt-report.txt
|
||||
- name: The numbers in the summary
|
||||
if: always()
|
||||
run: |
|
||||
{
|
||||
echo '### cold-pool hunt'
|
||||
echo
|
||||
echo "engine run $ENGINE_RUN_ID, core $CORE_REF, $REPETITIONS repetitions"
|
||||
echo
|
||||
echo '```'
|
||||
grep -E '^=== [0-9]+ red' hunt-report.txt || echo 'no summary line: the hunt did not finish'
|
||||
echo '```'
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Upload the logs of the red repetitions and of three green ones
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: cold-pool-hunt-${{ github.run_id }}
|
||||
path: |
|
||||
hunt
|
||||
hunt-report.txt
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
@@ -0,0 +1,9 @@
|
||||
[
|
||||
{"id": "wrapper.e2e.udp", "giro": "G2", "os": ["linux", "windows"], "min_tests": 41, "exact": true, "tests": ["tests/test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py", "tests/test_turn_over_tcp_is_tried_for_real_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_the_whole_udp_chain_by_name_e2e.py", "tests/test_declared_host_network_e2e.py", "tests/test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_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", "tests/test_webrtc_realness.py::test_a_proxy_whose_udp_leaves_from_another_address_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_relay_never_answers_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. 57 = 1+7+6+1+21 from the five files + 21 from the 10 UDP-line tests of test_webrtc_realness.py (parametrized)."},
|
||||
{"id": "wrapper.e2e.web", "giro": "G2", "os": ["linux", "windows"], "min_tests": 27, "exact": true, "tests": ["tests/test_networkidle_through_a_served_browser_with_routes_e2e.py", "tests/test_http3_through_the_proxy_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The networkidle e2e with routes and the HTTP/3 e2e, split from wrapper.e2e.udp (about 260 s of 500 on Linux; the whole suite did not fit the 15 minutes of Windows)."},
|
||||
{"id": "wrapper.e2e.doh", "giro": "G2", "os": ["linux", "windows"], "min_tests": 19, "exact": true, "tests": ["tests/test_the_hosts_file_of_the_host_is_never_read_e2e.py", "tests/test_resolver_race_e2e.py", "tests/test_doh_under_stress_e2e.py", "tests/test_context_proxy_only_resolves_by_doh_e2e.py", "tests/test_doh_through_the_proxy_e2e.py", "tests/test_ice_names_by_the_context_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.e2e.realness", "giro": "G2", "os": ["linux", "windows"], "min_tests": 32, "exact": true, "tests": ["tests/test_realness_behind_a_declared_exit_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "The realness check without a real proxy: six declared exits, the values a page reads, and the roads. Linux runs as root without xdist like the DoH suite (the resolver trap); on Windows the trap does not exist and the assertion on the system resolver is the only one omitted."},
|
||||
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 176, "exact": true, "tests": ["tests/test_the_doh_e2e_have_a_screen_on_linux.py", "tests/test_the_realness_helpers.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_host_address_helper.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", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added."},
|
||||
{"id": "wrapper.e2e.page", "giro": "G2", "os": ["linux", "windows"], "min_tests": 114, "exact": true, "tests": ["tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_popup_destinations_e2e.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_route_superseded_e2e.py"], "marker": "e2e", "needs_root": false, "note": "114 = 100 + the 14 of test_a_page_that_moves_on_e2e.py (a navigation the page overtook with location.replace ends; the engine fix 860ef8a6d9 is proved by it). 100 counted at the collection; was 96 = 10+32+16+34+4 before the popup tests of 6200bc2). A page is handed over when the engine says Page.ready; a popup reaches the client (link, noopener, window.open; own site and another; with and without a route; in-process and over launch_server) as Playwright's does; a superseded route. Needs the candidate binary, and the stock Playwright client of the dev extra."},
|
||||
{"id": "wrapper.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 34, "exact": true, "tests": ["tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_page_number_follows_the_call.py"], "marker": "unit", "needs_root": false, "note": "24 (counted at the collection; was 20 = 3+8+1+8 before 6200bc2). The page dispatcher's wait for Page.ready and what it hands over; the drive gate goes through the core (the engine waits for the session's road)."}
|
||||
]
|
||||
+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())
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Repeats ONE e2e test many times with the engine's SOCKS logs, one log folder per repetition, and reports the red ones with their times.
|
||||
|
||||
python scripts/cold_pool_hunt.py --test <nodeid> --repetitions 150 --out hunt [--greens 3]
|
||||
|
||||
For each repetition i the test runs alone in a fresh pytest process with
|
||||
MOZ_LOG="timestamp,sync,append,SOCKS:5,SOCKS-UDP:5,signaling:5" MOZ_LOG_FILE=<out>/rep-<i>/moz.log HUNT_EVENTS=<out>/rep-<i>/gateway.jsonl
|
||||
(`tests/_hunt_plugin.py` writes the wall-clock times of what the test gateway sees). A red repetition keeps its folder; the first
|
||||
`--greens` green ones keep theirs for comparison; the others are removed, so the artifact stays small. `append` keeps the logs of both engine
|
||||
launches of a repetition (the test launches two) in one file, told apart by the process id in each line.
|
||||
|
||||
It prints "red/total", and for every red repetition the sequence with times (see scripts/cold_pool_report.py). Exit 0: a red test is the
|
||||
finding, not a failure of the hunt; only a hunt that could not run at all (no pytest, no repetition finished) exits 1.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parent
|
||||
sys.path.insert(0, str(HERE))
|
||||
import cold_pool_report # noqa: E402
|
||||
|
||||
MOZ_LOG = "timestamp,sync,append,SOCKS:5,SOCKS-UDP:5,signaling:5"
|
||||
|
||||
|
||||
def one(test, folder, timeout):
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
env = dict(os.environ, MOZ_LOG=MOZ_LOG, MOZ_LOG_FILE=str(folder / "moz.log"), HUNT_EVENTS=str(folder / "gateway.jsonl"),
|
||||
PYTHONPATH=os.pathsep.join([str(ROOT / "tests"), os.environ.get("PYTHONPATH", "")]).rstrip(os.pathsep))
|
||||
cmd = [sys.executable, "-m", "pytest", test, "-m", "e2e", "-p", "_hunt_plugin", "-p", "no:cacheprovider", "-q", "-s", "-rA",
|
||||
"--timeout", str(timeout), "--timeout-method", "thread"]
|
||||
t0 = time.time()
|
||||
try:
|
||||
r = subprocess.run(cmd, cwd=str(ROOT), env=env, capture_output=True, text=True, timeout=timeout + 60)
|
||||
rc, out = r.returncode, r.stdout + r.stderr
|
||||
except subprocess.TimeoutExpired as e:
|
||||
rc, out = 124, "TIMEOUT\n%s" % ((e.stdout or b"").decode("utf-8", "replace") if isinstance(e.stdout, bytes) else (e.stdout or ""))
|
||||
(folder / "pytest.log").write_text(out, encoding="utf-8", errors="replace")
|
||||
(folder / "result.json").write_text(json.dumps({"rc": rc, "seconds": round(time.time() - t0, 1)}), encoding="utf-8")
|
||||
return rc
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--test", required=True)
|
||||
ap.add_argument("--repetitions", type=int, default=150)
|
||||
ap.add_argument("--out", default="hunt")
|
||||
ap.add_argument("--greens", type=int, default=3)
|
||||
ap.add_argument("--timeout", type=int, default=120, help="seconds one repetition may take")
|
||||
a = ap.parse_args()
|
||||
out = Path(a.out)
|
||||
shutil.rmtree(out, ignore_errors=True)
|
||||
out.mkdir(parents=True)
|
||||
reds, greens, errors, kept_green = [], 0, [], 0
|
||||
for i in range(1, a.repetitions + 1):
|
||||
folder = out / ("rep-%03d" % i)
|
||||
rc = one(a.test, folder, a.timeout)
|
||||
if rc == 0:
|
||||
greens += 1
|
||||
if kept_green < a.greens:
|
||||
kept_green += 1
|
||||
else:
|
||||
shutil.rmtree(folder, ignore_errors=True)
|
||||
elif rc == 1:
|
||||
reds.append(i)
|
||||
else:
|
||||
errors.append((i, rc))
|
||||
reds.append(i) # kept as well: a repetition that did not finish is not a green one
|
||||
print("repetition %03d: rc %s%s" % (i, rc, " (kept)" if folder.exists() else ""), flush=True)
|
||||
done = greens + len(reds)
|
||||
print("\n=== %d red / %d repetitions (%d green; %d ended with something other than pass/fail: %s)"
|
||||
% (len(reds), done, greens, len(errors), errors[:10]))
|
||||
summary = {"repetitions": done, "red": reds, "green": greens, "other": errors}
|
||||
(out / "summary.json").write_text(json.dumps(summary, indent=1), encoding="utf-8")
|
||||
for i in reds:
|
||||
print()
|
||||
print(cold_pool_report.report(out / ("rep-%03d" % i)))
|
||||
for folder in sorted(p for p in out.glob("rep-*") if p.name[4:] and int(p.name[4:]) not in reds):
|
||||
print()
|
||||
print("--- a green one, for comparison")
|
||||
print(cold_pool_report.report(folder))
|
||||
return 0 if done else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,112 @@
|
||||
"""The sequence with times of one repetition of the cold-pool hunt (scripts/cold_pool_hunt.py).
|
||||
|
||||
python scripts/cold_pool_report.py hunt/rep-007
|
||||
|
||||
Merges, on the wall clock, the engine's log (MOZ_LOG with `timestamp`, modules SOCKS, SOCKS-UDP, signaling) and the gateway's events
|
||||
(tests/_hunt_plugin.py): the first SOCKS5 connection, every UDP ASSOCIATE the gateway sees and every one the engine says is OK, the
|
||||
PeerConnection, every UDP layer pushed onto a socket, and for each push how many associations were ready (OK before it, minus the pushes
|
||||
before it, per engine process): 0 is a cold pool, the push had to open a new association. "Warm received" is not logged by the engine
|
||||
(nsSOCKSUDPIOLayerWarm has no log line): the associations that follow the first connection are its trace.
|
||||
"""
|
||||
import datetime
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
LINE = re.compile(r"^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d+) UTC - \[(\w+) (\d+):[^\]]*\]: (\w)/(\S+) (.*)$")
|
||||
|
||||
|
||||
def epoch(stamp):
|
||||
return datetime.datetime.strptime(stamp, "%Y-%m-%d %H:%M:%S.%f").replace(tzinfo=datetime.timezone.utc).timestamp()
|
||||
|
||||
|
||||
def engine_events(path):
|
||||
out = []
|
||||
if not path.exists():
|
||||
return out
|
||||
for raw in path.read_text(encoding="utf-8", errors="replace").splitlines():
|
||||
m = LINE.match(raw)
|
||||
if not m:
|
||||
continue
|
||||
stamp, process, pid, level, module, text = m.groups()
|
||||
out.append({"t": epoch(stamp), "process": process, "pid": int(pid), "level": level, "module": module, "text": text})
|
||||
return out
|
||||
|
||||
|
||||
def gateway_events(path):
|
||||
if not path.exists():
|
||||
return []
|
||||
return [json.loads(l) for l in path.read_text(encoding="utf-8").splitlines() if l.strip()]
|
||||
|
||||
|
||||
def classify(e):
|
||||
t = e["text"]
|
||||
if e["module"] == "SOCKS-UDP":
|
||||
if "UDP ASSOCIATE OK" in t:
|
||||
return "associate_ok"
|
||||
if "layer pushed onto fd" in t:
|
||||
return "pushed"
|
||||
if e["level"] == "E" or "failed" in t or "rejected" in t:
|
||||
return "udp_error"
|
||||
if e["module"] == "SOCKS" and "trying proxy server" in t:
|
||||
return "socks_tcp_first_try"
|
||||
if e["module"] == "SOCKS" and e["level"] == "E":
|
||||
return "socks_error"
|
||||
if e["module"] == "signaling" and "PeerConnectionImpl constructor" in t:
|
||||
return "peerconnection"
|
||||
return None
|
||||
|
||||
|
||||
def report(folder):
|
||||
folder = Path(folder)
|
||||
log = engine_events(folder / "moz.log")
|
||||
log += [e for p in sorted(folder.glob("moz.log.*")) for e in engine_events(p)] # child-process files, when the engine writes them
|
||||
gw = gateway_events(folder / "gateway.jsonl")
|
||||
rows = [] # (t, who, what, pid)
|
||||
for e in log:
|
||||
kind = classify(e)
|
||||
if kind:
|
||||
rows.append((e["t"], "engine %s %d" % (e["process"], e["pid"]), kind + (" " + e["text"][:70] if kind.endswith("error") else ""), e["pid"], kind))
|
||||
for e in gw:
|
||||
rows.append((e["t"], "gateway", e["kind"] + (" %s:%s" % (e.get("host"), e.get("port")) if e["kind"] == "connect" else ""), None, e["kind"]))
|
||||
rows.sort()
|
||||
result = {}
|
||||
try:
|
||||
result = json.loads((folder / "result.json").read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
lines = ["=== %s: rc %s, %s s" % (folder.name, result.get("rc"), result.get("seconds"))]
|
||||
pytest_log = (folder / "pytest.log")
|
||||
if pytest_log.exists():
|
||||
for l in pytest_log.read_text(encoding="utf-8", errors="replace").splitlines():
|
||||
if l.startswith("[page first]") or l.startswith("E ") and "srflx" in l:
|
||||
lines.append(" " + l[:260])
|
||||
if not rows:
|
||||
lines.append(" (no event: the engine wrote no log line and the gateway saw nothing)")
|
||||
return "\n".join(lines)
|
||||
t0 = next((r[0] for r in rows if r[4] in ("connect", "socks_tcp_first_try")), rows[0][0])
|
||||
ready = {} # pid -> associations OK minus pushes so far
|
||||
cold = []
|
||||
for t, who, what, pid, kind in rows:
|
||||
note = ""
|
||||
if kind == "associate_ok":
|
||||
ready[pid] = ready.get(pid, 0) + 1
|
||||
elif kind == "pushed":
|
||||
had = ready.get(pid, 0)
|
||||
note = " <- %d ready association(s) at this push%s" % (had, " COLD" if had < 1 else "")
|
||||
if had < 1:
|
||||
cold.append(t - t0)
|
||||
ready[pid] = max(0, had - 1)
|
||||
lines.append(" %+8.3f s %-24s %s%s" % (t - t0, who, what, note))
|
||||
first = lambda k: next((r[0] - t0 for r in rows if r[4] == k), None)
|
||||
fmt = lambda v: "-" if v is None else "%.3f s" % v
|
||||
lines.append(" summary: first SOCKS5 connection %s (gateway) | first association OK %s | PeerConnection %s | first push %s | cold pushes: %s"
|
||||
% (fmt(first("connect")), fmt(first("associate_ok")), fmt(first("peerconnection")), fmt(first("pushed")),
|
||||
", ".join("%.3f s" % c for c in cold) or "none"))
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
for arg in sys.argv[1:]:
|
||||
print(report(arg))
|
||||
@@ -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
|
||||
@@ -721,11 +721,12 @@ def _launch_params(session: Any, *, virtual_display: bool, headless: bool,
|
||||
from invisible_playwright._reaper import SessionToken
|
||||
|
||||
geo = prepare_session_geo(session._timezone, session._proxy,
|
||||
session._locale_requested)
|
||||
session._locale_requested, seed=session.seed,
|
||||
udp_stun_servers=session._udp_stun_servers)
|
||||
session._timezone = geo.timezone
|
||||
session._locale = geo.locale
|
||||
session._webrtc_egress_ip = geo.egress_ip
|
||||
session._srflx_declared = geo.srflx_to_declare()
|
||||
session._geolocation = geo.geolocation_override()
|
||||
executable = resolve_executable(session._binary_path)
|
||||
pw_headless = bool(headless)
|
||||
if not headless and virtual_display:
|
||||
@@ -778,6 +779,7 @@ def launch_server(host: str = DEFAULT_HOST, port: int = 0, *,
|
||||
context_options_override: bool = False,
|
||||
launch_timeout_ms: Optional[int] = 60000,
|
||||
on_engine_closed: Optional[Callable[[], None]] = None,
|
||||
udp_stun_servers: Optional[List[str]] = None,
|
||||
) -> RemoteServer:
|
||||
"""Launch ONE browser and serve it on a WebSocket; return when it listens
|
||||
and the browser is ready.
|
||||
@@ -789,7 +791,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
|
||||
@@ -806,6 +808,9 @@ def launch_server(host: str = DEFAULT_HOST, port: int = 0, *,
|
||||
`context_options_override=True`.
|
||||
on_engine_closed called, from another thread, when the engine dies
|
||||
(not when `close()` ends it).
|
||||
udp_stun_servers where a SOCKS5 proxy's UDP exit is measured from: "ip:port" IPv4 literals, None for the
|
||||
two public defaults. Kept on the session, so the launch and every context proxy a client
|
||||
later gives measure from the same list. Python only: nothing reaches the browser.
|
||||
The engine is the sealed one (`ensure_binary`, INVISIBLE_PLAYWRIGHT_ENGINE_DIR)
|
||||
and the launch FAILS if the version it reports is not the seal's.
|
||||
"""
|
||||
@@ -818,7 +823,7 @@ def launch_server(host: str = DEFAULT_HOST, port: int = 0, *,
|
||||
seed, pin=pin, headless=headless, proxy=proxy, extra_args=extra_args,
|
||||
humanize=humanize, locale=locale, timezone=timezone,
|
||||
extra_prefs=extra_prefs, binary_path=binary_path,
|
||||
show_cursor=show_cursor)
|
||||
show_cursor=show_cursor, udp_stun_servers=udp_stun_servers)
|
||||
notes: List[str] = []
|
||||
server = _SharedServer()
|
||||
endpoint: Optional[RemoteEndpoint] = None
|
||||
|
||||
@@ -71,6 +71,7 @@ from ._marshal import (_js_number, _as_script, _button, _caller_timeout,
|
||||
# here for the length of one fix. Two readings of what a proxy is would be
|
||||
# the same duplication that produced the defect, one layer down.
|
||||
from invisible_core import SessionLocale, parse_proxy
|
||||
from invisible_core._udp_exit import context_proxy_command, launch_proxy_command, stun_servers
|
||||
|
||||
from invisible_core import write_user_js
|
||||
from invisible_core.juggler import (SessionFiles, domain_matches, host_of,
|
||||
@@ -238,6 +239,12 @@ POINTER_PREF = "invisible.server.pointer"
|
||||
#: out here like the three above: the profile a launch writes is a composed
|
||||
#: session, or the server composes one (`session_for_launch`).
|
||||
COMPOSED_PREF = "invisible.server.composed"
|
||||
#: WHERE THE SESSION MEASURES A SOCKS5 PROXY'S UDP EXIT FROM (`udp_stun_servers=` of the launch, "ip:port" joined by
|
||||
#: commas). Like the seed it rides in the prefs the launcher composes, because that dict is the one thing that
|
||||
#: reaches this server from the session, and it is taken out in `op_launch` before the profile is written: it is
|
||||
#: a parameter of the Python launch, never a browser declaration. The server keeps it on the browser, so the launch
|
||||
#: and every later `new_context(proxy=...)` measure with the SAME list.
|
||||
UDP_STUN_PREF = "invisible.server.udp_stun_servers"
|
||||
#: The persona's keyboards, as Windows writes its input profiles (LANGID:KLID
|
||||
#: joined by semicolons, the language's first), decided by the core from the
|
||||
#: session's language AND country (`keyboard.profiles_for`). Server-only, like
|
||||
@@ -265,11 +272,21 @@ def take_session_motion(prefs: Dict) -> tuple:
|
||||
budget_ms = rest.pop(MOTION_BUDGET_PREF, None)
|
||||
rest.pop(POINTER_PREF, None)
|
||||
rest.pop(COMPOSED_PREF, None)
|
||||
rest.pop(UDP_STUN_PREF, None)
|
||||
return (rest,
|
||||
(None if seed is None else int(seed)),
|
||||
(None if budget_ms is None else int(budget_ms) / 1000.0))
|
||||
|
||||
|
||||
def session_udp_stun_servers(prefs: Dict) -> Optional[list]:
|
||||
"""The STUN servers the launcher named (`UDP_STUN_PREF`), validated again, or None for the defaults. Read
|
||||
BEFORE `take_session_motion` takes the key out."""
|
||||
value = prefs.get(UDP_STUN_PREF)
|
||||
if not value:
|
||||
return None
|
||||
return ["%s:%d" % server for server in stun_servers(str(value).split(","))]
|
||||
|
||||
|
||||
def session_for_launch(prefs: Dict, executable: str, proxy: Optional[Dict] = None) -> tuple:
|
||||
"""What a launch writes into its profile and adds to its environment: always a
|
||||
composed session. Returns (prefs, session_env).
|
||||
@@ -296,7 +313,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:
|
||||
@@ -4564,8 +4581,12 @@ class BrowserDispatcher(Dispatcher):
|
||||
conn: Any, version: str, session_seed: Any = None,
|
||||
motion_budget_s: Any = None,
|
||||
service_workers_enabled: bool = True,
|
||||
layout: str = "us", pointer_draws: bool = False) -> None:
|
||||
layout: str = "us", pointer_draws: bool = False,
|
||||
udp_stun_servers: Optional[list] = None) -> None:
|
||||
self.conn = conn
|
||||
#: Where this session measures a proxy's UDP exit from (the launch's `udp_stun_servers`, "ip:port"
|
||||
#: strings; None = the two public defaults): the launch and every context proxy use the same list.
|
||||
self.udp_stun_servers = udp_stun_servers
|
||||
#: Whether this browser's pages walk the pointer onto their targets
|
||||
#: (`pointer.py`): the launcher chose the Python generator. Off for a
|
||||
#: browser built without saying so, which acts as the caller wrote.
|
||||
@@ -4649,8 +4670,10 @@ class BrowserDispatcher(Dispatcher):
|
||||
self._adoptions: Dict[str, _Adoption] = {}
|
||||
#: The last 16 targets that were NOT announced (dropped with their context, or failed), with their trace: for whoever looks.
|
||||
self._dropped: "collections.deque" = collections.deque(maxlen=16)
|
||||
#: The opener of the last 16 targets whose adoption ended WITHOUT announcing them: a download that comes after the record is gone is
|
||||
#: still said on the opener (it is never lost, whichever step of the adoption it falls between).
|
||||
#: The opener of the targets whose adoption ended WITHOUT announcing them while the engine still had the target (at most the last
|
||||
#: 16): a download that comes after the record is gone is still said on the opener (it is never lost, whichever step of the
|
||||
#: adoption it falls between). The entry lives until the engine detaches the target (`_handle_detach`), and none is made for a
|
||||
#: target already detached: no download can come from it any more.
|
||||
self._gone_openers: "collections.OrderedDict" = collections.OrderedDict()
|
||||
#: Adoption failures, by target. The `newPage` waiter re-raises (and
|
||||
#: pops) them; capped because a spontaneous popup nobody waits for
|
||||
@@ -4923,7 +4946,7 @@ class BrowserDispatcher(Dispatcher):
|
||||
|
||||
def _remember_opener(self, adoption: Optional["_Adoption"]) -> None:
|
||||
"""Under `_targets_lock`, in the step that removes the record of a target that is NOT announced."""
|
||||
if adoption is not None and adoption.opener is not None:
|
||||
if adoption is not None and adoption.opener is not None and not adoption.gone:
|
||||
self._gone_openers[adoption.target_id] = adoption.opener
|
||||
while len(self._gone_openers) > 16:
|
||||
self._gone_openers.popitem(last=False)
|
||||
@@ -5113,6 +5136,8 @@ class BrowserDispatcher(Dispatcher):
|
||||
return
|
||||
waiting = None
|
||||
with self._targets_lock:
|
||||
# The target is gone: nothing comes from it any more, so the opener kept for its downloads goes too.
|
||||
self._gone_openers.pop(target_id, None)
|
||||
adoption = self._adoptions.get(target_id)
|
||||
if adoption is not None:
|
||||
adoption.gone = True
|
||||
@@ -5309,7 +5334,13 @@ class BrowserDispatcher(Dispatcher):
|
||||
# a context whose proxy cannot be expressed must not come back usable.
|
||||
if params.get("proxy"):
|
||||
try:
|
||||
proxy = parse_proxy(params["proxy"]).as_engine_command()
|
||||
# ⛔ MEASURED BEFORE IT IS SENT. The proxy's UDP exit (does its UDP leave from the address of its TCP?)
|
||||
# travels in this very command, as `udp`, and without it the engine drops the UDP of every SOCKS5
|
||||
# proxy. The core discovers the TCP exit through the proxy and measures the UDP beside it, once per
|
||||
# proxy (cached by endpoint, a hash of the credentials and the servers), from the STUN servers the
|
||||
# SESSION was launched with: this is the ONE place a context's proxy is applied, for the sync and
|
||||
# async clients and for a remote one alike. A `udp` key in what the caller wrote is not read.
|
||||
proxy = context_proxy_command(params["proxy"], self.udp_stun_servers)
|
||||
except ValueError as exc:
|
||||
raise ProtocolException(
|
||||
"new_context(proxy=...) cannot be applied: %s" % exc)
|
||||
@@ -5625,6 +5656,8 @@ class BrowserTypeDispatcher(Dispatcher):
|
||||
# `conn.close` has waited for the browser to exit.
|
||||
launch_prefs, session_env = session_for_launch(
|
||||
params.get("firefoxUserPrefs") or {}, executable, params.get("proxy"))
|
||||
# Read BEFORE `take_session_motion` takes it out: it never reaches the profile.
|
||||
udp_stun_servers = session_udp_stun_servers(launch_prefs)
|
||||
environment = _launch_environment(params.get("env"))
|
||||
named = {e["name"] for e in params.get("env") or []}
|
||||
environment.update({k: v for k, v in session_env.items() if k not in named})
|
||||
@@ -5675,15 +5708,17 @@ class BrowserTypeDispatcher(Dispatcher):
|
||||
proxy = None
|
||||
if params.get("proxy"):
|
||||
try:
|
||||
proxy = parse_proxy(params["proxy"]).as_engine_command()
|
||||
# The measure is the one the launch's geo step remembered for this proxy and these servers (nothing is
|
||||
# asked of the network here): `unmeasured` when there is none, never a claimed `coherent`.
|
||||
proxy = launch_proxy_command(params["proxy"], udp_stun_servers)
|
||||
except ValueError as exc:
|
||||
raise ProtocolException("launch(proxy=...) cannot be applied: "
|
||||
"%s" % exc)
|
||||
# ⛔ 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,
|
||||
@@ -5704,7 +5739,8 @@ class BrowserTypeDispatcher(Dispatcher):
|
||||
# The persona's keyboard: the one a Windows install gives the
|
||||
# session's language in its country (German in Switzerland
|
||||
# types on the Swiss keyboard).
|
||||
layout=keyboard_layout, pointer_draws=pointer_draws)
|
||||
layout=keyboard_layout, pointer_draws=pointer_draws,
|
||||
udp_stun_servers=udp_stun_servers)
|
||||
except BaseException:
|
||||
conn.close()
|
||||
raise
|
||||
|
||||
@@ -26,7 +26,7 @@ from ._cursor import (ENGINE_BINARY,
|
||||
enable_for as _enable_cursor_engine,
|
||||
max_seconds_for as _cursor_max_seconds)
|
||||
from ._engine import resolve_executable
|
||||
from ._juggler.server import COMPOSED_PREF, MOTION_BUDGET_PREF, POINTER_PREF, SESSION_SEED_PREF
|
||||
from ._juggler.server import COMPOSED_PREF, MOTION_BUDGET_PREF, POINTER_PREF, SESSION_SEED_PREF, UDP_STUN_PREF
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from invisible_core import compose_session_prefs, context_geometry, make_virtual_display
|
||||
@@ -65,11 +65,22 @@ __all__ = ["build_prefs", "true_headless_requested", "TRUE_HEADLESS_ENV",
|
||||
TRUE_HEADLESS_ENV = "INVPW_TRUE_HEADLESS"
|
||||
|
||||
|
||||
def session_geo(timezone: str, proxy: Optional[Dict[str, str]], locale: Any):
|
||||
def udp_stun_list(servers: Optional[Any]) -> Optional[list]:
|
||||
"""The `udp_stun_servers=` of a launch, validated by the core ("ip:port" IPv4 literals; a name or a bad port
|
||||
raises ValueError naming the parameter) and normalised to "ip:port" strings; None for the two public defaults."""
|
||||
if servers is None:
|
||||
return None
|
||||
from invisible_core._udp_exit import stun_servers
|
||||
return ["%s:%d" % server for server in stun_servers(servers)]
|
||||
|
||||
|
||||
def session_geo(timezone: str, proxy: Optional[Dict[str, str]], locale: Any,
|
||||
seed: Optional[int] = None):
|
||||
"""`invisible_core.prepare_session_geo`, the one network step of composing a
|
||||
session (the egress IP). One name, so a hermetic test replaces it alone."""
|
||||
session (the egress IP). One name, so a hermetic test replaces it alone.
|
||||
The seed places the session on the map (the declared position)."""
|
||||
from invisible_core import prepare_session_geo
|
||||
return prepare_session_geo(timezone, proxy, locale)
|
||||
return prepare_session_geo(timezone, proxy, locale, seed=seed)
|
||||
|
||||
|
||||
def default_session(executable: Optional[str] = None,
|
||||
@@ -83,14 +94,23 @@ def default_session(executable: Optional[str] = None,
|
||||
What `server.session_for_launch` gives a launch that names no session."""
|
||||
from .launcher import InvisiblePlaywright
|
||||
session = InvisiblePlaywright(binary_path=executable, humanize=False, proxy=proxy or None)
|
||||
geo = session_geo(session._timezone, session._proxy, session._locale_requested)
|
||||
geo = session_geo(session._timezone, session._proxy, session._locale_requested,
|
||||
seed=session.seed)
|
||||
session._timezone, session._locale = geo.timezone, geo.locale
|
||||
session._geolocation = geo.geolocation_override()
|
||||
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 +119,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 +182,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)
|
||||
|
||||
@@ -182,6 +198,7 @@ def build_prefs(
|
||||
humanize: Any,
|
||||
show_cursor: Optional[bool] = None,
|
||||
session_seed: Optional[int] = None,
|
||||
udp_stun_servers: Optional[Any] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Fingerprint prefs plus the humanize toggle, which is always set explicitly.
|
||||
|
||||
@@ -265,6 +282,10 @@ def build_prefs(
|
||||
# The persona's keyboards are in the prefs already: the core declares them
|
||||
# with the language and country (invisible_core.prefs._apply_locale).
|
||||
prefs[COMPOSED_PREF] = True
|
||||
# ⛔ THE STUN SERVERS OF THE UDP-EXIT MEASUREMENT ride here for the server only (`UDP_STUN_PREF`): `op_launch`
|
||||
# takes the key out before the profile is written, as it does the seed. Not written when the launch named none.
|
||||
if udp_stun_servers:
|
||||
prefs[UDP_STUN_PREF] = ",".join(udp_stun_servers)
|
||||
if session_seed is not None and humanize:
|
||||
prefs[SESSION_SEED_PREF] = int(session_seed)
|
||||
prefs[POINTER_PREF] = cursor_engine == ENGINE_PYTHON
|
||||
@@ -279,16 +300,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
|
||||
@@ -302,9 +321,9 @@ class ProxyEgressNonVerificabile(RuntimeError):
|
||||
|
||||
This is not drift and it is not parity: it is absence of measurement. A
|
||||
proxy that does not answer the probe for several checks in a row is not a
|
||||
proxy that holds, it is a proxy we are flying blind on while the engine
|
||||
keeps declaring to every page an address that nobody is confirming any
|
||||
more.
|
||||
proxy that holds, it is a proxy we are flying blind on while the timezone
|
||||
and the locale, decided from the egress at launch, go on being declared
|
||||
to every page with nobody confirming the egress they came from any more.
|
||||
"""
|
||||
|
||||
|
||||
@@ -384,10 +403,22 @@ 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
|
||||
`__init__`. They already did, identically, which is why this works at all.
|
||||
`_network_declared`, `_timezone` and `_virtual_display` in their own
|
||||
`__init__`; `_geolocation` (the position the session declares, the
|
||||
``geolocation`` object of a context, None until `__enter__` decides it
|
||||
and when the exit has no point) is the class default below. They already did, identically, which is why this works at all.
|
||||
"""
|
||||
|
||||
#: The position this session declares to the engine
|
||||
#: (``SessionGeo.geolocation_override()``: latitude, longitude, accuracy),
|
||||
#: or None. Set by `__enter__` from the egress, like `_timezone`.
|
||||
_geolocation: Optional[Dict[str, float]] = None
|
||||
|
||||
#: Where this session measures a SOCKS5 proxy's UDP exit from: the ``udp_stun_servers=`` of the launch, as
|
||||
#: "ip:port" strings (validated by the core), or None for the two public defaults. Kept on the session so the
|
||||
#: launch geo step and the browser's later context proxies use the same list.
|
||||
_udp_stun_servers: Optional[list] = None
|
||||
|
||||
def _resolve_headless(self) -> bool:
|
||||
"""Translate the user's ``headless`` flag.
|
||||
|
||||
@@ -443,13 +474,23 @@ class CommonLaunch:
|
||||
# None before __enter__ has decided.
|
||||
if self._locale is not None:
|
||||
kwargs["locale"] = self._locale.primary
|
||||
# The position the core declares for this machine. It travels as the
|
||||
# standard `geolocation` context option, so the engine gets
|
||||
# `Browser.setGeolocationOverride` for EVERY context (the default one
|
||||
# and each `new_context`/`new_page`), a caller's own `geolocation=`
|
||||
# wins like any other default, and the PERMISSION is not granted here:
|
||||
# the page's grant (the caller's `grant_permissions`) is what makes the
|
||||
# engine answer. The override belongs to each context (Juggler keys it
|
||||
# by `browserContextId`), so a context that closes takes its own with it.
|
||||
if self._geolocation is not None:
|
||||
kwargs["geolocation"] = dict(self._geolocation)
|
||||
return kwargs
|
||||
|
||||
def _build_env(self, prefs: Dict[str, Any]) -> Dict[str, str]:
|
||||
"""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 +499,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))
|
||||
@@ -481,6 +522,7 @@ class CommonLaunch:
|
||||
humanize=self._humanize,
|
||||
show_cursor=self._show_cursor,
|
||||
session_seed=self.seed,
|
||||
udp_stun_servers=self._udp_stun_servers,
|
||||
)
|
||||
|
||||
def _arm_cursor_engine(self, owner: Any) -> None:
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional, Union
|
||||
from typing import Any, Dict, Optional, Sequence, Union
|
||||
|
||||
from invisible_playwright._pw.async_api import Browser, BrowserContext, Playwright, async_playwright
|
||||
from invisible_playwright._pw._impl._browser_context import page_number_reserved
|
||||
@@ -37,6 +37,7 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
profile_dir: Optional[Union[str, Path]] = None,
|
||||
prep_recaptcha: bool = False,
|
||||
show_cursor: Optional[bool] = None,
|
||||
udp_stun_servers: Optional[Sequence[str]] = None,
|
||||
) -> None:
|
||||
# See sync launcher: `zoom.stealth.fpp.hw_seed` is int32_t - clamp.
|
||||
# One place decides the seed, and a profile directory remembers it
|
||||
@@ -45,6 +46,8 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
self._pin = pin
|
||||
self._headless = headless
|
||||
self._proxy = proxy
|
||||
# See the sync launcher: validated now, kept for the launch and for every context proxy.
|
||||
self._udp_stun_servers = _session.udp_stun_list(udp_stun_servers)
|
||||
self._extra_args = list(extra_args or [])
|
||||
self._humanize = humanize
|
||||
# See the sync launcher: who draws the cursor path (this package by
|
||||
@@ -88,13 +91,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
|
||||
@@ -111,22 +112,13 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
# session keeps the core's DECISION (a SessionLocale). See the sync
|
||||
# launcher.
|
||||
_geo = await asyncio.to_thread(
|
||||
prepare_session_geo, self._timezone, self._proxy, self._locale_requested
|
||||
prepare_session_geo, self._timezone, self._proxy, self._locale_requested,
|
||||
seed=self.seed, udp_stun_servers=self._udp_stun_servers,
|
||||
)
|
||||
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()
|
||||
self._geolocation = _geo.geolocation_override()
|
||||
# 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 +183,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 +202,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 +222,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
|
||||
|
||||
@@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional, Union
|
||||
from typing import Any, Dict, Optional, Sequence, Union
|
||||
|
||||
from invisible_playwright._pw.sync_api import Browser, BrowserContext, Playwright, sync_playwright
|
||||
|
||||
@@ -101,6 +101,7 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
profile_dir: Optional[Union[str, Path]] = None,
|
||||
prep_recaptcha: bool = False,
|
||||
show_cursor: Optional[bool] = None,
|
||||
udp_stun_servers: Optional[Sequence[str]] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Args:
|
||||
@@ -185,6 +186,10 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
self._pin = pin
|
||||
self._headless = headless
|
||||
self._proxy = proxy
|
||||
# Where a SOCKS5 proxy's UDP exit is measured from ("ip:port" IPv4 literals; None = the two public
|
||||
# defaults). Validated now, kept on the session for the launch AND for every context proxy; a parameter of
|
||||
# this Python launch only: nothing of it is put in the browser's environment, argv, prefs or pipe.
|
||||
self._udp_stun_servers = _session.udp_stun_list(udp_stun_servers)
|
||||
self._extra_args = list(extra_args or [])
|
||||
self._humanize = humanize
|
||||
# Who draws the cursor path: this package (default), the browser
|
||||
@@ -235,14 +240,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
|
||||
@@ -260,21 +262,12 @@ class InvisiblePlaywright(_session.CommonLaunch):
|
||||
# The language is decided in the same call, from the same egress: the
|
||||
# core resolves "auto" and applies Firefox's language table, and this
|
||||
# session keeps the DECISION (a SessionLocale), never a tag of its own.
|
||||
_geo = prepare_session_geo(self._timezone, self._proxy, self._locale_requested)
|
||||
_geo = prepare_session_geo(self._timezone, self._proxy, self._locale_requested,
|
||||
seed=self.seed, udp_stun_servers=self._udp_stun_servers)
|
||||
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()
|
||||
self._geolocation = _geo.geolocation_override()
|
||||
# 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 +402,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 +426,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 +436,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 +506,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,731 @@
|
||||
"""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.errors
|
||||
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, QTYPE_HTTPS = 1, 28, 65
|
||||
RCODE_OK, RCODE_SERVFAIL, RCODE_NXDOMAIN, RCODE_REFUSED = 0, 2, 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", 503: "Service Unavailable"}
|
||||
|
||||
|
||||
class DohQuery(NamedTuple):
|
||||
name: str
|
||||
qtype: int
|
||||
via: str
|
||||
|
||||
|
||||
#: The ways :class:`FakeDoh` can refuse a query (``fail_first``). All three are failures of the lookup for Firefox's TRR:
|
||||
#: ``close`` ends the exchange with no answer (an h2 stream reset, or a closed connection over HTTP/1.1): a failure of
|
||||
#: the CHANNEL, the kind ``TRRService::ConfirmationContext::RecordTRRStatus`` counts (``NS_FAILED(channelStatus)``);
|
||||
#: ``http503`` answers an HTTP error (``TRR_SERVER_RESPONSE_ERR``); ``servfail`` answers a well-formed DNS message with
|
||||
#: rcode 2 (``TRR_RCODE_FAIL``).
|
||||
FAILURE_KINDS = ("close", "http503", "servfail")
|
||||
|
||||
|
||||
class DohAnswer(NamedTuple):
|
||||
"""What the FakeDoh did with one query: ``outcome`` is ``"answered"`` or a failure kind, ``delay`` the seconds
|
||||
between the arrival of the query and the moment its answer (or its refusal) was sent."""
|
||||
name: str
|
||||
qtype: int
|
||||
via: str
|
||||
outcome: str
|
||||
delay: float
|
||||
|
||||
|
||||
class _Reply(NamedTuple):
|
||||
status: int
|
||||
body: bytes
|
||||
content_type: str
|
||||
delay: float = 0.0
|
||||
close: bool = False # no answer at all: reset the stream / close the connection
|
||||
record: Optional[Tuple[str, int, str, str]] = None # (name, qtype, via, outcome), logged when it is sent
|
||||
|
||||
|
||||
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,
|
||||
delay_s: float = 0.0, delay_names: Optional[Dict[str, float]] = None,
|
||||
fail_first: Optional[Dict[str, str]] = 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)
|
||||
#: Latency of EVERY answer, in seconds (each response is held that long after its query arrived, not only the
|
||||
#: connection set-up); ``delay_names`` overrides it per name (a name or any name under it). Both can be changed
|
||||
#: while the server runs. Over h2 the answers are held independently, so the A and the AAAA of one lookup come
|
||||
#: back together after the delay, not one after the other.
|
||||
self.delay_s = delay_s
|
||||
self.delay_names: Dict[str, float] = {k.lower().rstrip("."): v for k, v in (delay_names or {}).items()}
|
||||
#: ``{name: kind}`` (kind in :data:`FAILURE_KINDS`): the FIRST query of each type (A, AAAA...) for ``name`` is
|
||||
#: refused in that way; every later one is served as usual. Can be changed while the server runs.
|
||||
self.fail_first: Dict[str, str] = {k.lower().rstrip("."): v for k, v in (fail_first or {}).items()}
|
||||
for kind in self.fail_first.values():
|
||||
if kind not in FAILURE_KINDS:
|
||||
raise ValueError("unknown failure kind %r, expected one of %s" % (kind, FAILURE_KINDS))
|
||||
#: What was done with every query, in the order it was SENT (see :class:`DohAnswer`).
|
||||
self.answers: List[DohAnswer] = []
|
||||
self._failed: Set[Tuple[str, int]] = set()
|
||||
#: Every query, in order.
|
||||
self.queries: List[DohQuery] = []
|
||||
#: The names for which this server answered a type 65 (HTTPS) query WITH DATA. It never does: the retail Firefox reads
|
||||
#: h3 at its first visit when the DNS answer carries that record, so a test that expects h2 first (the h3 e2e) asserts
|
||||
#: that this stays empty, and says so if the server learns to serve it.
|
||||
self.https_served: List[str] = []
|
||||
#: 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 answers_for(self, name: str, qtype: Optional[int] = None) -> List[DohAnswer]:
|
||||
name = name.lower().rstrip(".")
|
||||
with self._lock:
|
||||
return [a for a in self.answers if a.name == name and (qtype is None or a.qtype == 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 _delay_of(self, name: str) -> float:
|
||||
for key, seconds in self.delay_names.items():
|
||||
if name == key or name.endswith("." + key):
|
||||
return seconds
|
||||
return self.delay_s
|
||||
|
||||
def _record(self, record: Optional[Tuple[str, int, str, str]], received: float) -> None:
|
||||
"""Log that an answer is being sent now (``received`` is the monotonic time its query arrived)."""
|
||||
if record is not None:
|
||||
with self._lock:
|
||||
self.answers.append(DohAnswer(*record, time.monotonic() - received))
|
||||
|
||||
def _answer(self, via: str, method: str, target: str, content_type: str, body: bytes) -> _Reply:
|
||||
"""What to send for one HTTP request, recording the DNS query it carries."""
|
||||
def bad(status: int) -> _Reply:
|
||||
with self._lock:
|
||||
self.bad_requests.append((via, method, target, status))
|
||||
return _Reply(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)
|
||||
kind = self.fail_first.get(query.name)
|
||||
if kind is not None and (query.name, query.qtype) in self._failed:
|
||||
kind = None
|
||||
elif kind is not None:
|
||||
self._failed.add((query.name, query.qtype))
|
||||
delay = self._delay_of(query.name)
|
||||
record = (query.name, query.qtype, via, kind or "answered")
|
||||
if kind == "close":
|
||||
return _Reply(0, b"", "", delay, True, record)
|
||||
if kind == "http503":
|
||||
return _Reply(503, b"", "text/plain", delay, False, record)
|
||||
if kind == "servfail":
|
||||
return _Reply(200, build_response(query, RCODE_SERVFAIL), "application/dns-message", delay, False, record)
|
||||
message = answer_for(names, query)
|
||||
if query.qtype == QTYPE_HTTPS and struct.unpack("!H", message[6:8])[0] > 0:
|
||||
with self._lock:
|
||||
self.https_served.append(query.name)
|
||||
return _Reply(200, message, "application/dns-message", delay, False, record)
|
||||
|
||||
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:]
|
||||
received = time.monotonic()
|
||||
reply = self._answer(via, method, target, headers.get("content-type", ""), body)
|
||||
if reply.delay:
|
||||
time.sleep(reply.delay)
|
||||
self._record(reply.record, received)
|
||||
if reply.close:
|
||||
return
|
||||
status, payload, content_type = reply.status, reply.body, reply.content_type
|
||||
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] = {}
|
||||
#: Answers being held back: (due monotonic time, stream id, reply, monotonic time the query arrived). One thread
|
||||
#: reads, holds and writes, so the TLS socket never has a reader and a writer at once, and the answers of one
|
||||
#: connection are held independently of each other (the A and the AAAA of a lookup both wait ``delay``).
|
||||
held: List[Tuple[float, int, _Reply, float]] = []
|
||||
tls.settimeout(0.05)
|
||||
last_activity = time.monotonic()
|
||||
|
||||
def send(stream_id: int, reply: _Reply, received: float) -> None:
|
||||
self._record(reply.record, received)
|
||||
try:
|
||||
if reply.close:
|
||||
connection.reset_stream(stream_id, error_code=h2.errors.ErrorCodes.INTERNAL_ERROR)
|
||||
else:
|
||||
connection.send_headers(stream_id, [
|
||||
(":status", str(reply.status)), ("content-type", reply.content_type),
|
||||
("content-length", str(len(reply.body))), ("cache-control", "max-age=%d" % DOH_TTL)])
|
||||
connection.send_data(stream_id, reply.body, end_stream=True)
|
||||
except h2.exceptions.H2Error: # the client reset the stream while its answer was held
|
||||
pass
|
||||
|
||||
while True:
|
||||
now = time.monotonic()
|
||||
for item in [h for h in held if h[0] <= now]:
|
||||
held.remove(item)
|
||||
send(item[1], item[2], item[3])
|
||||
pending = connection.data_to_send()
|
||||
if pending:
|
||||
tls.sendall(pending)
|
||||
try:
|
||||
data = tls.recv(65536)
|
||||
except (socket.timeout, ssl.SSLWantReadError):
|
||||
if not held and time.monotonic() - last_activity > 60:
|
||||
return
|
||||
continue
|
||||
if not data:
|
||||
return
|
||||
last_activity = time.monotonic()
|
||||
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"]
|
||||
received = time.monotonic()
|
||||
reply = self._answer(
|
||||
via, headers.get(":method", ""), headers.get(":path", ""),
|
||||
headers.get("content-type", ""), request["body"])
|
||||
if reply.delay:
|
||||
held.append((received + reply.delay, event.stream_id, reply, received))
|
||||
else:
|
||||
send(event.stream_id, reply, received)
|
||||
elif isinstance(event, h2.events.StreamReset):
|
||||
streams.pop(event.stream_id, None)
|
||||
held[:] = [h for h in held if h[1] != event.stream_id]
|
||||
elif isinstance(event, h2.events.ConnectionTerminated):
|
||||
return
|
||||
|
||||
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", "QTYPE_HTTPS", "RCODE_NXDOMAIN", "RCODE_OK", "RCODE_REFUSED", "RCODE_SERVFAIL", "DohAnswer", "DohGateway", "DohQuery",
|
||||
"FAILURE_KINDS", "FakeDoh", "Query",
|
||||
"answer_for", "build_response", "encode_query", "is_loopback", "make_certificate", "parse_query", "pump",
|
||||
"relay", "wait_until",
|
||||
]
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Support of the DoH e2e files and of the fixtures of conftest.py that serve them (no pytest in here)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
def a_display_when_the_host_has_none() -> dict:
|
||||
"""The launch arguments that give a browser a screen on a Linux machine that has none (a CI runner, a root
|
||||
shell under ``sudo``): ``headless=True`` is a headed browser on a virtual display the wrapper starts itself. A
|
||||
machine with a display of its own, and Windows, are left as they are."""
|
||||
if sys.platform.startswith("linux") and not os.environ.get("DISPLAY"):
|
||||
return {"headless": True}
|
||||
return {}
|
||||
|
||||
|
||||
#: 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"}
|
||||
|
||||
|
||||
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()
|
||||
@@ -0,0 +1,236 @@
|
||||
"""A local HTTPS server that speaks HTTP/3 as well, reached by its address.
|
||||
|
||||
The same port answers TCP (TLS, HTTP/2 by ALPN with an `Alt-Svc: h3` header, HTTP/1.1 for a client that offers nothing
|
||||
else) and UDP (QUIC, HTTP/3, aioquic), with a self-signed certificate for the address it is given. The TCP side speaks HTTP/2
|
||||
because that is what a real site does: the FIRST visit of a page reads `h2`, and only after the Alt-Svc it carries may a
|
||||
later one read `h3` (retail Firefox 159, native DNS in loopback: h2, h3, h3; behind a proxy h3 within a few visits, and at the first one when the DNS answer carries the HTTPS record: 3 sessions of 15 in the third run). 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` and `h2` (pip install aioquic h2; the dev extra installs both).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import datetime
|
||||
import ipaddress
|
||||
import socket
|
||||
import socketserver
|
||||
import ssl
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import List, Tuple
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
#: The one document every path answers, over TCP and over QUIC.
|
||||
PAGE = b"<!doctype html><meta charset=utf-8><title>h3</title><p>ok</p>"
|
||||
|
||||
|
||||
class _TcpServer(socketserver.ThreadingTCPServer):
|
||||
allow_reuse_address = True
|
||||
daemon_threads = True
|
||||
|
||||
|
||||
class _TcpHandler(socketserver.BaseRequestHandler):
|
||||
"""One TCP connection: the TLS handshake here (not in the accept loop), then HTTP/2 or HTTP/1.1 by the ALPN."""
|
||||
|
||||
def handle(self):
|
||||
owner = self.server.owner
|
||||
try:
|
||||
self.request.settimeout(10)
|
||||
tls = owner._tls.wrap_socket(self.request, server_side=True)
|
||||
except (ssl.SSLError, OSError):
|
||||
return
|
||||
try:
|
||||
tls.settimeout(60)
|
||||
alpn = tls.selected_alpn_protocol() or "http/1.1"
|
||||
owner.tcp_alpn.append(alpn)
|
||||
if alpn == "h2":
|
||||
self._h2(tls, owner)
|
||||
else:
|
||||
self._http1(tls, owner)
|
||||
except (ssl.SSLError, OSError):
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
tls.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def _h2(tls, owner):
|
||||
import h2.config
|
||||
import h2.connection
|
||||
import h2.events
|
||||
import h2.exceptions
|
||||
|
||||
conn = h2.connection.H2Connection(config=h2.config.H2Configuration(client_side=False, header_encoding="utf-8"))
|
||||
conn.initiate_connection()
|
||||
tls.sendall(conn.data_to_send())
|
||||
while True:
|
||||
data = tls.recv(65536)
|
||||
if not data:
|
||||
return
|
||||
try:
|
||||
events = conn.receive_data(data)
|
||||
except h2.exceptions.ProtocolError:
|
||||
tls.sendall(conn.data_to_send())
|
||||
return
|
||||
for event in events:
|
||||
if isinstance(event, h2.events.RequestReceived):
|
||||
owner.tcp_requests.append(dict(event.headers).get(":path", ""))
|
||||
conn.send_headers(event.stream_id, [
|
||||
(":status", "200"), ("content-type", "text/html; charset=utf-8"),
|
||||
("content-length", str(len(PAGE))), ("alt-svc", owner.alt_svc),
|
||||
("access-control-allow-origin", "*")])
|
||||
conn.send_data(event.stream_id, PAGE, end_stream=True)
|
||||
elif isinstance(event, h2.events.DataReceived):
|
||||
conn.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
|
||||
elif isinstance(event, h2.events.ConnectionTerminated):
|
||||
return
|
||||
out = conn.data_to_send()
|
||||
if out:
|
||||
tls.sendall(out)
|
||||
|
||||
@staticmethod
|
||||
def _http1(tls, owner):
|
||||
head = b""
|
||||
while b"\r\n\r\n" not in head:
|
||||
chunk = tls.recv(4096)
|
||||
if not chunk:
|
||||
return
|
||||
head += chunk
|
||||
parts = head.split(b"\r\n", 1)[0].split(b" ")
|
||||
owner.tcp_requests.append(parts[1].decode("latin-1") if len(parts) > 1 else "")
|
||||
tls.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: %d\r\n"
|
||||
b"Alt-Svc: %s\r\nAccess-Control-Allow-Origin: *\r\nConnection: close\r\n\r\n%s"
|
||||
% (len(PAGE), owner.alt_svc.encode(), PAGE))
|
||||
|
||||
|
||||
class H3Server:
|
||||
"""TCP+TLS (HTTP/2) and QUIC (HTTP/3) 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 same peers with the port they sent from: (address, port). On a machine where a gateway's relay sends from an address of
|
||||
#: this host (Windows cannot send from 127.0.0.1 to it) the address cannot tell the relay from a client that came direct; its port can.
|
||||
self.quic_peer_addrs: List[Tuple[str, int]] = []
|
||||
#: The paths of the requests that were answered over HTTP/3, and over TCP.
|
||||
self.h3_requests: List[str] = []
|
||||
self.tcp_requests: List[str] = []
|
||||
#: The ALPN each TCP connection negotiated ("h2", or "http/1.1").
|
||||
self.tcp_alpn: List[str] = []
|
||||
self._dir = tempfile.TemporaryDirectory()
|
||||
cert, key = _certificate(address, Path(self._dir.name))
|
||||
|
||||
server = self
|
||||
|
||||
# One port for both: the TCP port first, then the same number for UDP.
|
||||
for _ in range(50):
|
||||
tcp = _TcpServer((address, 0), _TcpHandler)
|
||||
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
|
||||
#: What the TCP answer says about HTTP/3: the same port, for an hour.
|
||||
self.alt_svc = 'h3=":%d"; ma=3600' % port
|
||||
self._tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
self._tls.load_cert_chain(str(cert), str(key))
|
||||
self._tls.set_alpn_protocols(["h2", "http/1.1"])
|
||||
tcp.owner = self
|
||||
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)
|
||||
peer = self._quic._network_paths[0].addr
|
||||
server.quic_peers.append(peer[0])
|
||||
server.quic_peer_addrs.append((peer[0], peer[1]))
|
||||
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/html; charset=utf-8"),
|
||||
(b"access-control-allow-origin", b"*")])
|
||||
self._http.send_data(http_event.stream_id, PAGE, 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,22 @@
|
||||
"""The address of this host that a relay or a server of an e2e test binds to: ONE helper for every test that needs it."""
|
||||
import socket
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def this_host_address() -> str:
|
||||
"""The IPv4 address this host sends from (the one of its default route, as a real gateway's relay has a routable one:
|
||||
a loopback relay only suits a client whose UDP socket is not bound to an interface, and an engine's ICE sockets are).
|
||||
No packet is sent.
|
||||
|
||||
A host with no default route (a container or a CI runner without a network, a laptop offline) has no such address: the
|
||||
test cannot pass by design there, so it SKIPS. Call it BEFORE starting any server of the test, so that nothing is left
|
||||
listening when it skips."""
|
||||
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
probe.connect(("192.0.2.1", 9))
|
||||
return probe.getsockname()[0]
|
||||
except OSError:
|
||||
pytest.skip("no default route: no LAN address to bind the relay")
|
||||
finally:
|
||||
probe.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"]
|
||||
@@ -0,0 +1,55 @@
|
||||
"""A pytest plugin for the cold-pool hunt (scripts/cold_pool_hunt.py): the wall-clock time of what the test gateway sees.
|
||||
|
||||
python -m pytest -p _hunt_plugin ... with HUNT_EVENTS=<file>
|
||||
|
||||
Appends one JSON line per event to HUNT_EVENTS: {"t": epoch seconds, "kind": ..., ...}. `connect` is a SOCKS5 CONNECT reaching the gateway,
|
||||
`associate` a UDP ASSOCIATE reaching it, `stun` a STUN request the fake server answers, `test_start` / `test_end` bracket the test. The gateway is
|
||||
only observed: nothing it does changes.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
|
||||
_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def _emit(kind, **fields):
|
||||
path = os.environ.get("HUNT_EVENTS")
|
||||
if not path:
|
||||
return
|
||||
with _LOCK, open(path, "a", encoding="utf-8") as fh:
|
||||
fh.write(json.dumps(dict(t=time.time(), kind=kind, **fields)) + "\n")
|
||||
|
||||
|
||||
def pytest_configure(config):
|
||||
import _socks_servers as sv
|
||||
|
||||
connect, associate = sv.Gateway._connect, sv.Gateway._associate
|
||||
|
||||
def seen_connect(self, c, host, port):
|
||||
_emit("connect", host=host, port=port)
|
||||
return connect(self, c, host, port)
|
||||
|
||||
def seen_associate(self, c):
|
||||
_emit("associate")
|
||||
return associate(self, c)
|
||||
|
||||
sv.Gateway._connect, sv.Gateway._associate = seen_connect, seen_associate
|
||||
stun = getattr(sv, "FakeStun", None)
|
||||
if stun is not None and hasattr(stun, "_serve"):
|
||||
serve = stun._serve
|
||||
|
||||
def seen_serve(self, *a, **k):
|
||||
_emit("stun_server_up")
|
||||
return serve(self, *a, **k)
|
||||
|
||||
stun._serve = seen_serve
|
||||
|
||||
|
||||
def pytest_runtest_setup(item):
|
||||
_emit("test_start", test=item.nodeid)
|
||||
|
||||
|
||||
def pytest_runtest_teardown(item):
|
||||
_emit("test_end", test=item.nodeid)
|
||||
+390
@@ -0,0 +1,390 @@
|
||||
"""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 (or the first of 127.0.0.2... it can bind: see TRAP_ADDRESSES) (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, ""
|
||||
|
||||
|
||||
#: The loopback addresses the trap tries for port 53, in order. A hosted runner can have something on 127.0.0.1:53 or on the
|
||||
#: wildcard of that port (systemd-resolved holds 127.0.0.53 and 127.0.0.54): every 127.x.x.x is loopback on Linux, so the trap
|
||||
#: takes the first one it can bind and writes THAT address into /etc/resolv.conf (a resolv.conf names no port). With a free
|
||||
#: port (port=0) only 127.0.0.1 is used.
|
||||
TRAP_ADDRESSES = ("127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.5", "127.0.0.6", "127.0.0.7", "127.0.0.8")
|
||||
|
||||
|
||||
def _who_holds(port: int) -> str:
|
||||
"""What the machine says about the sockets of `port` (Linux: ss), for the message of a trap that could not bind."""
|
||||
import subprocess
|
||||
for command in (["ss", "-H", "-lntup"], ["netstat", "-lntup"]):
|
||||
try:
|
||||
done = subprocess.run(command, capture_output=True, text=True, timeout=10)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
continue
|
||||
lines = [line for line in done.stdout.splitlines() if (":%d " % port) in line]
|
||||
return "; held by: " + (" | ".join(lines) if lines else "nothing listed by %s" % command[0])
|
||||
return "; no ss or netstat to say who holds it"
|
||||
|
||||
|
||||
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
|
||||
#: The loopback address the trap listens on once it is bound (see TRAP_ADDRESSES).
|
||||
self.address = "127.0.0.1"
|
||||
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] = []
|
||||
#: The threads that answer on `_sockets`, and the flag that ends them: see `_restore`.
|
||||
self._threads: List[threading.Thread] = []
|
||||
self._ending = threading.Event()
|
||||
self._original: Optional[bytes] = None
|
||||
self._running = False
|
||||
#: Why the last bind attempt failed (the error of the socket), for the message when none succeeds.
|
||||
self._bind_error: Optional[OSError] = None
|
||||
|
||||
# --- 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(("nameserver %s\noptions timeout:1 attempts:1\n" % self.address).encode("ascii"))
|
||||
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
|
||||
# ⛔ THE THREADS END BEFORE THE SOCKETS ARE CLOSED. A thread blocked in accept() or recvfrom() is not woken by a close()
|
||||
# of its socket from another thread (Linux): the kernel keeps the socket, still bound, until the call returns, and the
|
||||
# call never returns. The port stayed taken after the test, and the NEXT trap found 127.0.0.1-8:53 "already in use"
|
||||
# one address per test, until all eight were gone (run 43164943499; here: the eighth trap of a run of 19 tests).
|
||||
# The answering loops therefore wake up every 0.2 s to look at `_ending`, and the socket is closed once they are gone.
|
||||
self._ending.set()
|
||||
for t in self._threads:
|
||||
t.join(2.0)
|
||||
self._threads = []
|
||||
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:
|
||||
addresses = TRAP_ADDRESSES if self.port != 0 else TRAP_ADDRESSES[:1]
|
||||
for address in addresses:
|
||||
for attempt in range(200):
|
||||
made = self._bind_once(discarded, address)
|
||||
if made:
|
||||
break
|
||||
if self.port != 0:
|
||||
break
|
||||
if made:
|
||||
self.address = address
|
||||
break
|
||||
if not made:
|
||||
raise OSError("the resolver trap found no port it could bind for TCP and UDP (port %d on %s; the last error: %s)%s"
|
||||
% (self.port, ", ".join(addresses), self._bind_error, _who_holds(self.port)))
|
||||
finally:
|
||||
for s in discarded:
|
||||
s.close()
|
||||
self._sockets += made
|
||||
for s in made:
|
||||
s.settimeout(0.2)
|
||||
target = self._serve_udp if s.type == socket.SOCK_DGRAM else self._serve_tcp
|
||||
t = threading.Thread(target=target, args=(s,), daemon=True)
|
||||
self._threads.append(t)
|
||||
t.start()
|
||||
|
||||
def _bind_once(self, discarded: List[socket.socket], address: str = "127.0.0.1") -> 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, address, 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 as exc:
|
||||
self._bind_error = exc
|
||||
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 not self._ending.is_set():
|
||||
try:
|
||||
data, peer = sock.recvfrom(4096)
|
||||
except socket.timeout:
|
||||
continue
|
||||
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 not self._ending.is_set():
|
||||
try:
|
||||
conn, _ = listener.accept()
|
||||
except socket.timeout:
|
||||
continue
|
||||
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,392 @@
|
||||
"""What the tests of "the page behind a declared exit" share: the exits, a gateway that tells a local site which of its
|
||||
connections came through it, the page's reads, and the judges that turn what was read into sentences.
|
||||
|
||||
THE QUESTION. A person who buys a proxy expects every site to see ONE place: the address of its exit, the time zone of that
|
||||
address, the language of that country, no trace of the machine the browser runs on. The check used to be made by hand, through a
|
||||
paid proxy, against pages on the internet. Here the proxy is a local SOCKS5 gateway that DECLARES its exit
|
||||
(``Gateway.tcp_exit``, the address it answers to "what is my address"), and the pages are local ones that read the same values a
|
||||
page on the internet reads.
|
||||
|
||||
THE TRUTH FOR THE ZONE AND THE COUNTRY is the core's own offline geo database (``invisible_core._geo.ip_to_timezone`` and
|
||||
``ip_to_country``), not a second service: the tests ask whether the browser's pages say what the core's database says about the
|
||||
declared exit, which is the path ``prepare_session_geo`` takes. Whether the database is right about the world is not asked here.
|
||||
|
||||
THE ADDRESSES BELOW ARE PUBLIC, and each one is an address whose zone and country the geo database knows (the tests need that:
|
||||
a documentation address has no zone). They are built from parts so that no dotted public address stands in a file.
|
||||
|
||||
Nothing here opens a browser. ``test_the_realness_helpers.py`` holds the judges and the gateway to what they say.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import ipaddress
|
||||
import re
|
||||
import socket
|
||||
import threading
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from _doh_servers import DOH_TARGETS, DohGateway, is_loopback, relay
|
||||
from _servers import LocalServer
|
||||
from _socks_servers import WEB_NAME, WHOAMI4, WHOAMI6
|
||||
from test_webrtc_realness import candidates, host_candidates, is_mdns, srflx_candidates
|
||||
|
||||
|
||||
def _address(*parts: int) -> str:
|
||||
return ".".join(str(part) for part in parts)
|
||||
|
||||
|
||||
#: Six declared exits, each an address whose zone and country the geo database knows, on four continents: a zone west of UTC
|
||||
#: with daylight saving, a zone with a half-hour offset, one east of the date line's neighbours, a southern-hemisphere zone whose
|
||||
#: daylight saving runs the other way, and two in Europe/South America. The zone the tests expect is asked of the database at
|
||||
#: test time; only the address is fixed here.
|
||||
EXITS: Dict[str, str] = {
|
||||
"germany": _address(1, 178, 10, 5),
|
||||
"japan": _address(1, 0, 16, 5),
|
||||
"india": _address(1, 6, 0, 5),
|
||||
"australia": _address(1, 0, 4, 5),
|
||||
"brazil": _address(1, 178, 32, 5),
|
||||
"united_states": _address(1, 32, 239, 5),
|
||||
}
|
||||
|
||||
#: The names the pages are reached by. The FakeDoh answers them with the loopback where the site is, so the only way to the site
|
||||
#: is a name resolved by DoH through the gateway and a CONNECT by address.
|
||||
SITE_NAME = "exit-site.test"
|
||||
ZONE_NAMES = {SITE_NAME: "127.0.0.1"}
|
||||
|
||||
#: Two instants a page reads its offset at: 15 January and 15 July 2025, noon UTC, in milliseconds. One is in the northern
|
||||
#: winter and one in the northern summer, so a zone whose daylight saving is wrong in one hemisphere reads a wrong offset at one
|
||||
#: of them.
|
||||
INSTANTS_MS = (1736942400000, 1752580800000)
|
||||
|
||||
#: What a retail Firefox reports as the name of a zone for which ICU keeps an older canonical name. The database says the first,
|
||||
#: a retail browser in that zone prints the second (or the first): either is the zone of the exit.
|
||||
ZONE_NAMES_OF_A_RETAIL_FIREFOX: Dict[str, Tuple[str, ...]] = {
|
||||
"Asia/Kolkata": ("Asia/Kolkata", "Asia/Calcutta"),
|
||||
}
|
||||
|
||||
#: The primary language subtags that are plausible for the country of an exit: the national language of the country and
|
||||
#: English, which a Firefox of any country can carry (the English build is the commonest one everywhere). A country that is not
|
||||
#: in the table is checked for the agreement of the reads with one another only.
|
||||
PLAUSIBLE_PRIMARY: Dict[str, Set[str]] = {
|
||||
"US": {"en", "es"}, "GB": {"en"}, "CA": {"en", "fr"}, "AU": {"en"}, "NZ": {"en"}, "IE": {"en"}, "ZA": {"en", "af"},
|
||||
"IN": {"en", "hi"}, "SG": {"en", "zh"}, "DE": {"de", "en"}, "AT": {"de", "en"}, "CH": {"de", "fr", "it", "en"},
|
||||
"FR": {"fr", "en"}, "BE": {"fr", "nl", "en"}, "NL": {"nl", "en"}, "IT": {"it", "en"}, "ES": {"es", "ca", "en"},
|
||||
"PT": {"pt", "en"}, "BR": {"pt", "en"}, "MX": {"es", "en"}, "AR": {"es", "en"}, "CL": {"es", "en"}, "CO": {"es", "en"},
|
||||
"JP": {"ja", "en"}, "KR": {"ko", "en"}, "CN": {"zh", "en"}, "TW": {"zh", "en"}, "PL": {"pl", "en"}, "SE": {"sv", "en"},
|
||||
"NO": {"nb", "nn", "no", "en"}, "DK": {"da", "en"}, "FI": {"fi", "en"}, "RU": {"ru", "en"}, "UA": {"uk", "ru", "en"},
|
||||
"TR": {"tr", "en"},
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------- the gateway
|
||||
class ExitGateway(DohGateway):
|
||||
"""A gateway that declares an exit AND remembers the local port of every connection it opened for a page.
|
||||
|
||||
A real proxy's exit is the address a site sees as the peer of its connection. On loopback every peer is 127.0.0.1, so the
|
||||
gateway says which connections are its own instead: ``upstream_ports`` holds the source port of each connection it opened
|
||||
to a loopback server, recorded BEFORE it answers the CONNECT, so the server (which is asked only after the browser has the
|
||||
answer) always finds it. A connection of the browser that did not come through the gateway has a port that is not there:
|
||||
to the site it is a direct connection, a leak."""
|
||||
|
||||
def __init__(self, *args: Any, **kwargs: Any):
|
||||
self.upstream_ports: Set[int] = set()
|
||||
self._ports_lock = threading.Lock()
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def came_through(self, source_port: int) -> bool:
|
||||
with self._ports_lock:
|
||||
return source_port in self.upstream_ports
|
||||
|
||||
def _connect(self, c: socket.socket, host: str, port: int) -> None:
|
||||
special = (host, port) in DOH_TARGETS or (host, port) in (WHOAMI4, WHOAMI6, (WEB_NAME, 80))
|
||||
if special or not is_loopback(host):
|
||||
super()._connect(c, host, port)
|
||||
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)
|
||||
with self._ports_lock:
|
||||
self.upstream_ports.add(upstream.getsockname()[1])
|
||||
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 reads
|
||||
#: What a page and a worker read, as ONE function: the worker's source is made from it, so the two cannot drift. The offset is
|
||||
#: read two ways: from the clock of the page (``getTimezoneOffset``) and from the wall clock ``Intl`` prints for the zone the
|
||||
#: page itself names (the difference with UTC). ``0 - x`` and not ``-x``, so that a zero is +0 on the wire.
|
||||
READ_JS = """() => {
|
||||
const instants = %s;
|
||||
const zone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
const ahead = (t) => {
|
||||
const p = {};
|
||||
for (const x of new Intl.DateTimeFormat('en-US', {timeZone: zone, hourCycle: 'h23', year: 'numeric', month: 'numeric',
|
||||
day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric'}).formatToParts(new Date(t))) p[x.type] = x.value;
|
||||
return Math.round((Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour %% 24, +p.minute, +p.second) - t) / 60000);
|
||||
};
|
||||
return {
|
||||
zone,
|
||||
offsets_by_date: instants.map((t) => 0 - new Date(t).getTimezoneOffset()),
|
||||
offsets_by_intl: instants.map(ahead),
|
||||
language: navigator.language,
|
||||
languages: [...navigator.languages],
|
||||
intl: new Intl.DateTimeFormat().resolvedOptions().locale,
|
||||
};
|
||||
}""" % list(INSTANTS_MS)
|
||||
|
||||
#: The page: asks the site what address it sees, makes one fetch (the header the site receives from a fetch), reads, and has a
|
||||
#: dedicated worker read the same and fetch once (the header of a worker's request).
|
||||
PAGE_JS = """async () => {
|
||||
const read = %s;
|
||||
const ip = (await (await fetch('/ip', {cache: 'no-store'})).text()).trim();
|
||||
await (await fetch('/fetch', {cache: 'no-store'})).text();
|
||||
const own = read();
|
||||
const worker = await new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error('the worker never answered')), 20000);
|
||||
const w = new Worker('/worker.js');
|
||||
w.onmessage = (e) => { clearTimeout(timer); resolve(e.data); };
|
||||
w.onerror = (e) => { clearTimeout(timer); reject(new Error('worker error: ' + e.message)); };
|
||||
w.postMessage(0);
|
||||
});
|
||||
return {ip, page: own, worker};
|
||||
}""" % READ_JS
|
||||
|
||||
WORKER_JS = ("const read = %s;\nonmessage = async () => {\n await (await fetch('/worker-fetch', {cache: 'no-store'})).text();\n"
|
||||
" postMessage(read());\n};\n" % READ_JS)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------------- the site
|
||||
@dataclass(frozen=True)
|
||||
class Arrival:
|
||||
"""One request the site received: the path, the source port of the connection, and whether the gateway opened it."""
|
||||
path: str
|
||||
source: str
|
||||
via_gateway: bool
|
||||
accept_language: Optional[str]
|
||||
|
||||
|
||||
class Site:
|
||||
"""The local site: ``/ip`` says which address the site sees (the exit the gateway declares, or ``DIRECT <address>`` for a
|
||||
connection the gateway did not open), ``/fetch`` and ``/worker-fetch`` only count, ``/worker.js`` is the worker."""
|
||||
|
||||
def __init__(self, gateway: ExitGateway):
|
||||
outer = self
|
||||
self.gateway = gateway
|
||||
self.arrivals: List[Arrival] = []
|
||||
self._lock = threading.Lock()
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
path = self.path.split("?")[0]
|
||||
host, port = self.client_address[:2]
|
||||
through = outer.gateway.came_through(port)
|
||||
with outer._lock:
|
||||
outer.arrivals.append(Arrival(path, "%s:%d" % (host, port), through, self.headers.get("Accept-Language")))
|
||||
if path == "/ip":
|
||||
body, kind = (outer.gateway.tcp_exit if through else "DIRECT %s" % host).encode(), "text/plain"
|
||||
elif path == "/worker.js":
|
||||
body, kind = WORKER_JS.encode(), "text/javascript"
|
||||
elif path == "/":
|
||||
body, kind = b"<!doctype html><title>exit</title><body>exit</body>", "text/html; charset=utf-8"
|
||||
else:
|
||||
body, kind = b"ok", "text/plain"
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", kind)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args: Any) -> None:
|
||||
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: str = SITE_NAME, path: str = "/") -> str:
|
||||
return "http://%s:%d%s" % (name, self.port, path)
|
||||
|
||||
def headers_of(self, *paths: str) -> Dict[str, Optional[str]]:
|
||||
"""The Accept-Language of the LAST request of each path (None when the request carried none or never came)."""
|
||||
with self._lock:
|
||||
seen = list(self.arrivals)
|
||||
return {path: next((a.accept_language for a in reversed(seen) if a.path == path), None) for path in paths}
|
||||
|
||||
def close(self) -> None:
|
||||
self._server.shutdown()
|
||||
self._server.server_close()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------- the host's own
|
||||
def host_addresses() -> Set[str]:
|
||||
"""Every address of every interface of this machine, normalised (loopback and link-local included). ``psutil`` is a
|
||||
dependency of the package, and answers the same on Linux and on Windows."""
|
||||
import psutil
|
||||
|
||||
found: Set[str] = set()
|
||||
for addresses in psutil.net_if_addrs().values():
|
||||
for entry in addresses:
|
||||
if entry.family in (socket.AF_INET, socket.AF_INET6):
|
||||
try:
|
||||
found.add(ipaddress.ip_address(entry.address.split("%")[0]).compressed)
|
||||
except ValueError:
|
||||
continue
|
||||
return found
|
||||
|
||||
|
||||
_IPV4_WORD = re.compile(r"(?<![0-9A-Za-z.])(?:\d{1,3}\.){3}\d{1,3}(?![0-9A-Za-z.])")
|
||||
_IPV6_WORD = re.compile(r"(?<![0-9A-Za-z:])(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}(?![0-9A-Za-z:])")
|
||||
|
||||
|
||||
def addresses_in(text: str) -> List[ipaddress._BaseAddress]:
|
||||
"""Every IPv4 and IPv6 address written in ``text`` (a name such as ``<uuid>.local`` is none)."""
|
||||
found = []
|
||||
for token in _IPV4_WORD.findall(text) + _IPV6_WORD.findall(text):
|
||||
try:
|
||||
found.append(ipaddress.ip_address(token))
|
||||
except ValueError:
|
||||
continue
|
||||
return found
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------------------------------------------- the judges
|
||||
def ip_problems(ip_seen: str, arrivals: Sequence[Arrival], direct: Sequence[str], exit_ip: str, connects: Sequence[Tuple[str, int]],
|
||||
site_port: int) -> List[str]:
|
||||
"""What is wrong with "the site sees the exit and nothing reached it, or the network, directly"."""
|
||||
problems: List[str] = []
|
||||
if ip_seen != exit_ip:
|
||||
problems.append("the page was told its address is %r, the gateway's declared exit is %r" % (ip_seen, exit_ip))
|
||||
if not arrivals:
|
||||
problems.append("the site received no request at all")
|
||||
outside = [a for a in arrivals if not a.via_gateway]
|
||||
if outside:
|
||||
problems.append("the site received %d request(s) on connections the gateway did not open (a direct connection): %s"
|
||||
% (len(outside), [(a.path, a.source) for a in outside]))
|
||||
if ("127.0.0.1", site_port) not in connects:
|
||||
problems.append("the gateway never saw a CONNECT to the site, it saw %s" % list(connects))
|
||||
if direct:
|
||||
problems.append("the browser opened connections past the gateway: %s" % list(direct))
|
||||
return problems
|
||||
|
||||
|
||||
def webrtc_problems(probe: Dict[str, Any], exit_ip: str, host: Iterable[str]) -> List[str]:
|
||||
"""What of this machine, or what incoherent with the exit, the candidates and the SDP of a gather show."""
|
||||
lines = list(probe.get("candidates") or [])
|
||||
sdp = probe.get("sdp") or ""
|
||||
cands = candidates(lines)
|
||||
problems: List[str] = []
|
||||
if not cands:
|
||||
return ["the gather produced no candidate at all (%s)" % probe.get("errors")]
|
||||
raw = [c["address"] for c in host_candidates(cands) if not is_mdns(c["address"])]
|
||||
if raw:
|
||||
problems.append("host candidates that are not mDNS names: %s" % raw)
|
||||
six = [c["address"] for c in cands if ":" in c["address"] and not is_mdns(c["address"])]
|
||||
if six and ipaddress.ip_address(exit_ip).version == 4:
|
||||
problems.append("IPv6 candidates behind an IPv4 exit: %s" % six)
|
||||
reflexive = sorted({c["address"] for c in srflx_candidates(cands)})
|
||||
if reflexive and reflexive != [exit_ip]:
|
||||
problems.append("the server-reflexive candidate is %s, the exit is %s" % (reflexive, exit_ip))
|
||||
written = addresses_in(sdp + "\n" + "\n".join(lines))
|
||||
private = sorted({str(a) for a in written if a.version == 4 and not a.is_unspecified and (a.is_private or a.is_link_local
|
||||
or a.is_loopback)})
|
||||
if private:
|
||||
problems.append("private or loopback IPv4 addresses in the SDP or the candidates: %s" % private)
|
||||
mine = set(host)
|
||||
own = sorted({a.compressed for a in written if a.compressed in mine})
|
||||
if own:
|
||||
problems.append("addresses of this machine's interfaces in the SDP or the candidates: %s" % own)
|
||||
return problems
|
||||
|
||||
|
||||
def acceptable_zones(zone: str) -> Tuple[str, ...]:
|
||||
return ZONE_NAMES_OF_A_RETAIL_FIREFOX.get(zone, (zone,))
|
||||
|
||||
|
||||
def expected_offsets(zone: str) -> List[int]:
|
||||
"""The minutes a zone is ahead of UTC at each of :data:`INSTANTS_MS`, from the system tz database (``zoneinfo``)."""
|
||||
info = ZoneInfo(zone)
|
||||
return [int(datetime.fromtimestamp(t / 1000, tz=info).utcoffset().total_seconds() // 60) for t in INSTANTS_MS]
|
||||
|
||||
|
||||
def timezone_problems(reads: Dict[str, Dict[str, Any]], zone: str) -> List[str]:
|
||||
"""``reads`` maps a scope name (page, worker) to what :data:`READ_JS` returned there; every scope must say ``zone`` and the
|
||||
offsets of ``zone`` at both instants, read both ways."""
|
||||
problems: List[str] = []
|
||||
want = expected_offsets(zone)
|
||||
for scope, read in reads.items():
|
||||
if read.get("zone") not in acceptable_zones(zone):
|
||||
problems.append("%s: Intl says the zone is %r, the exit's is %s" % (scope, read.get("zone"), zone))
|
||||
for way in ("offsets_by_date", "offsets_by_intl"):
|
||||
if read.get(way) != want:
|
||||
problems.append("%s: %s are %s, the offsets of %s at the two instants are %s" % (scope, way, read.get(way), zone, want))
|
||||
return problems
|
||||
|
||||
|
||||
def _tags(header: str) -> List[str]:
|
||||
return [part.split(";")[0].strip() for part in header.split(",") if part.strip()]
|
||||
|
||||
|
||||
def language_problems(reads: Dict[str, Dict[str, Any]], headers: Dict[str, Optional[str]], country: Optional[str]) -> List[str]:
|
||||
"""The language of a session as everything a site can read says it: ``reads`` (page, worker), the Accept-Language of the
|
||||
requests (``headers``, by path), and the plausibility of the primary language for ``country``."""
|
||||
problems: List[str] = []
|
||||
page = reads["page"]
|
||||
languages = page.get("languages") or []
|
||||
if not languages:
|
||||
return ["navigator.languages is empty"]
|
||||
primary = languages[0]
|
||||
if page.get("language") != primary:
|
||||
problems.append("navigator.language is %r, navigator.languages starts with %r" % (page.get("language"), primary))
|
||||
for scope, read in reads.items():
|
||||
if read.get("intl") != primary:
|
||||
problems.append("%s: the Intl locale is %r, the language is %r" % (scope, read.get("intl"), primary))
|
||||
if scope != "page":
|
||||
for key in ("language", "languages"):
|
||||
if read.get(key) != page.get(key):
|
||||
problems.append("%s: %s is %r, the page's is %r" % (scope, key, read.get(key), page.get(key)))
|
||||
for path, header in headers.items():
|
||||
if header is None:
|
||||
problems.append("%s: the request carried no Accept-Language" % path)
|
||||
elif _tags(header) != languages:
|
||||
problems.append("%s: Accept-Language is %r, navigator.languages is %s" % (path, header, languages))
|
||||
table = PLAUSIBLE_PRIMARY.get(country or "")
|
||||
if table is not None and primary.split("-")[0].lower() not in table:
|
||||
problems.append("the language %r is not plausible for %s (plausible: %s)" % (primary, country, sorted(table)))
|
||||
return problems
|
||||
|
||||
|
||||
@dataclass
|
||||
class Observation:
|
||||
"""Everything one launch behind one declared exit showed, as plain data (the browser and the servers are closed)."""
|
||||
label: str
|
||||
exit_ip: str
|
||||
zone: str
|
||||
country: Optional[str]
|
||||
ip_seen: str = ""
|
||||
reads: Dict[str, Dict[str, Any]] = field(default_factory=dict)
|
||||
arrivals: List[Arrival] = field(default_factory=list)
|
||||
headers: Dict[str, Optional[str]] = field(default_factory=dict)
|
||||
probe: Dict[str, Any] = field(default_factory=dict)
|
||||
connects: List[Tuple[str, int]] = field(default_factory=list)
|
||||
site_port: int = 0
|
||||
direct: List[str] = field(default_factory=list)
|
||||
watched: int = 0
|
||||
host: Set[str] = field(default_factory=set)
|
||||
doh_vias: Dict[str, Set[str]] = field(default_factory=dict)
|
||||
doh_connects: List[Tuple[str, int]] = field(default_factory=list)
|
||||
gateway_name: str = ""
|
||||
trap_ran: bool = False
|
||||
trap_queries: List[str] = field(default_factory=list)
|
||||
datagrams: List[Tuple[str, int]] = field(default_factory=list)
|
||||
@@ -0,0 +1,619 @@
|
||||
"""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 gateways are the 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.
|
||||
* :func:`silent_udp` - UDP ASSOCIATE is granted and the relay carries datagrams, but
|
||||
no STUN server ever answers (a router that drops UDP behind a working handshake): the core's
|
||||
measurement ends in ``unmeasured``.
|
||||
|
||||
THE CORE MEASURES THE UDP EXIT of a SOCKS5 proxy before it declares it to the browser (``invisible_core._udp_exit``: a STUN
|
||||
Binding through the proxy's ASSOCIATE, compared with the TCP exit). A test that wants the relay to be used hands the core
|
||||
this gateway's measurement server, ``udp_stun_servers=gw.measure_servers`` (``MEASURE_NUMBER``: the fake STUN server by a
|
||||
documentation NUMBER of its own, so the datagrams of the measurement are told apart from those of the page, which asks
|
||||
``STUN_NUMBER``). The measurement is a UDP ASSOCIATE of its own: :attr:`Gateway.associates` and :attr:`Gateway.datagrams` count it.
|
||||
|
||||
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 select
|
||||
import socket
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
from typing import List, Optional, Set, 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"
|
||||
#: The same fake STUN server by ANOTHER number: where the core's own measurement of the UDP exit asks (``udp_stun_servers``),
|
||||
#: so that what the measurement sent through the relay is never mistaken for what the page sent. Documentation address too.
|
||||
MEASURE_NUMBER = "198.51.100.6"
|
||||
#: 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 same page by an address (RFC 5737 TEST-NET-3): since the browser resolves names itself and connects by address, a
|
||||
#: test that loads the gateway's page through a SOCKS gateway names it by this one.
|
||||
WEB_ADDRESS = "203.0.113.80"
|
||||
#: 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, bind_host: str = "127.0.0.1"):
|
||||
self.mapped_ip = mapped_ip
|
||||
self.mapped_port = mapped_port
|
||||
self.requests = 0
|
||||
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
# On the address the relay sends from: Windows sends neither from an address of the host to loopback (WinError 10049) nor
|
||||
# from loopback to an address of the host (10051), so a relay that leaves from the host's address needs its STUN there too.
|
||||
self._sock.bind((bind_host, 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, stun_answers: bool = True):
|
||||
assert udp in ("relay", "refuse")
|
||||
self.udp = udp
|
||||
#: False: the relay carries the datagrams but the fake STUN server is mute (its requests are dropped).
|
||||
self.stun_answers = stun_answers
|
||||
#: 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, bind_host="127.0.0.1" if exit_host.startswith("127.") else exit_host)
|
||||
#: 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()
|
||||
#: The same instant on the wall clock (seconds since the epoch), to compare with what a page reads from Date.now().
|
||||
self.wall0 = time.time()
|
||||
#: Every TCP connection the gateway accepted (a SOCKS handshake starts with one), as seconds from t0.
|
||||
self.accepted: List[float] = []
|
||||
#: 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]] = []
|
||||
#: The local port of the socket each granted association sends from: what a server behind the gateway sees as the port
|
||||
#: of the relay, and what tells a datagram that went by the relay from one that came direct from this host.
|
||||
self.exit_ports: List[int] = []
|
||||
#: A datagram the relay could not send (a socket that raised): said here and in the report of a test, never mute.
|
||||
self.send_errors: List[str] = []
|
||||
#: The hosts the relay forwards a datagram to (the fake STUN server aside); None: any host. A test that sends from an
|
||||
#: address of this host keeps its lab closed: the browser's own background QUIC does not leave the machine.
|
||||
self.forward_only_to: Optional[Set[str]] = None
|
||||
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 measure_servers(self) -> List[str]:
|
||||
"""The ``udp_stun_servers`` of a launch behind this gateway: where the core measures its UDP exit, in the
|
||||
form the parameter takes (``"ip:port"``, an IPv4 literal)."""
|
||||
return ["%s:%d" % (MEASURE_NUMBER, STUN_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
|
||||
self.accepted.append(time.monotonic() - self.t0)
|
||||
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) in ((WEB_NAME, 80), (WEB_ADDRESS, 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, what: str = "a datagram") -> None:
|
||||
"""Run ``fn`` after half the round trip (at once on loopback). A send that fails is RECORDED in ``send_errors`` (a
|
||||
silent one hid that Windows cannot send from 127.0.0.1 to an address of its own host: WinError 10051), except on a gateway
|
||||
that is already closed."""
|
||||
def run() -> None:
|
||||
try:
|
||||
fn()
|
||||
except OSError as e:
|
||||
if not self._closed:
|
||||
self.send_errors.append("%s: %s %s" % (what, type(e).__name__, e))
|
||||
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), "the answer to the client")
|
||||
|
||||
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), (MEASURE_NUMBER, STUN_PORT)):
|
||||
if not self.stun_answers:
|
||||
return None
|
||||
# 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)
|
||||
if self.forward_only_to is not None and host not in self.forward_only_to:
|
||||
return 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))
|
||||
self.exit_ports.append(out.getsockname()[1])
|
||||
if hasattr(socket, "SIO_UDP_CONNRESET"):
|
||||
# Windows: an ICMP "port unreachable" to a send makes the NEXT recvfrom raise WinError 10054 and, uncaught, ends the
|
||||
# thread that reads: a relay that stops carrying answers because one datagram found nobody. Off, as a real relay has it.
|
||||
for sock in (relay, out):
|
||||
sock.ioctl(socket.SIO_UDP_CONNRESET, False)
|
||||
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 ConnectionResetError:
|
||||
continue
|
||||
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), "the datagram to %s:%d" % target)
|
||||
|
||||
def outbound() -> None: # world -> client
|
||||
while True:
|
||||
try:
|
||||
d, src = out.recvfrom(65536)
|
||||
except ConnectionResetError:
|
||||
continue
|
||||
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,
|
||||
exit_host: str = "127.0.0.1") -> 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, exit_host=exit_host)
|
||||
|
||||
|
||||
def tcp_only(*, exit_ip: str = EXIT, user: Optional[str] = None,
|
||||
password: Optional[str] = None, relay_host: str = "127.0.0.1", exit_host: str = "127.0.0.1") -> 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, relay_host=relay_host, exit_host=exit_host)
|
||||
|
||||
|
||||
def mismatched(*, tcp_exit: str = EXIT, udp_exit: str = OTHER_EXIT,
|
||||
user: Optional[str] = None, password: Optional[str] = None, relay_host: str = "127.0.0.1",
|
||||
exit_host: str = "127.0.0.1") -> 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, relay_host=relay_host, exit_host=exit_host)
|
||||
|
||||
|
||||
def silent_udp(*, exit_ip: str = EXIT, user: Optional[str] = None, password: Optional[str] = None,
|
||||
relay_host: str = "127.0.0.1", exit_host: str = "127.0.0.1") -> Gateway:
|
||||
"""TCP works and UDP ASSOCIATE is granted, but no STUN request is ever answered: the core's measurement is
|
||||
``unmeasured``."""
|
||||
return Gateway(udp="relay", tcp_exit=exit_ip, udp_exit=exit_ip, user=user, password=password,
|
||||
relay_host=relay_host, exit_host=exit_host, stun_answers=False)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# A tiny TCP-only SOCKS5 server for the e2e tests (the fixture `socks5_tcp_only` of conftest.py makes one).
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
class Socks5TcpOnly:
|
||||
"""Minimal SOCKS5: no-auth, CONNECT (TCP) relayed, UDP ASSOCIATE refused.
|
||||
|
||||
Reproduces a residential TCP-only proxy: pages load over TCP, but WebRTC's
|
||||
UDP path is dead - which (for a no-camera page in default_address_only mode)
|
||||
is exactly what made the default-route probe fail and ICE return zero
|
||||
candidates before Fix C.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self._srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
self._srv.bind(("127.0.0.1", 0))
|
||||
self._srv.listen(16)
|
||||
self.port = self._srv.getsockname()[1]
|
||||
self.udp_associate_attempts = 0
|
||||
self._stop = False
|
||||
self._t = threading.Thread(target=self._serve, daemon=True)
|
||||
self._t.start()
|
||||
|
||||
def _serve(self):
|
||||
while not self._stop:
|
||||
try:
|
||||
conn, _ = self._srv.accept()
|
||||
except OSError:
|
||||
break
|
||||
threading.Thread(target=self._handle, args=(conn,), daemon=True).start()
|
||||
|
||||
def _recv_exact(self, sock, n):
|
||||
buf = b""
|
||||
while len(buf) < n:
|
||||
chunk = sock.recv(n - len(buf))
|
||||
if not chunk:
|
||||
return None
|
||||
buf += chunk
|
||||
return buf
|
||||
|
||||
def _handle(self, conn):
|
||||
try:
|
||||
head = self._recv_exact(conn, 2)
|
||||
if not head or head[0] != 0x05:
|
||||
conn.close()
|
||||
return
|
||||
nmethods = head[1]
|
||||
self._recv_exact(conn, nmethods)
|
||||
conn.sendall(b"\x05\x00") # no-auth
|
||||
req = self._recv_exact(conn, 4)
|
||||
if not req:
|
||||
conn.close()
|
||||
return
|
||||
ver, cmd, _, atyp = req
|
||||
if atyp == 0x01:
|
||||
addr = socket.inet_ntoa(self._recv_exact(conn, 4))
|
||||
elif atyp == 0x03:
|
||||
ln = self._recv_exact(conn, 1)[0]
|
||||
addr = self._recv_exact(conn, ln).decode("ascii", "ignore")
|
||||
elif atyp == 0x04:
|
||||
addr = socket.inet_ntop(socket.AF_INET6, self._recv_exact(conn, 16))
|
||||
else:
|
||||
conn.close()
|
||||
return
|
||||
port = struct.unpack("!H", self._recv_exact(conn, 2))[0]
|
||||
if cmd != 0x01: # not CONNECT (e.g. UDP ASSOCIATE) → refuse
|
||||
self.udp_associate_attempts += 1
|
||||
conn.sendall(b"\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00") # cmd not supported
|
||||
conn.close()
|
||||
return
|
||||
try:
|
||||
upstream = socket.create_connection((addr, port), timeout=15)
|
||||
except OSError:
|
||||
conn.sendall(b"\x05\x04\x00\x01\x00\x00\x00\x00\x00\x00") # host unreachable
|
||||
conn.close()
|
||||
return
|
||||
conn.sendall(b"\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00") # success
|
||||
self._relay(conn, upstream)
|
||||
except Exception:
|
||||
try:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _relay(self, a, b):
|
||||
try:
|
||||
while True:
|
||||
r, _, _ = select.select([a, b], [], [], 30)
|
||||
if not r:
|
||||
break
|
||||
for s in r:
|
||||
data = s.recv(65536)
|
||||
if not data:
|
||||
return
|
||||
(b if s is a else a).sendall(data)
|
||||
finally:
|
||||
for s in (a, b):
|
||||
try:
|
||||
s.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
self._stop = True
|
||||
try:
|
||||
self._srv.close()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -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,325 @@
|
||||
"""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 _host_address import this_host_address
|
||||
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"
|
||||
|
||||
|
||||
# ── 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:
|
||||
# The address of this host first: on a host with no default route the test skips, with no server started yet.
|
||||
relay_host = relay_host or this_host_address()
|
||||
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, 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()
|
||||
@@ -0,0 +1,173 @@
|
||||
"""What the e2e tests of the UDP line share: the STUN servers the core measures from, the TCP exit of each gateway, what the
|
||||
launch declared, and the sequence of protocols a page reads on each road.
|
||||
|
||||
THE CORE MEASURES THE UDP EXIT of a SOCKS5 proxy before it declares it (``invisible_core._udp_exit``): a STUN Binding sent
|
||||
through the ASSOCIATE of the proxy to a list of servers, compared with the TCP exit it discovers through the same proxy. Only
|
||||
``udp: coherent`` makes the engine send UDP to the relay; ``no`` and ``unmeasured`` are "a router that drops UDP" (HTTP/3
|
||||
too). The list of servers is the explicit launch parameter ``udp_stun_servers`` (``"ip:port"``, IPv4 literals), so a hermetic
|
||||
test points the measurement at the fake STUN server only its gateway's relay reaches. The caller never declares ``udp``.
|
||||
|
||||
Nothing here opens a browser; the unit test ``test_the_udp_line_helpers.py`` holds it to what it says.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
from typing import Any, Callable, Dict, List, Optional, Sequence
|
||||
|
||||
#: How much slower than the first visit a later visit may load, in milliseconds, on the roads where UDP does not work. A
|
||||
#: retail Firefox on a network that drops UDP loads the later visits as fast as the first (15 of 15 sessions, h2/h2/h2): an h3
|
||||
#: attempt that waits for a timeout before it falls back to h2 would be seconds.
|
||||
LOAD_MARGIN_MS = 1500
|
||||
|
||||
#: The visits of one page in one context, by kind of road. With NO proxy and the native DNS the retail is measured in loopback
|
||||
#: and is exact: h2, h3, h3 over three visits. BEHIND A PROXY the names are resolved by DoH, the browser learns the Alt-Svc
|
||||
#: from the first answer and the retail (Windows 159, DoH forced like our core, 15 sessions per condition) takes its time to
|
||||
#: move to h3: with UDP free h2/h2/h3 in 9 sessions, h2/h2/h2 in 4 and h2/h3/h3 in 2 in the first runs, and h3 already on the
|
||||
#: first visit (h3, h2, h2) in 3 sessions of 15 in the third, when the DNS answer carried the HTTPS record; so the page is
|
||||
#: visited up to ``PROXY_VISITS`` times, and every proxy road makes the same number of visits (a road where UDP is dropped
|
||||
#: reads h2 on all of them, as the retail does in 15 of 15: the one outcome that repeats). The fixture's first visit is h2
|
||||
#: because it is reached by an address (no HTTPS record exists), not because the retail never reads h3 first.
|
||||
DIRECT_VISITS = 3
|
||||
PROXY_VISITS = 5
|
||||
|
||||
#: The roads. ``direct``: no proxy, native DNS. ``socks5_coherent``: a SOCKS5 proxy whose UDP the core measured coherent (UDP
|
||||
#: free behind the proxy). The others are "a router that drops UDP": a SOCKS5 proxy that refuses UDP, whose UDP leaves
|
||||
#: elsewhere or that never answers; or an HTTP proxy.
|
||||
_DIRECT_ROAD = "direct"
|
||||
_H3_PROXY_ROAD = "socks5_coherent"
|
||||
_H2_ROADS = ("socks5_no_udp", "socks5_mismatched", "socks5_unmeasured", "http_proxy")
|
||||
ROADS = (_DIRECT_ROAD, _H3_PROXY_ROAD) + _H2_ROADS
|
||||
|
||||
|
||||
def _literal(entry: Any) -> str:
|
||||
"""``"ip:port"`` of an IPv4 literal and a port, or ValueError (the form the launch parameter takes)."""
|
||||
host, sep, port = str(entry).rpartition(":")
|
||||
if not sep or ipaddress.ip_address(host).version != 4 or not 1 <= int(port) <= 65535:
|
||||
raise ValueError("%r is not an \"ip:port\" IPv4 literal" % (entry,))
|
||||
return "%s:%s" % (ipaddress.ip_address(host), int(port))
|
||||
|
||||
|
||||
def measure_servers(gateway: Any) -> List[str]:
|
||||
"""The ``udp_stun_servers=`` of a launch behind ``gateway``: the server its relay answers for the core's measurement.
|
||||
One place, so that no test writes a list of its own."""
|
||||
return [_literal(entry) for entry in gateway.measure_servers]
|
||||
|
||||
|
||||
def egress_by_proxy(*gateways: Any, direct: Optional[str] = None) -> Callable[..., str]:
|
||||
"""A replacement for ``invisible_core._geo.discover_egress_ip``: the TCP exit of the proxy it is asked about, which is
|
||||
the one the gateway reports (no local gateway can answer the product's HTTPS question as itself). One gateway or
|
||||
several (a session proxy and a context proxy have each their own); the UDP probe that follows is NOT replaced, it runs
|
||||
through the relay for real. ``direct`` answers the discovery made with no proxy. An unknown proxy fails loudly."""
|
||||
exits = {gateway.server: gateway.tcp_exit for gateway in gateways}
|
||||
|
||||
def discover(proxy: Optional[Dict[str, Any]] = None, *_args: Any, **_kwargs: Any) -> str:
|
||||
if not proxy:
|
||||
if direct is None:
|
||||
raise AssertionError("the TCP exit was asked with no proxy and the test gave none")
|
||||
return direct
|
||||
server = proxy.get("server") if isinstance(proxy, dict) else None
|
||||
if server not in exits:
|
||||
raise AssertionError("the TCP exit of %r was asked and no gateway of the test owns it: %s" % (server, sorted(exits)))
|
||||
return exits[server]
|
||||
|
||||
return discover
|
||||
|
||||
|
||||
def declared_udp(proxy: Dict[str, Any], servers: Sequence[str]) -> str:
|
||||
"""The ``udp`` the launch measured for ``proxy`` with ``servers``: ``coherent``, ``no`` or ``unmeasured``. It is what the
|
||||
core remembered for the proxy (and declares to the engine); an AssertionError when the launch measured nothing, so
|
||||
``unmeasured`` cannot be mistaken for an absent measurement."""
|
||||
from invisible_core import _udp_exit
|
||||
from invisible_core._proxy import parse_proxy
|
||||
|
||||
endpoint = parse_proxy(proxy)
|
||||
key = _udp_exit.cache_key(endpoint, _udp_exit.stun_servers(list(servers)))
|
||||
entry = _udp_exit._cache.get(key)
|
||||
if entry is None:
|
||||
raise AssertionError("the launch measured nothing for %r with %s" % (proxy.get("server"), list(servers)))
|
||||
return entry[1]
|
||||
|
||||
|
||||
def visits_for(road: str) -> int:
|
||||
"""How many times the page is visited on ``road``: three with no proxy, :data:`PROXY_VISITS` behind any proxy."""
|
||||
if road == _DIRECT_ROAD:
|
||||
return DIRECT_VISITS
|
||||
if road in ROADS:
|
||||
return PROXY_VISITS
|
||||
raise KeyError("no such road: %r (roads: %s)" % (road, ", ".join(ROADS)))
|
||||
|
||||
|
||||
def expected_protocols(road: str) -> str:
|
||||
"""What a retail Firefox reads (``nextHopProtocol`` of the document) over the visits of ``road``, as a sentence."""
|
||||
visits = visits_for(road)
|
||||
if road == _DIRECT_ROAD:
|
||||
return "h2, h3, h3 over %d visits (no proxy, native DNS)" % visits
|
||||
if road == _H3_PROXY_ROAD:
|
||||
return ("h2 on the first visit, then h3 from a later visit on and h3 on every one after it, within %d visits "
|
||||
"(retail with DoH and UDP free: h2/h2/h3 in 9 of 15, h2/h2/h2 in 4, h2/h3/h3 in 2, and h3 first in 3 of 15 in the "
|
||||
"third run when the DNS answer carries the HTTPS record; this fixture has none: h2 first)" % visits)
|
||||
return "h2 on every one of %d visits, as fast as the first (retail with UDP dropped: h2/h2/h2 in 15 of 15)" % visits
|
||||
|
||||
|
||||
def no_https_record(host: str, doh: Any = None) -> List[str]:
|
||||
"""What is wrong with the claim "the first visit of this fixture is h2", as sentences; an empty list when nothing is.
|
||||
|
||||
The retail reads h3 at the first visit when the DNS answer for the site carries the HTTPS record (type 65): the third
|
||||
retail run did in 3 sessions of 15. The fixture reads h2 first only if no such record can reach the browser: the server
|
||||
is reached by an ADDRESS (no name, no lookup), and the FakeDoh, when one is in the path, has never served a type 65 with
|
||||
data (``FakeDoh.https_served``)."""
|
||||
problems: List[str] = []
|
||||
try:
|
||||
ipaddress.ip_address(host.strip("[]"))
|
||||
except ValueError:
|
||||
problems.append("the server is reached by the name %r: its DNS answer could carry an HTTPS record, and the retail "
|
||||
"reads h3 at the first visit when it does" % host)
|
||||
served = list(getattr(doh, "https_served", ())) if doh is not None else []
|
||||
if served:
|
||||
problems.append("the FakeDoh served an HTTPS record (type 65) for %s: the first visit may read h3, as the retail does"
|
||||
% sorted(set(served)))
|
||||
return problems
|
||||
|
||||
|
||||
def judge_visits(road: str, protocols: Sequence[str], walls_ms: Sequence[float]) -> List[str]:
|
||||
"""What is wrong with the visits of one page on ``road``, as sentences; an empty list when nothing is.
|
||||
|
||||
``protocols`` is the ``nextHopProtocol`` of each visit and ``walls_ms`` the time ``page.goto`` took to the load event;
|
||||
both have :func:`visits_for` entries. The rules, from the retail:
|
||||
|
||||
* ``direct``: exactly h2, h3, h3.
|
||||
* ``socks5_coherent``: the first visit is h2 (the fixture is reached by an address: no HTTPS record exists, so nothing
|
||||
tells the browser about h3 before the first connection; the retail itself reads h3 first when the DNS answer carries
|
||||
the record, so this is a rule of the fixture, checked with :func:`no_https_record`); every later visit is h2 or h3, but once one is h3 all the following are (h3 never goes back to h2); and at
|
||||
least one visit is h3 (it is NOT required at the second: h2/h2/h3 is the commonest retail sequence).
|
||||
* the roads where UDP is dropped: h2 on every visit, and no visit loads more than :data:`LOAD_MARGIN_MS` slower than the
|
||||
first (a fallback that waits for a timeout is a tell)."""
|
||||
problems: List[str] = []
|
||||
protocols, walls_ms = list(protocols), list(walls_ms)
|
||||
visits = visits_for(road)
|
||||
said = "a retail Firefox reads %s on this road" % expected_protocols(road)
|
||||
if len(protocols) != visits:
|
||||
problems.append("%d protocols for %d visits: %s" % (len(protocols), visits, protocols))
|
||||
if len(walls_ms) != visits:
|
||||
problems.append("%d load times for %d visits: %s" % (len(walls_ms), visits, walls_ms))
|
||||
if protocols and protocols[0] == "h3":
|
||||
problems.append("visit 1 read h3: in this fixture nothing had told the browser yet that the server speaks h3 (no "
|
||||
"name, no HTTPS record): something told it, or the fixture changed")
|
||||
if len(protocols) == visits:
|
||||
if road == _DIRECT_ROAD:
|
||||
if protocols != ["h2", "h3", "h3"]:
|
||||
problems.append("the protocols of the %d visits are %s, %s" % (visits, protocols, said))
|
||||
elif road == _H3_PROXY_ROAD:
|
||||
first = protocols.index("h3") if "h3" in protocols else None
|
||||
if first is None:
|
||||
problems.append("none of the %d visits read h3: %s, %s" % (visits, protocols, said))
|
||||
elif set(protocols) - {"h2", "h3"} or protocols[0] != "h2" or "h2" in protocols[first:]:
|
||||
problems.append("the protocols of the %d visits are %s, %s" % (visits, protocols, said))
|
||||
elif protocols != ["h2"] * visits:
|
||||
problems.append("the protocols of the %d visits are %s, %s" % (visits, protocols, said))
|
||||
if len(walls_ms) == visits and road in _H2_ROADS:
|
||||
for number in range(2, visits + 1):
|
||||
if walls_ms[number - 1] > walls_ms[0] + LOAD_MARGIN_MS:
|
||||
problems.append("visit %d loaded in %d ms against %d ms for visit 1 (more than %d ms slower): an h3 attempt "
|
||||
"that waited for a timeout before the fallback" % (number, walls_ms[number - 1], walls_ms[0], LOAD_MARGIN_MS))
|
||||
return problems
|
||||
@@ -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).
|
||||
@@ -336,3 +343,149 @@ def fixture_server():
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
# ======================================================================================================================
|
||||
# Fixtures shared by several e2e files. They live here, not in one file that the others import from: an imported fixture
|
||||
# that a test then names as an argument is a redefinition (ruff F811, the lint of the `tests` job).
|
||||
# ======================================================================================================================
|
||||
@pytest.fixture
|
||||
def doh():
|
||||
import h2 # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
from _doh_servers import FakeDoh
|
||||
from _doh_support import ZONE
|
||||
|
||||
server = FakeDoh(ZONE)
|
||||
yield server
|
||||
server.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def gateway(doh):
|
||||
from _doh_servers import DohGateway
|
||||
|
||||
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."""
|
||||
import _trap_policy
|
||||
from _leaks import ResolverTrap
|
||||
|
||||
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."""
|
||||
from pathlib import Path
|
||||
|
||||
from _leaks import Watcher
|
||||
|
||||
w = Watcher(match=("firefox", Path(firefox_binary).stem.lower())).start()
|
||||
yield w
|
||||
w.stop()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pages():
|
||||
from _doh_support import Pages
|
||||
|
||||
server = Pages()
|
||||
yield server
|
||||
server.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def socks5_tcp_only():
|
||||
from _socks_servers import Socks5TcpOnly
|
||||
|
||||
srv = Socks5TcpOnly()
|
||||
yield srv
|
||||
srv.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def local_https_page():
|
||||
"""A trivial localhost page (used by the no-proxy srflx test)."""
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
#: A silent socket no longer pins a thread down: after five seconds it drops.
|
||||
timeout = 5
|
||||
|
||||
def do_GET(self):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html")
|
||||
self.end_headers()
|
||||
self.wfile.write(b"<html><body>wrtc</body></html>")
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
httpd = ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
httpd.daemon_threads = True
|
||||
threading.Thread(target=httpd.serve_forever, daemon=True).start()
|
||||
yield f"http://127.0.0.1:{httpd.server_address[1]}/"
|
||||
httpd.shutdown()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=["in-process", "stock-client"])
|
||||
def browser(request, firefox_binary):
|
||||
"""One browser per transport for the whole file (the popup tests of two files use it)."""
|
||||
import importlib
|
||||
if request.param == "in-process":
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(binary_path=firefox_binary, headless=True) as b:
|
||||
yield b
|
||||
return
|
||||
try: # the stock client (a pinned dev dependency), imported by name: the fork's guard forbids a static import
|
||||
sync_playwright = importlib.import_module("playwright.sync_api").sync_playwright
|
||||
except ImportError as exc:
|
||||
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc,
|
||||
pytrace=False)
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
b = p.firefox.connect(server.ws_endpoint)
|
||||
try:
|
||||
yield b
|
||||
finally:
|
||||
b.close()
|
||||
finally:
|
||||
server.close()
|
||||
@@ -0,0 +1,249 @@
|
||||
"""A proxy given to a context declares where its UDP leaves from, MEASURED before the command is sent.
|
||||
|
||||
The core measures the UDP exit of a SOCKS5 proxy (`invisible_core._udp_exit`: UDP ASSOCIATE, then a STUN Binding request
|
||||
with ICE's retransmissions, compared with the TCP exit it discovers through the same proxy) and the answer is the
|
||||
optional field ``udp`` of ``Browser.setContextProxy``: ``coherent``, ``no`` or ``unmeasured``. Without it the engine
|
||||
drops the UDP of every SOCKS5 proxy, so a context that is given its own proxy would never get a server-reflexive
|
||||
candidate. The caller never declares it: a ``udp`` key in the dict of a proxy is not read.
|
||||
|
||||
``new_context(proxy=...)`` of the sync client, of the async client and of a remote one all end in
|
||||
``BrowserDispatcher._apply_context_options``: one place, tested here with a recorder in place of the engine. The
|
||||
gateway is the fake of ``_socks_servers`` (a SOCKS5 server with a UDP relay and a STUN server only the relay reaches).
|
||||
|
||||
THE STUN SERVERS ARE A PARAMETER OF THE LAUNCH: ``InvisiblePlaywright(..., udp_stun_servers=[...])`` and
|
||||
``launch_server(..., udp_stun_servers=[...])`` ("ip:port" IPv4 literals; None = the two public defaults). The session
|
||||
keeps the list, the launch's geo step and every later context proxy use it, and none of it reaches the browser: not its
|
||||
environment, argv, prefs or pipe.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from _socks_servers import EXIT, STUN_NUMBER, STUN_PORT, coherent, mismatched, tcp_only
|
||||
from invisible_core import _geo, _udp_exit
|
||||
from invisible_core.juggler.connection import EventListeners
|
||||
from invisible_playwright import _session
|
||||
from invisible_playwright._juggler.server import (BrowserDispatcher, Server, UDP_STUN_PREF,
|
||||
session_udp_stun_servers, take_session_motion)
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
#: The fake STUN server only the gateway's relay reaches, in the form the launch parameter takes.
|
||||
STUN = ["%s:%d" % (STUN_NUMBER, STUN_PORT)]
|
||||
|
||||
|
||||
class _Connection(EventListeners):
|
||||
def __init__(self, gateways=()):
|
||||
super().__init__()
|
||||
self.sent = []
|
||||
self.datagrams_before = {}
|
||||
self._gateways = gateways
|
||||
|
||||
def startup_send(self, method, params=None):
|
||||
return self.send(method, params, timeout=None)
|
||||
|
||||
def send(self, method, params=None, session=None, timeout=30):
|
||||
# How many datagrams the relays had carried when each command was sent: the measure comes BEFORE it.
|
||||
self.datagrams_before[len(self.sent)] = sum(len(g.datagrams) for g in self._gateways)
|
||||
self.sent.append((method, params))
|
||||
return {"browserContextId": "CTX"}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fresh(monkeypatch):
|
||||
monkeypatch.setattr(_udp_exit, "_cache", {})
|
||||
# The fake gateway answers the exit question the way the product asks it (api.ipify.org through socks5h), but
|
||||
# these tests are about the measurement, so the TCP exit is the gateway's own declaration.
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", lambda proxy=None, **kw: EXIT)
|
||||
|
||||
|
||||
def _apply(options, gateways=(), stun=STUN):
|
||||
conn = _Connection(gateways)
|
||||
dispatcher = BrowserDispatcher(Server(), None, conn, "151.0", udp_stun_servers=stun)
|
||||
conn.sent.clear()
|
||||
dispatcher._apply_context_options("CTX", options)
|
||||
return conn
|
||||
|
||||
|
||||
def _context_proxy(conn):
|
||||
found = [(i, p) for i, (m, p) in enumerate(conn.sent) if m == "Browser.setContextProxy"]
|
||||
assert len(found) == 1, conn.sent
|
||||
return found[0]
|
||||
|
||||
|
||||
def test_a_coherent_socks5_context_proxy_declares_coherent_after_it_was_measured():
|
||||
with coherent() as gw:
|
||||
conn = _apply({"proxy": gw.proxy}, [gw])
|
||||
index, params = _context_proxy(conn)
|
||||
assert params["udp"] == "coherent"
|
||||
assert params["type"] == "socks" and params["browserContextId"] == "CTX"
|
||||
assert conn.datagrams_before[index] >= 1, "the Binding request was sent before the command"
|
||||
assert gw.associates == 1
|
||||
|
||||
|
||||
def test_a_udp_that_leaves_from_another_address_declares_no():
|
||||
with mismatched() as gw:
|
||||
assert _context_proxy(_apply({"proxy": gw.proxy}, [gw]))[1]["udp"] == "no"
|
||||
|
||||
|
||||
def test_a_proxy_that_refuses_udp_declares_no():
|
||||
with tcp_only() as gw:
|
||||
assert _context_proxy(_apply({"proxy": gw.proxy}, [gw]))[1]["udp"] == "no"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("scheme", ["http", "https", "socks4"])
|
||||
def test_a_proxy_that_is_not_socks5_declares_no_field_and_opens_no_connection(scheme):
|
||||
with coherent() as gw:
|
||||
proxy = {"server": "%s://127.0.0.1:%d" % (scheme, gw.port)}
|
||||
params = _context_proxy(_apply({"proxy": proxy}, [gw]))[1]
|
||||
assert "udp" not in params
|
||||
assert gw.associates == 0 and not gw.connects
|
||||
|
||||
|
||||
def test_the_caller_never_declares_udp_on_a_context_proxy():
|
||||
"""Red on the code that read the key: a caller-written `coherent` for a proxy whose UDP exits elsewhere (or
|
||||
is refused) must come out as what was MEASURED."""
|
||||
with tcp_only() as gw:
|
||||
assert _context_proxy(_apply({"proxy": dict(gw.proxy, udp="coherent")}, [gw]))[1]["udp"] == "no"
|
||||
with mismatched() as gw:
|
||||
assert _context_proxy(_apply({"proxy": dict(gw.proxy, udp="coherent")}, [gw]))[1]["udp"] == "no"
|
||||
|
||||
|
||||
def test_one_proxy_is_measured_once_however_many_contexts_are_given_it():
|
||||
with coherent() as gw:
|
||||
for _ in range(3):
|
||||
assert _context_proxy(_apply({"proxy": dict(gw.proxy)}, [gw]))[1]["udp"] == "coherent"
|
||||
assert gw.associates == 1
|
||||
|
||||
|
||||
def test_the_cache_is_keyed_without_the_secret():
|
||||
with coherent(user="a", password="hunter2-zzz") as gw:
|
||||
_apply({"proxy": gw.proxy}, [gw])
|
||||
assert _udp_exit._cache
|
||||
for key in _udp_exit._cache:
|
||||
assert "hunter2-zzz" not in repr(key)
|
||||
|
||||
|
||||
def test_the_credentials_are_used_on_the_socket_and_nowhere_else(caplog):
|
||||
user, password = "u-7c1e4b9a02", "p-3d5f8a6e41"
|
||||
env_before = dict(os.environ)
|
||||
with coherent(user=user, password=password) as gw:
|
||||
with caplog.at_level(logging.DEBUG):
|
||||
params = _context_proxy(_apply({"proxy": gw.proxy}, [gw]))[1]
|
||||
assert params["udp"] == "coherent"
|
||||
text = "\n".join(r.getMessage() + repr(r.args) + str(r.exc_info) for r in caplog.records)
|
||||
assert user not in text and password not in text
|
||||
assert dict(os.environ) == env_before
|
||||
assert not [a for a in sys.argv if user in a or password in a]
|
||||
|
||||
|
||||
def test_a_context_without_its_own_proxy_measures_nothing():
|
||||
with coherent() as gw:
|
||||
conn = _apply({}, [gw])
|
||||
assert not [m for m, _ in conn.sent if m == "Browser.setContextProxy"]
|
||||
assert gw.associates == 0
|
||||
|
||||
|
||||
def test_a_context_proxy_that_cannot_be_read_is_refused_and_nothing_is_measured():
|
||||
from invisible_playwright._juggler.server import ProtocolException as Refusal
|
||||
with coherent() as gw:
|
||||
with pytest.raises(Refusal):
|
||||
_apply({"proxy": {"server": "ftp://127.0.0.1:%d" % gw.port}}, [gw])
|
||||
assert gw.associates == 0
|
||||
|
||||
|
||||
def test_a_browser_built_without_a_list_measures_from_the_two_defaults():
|
||||
conn = _Connection()
|
||||
assert BrowserDispatcher(Server(), None, conn, "151.0").udp_stun_servers is None
|
||||
|
||||
|
||||
# the launch: the list is a parameter of the session, kept on it, never given to the browser ------------------
|
||||
def test_the_session_keeps_the_list_the_launch_named_and_the_server_gets_it():
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
from invisible_playwright.async_api import InvisiblePlaywright as AsyncInvisiblePlaywright
|
||||
expected = ["198.51.100.5:19302", "203.0.113.9:3478"]
|
||||
for cls in (InvisiblePlaywright, AsyncInvisiblePlaywright):
|
||||
session = cls(seed=1, udp_stun_servers=["198.51.100.5:19302", ("203.0.113.9", 3478)])
|
||||
assert session._udp_stun_servers == expected
|
||||
assert cls(seed=1)._udp_stun_servers is None
|
||||
|
||||
|
||||
def test_a_bad_list_is_refused_by_every_public_entry_point():
|
||||
import inspect
|
||||
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
from invisible_playwright.async_api import InvisiblePlaywright as AsyncInvisiblePlaywright
|
||||
for cls in (InvisiblePlaywright, AsyncInvisiblePlaywright):
|
||||
with pytest.raises(ValueError, match="udp_stun_servers"):
|
||||
cls(seed=1, udp_stun_servers=["stun.example.org:3478"])
|
||||
assert "udp_stun_servers" in inspect.signature(launch_server).parameters
|
||||
|
||||
|
||||
def test_the_server_takes_the_list_out_of_the_prefs_before_the_profile():
|
||||
prefs = {"a.b": 1, UDP_STUN_PREF: "198.51.100.5:19302,203.0.113.9:3478"}
|
||||
assert session_udp_stun_servers(prefs) == ["198.51.100.5:19302", "203.0.113.9:3478"]
|
||||
rest, _seed, _budget = take_session_motion(prefs)
|
||||
assert UDP_STUN_PREF not in rest and rest == {"a.b": 1}
|
||||
assert session_udp_stun_servers({"a.b": 1}) is None
|
||||
|
||||
|
||||
def test_op_launch_reads_the_list_before_the_prefs_are_cleaned_and_writes_a_profile_without_it():
|
||||
import inspect
|
||||
|
||||
from invisible_playwright._juggler import server
|
||||
source = inspect.getsource(server.BrowserTypeDispatcher.op_launch)
|
||||
assert source.index("session_udp_stun_servers(launch_prefs)") < source.index("take_session_motion(launch_prefs)")
|
||||
assert source.index("take_session_motion(launch_prefs)") < source.index("write_user_js(")
|
||||
assert "launch_proxy_command(params[\"proxy\"], udp_stun_servers)" in source
|
||||
assert "parse_proxy(params[\"proxy\"]).as_engine_command()" not in source
|
||||
|
||||
|
||||
def test_every_entry_point_hands_the_list_to_the_geo_step():
|
||||
"""The sync launcher, the async launcher and `launch_server` call `prepare_session_geo` with the session's list."""
|
||||
import ast
|
||||
import importlib
|
||||
import inspect
|
||||
for module in ("launcher", "async_api", "_juggler.remote"):
|
||||
source = inspect.getsource(importlib.import_module("invisible_playwright." + module))
|
||||
tree = ast.parse(source)
|
||||
calls = [n for n in ast.walk(tree) if isinstance(n, ast.Call)
|
||||
and getattr(n.func, "id", None) == "prepare_session_geo"]
|
||||
# (the async launcher passes the function to `asyncio.to_thread`: its keywords are on that call)
|
||||
calls += [n for n in ast.walk(tree) if isinstance(n, ast.Call)
|
||||
and getattr(n.func, "attr", None) == "to_thread"
|
||||
and any(getattr(a, "id", None) == "prepare_session_geo" for a in n.args)]
|
||||
assert calls, module
|
||||
for call in calls:
|
||||
assert "udp_stun_servers" in [k.arg for k in call.keywords], module
|
||||
|
||||
|
||||
def test_no_stun_address_reaches_the_browsers_environment_argv_prefs_or_pipe():
|
||||
from invisible_core import decide_session_locale
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
servers = ["198.51.100.5:19302", "203.0.113.9:3478"]
|
||||
session = InvisiblePlaywright(seed=7, udp_stun_servers=servers, binary_path="firefox")
|
||||
session._timezone, session._locale = "Asia/Tokyo", decide_session_locale("en-US")
|
||||
prefs = session._build_prefs()
|
||||
assert session_udp_stun_servers(prefs) == servers # the server's own key is there...
|
||||
env = _session.build_env(network_declared="v4=198.51.100.7;v6=0", profile=session._profile,
|
||||
executable=None, base_env={})
|
||||
# ...and what the engine is given: the prefs after the server took its own keys out, the environment, the pipe.
|
||||
browser_prefs, _seed, _budget = take_session_motion(prefs)
|
||||
pipe = repr(_udp_exit.launch_proxy_command({"server": "socks5://10.0.0.1:1080"}, servers))
|
||||
given = repr(browser_prefs) + repr(env) + pipe
|
||||
for needle in servers + ["198.51.100.5", "203.0.113.9"]:
|
||||
assert needle not in given, needle
|
||||
assert not [k for k in env if "STUN" in k.upper()]
|
||||
|
||||
|
||||
# the launch of a client that composed no session ----------------------------------------------------------
|
||||
def test_a_hand_made_launch_proxy_cannot_claim_a_coherent_udp():
|
||||
"""`launch(proxy={..., "udp": "coherent"})` through a bare client: nothing was measured, so `unmeasured`."""
|
||||
with mismatched() as gw:
|
||||
command = _udp_exit.launch_proxy_command(dict(gw.proxy, udp="coherent"), STUN)
|
||||
assert command["udp"] == "unmeasured"
|
||||
@@ -27,7 +27,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 _processes import site_processes_below # noqa: E402
|
||||
|
||||
@@ -40,7 +40,7 @@ def display(monkeypatch):
|
||||
geo = types.SimpleNamespace(timezone="Europe/Rome",
|
||||
locale=SessionLocale.of("it-IT"),
|
||||
egress_ip=None,
|
||||
srflx_to_declare=lambda: None)
|
||||
geolocation_override=lambda: None)
|
||||
|
||||
def refuse(**_kw):
|
||||
raise FontManifestMismatch("the engine does not carry these faces")
|
||||
@@ -53,7 +53,7 @@ def display(monkeypatch):
|
||||
monkeypatch.setattr(_session, "resolve_executable", lambda _p: "firefox")
|
||||
monkeypatch.setattr(_session, "build_env", refuse)
|
||||
for mod in (launcher, async_api):
|
||||
monkeypatch.setattr(mod, "prepare_session_geo", lambda *_a: geo)
|
||||
monkeypatch.setattr(mod, "prepare_session_geo", lambda *_a, **_k: geo)
|
||||
monkeypatch.setattr(mod, "resolve_executable", lambda _p: "firefox")
|
||||
monkeypatch.setattr(launcher, "sync_playwright", no_playwright)
|
||||
monkeypatch.setattr(async_api, "async_playwright", no_playwright)
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""A `fetch(..., {keepalive: true})` is a request of the page: the client hears `request` and its end.
|
||||
|
||||
Stock Playwright's Firefox reports the keepalive fetch of a page like any other request: `page.on("request")` fires, and
|
||||
`requestfinished` follows. Here the server saw the request and the client heard nothing, so a client that follows the page's
|
||||
network by those events (tf-fetch's network recorder does) never knew the request existed.
|
||||
|
||||
The page asks for the same address four ways. `plain` is the control (a fetch without keepalive), `keepalive` and
|
||||
`beacon` are the two that the engine runs in the parent process, and each must give exactly one `request` and one end.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
|
||||
import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
PAGE = b"""<!doctype html><title>keepalive</title><script>
|
||||
addEventListener('load', () => {
|
||||
fetch('/seen/plain', {method: 'POST', body: 'x'});
|
||||
fetch('/seen/keepalive', {method: 'POST', body: 'x', keepalive: true});
|
||||
fetch('/seen/keepalive-nocors', {keepalive: true, mode: 'no-cors'});
|
||||
navigator.sendBeacon('/seen/beacon', 'x');
|
||||
});
|
||||
</script>"""
|
||||
|
||||
|
||||
class _Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def _answer(self, body, ctype="text/plain"):
|
||||
self.send_response(200)
|
||||
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):
|
||||
if self.path == "/":
|
||||
self._answer(PAGE, "text/html; charset=utf-8")
|
||||
else:
|
||||
self._answer(b"ok")
|
||||
|
||||
def do_POST(self):
|
||||
self.rfile.read(int(self.headers.get("Content-Length") or 0))
|
||||
self._answer(b"ok")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def site():
|
||||
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()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("route", [False, True])
|
||||
def test_every_request_of_the_page_reaches_the_client_with_its_end(firefox_binary, site, route):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
started, ended = [], []
|
||||
with InvisiblePlaywright(seed=4261, binary_path=firefox_binary, headless=True) as browser:
|
||||
context = browser.new_context()
|
||||
if route:
|
||||
context.route("**/*", lambda r: r.continue_())
|
||||
page = context.new_page()
|
||||
page.on("request", lambda r: started.append(r.url.replace(site, "")))
|
||||
page.on("requestfinished", lambda r: ended.append(r.url.replace(site, "")))
|
||||
page.on("requestfailed", lambda r: ended.append(r.url.replace(site, "")))
|
||||
page.goto(site + "/", wait_until="load")
|
||||
page.wait_for_timeout(2000) # the client is a sync one: events are delivered while it calls the browser
|
||||
seen = sorted(u for u in started if u.startswith("/seen/"))
|
||||
assert seen == ["/seen/beacon", "/seen/keepalive", "/seen/keepalive-nocors", "/seen/plain"], \
|
||||
"the client heard these requests: %r" % started
|
||||
assert sorted(u for u in ended if u.startswith("/seen/")) == seen, \
|
||||
"requests without an end for the client: %r" % sorted(set(seen) - set(ended))
|
||||
@@ -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,16 @@ 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 _socks_servers import Socks5TcpOnly
|
||||
from test_webrtc_realness import _PROBE_JS, 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):
|
||||
def through_the_proxy(timezone, proxy, locale, **_kw):
|
||||
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
|
||||
@@ -132,7 +133,7 @@ def test_a_bare_launch_behind_a_proxy_declares_the_egress_as_its_srflx(firefox_b
|
||||
|
||||
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Page)
|
||||
threading.Thread(target=httpd.serve_forever, daemon=True).start()
|
||||
socks = _Socks5TcpOnly()
|
||||
socks = Socks5TcpOnly()
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.firefox.launch(executable_path=firefox_binary, headless=True,
|
||||
@@ -146,7 +147,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)
|
||||
@@ -553,3 +553,29 @@ def test_a_download_that_comes_while_the_adoption_fails_is_said_once_on_the_open
|
||||
time.sleep(0.2)
|
||||
assert state["delivered"], "the adoption never failed"
|
||||
assert said.count("download") == 1, "the download that came while the adoption failed was said %d times: %r" % (said.count("download"), said)
|
||||
|
||||
|
||||
def test_the_opener_of_a_target_the_engine_already_took_away_is_not_remembered(late_browser):
|
||||
"""A download cannot come from a target that is detached: no entry is made for it (the table of openers is for the targets the
|
||||
engine still has when their adoption ends without announcing them)."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
gone = SimpleNamespace(target_id="t-gone", opener="o-1", gone=True)
|
||||
with late_browser._targets_lock:
|
||||
late_browser._remember_opener(gone)
|
||||
assert "t-gone" not in late_browser._gone_openers
|
||||
|
||||
|
||||
def test_the_opener_of_a_failed_adoption_lives_until_the_target_detaches_and_the_cap_holds(late_browser):
|
||||
from types import SimpleNamespace
|
||||
|
||||
alive = SimpleNamespace(target_id="t-alive", opener="o-2", gone=False)
|
||||
with late_browser._targets_lock:
|
||||
late_browser._remember_opener(alive)
|
||||
assert late_browser._gone_openers.get("t-alive") == "o-2", "the opener of a failed adoption was not remembered"
|
||||
late_browser._handle_detach("t-alive", "s-alive")
|
||||
assert "t-alive" not in late_browser._gone_openers, "the entry outlived the detach of its target"
|
||||
for number in range(20):
|
||||
with late_browser._targets_lock:
|
||||
late_browser._remember_opener(SimpleNamespace(target_id="t%d" % number, opener="o", gone=False))
|
||||
assert len(late_browser._gone_openers) == 16 and "t0" not in late_browser._gone_openers and "t19" in late_browser._gone_openers
|
||||
@@ -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,113 @@
|
||||
"""E2E: the rule "a context WITH a proxy resolves by DoH through it, a context WITHOUT one resolves natively and never
|
||||
uses the DoH", on the case where the two meet: a session with NO launch proxy and a context with a proxy of its own.
|
||||
|
||||
The session is launched without a proxy (the DEFAULT context is the browser's own network: it resolves natively), then a
|
||||
context is made with its own SOCKS5 gateway (`new_context(proxy=..., ignore_https_errors=True)`) and loads
|
||||
`http://page-a.test:<port>/`. The name `page-a.test` is one that only the FakeDoh can resolve: the machine's resolver
|
||||
cannot (a `.test` name is on no zone), and the gateway never resolves a name (it refuses a CONNECT that carries one). So
|
||||
the page loads only if the lookup of that context went to the DoH, through the proxy it was handed, even though no proxy
|
||||
exists at launch: the choice follows the proxy of the CONTEXT of each lookup, not the proxy of the launch.
|
||||
|
||||
The same test is the other half of the rule. While the proxied context loads its page, the default context is busy with
|
||||
its own background lookups (telemetry, update and extension endpoints...), and those are the machine's own network:
|
||||
|
||||
* they must NOT go to the DoH: nothing connects to the bootstrap address or to port 53 by a direct road (the watcher), the
|
||||
FakeDoh has no query for a name that is not one of the zone names this test asked (a background name of the default
|
||||
context in `doh.queries` is a lookup of the wrong context sent to the DoH), and the FakeDoh has no failed handshake (a
|
||||
lookup of a context without `ignore_https_errors` can only fail it, so a failure IS a default-context lookup sent to the
|
||||
DoH);
|
||||
* they go to the system resolver. Where the resolver trap runs (Linux, root) the trap sees at least one question that is
|
||||
no zone name: the background question of the default context. On Windows the native question cannot be observed
|
||||
without a resolver trap, so there the assertion is the negative one above (nothing of that traffic reaches the DoH).
|
||||
|
||||
Red on an engine that picks the road of a lookup by the session instead of by the user context: the background lookups of
|
||||
the default context go to the DoH by a DIRECT connection (the bootstrap address 192.0.2.53:443 is reached with no proxy;
|
||||
the giro-2 binary), or, if the proxy resolves remotely, arrive at the gateway as a NAME (refused, listed in `refused`) and
|
||||
the page does not load. Green when the resolver hook of the engine chooses per lookup by the user context.
|
||||
|
||||
Hermetic like the DoH e2e it borrows from (`test_doh_through_the_proxy_e2e.py`: the fixtures, the FakeDoh, the gateway, the
|
||||
watcher, the trap and the accounting of the end of a test are imported, not copied), with one difference in what is asserted:
|
||||
with no launch proxy the default context is the machine's own network, so its background traffic is allowed to be direct
|
||||
and to ask the machine's resolver; every assertion here is about the DoH road, the zone's names and this context.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
# The fixtures and the helpers of the DoH e2e (imported, not copied): the hermetic session (autouse), the resolver trap, the
|
||||
# watcher, the page server, the gateway factory, and the accounting of the connections to the FakeDoh.
|
||||
from test_doh_through_the_proxy_e2e import ( # noqa: F401 (the hermetic session is autouse and imported by name; the
|
||||
# other fixtures of the DoH e2e are in conftest.py)
|
||||
DOH_ADDRESSES, ZONE, _asked_outside, _assert_every_connection_went_through_the_gateway, _direct_to_the_doh,
|
||||
_hermetic_session, _is_address, _launch, _page_in, _text, _why)
|
||||
|
||||
import _doh_servers as ds
|
||||
from _doh_servers import DOH_BOOTSTRAP, DOH_HOST, DOH_PORT, QTYPE_A
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
#: How long to wait, where the resolver trap runs, for the background question of the default context to reach it.
|
||||
BACKGROUND_QUESTION_SECONDS = 20
|
||||
|
||||
|
||||
def test_a_context_that_is_the_only_proxy_resolves_its_names_by_doh_through_it(firefox_binary, doh, pages, gateway, trap,
|
||||
watcher):
|
||||
"""No proxy at launch; the context has gw. `page-a.test` is asked to the FakeDoh BY gw, the page is reached by ADDRESS
|
||||
through gw, nothing reaches the DoH directly, the machine's resolver is never asked for the name, and the background
|
||||
names of the default context neither reach the DoH nor are lost: they go to the system resolver."""
|
||||
gw = gateway("gw")
|
||||
background_question = None
|
||||
with _launch(firefox_binary, None) as browser: # no launch proxy: the session itself is on the host's network
|
||||
context, page = _page_in(browser, proxy=gw.proxy) # the only proxy there is: the context's own
|
||||
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
|
||||
text = _text(page)
|
||||
if trap is not None:
|
||||
# The default context asks the system resolver for its own background names while the session lives; the trap
|
||||
# answers nothing but REFUSED, so the question is all that is left of them. Wait for it here, before teardown.
|
||||
background_question = ds.wait_until(
|
||||
lambda: [q for q in trap.queries if q.name not in ZONE], BACKGROUND_QUESTION_SECONDS)
|
||||
context.close()
|
||||
watcher.stop()
|
||||
|
||||
why = _why(doh, gw)
|
||||
assert "HOST=page-a.test:%d" % pages.port in text, (
|
||||
"the page did not load: the name page-a.test, which only the FakeDoh can resolve, was not resolved by DoH through "
|
||||
"the proxy of the context (the lookup of a context with a proxy did not go to the DoH?): %r" % text + why)
|
||||
assert doh.vias_of("page-a.test", QTYPE_A) == {"gw"}, "page-a.test (A) was not asked by gw (the proxy of the context) only" + why
|
||||
assert (DOH_BOOTSTRAP, DOH_PORT) in gw.connects, "no DoH CONNECT to the bootstrap address reached the gateway of the context" + why
|
||||
assert not [h for h, _p in gw.connects if h == "page-a.test"], (
|
||||
"the browser sent the NAME page-a.test to the gateway instead of resolving it with the DoH" + why)
|
||||
assert [h for h, _p in gw.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 gw.connects, "the page was not reached by address through the gateway of the context" + why
|
||||
assert pages.hits and all(host.startswith("page-a.test") for host, _p in pages.hits), pages.hits
|
||||
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy of the context" + why
|
||||
_assert_every_connection_went_through_the_gateway(doh, gw)
|
||||
|
||||
# The names the DoH was asked for are the names of THIS context and no other: a background name of the default context
|
||||
# (a mozilla.org or github.com name...) in the log is a lookup of a context without a proxy sent to the DoH.
|
||||
assert _asked_outside(doh, "page-a.test") == [], (
|
||||
"the DoH was asked for a name that is not the proxied context's: the default context, which has no proxy, must "
|
||||
"resolve natively and never use the DoH: %s" % _asked_outside(doh, "page-a.test") + why)
|
||||
# A lookup of a context without `ignore_https_errors` (the default one) can only fail the handshake with the FakeDoh:
|
||||
# a failed handshake is a lookup of the wrong context that reached the DoH through this gateway.
|
||||
assert doh.tls_failures == [], (
|
||||
"a DoH handshake failed: a context that does not accept the FakeDoh certificate (the default context, which has no "
|
||||
"proxy) used the DoH: %s" % doh.tls_failures + why)
|
||||
|
||||
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 _direct_to_the_doh(watcher) == [], (
|
||||
"the browser reached a DoH (%s) or a DNS server (port 53) without the proxy: the background lookups of the default "
|
||||
"context, which has no proxy, went to the DoH instead of the system resolver: %s"
|
||||
% (", ".join(DOH_ADDRESSES), watcher.describe()))
|
||||
if trap is not None:
|
||||
assert [name for name in ZONE if trap.asked(name)] == [], (
|
||||
"the browser asked the resolver of the machine for a name of the zone: %s" % trap.describe() + why)
|
||||
assert background_question, (
|
||||
"the system resolver was asked nothing but zone names (nothing at all, here): the background names of the "
|
||||
"default context did not go to it. They went to the DoH, or the default context made no lookup in %d s: %s"
|
||||
% (BACKGROUND_QUESTION_SECONDS, trap.describe()) + why)
|
||||
# Where the trap cannot run (Windows, or Linux without root) the native question of the default context cannot be
|
||||
# observed: the assertion for it is the negative one above (no direct DoH connection, no query outside the zone, no
|
||||
# failed handshake).
|
||||
@@ -982,6 +982,11 @@ _EXPECTED_SIGNATURE = [
|
||||
# has nothing to arrive through - it is a property of the session, decided
|
||||
# before the first window is built, so it has to be said at construction.
|
||||
("show_cursor", inspect.Parameter.KEYWORD_ONLY),
|
||||
# Added 2026-11-11 on the owner's order, by name: where a SOCKS5 proxy's UDP exit is measured from ("ip:port"
|
||||
# IPv4 literals; None = the two public defaults). A parameter of the Python launch, kept on the session so the
|
||||
# launch and every later context proxy use the same list; it is not a browser declaration and reaches neither
|
||||
# its environment, argv, prefs nor pipe. Both entry points get it.
|
||||
("udp_stun_servers", inspect.Parameter.KEYWORD_ONLY),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
"""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 _e2e_binary, _launch, candidates, decode_priority, host_candidates, is_mdns # noqa: F401
|
||||
|
||||
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 gathered = {pc1: [], pc2: []};
|
||||
const keep = (name, e) => { if (e.candidate && e.candidate.candidate) gathered[name].push(e.candidate.candidate); };
|
||||
pc1.addEventListener('icecandidate', e => keep('pc1', e));
|
||||
pc2.addEventListener('icecandidate', e => keep('pc2', e));
|
||||
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));
|
||||
// The road the connection took, read from the browser's own statistics: the nominated pair, and the protocol of each end.
|
||||
let pair = null;
|
||||
try {
|
||||
const stats = await pc1.getStats();
|
||||
const byId = {};
|
||||
stats.forEach(r => { byId[r.id] = r; });
|
||||
stats.forEach(r => {
|
||||
if (r.type === 'candidate-pair' && r.state === 'succeeded' && (r.nominated || !pair)) {
|
||||
const l = byId[r.localCandidateId] || {}, rm = byId[r.remoteCandidateId] || {};
|
||||
pair = {local: l.protocol, remote: rm.protocol, localType: l.candidateType, remoteType: rm.candidateType,
|
||||
remoteAddress: rm.address || null};
|
||||
}
|
||||
});
|
||||
} catch (e) {}
|
||||
pc1.close(); pc2.close();
|
||||
return {opened, echoed, pair, gathered};
|
||||
}"""
|
||||
|
||||
# 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. That is a MEASURE of a fast machine and is printed, never judged: on a
|
||||
# GitHub runner the same road takes 67 ms (Windows) and 122 ms (Linux), and a verdict on an absolute time is a verdict on
|
||||
# the machine. What the test judges is the ROAD, which the machine cannot change (see the test), and a ceiling under the
|
||||
# first retry of the mDNS responder (3 s), which no machine is slow enough to reach by being slow.
|
||||
RETAIL_MEDIAN_WINDOW_MS = (30, 55) # printed beside the measure, for the reader
|
||||
MDNS_RETRY_MS = 3000 # the responder asks again after 3 s: a run that opens only then took the slow road
|
||||
|
||||
|
||||
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(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, capsys):
|
||||
"""The names the browser registered for itself must resolve although the declared address is not the host's, and
|
||||
the connection must take the road retail takes. Five cold launches; EVERY one is judged on the road, none on the clock:
|
||||
|
||||
* the data channel opens and echoes (a responder that cannot hear itself, or an OS list that is empty, kills it);
|
||||
* each connection gathered a UDP host candidate named by mDNS (a run without UDP is the reserved-port failure: the
|
||||
socket could not bind and the connection fell back to TCP, about 600 ms on average);
|
||||
* the nominated pair is direct and local over UDP at both ends: host or peer-reflexive, never relay or server-reflexive, never
|
||||
TCP (a peer-reflexive end is legitimate: the other connection's mDNS name was not resolved yet and its check came first);
|
||||
* it opens in less than the responder's first retry (3 s): a name that does not come back opens only at the retry.
|
||||
|
||||
The time itself is printed with the retail window beside it: a fast machine shows 30-55 ms, a runner shows more, and
|
||||
neither is a verdict (an absolute time failed on both GitHub runners with a healthy engine)."""
|
||||
runs = []
|
||||
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)
|
||||
runs.append(res)
|
||||
for side in ("pc1", "pc2"):
|
||||
hosts = [c for c in res["gathered"][side] if " typ host" in c]
|
||||
udp = [c for c in hosts if " UDP " in c.upper() or " udp " in c]
|
||||
assert udp, "run %d: %s gathered no UDP host candidate (the road without UDP): %r" % (n, side, res["gathered"][side])
|
||||
assert any(c.split()[4].endswith(".local") for c in udp), (
|
||||
"run %d: %s has no mDNS name among its UDP host candidates: %r" % (n, side, udp))
|
||||
pair = res["pair"]
|
||||
assert pair, "run %d: the browser reports no nominated pair: %r" % (n, res)
|
||||
assert pair["local"] == "udp" and pair["remote"] == "udp", (
|
||||
"run %d: the connection did not take UDP at both ends (the road through TCP): %r" % (n, pair))
|
||||
# DIRECT and local: each end is a host candidate, or a peer-reflexive one. The remote end is prflx when the other connection's mDNS
|
||||
# name was not resolved yet and its connectivity check arrived first: the address the check came from is learned as prflx, and
|
||||
# that is the same road. What it must never be is a relay or a server-reflexive candidate (a road through the proxy or the
|
||||
# network), and never TCP (checked above).
|
||||
assert pair["localType"] in ("host", "prflx") and pair["remoteType"] in ("host", "prflx"), (
|
||||
"run %d: the pair is not direct and local (a relay or a server-reflexive road): %r" % (n, pair))
|
||||
assert res["opened"] < MDNS_RETRY_MS, "run %d: opened after %d ms, at the responder's retry" % (n, res["opened"])
|
||||
times = sorted(r["opened"] for r in runs)
|
||||
low, high = RETAIL_MEDIAN_WINDOW_MS
|
||||
with capsys.disabled():
|
||||
print("\n[measure] two connections on one page open in %r ms, median %s (retail on a fast machine %d-%d ms; not a verdict)"
|
||||
% (times, statistics.median(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,437 @@
|
||||
"""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): the core declares the DoH PROVIDER for every session (`network.trr.uri` the DoH of
|
||||
Mozilla, `network.trr.bootstrapAddr` an address so the DoH host is found with no DNS) and, with a proxy,
|
||||
`network.proxy.allow_bypass` false; the ENGINE owns the state, so the core never writes `network.trr.mode`,
|
||||
`exclude-etc-hosts` or `excluded-domains`. Each browser context is a whole situation, decided per lookup by the user
|
||||
context of the lookup (the DoH service itself stays in mode 0; Juggler publishes the contexts that have a proxy):
|
||||
|
||||
* a context WITH a proxy - its own, or the launch proxy, which is the proxy of every context that has none of its own,
|
||||
the default one included - resolves its names ONLY by DoH, THROUGH that proxy, fail-closed: a DoH request is a channel
|
||||
like any other, so it leaves by a SOCKS5 CONNECT or an HTTP CONNECT to the DoH address, by the proxy of the context of
|
||||
the lookup, and the browser then connects to the resolved ADDRESS (SOCKS5 by address, never by name);
|
||||
* a context WITHOUT a proxy resolves natively (the system resolver) and NEVER reaches the DoH.
|
||||
|
||||
Page hosts, ICE server names and HTTP/3 hosts of a proxied context all follow the first rule. The session proxy is the
|
||||
first command on the pipe, and every proxied channel waits for it: nothing of a proxied context goes DIRECT. No UDP/53
|
||||
and no direct TCP to a DoH leave the browser, and no helper process (crash reporter, default browser agent,
|
||||
maintenance service, updater, pingsender) is started. The tests of a session WITH a launch proxy may therefore assert
|
||||
that nothing at all goes direct and nothing asks the system resolver (the default context is proxied too); the tests of a
|
||||
session WITHOUT one assert only about the DoH road, because the default context is then the machine's own network.
|
||||
`test_context_proxy_only_resolves_by_doh_e2e.py` and `test_resolver_race_e2e.py` test the rule where it is sharpest.
|
||||
|
||||
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. In a session
|
||||
WITH a launch proxy the default context is proxied too, so its background lookups go to the FakeDoh through the launch
|
||||
proxy and fail the handshake BY DESIGN: no assertion there counts the FakeDoh's TLS failures or treats a name of the
|
||||
default context as a result (the accounting helper below counts them against the CONNECTs of the gateway). In a session
|
||||
WITHOUT a launch proxy the default context resolves natively and never reaches the FakeDoh: there a TLS failure at the
|
||||
FakeDoh is itself the sign of the defect. 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 _doh_support import ZONE, Pages, a_display_when_the_host_has_none # noqa: F401 (Pages and ZONE are imported by name by the sibling tests)
|
||||
from _servers import LocalServer # noqa: F401
|
||||
|
||||
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
|
||||
|
||||
#: 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
|
||||
# `doh`, `gateway`, `trap`, `watcher` and `pages` are in conftest.py: the sibling files use them without importing them.
|
||||
@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, **_kw: GEO)
|
||||
monkeypatch.setattr(InvisiblePlaywright, "_assert_uscita_invariata", lambda self: None)
|
||||
# The core also asks the exit of a SOCKS5 proxy (its UDP measurement, invisible_core._udp_exit): api.ipify.org, icanhazip.com and
|
||||
# checkip.amazonaws.com BY NAME through the gateway of the context, which the tests below read as "a CONNECT carried a name"
|
||||
# (run 43164943499, Windows). The answer is declared here too.
|
||||
monkeypatch.setattr("invisible_core._geo.discover_egress_ip", lambda *_a, **_k: GEO.egress_ip)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------- helpers
|
||||
def _launch(binary, proxy, **kwargs):
|
||||
return InvisiblePlaywright(seed=42, binary_path=binary, proxy=proxy, extra_prefs=dict(PREFS),
|
||||
**{**a_display_when_the_host_has_none(), **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
|
||||
|
||||
|
||||
#: The addresses a DoH request could reach by a road other than the proxy of its context: the bootstrap address of the
|
||||
#: test's provider and the one of the core's default provider.
|
||||
DOH_ADDRESSES = (DOH_BOOTSTRAP, "162.159.61.4")
|
||||
|
||||
|
||||
def _direct_to_the_doh(watcher):
|
||||
"""The direct connections the watcher saw to a DoH address or to a DNS port (53)."""
|
||||
return [c for c in watcher.direct
|
||||
if c.remote.rsplit(":", 1)[0] in DOH_ADDRESSES or c.remote.endswith(":53")]
|
||||
|
||||
|
||||
def _asked_outside(doh, *zone_names):
|
||||
"""The FakeDoh queries whose name is none of `zone_names` nor a name under one of them (the question of the HTTPS
|
||||
record of a name is `_<port>._https.<name>`, which ends with it). Empty when only the names of the test's own
|
||||
contexts were asked, i.e. when no background name of another context reached the DoH."""
|
||||
names = tuple(n.lower() for n in zone_names)
|
||||
return [q for q in doh.queries if not any(q.name == n or q.name.endswith("." + n) for n in names)]
|
||||
|
||||
|
||||
def _assert_every_connection_went_through_the_gateway(doh, *proxies):
|
||||
"""Every connection the browser made, the test's own and (in a session with a launch proxy) 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 a proxied 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 anywhere the exit is the machine's own network and retail resolves with the
|
||||
system resolver. The core declares the DoH provider (uri + bootstrapAddr) in every session, but no engine-owned
|
||||
state (`network.trr.mode` and the other two), and no context has a proxy, so no lookup is a DoH lookup: the
|
||||
resolver trap sees the question and no connection goes to a DoH address."""
|
||||
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())
|
||||
assert watcher.watched_pids, "the watcher never saw a browser process: %s" % watcher.process_names
|
||||
assert _direct_to_the_doh(watcher) == [], (
|
||||
"a session with no proxy reached a DoH (or a DNS server) instead of the system resolver: %s" % watcher.describe())
|
||||
@@ -0,0 +1,217 @@
|
||||
"""E2E: the DoH of a proxied context when it is slow, and when it refuses once.
|
||||
|
||||
The engine resolves the names of a context with a proxy by the DoH service, which stays in global mode 0, and asks it
|
||||
with a per-request TRR_ONLY (fail-closed: no native fallback). Mozilla does not exercise that combination: its TRR-only
|
||||
is the GLOBAL mode 3, and several timeouts and counters of `TRRService` depend on the global mode. These two tests put
|
||||
the combination under the two stresses a real DoH gives, on the layout of `test_context_proxy_only_resolves_by_doh_e2e.py`
|
||||
(no launch proxy, one context with its own SOCKS5 gateway; the FakeDoh can be reached only through it, and only it
|
||||
knows the names used here, so a page loads only if the lookup went to the DoH).
|
||||
|
||||
* `test_a_slow_doh_still_resolves_the_name_of_a_proxied_context`: the FakeDoh holds EVERY answer for `slow-a.test` for 2 s
|
||||
(`delay_names`; each response is held after its query arrived, the A and the AAAA of the lookup together, so the
|
||||
connection to the DoH is up at once and only the answer is late: this is what the browser's DoH request timeout
|
||||
measures). In global mode 0 `TRRService::GetRequestTimeout` returns `network.trr.request_timeout_ms` (1.5 s); in global
|
||||
mode 3 it returns `network.trr.request_timeout_mode_trronly_ms` (30 s). A request made TRR_ONLY per request under a global
|
||||
mode 0 would keep the 1.5 s one and fail a lookup whose answer is only 2 s away, with nothing to fall back to. The page
|
||||
must load, within 20 s, and the FakeDoh log must show the queries answered after the delay.
|
||||
* `test_a_name_the_doh_refused_once_resolves_on_the_next_request`: the FakeDoh refuses the FIRST query of each type for
|
||||
`flaky-a.test` by ending the exchange with no answer (a reset h2 stream: a failure of the CHANNEL, the kind
|
||||
`ConfirmationContext::RecordTRRStatus` counts; `_doh_servers.FAILURE_KINDS` has the other two) and serves it afterwards.
|
||||
The first navigation may fail (NS_ERROR_UNKNOWN_HOST) or load; then a retry loop (up to 5 navigations 2 s apart, each in a
|
||||
fresh page of the same context, nothing cleared) must load within 15 s AND the FakeDoh must have been asked a second time:
|
||||
the browser asks again instead of serving the failure from a cache or from a temporary block that a global TRR-only
|
||||
mode would not have (`IsTemporarilyBlocked` returns false under global mode 3, and its blocklist is fed by failures
|
||||
counted under the global modes).
|
||||
|
||||
Red on an engine with the 1.5 s DoH timeout (the giro-2 and giro-3 binaries before the timeout fix) for the first test:
|
||||
the lookup of `slow-a.test` fails after 1.5 s, the navigation ends in NS_ERROR_UNKNOWN_HOST and the page never loads. The
|
||||
second test is red if the failure of the first lookup sticks (negative cache or temporary block) longer than the retry loop.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
# The fixtures and the helpers of the DoH e2e (imported, not copied): the hermetic session (autouse), the resolver trap,
|
||||
# the watcher, the page server, the gateway factory, and the accounting of the connections to the FakeDoh.
|
||||
from test_doh_through_the_proxy_e2e import ( # noqa: F401 (the hermetic session is autouse and imported by name; the
|
||||
# other fixtures of the DoH e2e are in conftest.py)
|
||||
DOH_ADDRESSES, _asked_outside, _assert_every_connection_went_through_the_gateway, _direct_to_the_doh,
|
||||
_hermetic_session, _is_address, _launch, _page_in, _text, _why)
|
||||
|
||||
import _doh_servers as ds
|
||||
from _doh_servers import DOH_BOOTSTRAP, DOH_HOST, DOH_PORT, QTYPE_A, QTYPE_AAAA
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
#: The latency of the slow DoH, and what a page behind it may take at most.
|
||||
DOH_LATENCY_S = 2.0
|
||||
SLOW_LOAD_LIMIT_S = 20.0
|
||||
#: The retries after a refusal: how many, how far apart, and the time they all have.
|
||||
RETRIES = 5
|
||||
RETRY_GAP_S = 2.0
|
||||
RETRY_WINDOW_S = 15.0
|
||||
|
||||
|
||||
#: Firefox keeps the failure of ANY lookup (a refused DoH query included) in the DNS cache for network.dnsNegativeCacheExpiration
|
||||
#: = 60 s, plus 60 s of grace (network.dnsNegativeCacheExpirationGracePeriod): retail behaviour, under a global TRR-only mode
|
||||
#: too, measured by reading nsHostResolver.cpp:1333-1349 (not by a run). To isolate what this test is about (no TEMPORARY BLOCK
|
||||
#: of the DoH and no stickiness beyond that cache) the session shortens the cache to 1 s and drops the grace period: the
|
||||
#: refusal is then forgotten within the retry window. This only touches a cache; the code path of the lookup is the same.
|
||||
SHORT_NEGATIVE_CACHE = {"network.dnsNegativeCacheExpiration": 1, "network.dnsNegativeCacheExpirationGracePeriod": 0}
|
||||
|
||||
|
||||
def _launch_with_a_short_negative_cache(binary):
|
||||
"""A session without a launch proxy (the proxy is the context's) whose DNS negative cache is 1 s."""
|
||||
from _doh_support import a_display_when_the_host_has_none
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
from test_doh_through_the_proxy_e2e import PREFS
|
||||
return InvisiblePlaywright(seed=42, binary_path=binary, proxy=None, extra_prefs={**PREFS, **SHORT_NEGATIVE_CACHE},
|
||||
**a_display_when_the_host_has_none())
|
||||
|
||||
|
||||
def _navigate(context, url, timeout_ms):
|
||||
"""(text or None, error or None, seconds) of one navigation in a fresh page of `context`, which is closed after."""
|
||||
page = context.new_page()
|
||||
started = time.monotonic()
|
||||
try:
|
||||
page.goto(url, wait_until="load", timeout=timeout_ms)
|
||||
return _text(page), None, time.monotonic() - started
|
||||
except Exception as exc: # noqa: BLE001 - the failure is the result
|
||||
return None, "%s: %s" % (type(exc).__name__, str(exc).splitlines()[0] if str(exc) else ""), \
|
||||
time.monotonic() - started
|
||||
finally:
|
||||
try:
|
||||
page.close()
|
||||
except Exception: # noqa: BLE001 - a page that cannot be closed is not the subject
|
||||
pass
|
||||
|
||||
|
||||
def _only_the_doh_road_was_used(doh, gw, watcher):
|
||||
"""The layout assertions of the context-only e2e: the DoH was reached by the gateway of the context, by address,
|
||||
and nothing went past it."""
|
||||
why = _why(doh, gw)
|
||||
assert (DOH_BOOTSTRAP, DOH_PORT) in gw.connects, "no DoH CONNECT to the bootstrap address reached the gateway" + why
|
||||
assert [h for h, _p in gw.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 "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy of the context" + why
|
||||
_assert_every_connection_went_through_the_gateway(doh, gw)
|
||||
# Context-only layout: the default context resolves natively and never uses the DoH, so a failed handshake (the lookup
|
||||
# of a context that does not accept the FakeDoh certificate) is a lookup of the wrong context sent to the DoH.
|
||||
assert doh.tls_failures == [], "a DoH handshake failed: the default context used the DoH: %s" % doh.tls_failures + why
|
||||
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 _direct_to_the_doh(watcher) == [], (
|
||||
"the browser reached a DoH (%s) or a DNS server (port 53) without the proxy: %s"
|
||||
% (", ".join(DOH_ADDRESSES), watcher.describe()))
|
||||
|
||||
|
||||
def test_a_slow_doh_still_resolves_the_name_of_a_proxied_context(firefox_binary, doh, pages, gateway, watcher,
|
||||
record_property):
|
||||
"""`slow-a.test` is known only to the FakeDoh, which answers it 2 s after the query. The page of a context with a
|
||||
proxy of its own must load within 20 s, reached by address through that proxy."""
|
||||
doh.names["slow-a.test"] = "127.0.0.1"
|
||||
doh.delay_names["slow-a.test"] = DOH_LATENCY_S
|
||||
gw = gateway("gw")
|
||||
text = error = None
|
||||
seconds = 0.0
|
||||
with _launch(firefox_binary, None) as browser: # no launch proxy: only the context has one
|
||||
context, page = _page_in(browser, proxy=gw.proxy)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
page.goto(pages.url("slow-a.test"), wait_until="load", timeout=int(SLOW_LOAD_LIMIT_S * 1000))
|
||||
text = _text(page)
|
||||
except Exception as exc: # noqa: BLE001 - reported below with what the FakeDoh saw
|
||||
error = "%s: %s" % (type(exc).__name__, str(exc).splitlines()[0] if str(exc) else "")
|
||||
seconds = time.monotonic() - started
|
||||
context.close()
|
||||
watcher.stop()
|
||||
record_property("goto_seconds", "%.2f" % seconds)
|
||||
|
||||
answers = doh.answers_for("slow-a.test")
|
||||
why = _why(doh, gw) + "\n FakeDoh answers (name, qtype, via, outcome, seconds held): %s\n goto took %.2f s" % (
|
||||
[tuple(a) for a in doh.answers], seconds)
|
||||
assert error is None and text is not None, (
|
||||
"the page behind a DoH that answers in %.0f s did not load (%s): the DoH request of a lookup made TRR_ONLY per "
|
||||
"request gave up before the answer (the 1.5 s timeout of global mode 0?)" % (DOH_LATENCY_S, error) + why)
|
||||
assert "HOST=slow-a.test:%d" % pages.port in text, "the page is not the page of the name: %r" % text + why
|
||||
assert seconds < SLOW_LOAD_LIMIT_S, "the page took %.1f s to load, the limit is %.0f s" % (seconds, SLOW_LOAD_LIMIT_S) + why
|
||||
assert seconds >= DOH_LATENCY_S - 0.2, (
|
||||
"the page loaded in %.2f s, before the DoH could have answered (%.0f s): the name was not resolved by it"
|
||||
% (seconds, DOH_LATENCY_S) + why)
|
||||
assert [a for a in answers if a.qtype == QTYPE_A], "the DoH was never asked for the A record of the name" + why
|
||||
assert answers and all(a.outcome == "answered" for a in answers), "the DoH refused something here" + why
|
||||
assert min(a.delay for a in answers) >= 1.8, (
|
||||
"a query was answered after only %.2f s: the FakeDoh did not hold it (A and AAAA: %s)"
|
||||
% (min(a.delay for a in answers), [(a.qtype, round(a.delay, 2)) for a in answers]) + why)
|
||||
assert doh.vias_of("slow-a.test", QTYPE_A) == {"gw"}, "slow-a.test (A) was not asked by gw (the proxy of the context)" + why
|
||||
assert not [h for h, _p in gw.connects if h == "slow-a.test"], "the browser sent the NAME to the gateway" + why
|
||||
assert ("127.0.0.1", pages.port) in gw.connects, "the page was not reached by address through the gateway" + why
|
||||
assert _asked_outside(doh, "slow-a.test") == [], (
|
||||
"the DoH was asked for a name that is not the proxied context's: %s" % _asked_outside(doh, "slow-a.test") + why)
|
||||
_only_the_doh_road_was_used(doh, gw, watcher)
|
||||
|
||||
|
||||
def test_a_name_the_doh_refused_once_resolves_on_the_next_request(firefox_binary, doh, pages, gateway, watcher,
|
||||
record_property):
|
||||
"""The FakeDoh ends the exchange of the first A (and the first AAAA) query for `flaky-a.test` with no answer, then
|
||||
serves the name. The first navigation may fail with NS_ERROR_UNKNOWN_HOST or load; a retry (a fresh page of the same
|
||||
context, 2 s apart, up to 5 times, within 15 s) must load, and the browser must have asked the DoH again. The
|
||||
DNS negative cache (60 s + 60 s of grace in a release, the same under a global TRR-only mode) is shortened to 1 s
|
||||
for this test (SHORT_NEGATIVE_CACHE): without it the retries would be answered from the cache, as in a retail
|
||||
Firefox, and the test would say nothing about a temporary block of the DoH.
|
||||
|
||||
WHAT IT MEASURES: that a lookup the DoH refused once is not blocked by anything of the DoH itself (no temporary
|
||||
blocklist, no failure counter: under a per-request TRR_ONLY with the service in global mode 0 neither applies, by
|
||||
reading TRRService.cpp:1025-1066, :1126, :1250-1298 and TRR.cpp:177-217) and that the browser asks the DoH again
|
||||
(a second A query at the FakeDoh) and resolves the name when it is served. WHAT IT DOES NOT MEASURE: how long Firefox
|
||||
keeps the failure of a lookup in its DNS cache (60 s + 60 s of grace in a release, retail behaviour, the same in a
|
||||
global TRR-only mode); that duration is shortened here on purpose and is not tested."""
|
||||
doh.names["flaky-a.test"] = "127.0.0.1"
|
||||
doh.fail_first["flaky-a.test"] = "close"
|
||||
gw = gateway("gw")
|
||||
url = pages.url("flaky-a.test")
|
||||
attempts = [] # (text or None, error or None, seconds)
|
||||
with _launch_with_a_short_negative_cache(firefox_binary) as browser:
|
||||
context, page = _page_in(browser, proxy=gw.proxy)
|
||||
page.close()
|
||||
attempts.append(_navigate(context, url, 20000))
|
||||
window_starts = time.monotonic()
|
||||
while attempts[-1][0] is None and len(attempts) <= RETRIES:
|
||||
remaining = RETRY_WINDOW_S - (time.monotonic() - window_starts)
|
||||
if remaining <= 0:
|
||||
break
|
||||
time.sleep(min(RETRY_GAP_S, remaining))
|
||||
remaining = RETRY_WINDOW_S - (time.monotonic() - window_starts)
|
||||
if remaining <= 0:
|
||||
break
|
||||
attempts.append(_navigate(context, url, int(min(8.0, remaining) * 1000)))
|
||||
context.close()
|
||||
watcher.stop()
|
||||
record_property("attempts", str([(ok is not None, err, round(s, 2)) for ok, err, s in attempts]))
|
||||
|
||||
queries = doh.queries_for("flaky-a.test", QTYPE_A)
|
||||
why = _why(doh, gw) + "\n FakeDoh answers (name, qtype, via, outcome, seconds held): %s\n navigations (text, error, s): %s" % (
|
||||
[tuple(a) for a in doh.answers], attempts)
|
||||
first_text, first_error, _s = attempts[0]
|
||||
assert first_text is not None or "NS_ERROR_UNKNOWN_HOST" in (first_error or ""), (
|
||||
"the first navigation failed in a way that is not the refusal of the name: %s" % first_error + why)
|
||||
refused = [a for a in doh.answers_for("flaky-a.test") if a.outcome == "close"]
|
||||
assert {a.qtype for a in refused} <= {QTYPE_A, QTYPE_AAAA} and [a for a in refused if a.qtype == QTYPE_A], (
|
||||
"the FakeDoh never refused the first A query of the name: the test did not exercise a refusal" + why)
|
||||
loaded = [a for a in attempts if a[0] is not None]
|
||||
assert loaded, (
|
||||
"no navigation to a name the DoH refused once loaded in %d attempts / %.0f s: the failure of the first lookup "
|
||||
"sticks (a cached failure or a temporary block)" % (len(attempts), RETRY_WINDOW_S) + why)
|
||||
assert "HOST=flaky-a.test:%d" % pages.port in loaded[0][0], "the page is not the page of the name: %r" % loaded[0][0] + why
|
||||
assert len(queries) >= 2, (
|
||||
"the DoH was asked for the A record of the name %d time(s): the browser must ask again after a refusal, not serve "
|
||||
"a cached failure beyond the DoH's own negative TTL" % len(queries) + why)
|
||||
assert [a for a in doh.answers_for("flaky-a.test", QTYPE_A) if a.outcome == "answered"], (
|
||||
"the DoH never answered the name after the refusal" + why)
|
||||
assert doh.vias_of("flaky-a.test", QTYPE_A) == {"gw"}, "flaky-a.test (A) was not asked by gw only" + why
|
||||
assert not [h for h, _p in gw.connects if h == "flaky-a.test"], "the browser sent the NAME to the gateway" + why
|
||||
assert _asked_outside(doh, "flaky-a.test") == [], (
|
||||
"the DoH was asked for a name that is not the proxied context's: %s" % _asked_outside(doh, "flaky-a.test") + why)
|
||||
_only_the_doh_road_was_used(doh, gw, watcher)
|
||||
@@ -0,0 +1,223 @@
|
||||
"""HTTP/3 behind a proxy: visits of one page read the protocols a retail Firefox reads, road by road.
|
||||
|
||||
⛔ THE KNOWN-BAD INPUT: an engine that refuses HTTP/3 whenever a proxy is in use reads `h2` on every visit behind a SOCKS5 gateway
|
||||
that relays UDP where the same Firefox reads `h3` after the first visits; one that reads `h3` at the FIRST visit of THIS
|
||||
fixture (see below: it is not a retail fact, it is a property of the fixture); and one that tries h3 over a UDP that goes nowhere
|
||||
makes the page wait for a timeout before it falls back to h2.
|
||||
|
||||
THE REFERENCE is a retail Firefox 159 on Windows, measured with DoH forced like our core (15 sessions per condition, one
|
||||
profile per session). With UDP free the first runs read h2/h2/h3 in 9 sessions, h2/h2/h2 in 4 and h2/h3/h3 in 2, and h3 does
|
||||
not have to come at the second visit. THE THIRD RUN (Windows, DoH and UDP free) READ h3 AT THE FIRST VISIT IN 3 SESSIONS OF 15
|
||||
(h3, h2, h2): behind a proxy "visit 1 is always h2" is NOT a retail fact. With UDP blocked it is h2/h2/h2 in 15 of 15, with no
|
||||
delay of the load: the only outcome of the retail that repeats every time. With no
|
||||
proxy and the native DNS (measured in loopback) it is h2, h3, h3. The method is the retail's: one context, the same page again
|
||||
and again (``?v=N`` keeps each visit off the HTTP cache), a pause of two seconds after each load so that the Alt-Svc it carries
|
||||
settles, and the ``nextHopProtocol`` of the navigation entry of the document,
|
||||
``performance.getEntriesByType('navigation')[0].nextHopProtocol``. What each road reads is in ``_udp_line.expected_protocols``
|
||||
and is judged by ``_udp_line.judge_visits``.
|
||||
|
||||
WHY VISIT 1 IS h2 HERE. The retail reads h3 at the first visit when the DNS answer carries the HTTPS record (type 65, with
|
||||
``alpn=h3``): the browser then knows before it connects. The server of these tests is reached by its ADDRESS, so no name is
|
||||
looked up and no HTTPS record exists; and the FakeDoh of the tests (tests/_doh_servers.py) never serves a type 65 with data
|
||||
(``FakeDoh.https_served`` stays empty; each test below asserts it, or that the page was reached by an address). That is what
|
||||
makes the first visit h2 in a hermetic test, and only that: a FakeDoh that learns to serve type 65 changes the expectation
|
||||
for the name it serves, and this test says so before it goes red on a protocol.
|
||||
|
||||
THE VISITS. No proxy: three, exactly h2, h3, h3. Behind a proxy: FIVE, on every road (the same number for all, for symmetry), and
|
||||
all five are done (no early stop: the judge is a pure function of the list, so it is deterministic). On the road with UDP free
|
||||
the first visit must be h2 (the fixture has no HTTPS record), at least one visit must be h3 within the five, and once a visit is
|
||||
h3 the next ones are h3 too; the second visit is not required to be h3. On the roads without usable UDP every one of the five is h2 and visits 2 to 5 load no more
|
||||
than ``LOAD_MARGIN_MS`` slower than the first. Time: about 3 s a visit (load plus the pause), so about 15 s of browsing per
|
||||
proxy test and 9 s for the one with no proxy.
|
||||
|
||||
THE ROADS. A proxy whose UDP the core MEASURED ``coherent`` (a STUN Binding through its ASSOCIATE came back from the address of
|
||||
its TCP exit) carries QUIC through the relay, the server sees the relay and never this host, and the page ends up on h3 as the
|
||||
retail does with UDP free. Every other proxy is "a router that drops UDP", and the engine acts on it: the SOCKS5 proxy
|
||||
that refuses UDP (``no``), whose UDP leaves from another address (``no``) or that never answers (``unmeasured``), and an HTTP
|
||||
proxy (which has no UDP at all): h2 on every visit, nothing QUIC reaches the server, no datagram of the page goes to a relay, and
|
||||
no visit waits for a timeout. The core's measurement is not replaced: it asks the relay of each gateway for a Binding for real,
|
||||
at the server the launch names (``udp_stun_servers``), and the test says what the launch declared.
|
||||
|
||||
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); its TCP side speaks HTTP/2 and
|
||||
carries ``Alt-Svc: h3`` (tests/_h3_server.py).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from _host_address import this_host_address
|
||||
from _udp_line import (declared_udp, egress_by_proxy, expected_protocols, judge_visits, measure_servers, no_https_record,
|
||||
visits_for)
|
||||
|
||||
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
|
||||
|
||||
#: What the product's own probe of the egress is told when there is no proxy: RFC 5737 TEST-NET-3.
|
||||
EXIT_DIRECT = "203.0.113.7"
|
||||
#: What the core is expected to have measured, by road.
|
||||
_DECLARED = {"socks5_coherent": "coherent", "socks5_no_udp": "no", "socks5_mismatched": "no", "socks5_unmeasured": "unmeasured"}
|
||||
#: The pause after each load (the retail method), and the nextHopProtocol of the document.
|
||||
PAUSE_MS = 2000
|
||||
_NAV_JS = "() => performance.getEntriesByType('navigation')[0].nextHopProtocol"
|
||||
|
||||
|
||||
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 _gateway(road: str, host: str):
|
||||
from _socks_servers import coherent, mismatched, silent_udp, tcp_only
|
||||
make = {"socks5_coherent": coherent, "socks5_no_udp": tcp_only, "socks5_mismatched": mismatched,
|
||||
"socks5_unmeasured": silent_udp}[road]
|
||||
# The relay sits on the address of this host, as a real gateway's does: the engine's UDP sockets are bound to an interface.
|
||||
# Its datagrams leave from that address too, on every system: Windows cannot send from 127.0.0.1 to an address of its own host
|
||||
# (WinError 10051, which this test once read as "the server saw QUIC from []"). The relay is told from a client that came direct
|
||||
# by the PORT it sends from (``gateway.exit_ports``), and it forwards only to this host: the browser's own QUIC to the Internet
|
||||
# stays in the lab.
|
||||
gateway = make(user="alice", password="s3cret", relay_host=host, exit_host=host)
|
||||
gateway.forward_only_to = {host}
|
||||
return gateway
|
||||
|
||||
|
||||
def _visits(road, server, monkeypatch, discover, **launch):
|
||||
"""Visit the page of ``server`` ``visits_for(road)`` times in one context; the nextHopProtocol of the document of each visit
|
||||
and the time ``page.goto`` took to the load event, in milliseconds."""
|
||||
from invisible_core import _geo
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", discover)
|
||||
protocols, walls = [], []
|
||||
# Firefox turns HTTP/3 off when the certificate chain ends in a root that is not one of its own (a self-signed test
|
||||
# server always does): measured, the Alt-Svc is learned, the QUIC handshake of validation succeeds with the override and
|
||||
# Firefox then closes it itself (hasThirdPartyRoots), so the visits stay h2. A test with a certificate of its own turns
|
||||
# that check off; the product does not (it would change what Firefox does with a root it does not know).
|
||||
prefs = {"network.http.http3.disable_when_third_party_roots_found": False, **launch.pop("extra_prefs", {})}
|
||||
with InvisiblePlaywright(headless=True, binary_path=_binary(), timezone="America/New_York", locale="en-US",
|
||||
extra_prefs=prefs, **launch) as browser:
|
||||
context = browser.new_context(ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
for visit in range(1, visits_for(road) + 1):
|
||||
url = server.url if visit == 1 else "%s?v=%d" % (server.url, visit)
|
||||
started = time.monotonic()
|
||||
page.goto(url, wait_until="load", timeout=60000)
|
||||
walls.append(round((time.monotonic() - started) * 1000))
|
||||
page.wait_for_timeout(PAUSE_MS) # let the later resources and the Alt-Svc settle
|
||||
protocols.append(page.evaluate(_NAV_JS))
|
||||
return protocols, walls
|
||||
|
||||
|
||||
def _report(road, protocols, walls, server, gateway=None):
|
||||
said = ("the %d visits of road %s read %s (a retail Firefox reads %s), loaded in %s ms; the server answered TCP with "
|
||||
"ALPN %s and saw QUIC from %s" % (len(protocols), road, protocols, expected_protocols(road), walls,
|
||||
server.tcp_alpn, server.quic_peers))
|
||||
if gateway is not None:
|
||||
said += "; datagrams the relay carried: %s" % sorted({(h, p) for h, p, _data in gateway.datagrams})
|
||||
if gateway.send_errors:
|
||||
said += "; sends of the relay that failed: %s" % sorted(set(gateway.send_errors))
|
||||
return said
|
||||
|
||||
|
||||
def test_a_page_with_no_proxy_reads_h2_then_h3_then_h3(monkeypatch):
|
||||
import aioquic # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
from _h3_server import H3Server
|
||||
|
||||
with H3Server(this_host_address()) as server:
|
||||
assert not no_https_record(server.address), no_https_record(server.address)
|
||||
protocols, walls = _visits("direct", server, monkeypatch, egress_by_proxy(direct=EXIT_DIRECT))
|
||||
problems = judge_visits("direct", protocols, walls)
|
||||
assert not problems, "; ".join(problems) + ". " + _report("direct", protocols, walls, server)
|
||||
assert server.quic_peers, "the h3 visits did not reach the server by QUIC"
|
||||
|
||||
|
||||
def test_a_page_behind_a_gateway_that_relays_udp_starts_on_h2_reaches_h3_within_five_visits_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
|
||||
|
||||
host = this_host_address()
|
||||
with H3Server(host) as server, _gateway("socks5_coherent", host) as gateway:
|
||||
assert not no_https_record(host), no_https_record(host)
|
||||
protocols, walls = _visits("socks5_coherent", server, monkeypatch, egress_by_proxy(gateway), proxy=gateway.proxy,
|
||||
udp_stun_servers=measure_servers(gateway))
|
||||
carried = [(h, p) for h, p, _data in gateway.datagrams if (h, p) == (host, server.port)]
|
||||
declared = declared_udp(gateway.proxy, measure_servers(gateway))
|
||||
said = _report("socks5_coherent", protocols, walls, server, gateway)
|
||||
assert declared == "coherent", "the core measured the gateway %s, not coherent: the engine would not use its relay. %s" % (declared, said)
|
||||
problems = judge_visits("socks5_coherent", protocols, walls)
|
||||
assert not problems, "; ".join(problems) + ". " + said
|
||||
assert carried, "the QUIC datagrams did not go by the relay of the gateway. " + said
|
||||
assert not gateway.send_errors, "the relay of the gateway could not send. " + said
|
||||
assert server.quic_peer_addrs and {a for a, _p in server.quic_peer_addrs} == {host} and {p for _a, p in server.quic_peer_addrs} <= set(gateway.exit_ports), (
|
||||
"the QUIC server saw %s: only the relay of the gateway (%s, from the ports %s) may reach it. %s" % (
|
||||
server.quic_peer_addrs, host, gateway.exit_ports, said))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("road", ["socks5_no_udp", "socks5_mismatched", "socks5_unmeasured"])
|
||||
def test_a_page_behind_a_socks5_proxy_that_is_not_coherent_reads_h2_on_every_visit_and_loads_without_delay(monkeypatch, road):
|
||||
"""A relay that is refused, that leaves from another address or that never answers is a router that drops UDP: every
|
||||
visit (five) is h2, nothing QUIC reaches the server, nothing of the page goes to the relay, and visits 2 to 5 load as fast as 1."""
|
||||
import aioquic # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
from _h3_server import H3Server
|
||||
|
||||
host = this_host_address()
|
||||
with H3Server(host) as server, _gateway(road, host) as gateway:
|
||||
assert not no_https_record(host), no_https_record(host)
|
||||
protocols, walls = _visits(road, server, monkeypatch, egress_by_proxy(gateway), proxy=gateway.proxy,
|
||||
udp_stun_servers=measure_servers(gateway))
|
||||
to_the_server = [(h, p) for h, p, _data in gateway.datagrams if (h, p) == (host, server.port)]
|
||||
declared = declared_udp(gateway.proxy, measure_servers(gateway))
|
||||
said = _report(road, protocols, walls, server, gateway)
|
||||
assert declared == _DECLARED[road], "the core declared udp=%s, the road is %s. %s" % (declared, _DECLARED[road], said)
|
||||
problems = judge_visits(road, protocols, walls)
|
||||
assert not problems, "; ".join(problems) + ". " + said
|
||||
assert not server.quic_peers, "a QUIC connection reached the server: %s. %s" % (server.quic_peers, said)
|
||||
assert not to_the_server, "the page's UDP went to a relay that was not measured coherent. " + said
|
||||
|
||||
|
||||
def test_a_page_behind_an_http_proxy_reads_h2_on_every_visit_and_loads_without_delay(monkeypatch):
|
||||
"""An HTTP proxy has no UDP at all: the engine refuses HTTP/3 behind it and the page falls to h2 by itself."""
|
||||
import aioquic # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
from _doh_servers import FakeDoh, relay
|
||||
from _h3_server import H3Server
|
||||
from _http_proxy import HttpProxy
|
||||
|
||||
class ProxyToTheServer(HttpProxy):
|
||||
"""The HTTP proxy of the tests relays a CONNECT to a loopback address only; this one also relays the one to the server."""
|
||||
target = None
|
||||
|
||||
def _connect(self, conn, host, port, authorization):
|
||||
if (host, port) != self.target:
|
||||
return super()._connect(conn, host, port, authorization)
|
||||
upstream = socket.create_connection((host, port), timeout=10)
|
||||
self._record("CONNECT", host, port, authorization, 200)
|
||||
self._answer(conn, 200)
|
||||
try:
|
||||
relay(conn, upstream)
|
||||
finally:
|
||||
upstream.close()
|
||||
|
||||
host = this_host_address()
|
||||
doh = FakeDoh({})
|
||||
try:
|
||||
with H3Server(host) as server:
|
||||
proxy = ProxyToTheServer("http1", doh)
|
||||
proxy.target = (host, server.port)
|
||||
try:
|
||||
protocols, walls = _visits("http_proxy", server, monkeypatch, lambda *_a, **_k: EXIT_DIRECT, proxy=proxy.proxy)
|
||||
connects = [c for c in proxy.connects if c == (host, server.port)]
|
||||
finally:
|
||||
proxy.close()
|
||||
said = _report("http_proxy", protocols, walls, server) + "; CONNECTs to the server: %d" % len(connects)
|
||||
problems = judge_visits("http_proxy", protocols, walls)
|
||||
assert not problems, "; ".join(problems) + ". " + said
|
||||
assert not no_https_record(host, doh), no_https_record(host, doh)
|
||||
assert connects, "the page did not go through the proxy. " + said
|
||||
assert not server.quic_peers, "a QUIC connection reached the server direct, around the proxy: %s. %s" % (server.quic_peers, said)
|
||||
finally:
|
||||
doh.close()
|
||||
@@ -0,0 +1,177 @@
|
||||
"""E2E: the name of an ICE server is resolved in the USER CONTEXT of the page, so it goes by the proxy of that context.
|
||||
|
||||
The defect these tests hold: the ICE resolver of a PeerConnection (NrIceResolver) resolved the NAME in `iceServers`
|
||||
with default OriginAttributes, so the DoH request of that lookup left in the default user context (user context 0) and
|
||||
not in the context of the page. In the log of the engine the page's own lookups read `Resolving host
|
||||
[page-a.test]<^userContextId=6...>` and the ICE one reads `Resolving host [stun-a.test]<>`. Two consequences a page
|
||||
(or the other side of the wire) can see:
|
||||
|
||||
* the DoH request of the ICE name went by the proxy of the SESSION and not by the one of the context of the page, and
|
||||
with `ignore_https_errors` a property of the context, the lookup of the default context cannot accept the DoH
|
||||
certificate: it fails at once (TRR error, no DNS answer) and the STUN server is marked FAILED a millisecond later;
|
||||
* so the gather of a page behind a gateway that does not relay UDP ended at once, without the ~11 s of nICEr's own
|
||||
timer that a retail Firefox on a network that drops UDP shows (the 701 at 11.1-11.3 s, see
|
||||
`test_a_proxy_that_does_not_relay_udp_gives_no_srflx_at_all` in test_webrtc_realness.py).
|
||||
|
||||
How each test sees it, with nothing but loopback (the tools are the ones of test_doh_through_the_proxy_e2e.py,
|
||||
`_doh_servers.py`, `_http_proxy.py` and `_socks_servers.py`):
|
||||
|
||||
* the FakeDoh maps the ICE names to 198.51.100.5 (`STUN_NUMBER`, TEST-NET-2), NOT to loopback: the ICE code skips a
|
||||
loopback STUN server, so a loopback answer would end the gather at once for a reason that has nothing to do with
|
||||
the context;
|
||||
* the gateway is a SOCKS5 one that is TCP only: `DohGateway` is a `Gateway` built with `udp="refuse"` (the option of
|
||||
`_socks_servers.py`; `tcp_only()` is the same thing for the plain gateway), so UDP ASSOCIATE is answered with reply
|
||||
code 7 and the page gets no srflx; or an HTTP proxy with credentials, which has no UDP at all;
|
||||
* the FakeDoh cannot read the user context of a DoH request (the request does not carry it), so a test attributes a
|
||||
question to a context by the GATEWAY it arrived by: the default context goes through the session proxy, each
|
||||
context under test through a proxy of its own. A question for an ICE name that arrives by the session proxy would
|
||||
be a question of the default context.
|
||||
|
||||
Every test is RED on an engine that resolves the ICE name with default OriginAttributes (the FakeDoh is never asked
|
||||
the name: the lookup of the default context fails its TLS handshake with the FakeDoh BY DESIGN) and GREEN on one that
|
||||
carries the attributes of the PeerConnection into the resolver. Two tests of test_doh_through_the_proxy_e2e.py turn
|
||||
green with the same fix without change: `test_an_ice_server_name_resolves_the_same_way` and
|
||||
`test_an_authenticated_http_proxy_resolves`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
# The fixtures and the helpers of the DoH e2e (imported, not copied): the hermetic session (autouse), the resolver
|
||||
# trap, the watcher, the page server, the gateway factory, and the checks of the end-of-test accounting.
|
||||
from test_doh_through_the_proxy_e2e import ( # noqa: F401 (the hermetic session is autouse and imported by name; the
|
||||
# other fixtures of the DoH e2e are in conftest.py)
|
||||
PREFS, ZONE, _assert_stayed_home, _create_a_peer_connection_for, _hermetic_session, _page_in, _why)
|
||||
# The page-side probe of the realness test: one STUN server, the candidates, the ICE errors, the timeline in ms
|
||||
# (`at_ms`: host/srflx/error/complete from the offer) and the end of the gather. Imported, not edited.
|
||||
from test_webrtc_realness import _RELAY_PROBE_JS, candidates
|
||||
|
||||
import _doh_servers as ds
|
||||
from _doh_servers import QTYPE_A, FakeDoh
|
||||
from _http_proxy import HttpProxy, basic
|
||||
from _socks_servers import STUN_NUMBER
|
||||
|
||||
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
|
||||
|
||||
#: The ICE names of the tests. Both resolve to a routable documentation address that only a relay could reach.
|
||||
ICE_ZONE = {**ZONE, "stun-a.test": STUN_NUMBER, "stun-b.test": STUN_NUMBER}
|
||||
STUN_A = "stun:stun-a.test:3478"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def doh():
|
||||
"""The FakeDoh with the ICE names pointing at STUN_NUMBER (overrides the one of the DoH e2e)."""
|
||||
pytest.importorskip("h2", reason="Firefox's TRR speaks h2: the FakeDoh serves it with the h2 package")
|
||||
server = FakeDoh(ICE_ZONE)
|
||||
yield server
|
||||
server.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tcp_only_proxy(doh, gateway, request):
|
||||
"""A proxy without UDP, by kind: a SOCKS5 gateway whose UDP ASSOCIATE is refused, or an HTTP proxy with credentials."""
|
||||
if request.param == "socks5":
|
||||
# DohGateway is built with udp="refuse": the TCP-only option of _socks_servers.Gateway (reply code 7).
|
||||
gw = gateway("gw1")
|
||||
assert gw.udp == "refuse"
|
||||
yield gw
|
||||
return
|
||||
proxy = HttpProxy("http1", doh, user="ferd_http_user", password="pw-é42")
|
||||
try:
|
||||
yield proxy
|
||||
finally:
|
||||
proxy.close()
|
||||
|
||||
|
||||
def _launch(binary, proxy):
|
||||
"""Like the DoH e2e's `_launch`, with the baseline's mDNS host candidates declared as the realness test does."""
|
||||
from _doh_support import a_display_when_the_host_has_none
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
return InvisiblePlaywright(seed=42, binary_path=binary, proxy=proxy, **a_display_when_the_host_has_none(),
|
||||
extra_prefs={**PREFS, "media.peerconnection.ice.obfuscate_host_addresses": True})
|
||||
|
||||
|
||||
# ============================================================================================================ tests
|
||||
@pytest.mark.parametrize("tcp_only_proxy", ["socks5", "http_with_credentials"], indirect=True,
|
||||
ids=["socks5_tcp_only", "http_with_credentials"])
|
||||
def test_a_gateway_without_udp_resolves_the_ice_name_then_ends_in_701(firefox_binary, doh, pages, tcp_only_proxy,
|
||||
trap, watcher):
|
||||
"""A page in a context with no proxy of its own (the proxy of the session is its proxy) gives `iceServers` a NAME.
|
||||
The name is asked to the DoH THROUGH that proxy, in the context of the page (whose certificate override accepts the
|
||||
FakeDoh), the answer is 198.51.100.5, the STUN request has no road (the proxy has no UDP) and the gather ends the
|
||||
way a retail Firefox on a network that drops UDP ends: host UDP and TCP candidates, no srflx, ONE ICE error 701 at
|
||||
nICEr's own time (10-13 s) together with the end of the gather. On an engine that resolves the name in the default
|
||||
context the FakeDoh is never asked and the gather ends at once (the name is unresolved)."""
|
||||
proxy = tcp_only_proxy
|
||||
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)
|
||||
res = page.evaluate(_RELAY_PROBE_JS, STUN_A)
|
||||
context.close()
|
||||
watcher.stop()
|
||||
|
||||
why = _why(doh, proxy) + "\n page: candidates %s, ICE errors %s, timeline (ms from the offer) %s" % (
|
||||
res["candidates"], res["errors"], res["at_ms"])
|
||||
# 1. The name was asked, by the proxy of the context and by no other road.
|
||||
ds.wait_until(lambda: doh.queries_for("stun-a.test", QTYPE_A), 3)
|
||||
assert doh.queries_for("stun-a.test", QTYPE_A), (
|
||||
"the DoH was never asked stun-a.test (A): the ICE resolver looked the name up in the default user context, whose "
|
||||
"DoH request cannot accept the FakeDoh certificate" + why)
|
||||
assert doh.vias_of("stun-a.test", QTYPE_A) == {proxy.name}, (
|
||||
"stun-a.test (A) was not asked by the proxy of the context only" + why)
|
||||
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy" + why
|
||||
assert proxy.doh_connects(), "the proxy carried no DoH CONNECT" + why
|
||||
if isinstance(proxy, HttpProxy):
|
||||
expected = basic("ferd_http_user", "pw-é42")
|
||||
assert set(proxy.doh_authorizations()) == {expected}, (
|
||||
"every DoH CONNECT must carry the preemptive Basic header" + 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)
|
||||
# 2. The end of the gather, as a retail Firefox with UDP blocked.
|
||||
cands = candidates(res["candidates"])
|
||||
typ = [c["typ"] for c in cands]
|
||||
assert "srflx" not in typ and "relay" not in typ, "a candidate that nothing allocated" + why
|
||||
assert [e["code"] for e in res["errors"]] == [701], "the STUN request must end in ONE ICE error 701" + why
|
||||
protocols = sorted({c["proto"].upper() for c in cands if c["typ"] == "host"})
|
||||
assert protocols == ["TCP", "UDP"], "host candidates of a retail with UDP blocked: UDP and TCP" + why
|
||||
assert 10_000 <= res["at_ms"]["error"] <= 13_000, (
|
||||
"the 701 came at %s ms; nICEr's time on a network that drops UDP is 11.1-11.3 s (an immediate error means the "
|
||||
"name was never resolved)" % res["at_ms"]["error"] + why)
|
||||
assert "complete" in res["at_ms"], "the gather did not end by itself" + why
|
||||
_assert_stayed_home(watcher, trap, doh, proxy)
|
||||
|
||||
|
||||
def test_the_ice_name_of_a_context_goes_by_the_proxy_of_that_context(firefox_binary, doh, pages, gateway, trap,
|
||||
watcher):
|
||||
"""The session proxy is gw0; the context 1 has gw1, the context 2 has gw2. The page of each context asks for the
|
||||
name of its own (stun-a.test, stun-b.test) and each name is asked at the gateway of ITS context only. No question
|
||||
for an ICE name leaves in the default context: the FakeDoh cannot read the user context of a request, so the
|
||||
default context is told by its road, the session proxy gw0, which must have carried no question for either name."""
|
||||
gw0, gw1, gw2 = gateway("gw0"), gateway("gw1"), gateway("gw2")
|
||||
with _launch(firefox_binary, gw0.proxy) as browser:
|
||||
context_1, page_1 = _page_in(browser, proxy=gw1.proxy)
|
||||
context_2, page_2 = _page_in(browser, proxy=gw2.proxy)
|
||||
page_1.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
|
||||
page_2.goto(pages.url("page-b.test"), wait_until="load", timeout=30000)
|
||||
_create_a_peer_connection_for(page_1, "stun-a.test")
|
||||
_create_a_peer_connection_for(page_2, "stun-b.test")
|
||||
asked_a = ds.wait_until(lambda: doh.queries_for("stun-a.test", QTYPE_A), 30)
|
||||
asked_b = ds.wait_until(lambda: doh.queries_for("stun-b.test", QTYPE_A), 30)
|
||||
for page in (page_1, page_2):
|
||||
page.evaluate("() => window.__pc.close()")
|
||||
context_1.close()
|
||||
context_2.close()
|
||||
watcher.stop()
|
||||
|
||||
why = _why(doh, gw0, gw1, gw2)
|
||||
assert asked_a, "the DoH was never asked stun-a.test (the lookup left in the default context)" + why
|
||||
assert asked_b, "the DoH was never asked stun-b.test (the lookup left in the default context)" + why
|
||||
assert doh.vias_of("stun-a.test", QTYPE_A) == {"gw1"}, "stun-a.test must be asked by gw1 (context 1) only" + why
|
||||
assert doh.vias_of("stun-b.test", QTYPE_A) == {"gw2"}, "stun-b.test must be asked by gw2 (context 2) only" + why
|
||||
on_the_session_proxy = [q for q in doh.queries if q.via == "gw0" and q.name in ("stun-a.test", "stun-b.test")]
|
||||
assert on_the_session_proxy == [], (
|
||||
"a question for an ICE name left in the default context (by the session proxy gw0): %s" % on_the_session_proxy
|
||||
+ why)
|
||||
assert gw1.doh_connects() and gw2.doh_connects(), "each context's proxy must have carried a DoH CONNECT" + why
|
||||
_assert_stayed_home(watcher, trap, doh, gw0, gw1, gw2)
|
||||
@@ -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:
|
||||
|
||||
@@ -168,7 +168,7 @@ def no_geo_lookup(monkeypatch):
|
||||
# Before, `resolve_session_locale` was a separate network call imported
|
||||
# inside __enter__, and stubbing only the geo left these tests at 34 s.
|
||||
monkeypatch.setattr("invisible_playwright.launcher.prepare_session_geo",
|
||||
lambda tz, proxy, locale: SessionGeo(
|
||||
lambda tz, proxy, locale, **_kw: SessionGeo(
|
||||
"America/New_York", "198.51.100.4",
|
||||
locale=decide_session_locale("en-US")))
|
||||
# And the lifetime guard. `bind` waits for the browser tree to APPEAR -
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -18,7 +18,8 @@ import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
# Bound to the engine that carries the UDP line: red on firefox-61/62 (the engine fix is in the 63): skips on the published engine; runs on the candidate.
|
||||
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
|
||||
|
||||
|
||||
def _stock_client(module):
|
||||
|
||||
@@ -27,8 +27,6 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import pytest
|
||||
|
||||
from test_popups_reach_the_client_e2e import browser # noqa: F401 (the two-transport fixture of the sibling file)
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
SLOW_SECONDS = 4
|
||||
@@ -124,7 +122,7 @@ class _Run:
|
||||
|
||||
|
||||
@pytest.mark.parametrize("how", ["open", "link"])
|
||||
def test_a_popup_to_a_204_is_never_announced(browser, site, how): # noqa: F811
|
||||
def test_a_popup_to_a_204_is_never_announced(browser, site, how):
|
||||
run = _Run(browser, site, how, "1")
|
||||
try:
|
||||
assert not run.wait_until(lambda: run.popups, NO_EVENT_SECONDS), \
|
||||
@@ -135,7 +133,7 @@ def test_a_popup_to_a_204_is_never_announced(browser, site, how): # noqa: F
|
||||
|
||||
|
||||
@pytest.mark.parametrize("how", ["open", "link"])
|
||||
def test_a_popup_to_a_server_that_never_answers_is_never_announced(browser, site, how): # noqa: F811
|
||||
def test_a_popup_to_a_server_that_never_answers_is_never_announced(browser, site, how):
|
||||
run = _Run(browser, site, how, "3")
|
||||
try:
|
||||
assert not run.wait_until(lambda: run.popups, NO_EVENT_SECONDS), \
|
||||
@@ -146,7 +144,7 @@ def test_a_popup_to_a_server_that_never_answers_is_never_announced(browser, site
|
||||
|
||||
|
||||
@pytest.mark.parametrize("how", ["open", "link"])
|
||||
def test_a_popup_to_a_slow_page_is_announced_when_it_answers(browser, site, how): # noqa: F811
|
||||
def test_a_popup_to_a_slow_page_is_announced_when_it_answers(browser, site, how):
|
||||
run = _Run(browser, site, how, "2")
|
||||
try:
|
||||
assert run.wait_until(lambda: run.popups, SLOW_SECONDS + 6), "the slow popup never arrived"
|
||||
@@ -161,7 +159,7 @@ def test_a_popup_to_a_slow_page_is_announced_when_it_answers(browser, site, how)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("how", ["open", "link"])
|
||||
def test_a_popup_to_an_attachment_reports_the_download_on_the_opener_and_closes(browser, site, how): # noqa: F811
|
||||
def test_a_popup_to_an_attachment_reports_the_download_on_the_opener_and_closes(browser, site, how):
|
||||
run = _Run(browser, site, how, "4")
|
||||
try:
|
||||
assert run.wait_until(lambda: run.downloads, 10), "no `download` event on the opener (stock gives one)"
|
||||
|
||||
@@ -74,34 +74,6 @@ def site():
|
||||
srv.server_close()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=["in-process", "stock-client"])
|
||||
def browser(request, firefox_binary):
|
||||
"""One browser per transport for the whole file."""
|
||||
if request.param == "in-process":
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(binary_path=firefox_binary, headless=True) as b:
|
||||
yield b
|
||||
return
|
||||
try: # the stock client (a pinned dev dependency), imported by name: the fork's guard forbids a static import
|
||||
sync_playwright = importlib.import_module("playwright.sync_api").sync_playwright
|
||||
except ImportError as exc:
|
||||
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc,
|
||||
pytrace=False)
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
b = p.firefox.connect(server.ws_endpoint)
|
||||
try:
|
||||
yield b
|
||||
finally:
|
||||
b.close()
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
def _route(context):
|
||||
context.route("**/*", lambda route: route.abort() if route.request.resource_type in ("image", "media")
|
||||
else route.continue_())
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
"""E2E: behind a gateway that DECLARES its exit, every value a page can read says that exit and nothing says this machine.
|
||||
|
||||
This replaces a check that was made by hand through a paid proxy against pages on the internet. No test here needs a real proxy
|
||||
or a site on the internet: the proxy is a local SOCKS5 gateway (``ExitGateway``, a ``coherent`` UDP road) that answers "what is my
|
||||
address" with the exit it declares, the names of the pages are resolved by a FakeDoh through that gateway, and the pages are a
|
||||
local site that reads the same values a page on the internet reads. The truth for the zone and the country of an exit is the
|
||||
core's own offline geo database (``ip_to_timezone`` and ``ip_to_country``, asked at test time), not a second service: the tests
|
||||
ask whether the pages say what the path ``prepare_session_geo`` takes says, for six exits in six countries. The session geo is
|
||||
NOT stubbed: the only replaced step is the HTTPS question "what is my address" (``egress_by_proxy``), which no local gateway can
|
||||
answer as itself; the zone, the language and the srflx are decided by the core from that answer.
|
||||
|
||||
One launch per exit (``observed``, six of them) is read by the tests below; each test judges one thing:
|
||||
|
||||
* the address a site sees, and that nothing reached the site, or the network, past the gateway;
|
||||
* WebRTC: the candidates and the SDP carry nothing of this machine;
|
||||
* DNS: the names of the pages reach the gateway (as DoH) and are not asked of the system resolver;
|
||||
* the time zone of the page, of its offsets read two ways, and of a worker;
|
||||
* the language of the page, of a worker and of the Accept-Language the site receives, and that it fits the exit's country;
|
||||
* a vendored detection page, served locally and loaded behind the gateway.
|
||||
|
||||
The four states of the gateway (coherent, TCP only, mismatched, silent) are tested by ``test_webrtc_realness.py``; here only the
|
||||
"nothing of the host" part of a coherent gather is added.
|
||||
|
||||
Hermetic on a real binary; the resolver trap runs where it can (Linux, root; ``INVPW_REQUIRE_TRAP=1`` makes a trap that cannot
|
||||
run a failure, as in the DoH suite), and the other assertions do not depend on it. On Windows the trap does not exist, and the
|
||||
Watcher still sees a connection to a DNS port.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
import _realness_support as rs
|
||||
import _trap_policy
|
||||
from _doh_servers import DOH_PROVIDER_PREFS, QTYPE_A, FakeDoh
|
||||
from _host_address import this_host_address
|
||||
from _leaks import ResolverTrap, Watcher
|
||||
from _socks_servers import STUN_NUMBER, STUN_PORT
|
||||
from _udp_line import egress_by_proxy, measure_servers
|
||||
from test_detectors_e2e import _DetectorSite
|
||||
from test_webrtc_realness import _RELAY_PROBE_JS
|
||||
|
||||
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
|
||||
|
||||
#: Loopback goes through the gateway too (the site is on loopback), and the DoH provider is the FakeDoh's (a preloaded host's
|
||||
#: certificate cannot be overridden): the same two things the DoH suite declares.
|
||||
PREFS = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": "", **DOH_PROVIDER_PREFS,
|
||||
"media.peerconnection.ice.obfuscate_host_addresses": True}
|
||||
STUN = "stun:%s:%d" % (STUN_NUMBER, STUN_PORT)
|
||||
|
||||
|
||||
def _start_trap():
|
||||
"""The resolver trap, or None where it cannot run and the gate does not require it (see the ``trap`` fixture)."""
|
||||
if not ResolverTrap.available:
|
||||
why = _trap_policy.failure(None, False, ResolverTrap.reason)
|
||||
if why:
|
||||
pytest.fail(why)
|
||||
return None
|
||||
trap = ResolverTrap()
|
||||
try:
|
||||
trap.__enter__()
|
||||
except OSError as exc:
|
||||
why = _trap_policy.failure(None, True, bind_error=exc)
|
||||
if why:
|
||||
pytest.fail(why)
|
||||
return None
|
||||
return trap
|
||||
|
||||
|
||||
def _truth_of(exit_ip):
|
||||
"""The zone and the country the core's geo database gives the exit: the truth of these tests."""
|
||||
from invisible_core._geo import ip_to_country, ip_to_timezone
|
||||
from invisible_core.download import ensure_geoip_mmdb
|
||||
|
||||
database = ensure_geoip_mmdb()
|
||||
return ip_to_timezone(exit_ip, database), ip_to_country(exit_ip, database)
|
||||
|
||||
|
||||
def _launch(binary, gateway, **extra):
|
||||
return InvisiblePlaywright(seed=42, headless=True, binary_path=binary, proxy=gateway.proxy,
|
||||
udp_stun_servers=measure_servers(gateway), extra_prefs=dict(PREFS), **extra)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=list(rs.EXITS), ids=list(rs.EXITS))
|
||||
def observed(request, firefox_binary):
|
||||
"""One launch behind the exit ``request.param``, read once: the plain data of everything it showed (the browser and the
|
||||
servers are closed before this returns)."""
|
||||
from invisible_core import _geo
|
||||
|
||||
label = request.param
|
||||
exit_ip = rs.EXITS[label]
|
||||
zone, country = _truth_of(exit_ip)
|
||||
relay_host = this_host_address() # before any server: a host with no route skips with nothing left listening
|
||||
seen = rs.Observation(label=label, exit_ip=exit_ip, zone=zone, country=country, host=rs.host_addresses() | {relay_host})
|
||||
patch = pytest.MonkeyPatch()
|
||||
doh = FakeDoh(rs.ZONE_NAMES)
|
||||
gateway = rs.ExitGateway("exit", doh, udp="relay", tcp_exit=exit_ip, udp_exit=exit_ip, relay_host=relay_host)
|
||||
site = rs.Site(gateway)
|
||||
trap = None
|
||||
watcher = Watcher(match=("firefox", Path(firefox_binary).stem.lower()))
|
||||
try:
|
||||
patch.setattr(_geo, "discover_egress_ip", egress_by_proxy(gateway))
|
||||
trap = _start_trap()
|
||||
watcher.start()
|
||||
with _launch(firefox_binary, gateway) as browser:
|
||||
context = browser.new_context(ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
page.goto(site.url(), wait_until="load", timeout=60000)
|
||||
result = page.evaluate(rs.PAGE_JS)
|
||||
seen.probe = page.evaluate(_RELAY_PROBE_JS, STUN)
|
||||
context.close()
|
||||
watcher.stop()
|
||||
seen.ip_seen, seen.reads = result["ip"], {"page": result["page"], "worker": result["worker"]}
|
||||
seen.arrivals = list(site.arrivals)
|
||||
seen.headers = site.headers_of("/", "/fetch", "/worker-fetch")
|
||||
seen.connects, seen.site_port = list(gateway.connects), site.port
|
||||
# The relay of the gateway is on this host's address (the ICE sockets cannot send to loopback on Windows): the UDP
|
||||
# that goes to it is the road, not a leak.
|
||||
seen.direct = [c.remote for c in watcher.direct if not (c.protocol == "udp" and c.remote.rsplit(":", 1)[0] == relay_host)]
|
||||
seen.watched = len(watcher.watched_pids)
|
||||
seen.doh_vias = {name: set(doh.vias_of(name, QTYPE_A)) for name in rs.ZONE_NAMES}
|
||||
seen.doh_connects = list(gateway.doh_connects())
|
||||
seen.gateway_name = gateway.name
|
||||
seen.trap_ran = trap is not None
|
||||
seen.trap_queries = [q.name for q in trap.queries] if trap is not None else []
|
||||
seen.datagrams = [(h, p) for h, p, _payload in gateway.datagrams]
|
||||
finally:
|
||||
watcher.stop()
|
||||
if trap is not None:
|
||||
trap.__exit__(None, None, None)
|
||||
patch.undo()
|
||||
site.close()
|
||||
gateway.close()
|
||||
doh.close()
|
||||
return seen
|
||||
|
||||
|
||||
# ============================================================================================================ the tests
|
||||
def test_a_site_sees_the_declared_exit_and_nothing_reaches_it_past_the_gateway(observed):
|
||||
"""1. A page asks a local "what is my address" endpoint, through the gateway, and is told the exit the gateway declares.
|
||||
The site tells a connection the gateway opened from one it did not (``ExitGateway.upstream_ports``): any request on the
|
||||
second kind is a direct connection. The watcher, which samples the connections of every browser process from before the
|
||||
launch, sees none to a non-loopback address either (other than the gateway's own UDP relay)."""
|
||||
assert observed.watched, "the watcher never saw a browser process: it proves nothing"
|
||||
problems = rs.ip_problems(observed.ip_seen, observed.arrivals, observed.direct, observed.exit_ip, observed.connects,
|
||||
observed.site_port)
|
||||
assert problems == [], "exit %s (%s): %s" % (observed.exit_ip, observed.label, problems)
|
||||
|
||||
|
||||
def test_a_coherent_gather_shows_nothing_of_this_machine(observed):
|
||||
"""2. The candidates and the SDP of a gather behind a coherent gateway: host candidates are mDNS names, there is no IPv6
|
||||
candidate behind an IPv4 exit, the server-reflexive candidate (if one is born) is the exit, and neither the SDP nor the
|
||||
candidates write a private address, a loopback one, or any address of this machine's interfaces."""
|
||||
problems = rs.webrtc_problems(observed.probe, observed.exit_ip, observed.host)
|
||||
assert problems == [], "exit %s (%s): %s; candidates: %s; sdp: %r" % (
|
||||
observed.exit_ip, observed.label, problems, observed.probe.get("candidates"), observed.probe.get("sdp"))
|
||||
|
||||
|
||||
def test_the_names_of_the_pages_reach_the_gateway_and_not_the_system_resolver(observed):
|
||||
"""3. The page was reached by a NAME. The browser asked the FakeDoh for it, through the gateway (a DoH CONNECT), connected
|
||||
to the answer by ADDRESS (no CONNECT carries the name), and asked the resolver of the machine nothing: the trap, where it
|
||||
can run, counted no question; where it cannot, no connection to port 53 was seen by the watcher."""
|
||||
assert observed.doh_vias[rs.SITE_NAME] == {observed.gateway_name}, (
|
||||
"%s was asked of the DoH by %s, not by the gateway only" % (rs.SITE_NAME, observed.doh_vias[rs.SITE_NAME]))
|
||||
assert observed.doh_connects, "no DoH CONNECT reached the gateway"
|
||||
assert [h for h, _p in observed.connects if h.lower() in rs.ZONE_NAMES] == [], (
|
||||
"a CONNECT carried the NAME of a page instead of its address: %s" % observed.connects)
|
||||
assert [c for c in observed.direct if c.endswith(":53")] == [], "a connection to a DNS port: %s" % observed.direct
|
||||
assert [q for q in observed.trap_queries if q.endswith(".test")] == [], (
|
||||
"the browser asked the resolver of the machine for %s" % observed.trap_queries)
|
||||
if observed.trap_ran:
|
||||
assert observed.trap_queries == [], "the browser asked the resolver of the machine: %s" % observed.trap_queries
|
||||
|
||||
|
||||
def test_the_timezone_of_the_page_its_offsets_and_its_worker_are_the_exits(observed):
|
||||
"""4. ``Intl.DateTimeFormat().resolvedOptions().timeZone``, the UTC offset computed two ways in the page (the clock of the
|
||||
page, ``getTimezoneOffset``, and the wall clock ``Intl`` prints for the zone the page names) at a northern-winter and a
|
||||
northern-summer instant, and the same reads inside a dedicated Worker, all equal the zone of the exit. The zone expected is
|
||||
what the core's own geo database gives the declared exit (``ip_to_timezone``): the truth here is the core's database, not a
|
||||
second service. The offsets expected come from the system tz database (``zoneinfo``)."""
|
||||
problems = rs.timezone_problems(observed.reads, observed.zone)
|
||||
assert problems == [], "exit %s (%s, %s): %s" % (observed.exit_ip, observed.label, observed.zone, problems)
|
||||
|
||||
|
||||
def test_the_language_of_the_page_its_worker_and_the_header_agree_and_fit_the_country(observed):
|
||||
"""5. ``navigator.language``, ``navigator.languages``, the ``Intl`` locale, the same inside a Worker, and the
|
||||
``Accept-Language`` the site receives (of the navigation, of a fetch and of the fetch of a worker) agree with each other,
|
||||
and the primary language is plausible for the country of the exit (a table of this suite, ``PLAUSIBLE_PRIMARY``; a country
|
||||
that is not in it is checked for agreement only)."""
|
||||
problems = rs.language_problems(observed.reads, observed.headers, observed.country)
|
||||
assert problems == [], "exit %s (%s, %s): %s" % (observed.exit_ip, observed.label, observed.country, problems)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------- the vendored detection page
|
||||
#: What the vendored detection page reads, in the page itself: the outcome fields only (the lies, the flags of a headless
|
||||
#: browser, and the three "lied" fields of the zone, the Intl and the worker).
|
||||
_DETECTION_JS = """() => {
|
||||
const f = window.Fingerprint;
|
||||
if (!f || !f.headless) return {ready: false};
|
||||
const on = (o) => Object.entries(o || {}).filter(([, v]) => v === true).map(([k]) => k).sort();
|
||||
return {
|
||||
ready: true,
|
||||
lies: (f.lies && f.lies.totalLies) || 0,
|
||||
headless: on(f.headless.headless),
|
||||
zone: f.timezone ? {location: f.timezone.location, lied: !!f.timezone.lied} : null,
|
||||
intl: f.intl ? {lied: !!f.intl.lied} : null,
|
||||
worker: f.workerScope ? {lied: !!f.workerScope.lied} : null,
|
||||
};
|
||||
}"""
|
||||
|
||||
|
||||
def _detection_page_of(site):
|
||||
"""The URL of the vendored detection page of the local site of ``test_detectors_e2e.py``: the one of its URL properties that
|
||||
is not the root (the root serves three other libraries; this page is the one that reports lies and headless flags)."""
|
||||
own = [name for name, value in vars(type(site)).items() if isinstance(value, property) and name.endswith("_url")]
|
||||
assert len(own) == 1, own
|
||||
return getattr(site, own[0])
|
||||
|
||||
|
||||
def test_the_vendored_detection_page_finds_nothing_behind_the_gateway(firefox_binary, monkeypatch):
|
||||
"""6. The vendored detection page, served locally, loaded behind the gateway: no lies, no flag of a headless browser, and
|
||||
none of the zone, the Intl or the worker reads marked as lied; and the zone the page reads is the exit's.
|
||||
|
||||
Stock Playwright Firefox 1.62 (its own Firefox, no proxy, the same page, observed once on the machine this was written on)
|
||||
shows ZERO lies and ZERO lied fields, and ONE headless flag: ``webDriverIsOn``, because stock runs with ``navigator.webdriver``
|
||||
true. That flag is the automation itself and not a reading the browser should share, so the assertion here stays zero for
|
||||
the headless flags; for the lies and the lied fields stock's outcome is zero too, so they are asserted zero. The page's
|
||||
worker-scope key was absent from stock's fingerprint, so it is asserted only when the page produces it."""
|
||||
from invisible_core import _geo
|
||||
|
||||
exit_ip = rs.EXITS["germany"]
|
||||
expected_zone, _country = _truth_of(exit_ip)
|
||||
doh = FakeDoh(rs.ZONE_NAMES)
|
||||
site = _DetectorSite()
|
||||
gateway = rs.ExitGateway("exit", doh, udp="relay", tcp_exit=exit_ip, udp_exit=exit_ip, relay_host=this_host_address())
|
||||
try:
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(gateway))
|
||||
with _launch(firefox_binary, gateway) as browser:
|
||||
context = browser.new_context(ignore_https_errors=True)
|
||||
page = context.new_page()
|
||||
page.goto(_detection_page_of(site), wait_until="domcontentloaded", timeout=60000)
|
||||
page.wait_for_function("() => !!(window.Fingerprint && window.Fingerprint.headless)", timeout=90000)
|
||||
outcome = page.evaluate(_DETECTION_JS)
|
||||
context.close()
|
||||
reached = ("127.0.0.1", site.port) in gateway.connects
|
||||
finally:
|
||||
site.close()
|
||||
gateway.close()
|
||||
doh.close()
|
||||
print("[detection page behind %s] %r" % (exit_ip, outcome))
|
||||
assert outcome["ready"], "the detection page never produced its fingerprint: %r" % outcome
|
||||
assert reached, "the detection page was not loaded through the gateway: %s" % gateway.connects
|
||||
assert outcome["lies"] == 0, "the detection page found %d lie(s): %r" % (outcome["lies"], outcome)
|
||||
assert outcome["headless"] == [], "the detection page raised headless flags: %r" % outcome
|
||||
lied = {k: v for k, v in (("zone", outcome["zone"]), ("intl", outcome["intl"]), ("worker", outcome["worker"]))
|
||||
if v and v.get("lied")}
|
||||
assert not lied, "the detection page marked as lied: %r" % lied
|
||||
assert outcome["zone"] is not None, "the detection page read no zone: %r" % outcome
|
||||
read = outcome["zone"]["location"].replace(", ", "/").replace(" ", "_")
|
||||
assert read in rs.acceptable_zones(expected_zone) or read == expected_zone, (
|
||||
"the detection page reads the zone %r, the exit's is %s" % (outcome["zone"]["location"], expected_zone))
|
||||
|
||||
|
||||
def test_the_exits_are_distinct_places():
|
||||
"""The six exits are six different zones (a test of the table, with no browser: it asks the database only), so a page that
|
||||
ignored the exit and kept one zone could not pass them all."""
|
||||
zones = {label: _truth_of(ip)[0] for label, ip in rs.EXITS.items()}
|
||||
assert len(set(zones.values())) == len(zones), zones
|
||||
for ip in rs.EXITS.values():
|
||||
assert ipaddress.ip_address(ip).is_global, ip
|
||||
@@ -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,202 @@
|
||||
"""E2E: the first navigation of a fresh context never asks the system resolver, whatever the situation of the context.
|
||||
|
||||
The rule (owner decision B): each browser context is a whole situation. A context WITH a proxy (its own, or the launch
|
||||
proxy that every context without a proxy of its own inherits) resolves its names ONLY by DoH, through that proxy,
|
||||
fail-closed; a context WITHOUT a proxy resolves natively and never uses the DoH. The resolver hook of the engine chooses
|
||||
per lookup by the user context of the lookup, from the contexts that Juggler publishes as proxied in a pref.
|
||||
|
||||
The race this file is about: the proxy of a context is declared by the wrapper AFTER `Browser.createBrowserContext` and the
|
||||
first lookup of its first page can be made at once. If the engine does not know yet that the context is proxied, the first
|
||||
lookup takes the native road: the system resolver is asked for a name of a proxied context (a leak of the name, and on a
|
||||
real network the page does not even load). Every case here therefore creates the context and navigates IMMEDIATELY: no
|
||||
wait, no warm-up, no earlier page in the same context. The names are known only to the FakeDoh (`race-<n>.test` are on no
|
||||
zone of the machine and the gateway never resolves a name), so a native lookup ends in NS_ERROR_UNKNOWN_HOST and a page
|
||||
that loads proves that the DoH, through the gateway of its context, resolved the name.
|
||||
|
||||
Three situations (the parameter):
|
||||
|
||||
* `context_proxy`: no launch proxy; 8 contexts created back-to-back, each with a gateway of its own and a distinct name,
|
||||
each navigated at once and closed. Every page loads, every name is asked only by the gateway of its context, none is
|
||||
ever asked `direct`, nothing reaches the DoH by a direct connection, and no DoH query or failed handshake belongs to the
|
||||
default context (which has no proxy and resolves natively);
|
||||
* `browser_proxy`: a launch proxy and contexts WITHOUT a proxy of their own, navigated at once: they use the launch proxy
|
||||
(the DoH through it), as does the default context, so here nothing at all may go direct or ask the system resolver;
|
||||
* `context_without_proxy_beside_a_proxied_one`: no launch proxy, a proxied context A and a context B without a proxy.
|
||||
A name is not hermetic for B (the names the system resolver knows are the host's), so B navigates by ADDRESS
|
||||
(`http://127.0.0.1:<port>/`, which needs no name) before and after A has used the DoH, and the test shows that B never
|
||||
borrowed the proxy of A (its server is not in A's gateway log) and never shows up at the FakeDoh (the only queries are
|
||||
A's names, by A's gateway).
|
||||
|
||||
Where the resolver trap runs (Linux, root) it adds the direct proof: it is never asked for a name of the proxied contexts.
|
||||
On Windows the native question cannot be observed without a resolver trap, so there the proof is the one above: the page of
|
||||
a name known only to the DoH loads, and the DoH log and the gateways account for every name.
|
||||
|
||||
Fixtures, FakeDoh, gateway, watcher, trap and the accounting of the end of a test are those of
|
||||
`test_doh_through_the_proxy_e2e.py` (imported, not copied).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from test_doh_through_the_proxy_e2e import ( # noqa: F401 (the hermetic session is autouse and imported by name; the
|
||||
# other fixtures of the DoH e2e are in conftest.py)
|
||||
DOH_ADDRESSES, Pages, _asked_outside, _assert_every_connection_went_through_the_gateway, _assert_stayed_home,
|
||||
_direct_to_the_doh, _hermetic_session, _is_address, _launch, _page_in, _text, _why)
|
||||
|
||||
from _doh_servers import DOH_HOST, QTYPE_A
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
#: Contexts created back-to-back in one session.
|
||||
ROUNDS = 8
|
||||
#: A navigation that cannot resolve its name must fail fast (NS_ERROR_UNKNOWN_HOST), not wait the default 30 s per round.
|
||||
GOTO_MS = 20000
|
||||
|
||||
|
||||
def _race_names(prefix):
|
||||
return ["%s-%d.test" % (prefix, i) for i in range(ROUNDS)]
|
||||
|
||||
|
||||
def _navigate_at_once(browser, pages, name, proxy):
|
||||
"""Create a context (with `proxy` when given), open its first page and navigate at once, with nothing in between.
|
||||
Returns (text of the page or None, error text or None). The context is closed either way."""
|
||||
context, page = _page_in(browser, proxy=proxy)
|
||||
try:
|
||||
page.goto(pages.url(name), wait_until="load", timeout=GOTO_MS)
|
||||
return _text(page), None
|
||||
except Exception as exc: # noqa: BLE001 - the failure is the result: it is reported with the other rounds
|
||||
return None, "%s: %s" % (type(exc).__name__, str(exc).splitlines()[0] if str(exc) else "")
|
||||
finally:
|
||||
context.close()
|
||||
|
||||
|
||||
def _names_asked_to_the_system_resolver(trap, names):
|
||||
"""The trap's questions about one of `names` or a name under one (None when there is no trap)."""
|
||||
if trap is None:
|
||||
return None
|
||||
return [q for q in trap.queries if any(q.name == n or q.name.endswith("." + n) for n in names)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["context_proxy", "browser_proxy", "context_without_proxy_beside_a_proxied_one"])
|
||||
def test_the_first_navigation_of_a_fresh_context_never_asks_the_system_resolver(
|
||||
mode, firefox_binary, doh, pages, gateway, trap, watcher):
|
||||
if mode == "context_without_proxy_beside_a_proxied_one":
|
||||
_beside_a_proxied_context(firefox_binary, doh, pages, gateway, trap, watcher)
|
||||
else:
|
||||
_back_to_back_contexts(mode, firefox_binary, doh, pages, gateway, trap, watcher)
|
||||
|
||||
|
||||
def _back_to_back_contexts(mode, firefox_binary, doh, pages, gateway, trap, watcher):
|
||||
names = _race_names("race-" + mode.split("_")[0])
|
||||
doh.names.update({n: "127.0.0.1" for n in names})
|
||||
if mode == "context_proxy":
|
||||
# no launch proxy; one gateway per context, so "asked only by the gateway of its own context" is checkable
|
||||
launch_gateway, roads = None, {n: gateway("gw-%d" % i) for i, n in enumerate(names)}
|
||||
else:
|
||||
# a launch proxy; the contexts have none of their own and inherit it
|
||||
launch_gateway = gateway("launch")
|
||||
roads = {n: launch_gateway for n in names}
|
||||
gateways = list(dict.fromkeys(roads.values()))
|
||||
outcomes = {}
|
||||
|
||||
with _launch(firefox_binary, launch_gateway.proxy if launch_gateway else None) as browser:
|
||||
for name in names:
|
||||
own_proxy = roads[name].proxy if launch_gateway is None else None
|
||||
outcomes[name] = _navigate_at_once(browser, pages, name, own_proxy)
|
||||
watcher.stop()
|
||||
|
||||
why = _why(doh, *gateways)
|
||||
failed = {n: err for n, (text, err) in outcomes.items() if text is None}
|
||||
assert failed == {}, (
|
||||
"%d of %d first navigations failed: the name, known only to the DoH, was not resolved by it through the proxy of "
|
||||
"its context (a native lookup would end in NS_ERROR_UNKNOWN_HOST): %s" % (len(failed), ROUNDS, failed) + why)
|
||||
wrong = {n: text for n, (text, _e) in outcomes.items() if "HOST=%s:%d" % (n, pages.port) not in text}
|
||||
assert wrong == {}, "a page loaded but is not the page of its name: %s" % wrong + why
|
||||
|
||||
for name in names:
|
||||
road = roads[name]
|
||||
assert doh.vias_of(name, QTYPE_A) == {road.name}, (
|
||||
"%s (A) was not asked by %s (the proxy of its context) only: %s" % (name, road.name, doh.vias_of(name)) + why)
|
||||
assert not [h for h, _p in road.connects if h == name], (
|
||||
"the browser sent the NAME %s to the gateway instead of resolving it with the DoH" % name + why)
|
||||
assert ("127.0.0.1", pages.port) in road.connects, "%s was not reached by address through %s" % (name, road.name) + why
|
||||
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy of its context" + why
|
||||
for gw in gateways:
|
||||
assert gw.doh_connects(), "%s carried no DoH CONNECT" % gw.name + why
|
||||
assert [h for h, _p in gw.connects if not _is_address(h) and h != DOH_HOST] == [], (
|
||||
"a CONNECT of %s carried a name: the browser must resolve with the DoH and connect by address" % gw.name + why)
|
||||
assert pages.hits and {host.split(":")[0] for host, _p in pages.hits} == set(names), (
|
||||
"the page server saw hosts other than the names of the rounds: %s" % pages.hits)
|
||||
_assert_every_connection_went_through_the_gateway(doh, *gateways)
|
||||
|
||||
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 _direct_to_the_doh(watcher) == [], (
|
||||
"the browser reached a DoH (%s) or a DNS server without the proxy of its context: %s"
|
||||
% (", ".join(DOH_ADDRESSES), watcher.describe()) + why)
|
||||
asked_natively = _names_asked_to_the_system_resolver(trap, names)
|
||||
if asked_natively is not None:
|
||||
assert asked_natively == [], (
|
||||
"the system resolver was asked for a name of a proxied context: %s" % trap.describe() + why)
|
||||
|
||||
if launch_gateway is None:
|
||||
# No launch proxy: the default context is the machine's own network. It resolves natively and never uses the DoH:
|
||||
# no name but the rounds' in the DoH log, and no failed handshake (only the default context lacks the certificate
|
||||
# exception, so a failed handshake is a lookup of the default context that reached the DoH).
|
||||
assert _asked_outside(doh, *names) == [], (
|
||||
"the DoH was asked for a name that is not one of the proxied contexts' (the default context has no proxy and "
|
||||
"must resolve natively): %s" % _asked_outside(doh, *names) + why)
|
||||
assert doh.tls_failures == [], "a context without the FakeDoh certificate exception used the DoH: %s" % doh.tls_failures + why
|
||||
else:
|
||||
# The launch proxy is the proxy of the default context too: its background names go to the DoH through the launch
|
||||
# proxy (their handshakes fail BY DESIGN and are counted by the accounting above), so here nothing may go direct or
|
||||
# ask the system resolver at all.
|
||||
_assert_stayed_home(watcher, trap, doh, launch_gateway)
|
||||
|
||||
|
||||
def _beside_a_proxied_context(firefox_binary, doh, pages, gateway, trap, watcher):
|
||||
name_a = "race-beside-a.test"
|
||||
doh.names[name_a] = "127.0.0.1"
|
||||
gw_a = gateway("gw-a")
|
||||
home_b = Pages() # B's own server: whose gateway log it is in says which road B took
|
||||
try:
|
||||
with _launch(firefox_binary, None) as browser:
|
||||
context_b, page_b = _page_in(browser) # no proxy of its own, no launch proxy
|
||||
context_a, page_a = _page_in(browser, proxy=gw_a.proxy) # created while B lives
|
||||
page_b.goto(home_b.url("127.0.0.1"), wait_until="load", timeout=GOTO_MS)
|
||||
first_b = _text(page_b)
|
||||
page_a.goto(pages.url(name_a), wait_until="load", timeout=GOTO_MS)
|
||||
text_a = _text(page_a)
|
||||
page_b.goto(home_b.url("127.0.0.1") + "again", wait_until="load", timeout=GOTO_MS) # after A has used the DoH
|
||||
second_b = _text(page_b)
|
||||
context_a.close()
|
||||
context_b.close()
|
||||
watcher.stop()
|
||||
|
||||
why = _why(doh, gw_a)
|
||||
assert "HOST=%s:%d" % (name_a, pages.port) in text_a, (
|
||||
"A's page did not load: the name, known only to the DoH, was not resolved by it through A's proxy: %r" % text_a + why)
|
||||
assert "HOST=127.0.0.1:%d" % home_b.port in first_b and "HOST=127.0.0.1:%d" % home_b.port in second_b, (
|
||||
"B's pages did not load by address: %r %r" % (first_b, second_b) + why)
|
||||
assert [path for _h, path in home_b.hits if path != "/favicon.ico"] == ["/", "/again"], "B's server saw: %s" % home_b.hits
|
||||
assert doh.vias_of(name_a, QTYPE_A) == {"gw-a"}, "%s (A) was not asked by A's gateway only" % name_a + why
|
||||
assert ("127.0.0.1", pages.port) in gw_a.connects, "A's page was not reached by address through A's gateway" + why
|
||||
assert ("127.0.0.1", home_b.port) not in gw_a.connects, (
|
||||
"B's page went through A's gateway: B, which has no proxy, borrowed the proxy of A" + why)
|
||||
# B's lookups are the machine's own and never show up at the FakeDoh: only A's name was asked, by A's gateway.
|
||||
assert _asked_outside(doh, name_a) == [], (
|
||||
"the FakeDoh was asked for a name that is not A's (B and the default context have no proxy and must not use the "
|
||||
"DoH): %s" % _asked_outside(doh, name_a) + why)
|
||||
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without A's proxy" + why
|
||||
assert doh.tls_failures == [], "a context without the FakeDoh certificate exception used the DoH: %s" % doh.tls_failures + why
|
||||
_assert_every_connection_went_through_the_gateway(doh, gw_a)
|
||||
|
||||
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 _direct_to_the_doh(watcher) == [], (
|
||||
"the browser reached a DoH or a DNS server without the proxy: %s" % watcher.describe() + why)
|
||||
asked_natively = _names_asked_to_the_system_resolver(trap, [name_a])
|
||||
if asked_natively is not None:
|
||||
assert asked_natively == [], "the system resolver was asked for A's name: %s" % trap.describe() + why
|
||||
finally:
|
||||
home_b.close()
|
||||
@@ -0,0 +1,84 @@
|
||||
"""The UDP association of the proxy is ready BEFORE the PeerConnection is born: its first datagram does not wait for a handshake.
|
||||
|
||||
⛔ THE KNOWN-BAD INPUT. The sockets of a PeerConnection are made in the SOCKET process; the pool of UDP associations was warmed only
|
||||
where Necko opens a SOCKS5 connection (the parent, where HTTP lives). So the first ICE socket found the pool empty and made its
|
||||
association from scratch: TCP, greeting, auth, ASSOCIATE, four round trips before the first STUN datagram left (605 ms of 1083 on a
|
||||
real proxy 150 ms away; measured in the logs of the giro 2 binary: "layer pushed" at +34 ms from the birth of the PeerConnection,
|
||||
"ASSOCIATE OK" at +639 ms). A retail Firefox at home has no such wait.
|
||||
|
||||
What is asserted, with a gateway that answers every step of the handshake after a round trip (130 ms):
|
||||
1. an association the gateway granted was completed before the PeerConnection was created (the page loaded through the same
|
||||
proxy first, which is when Firefox learns the proxy); alone this does not tell the processes apart (the parent's pool is
|
||||
warmed by the page load), the second line does;
|
||||
2. the first STUN datagram of the PeerConnection reaches the relay within a fraction of a handshake of its birth (a cold
|
||||
association needs three answered steps, 3 x 130 ms, before it can send).
|
||||
Hermetic: a local SOCKS5 gateway with a relay and a fake STUN server, a local page reached through the proxy, no external network.
|
||||
Red on an engine that warms the pool only in the process of the HTTP connections: measured on the giro 2 binary, the first datagram left
|
||||
396 ms after the birth of the PeerConnection (3 x 130 ms) instead of at once.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from _socks_servers import STUN_NUMBER, STUN_PORT, coherent
|
||||
from _udp_line import egress_by_proxy
|
||||
from test_webrtc_realness import _e2e_binary, _launch # noqa: F401
|
||||
|
||||
# Bound to the engine that carries the UDP line: red before the UDP line (firefox-63): skips on the published engine; runs on the candidate.
|
||||
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
|
||||
|
||||
RTT_MS = 130
|
||||
|
||||
_PC_JS = """async (stun) => {
|
||||
const t_pc = Date.now();
|
||||
const pc = new RTCPeerConnection({iceServers: [{urls: ['stun:' + stun]}]});
|
||||
pc.createDataChannel('x');
|
||||
let t_srflx = null;
|
||||
pc.onicecandidate = e => { if (e.candidate && e.candidate.type === 'srflx' && t_srflx === null) t_srflx = Date.now(); };
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
const deadline = Date.now() + 8000;
|
||||
while (t_srflx === null && Date.now() < deadline) await new Promise(r => setTimeout(r, 5));
|
||||
pc.close();
|
||||
return {t_pc, t_srflx};
|
||||
}"""
|
||||
|
||||
|
||||
def test_the_first_datagram_does_not_wait_for_a_handshake(local_https_page, monkeypatch):
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
from invisible_core import _geo
|
||||
with coherent(user="alice", password="s3cret", rtt_ms=RTT_MS) as gateway:
|
||||
# ⛔ THE SESSION'S UDP HAS TO BE DECLARED COHERENT, or the engine treats the proxy as a router that drops UDP (no association is
|
||||
# asked, no datagram leaves) - the red of the giro 3 gate. The core declares `coherent` when the UDP probe's mapped address IS
|
||||
# the TCP exit it discovered; a hermetic test gives it the gateway's TCP exit as every e2e of the line does (the probe that
|
||||
# follows still runs through the relay, for real). The hermetic world has no network but the gateway, so the core's own discovery of the
|
||||
# exit (third-party echo services) fails and the verdict would be `unmeasured`.
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(gateway))
|
||||
prefs = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": ""}
|
||||
with _launch(binary_path=binary, proxy=gateway.proxy, extra_prefs=prefs, seed=7) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto(local_https_page, wait_until="load", timeout=60000) # through the proxy: Firefox learns it here
|
||||
page.wait_for_timeout(2500) # the pool has time to make its associations
|
||||
result = page.evaluate(_PC_JS, "%s:%d" % (STUN_NUMBER, STUN_PORT))
|
||||
t_pc = result["t_pc"] / 1000.0
|
||||
granted = [a for a in gateway.associations if a[1] is not None]
|
||||
first = next((t for host, port, _atyp, t in gateway.datagram_log if host == STUN_NUMBER), None)
|
||||
assert granted, "the proxy was never asked for an association"
|
||||
# the first association of the gateway is the core's own UDP probe, made before the browser exists: it is no pool
|
||||
# association of the engine, and counting it made this test pass with an engine that asked for none
|
||||
granted = granted[1:]
|
||||
assert granted, "the engine never asked the proxy for an association (only the core's probe did): the session's UDP was not declared coherent"
|
||||
ready_before = [a for a in granted if gateway.wall0 + a[1] < t_pc]
|
||||
assert ready_before, (
|
||||
"no association was completed before the PeerConnection was born (granted at %s s from the gateway's start, the "
|
||||
"PeerConnection at %.3f s): the first ICE socket made its own, from scratch"
|
||||
% ([round(a[1], 3) for a in granted], t_pc - gateway.wall0))
|
||||
assert first is not None, "no STUN datagram of the PeerConnection reached the relay"
|
||||
wait = gateway.wall0 + first - t_pc
|
||||
assert wait < 0.25, (
|
||||
"the first STUN datagram left %.0f ms after the PeerConnection was born; a ready association sends at once, a cold one "
|
||||
"needs three answered steps of %d ms" % (wait * 1000, RTT_MS))
|
||||
assert result["t_srflx"] is not None, "no srflx candidate came back through the relay"
|
||||
@@ -0,0 +1,54 @@
|
||||
"""The DoH e2e launch a browser on a Linux machine that has no screen (run 43176569993: 19 of 19 of wrapper.e2e.doh on
|
||||
Linux died at the launch with "no DISPLAY environment variable specified", under sudo and without a display).
|
||||
|
||||
Every launcher of those files asks for a virtual display when the machine has none, and leaves a machine that has one,
|
||||
and Windows, as they are. Nothing is launched here: the session object holds the answer."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
import _doh_support
|
||||
import test_doh_through_the_proxy_e2e as through_the_proxy
|
||||
import test_doh_under_stress_e2e as under_stress
|
||||
import test_ice_names_by_the_context_proxy_e2e as ice_names
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
LAUNCHERS = {
|
||||
"the DoH e2e": lambda: through_the_proxy._launch("/nowhere/firefox", None),
|
||||
"the stress e2e": lambda: under_stress._launch_with_a_short_negative_cache("/nowhere/firefox"),
|
||||
"the ICE names e2e": lambda: ice_names._launch("/nowhere/firefox", None),
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def host(monkeypatch):
|
||||
def set_host(platform, display):
|
||||
monkeypatch.setattr(sys, "platform", platform)
|
||||
if display is None:
|
||||
monkeypatch.delenv("DISPLAY", raising=False)
|
||||
else:
|
||||
monkeypatch.setenv("DISPLAY", display)
|
||||
return set_host
|
||||
|
||||
|
||||
@pytest.mark.parametrize("which", sorted(LAUNCHERS))
|
||||
def test_a_linux_host_without_a_display_gets_a_virtual_one(host, which):
|
||||
host("linux", None)
|
||||
assert LAUNCHERS[which]()._headless is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("which", sorted(LAUNCHERS))
|
||||
def test_a_linux_host_with_a_display_and_windows_are_left_as_they_are(host, which):
|
||||
host("linux", ":0")
|
||||
assert LAUNCHERS[which]()._headless is False
|
||||
host("win32", None)
|
||||
assert LAUNCHERS[which]()._headless is False
|
||||
|
||||
|
||||
def test_what_the_caller_asks_for_wins(host):
|
||||
host("linux", None)
|
||||
assert through_the_proxy._launch("/nowhere/firefox", None, headless=False)._headless is False
|
||||
assert _doh_support.a_display_when_the_host_has_none() == {"headless": True}
|
||||
@@ -0,0 +1,38 @@
|
||||
"""The core discovers the exit of a context's proxy by asking the PROXY, by NAME, and nothing else leaves.
|
||||
|
||||
When a context is given a SOCKS5 proxy, the core measures what it needs before it sends ``Browser.setContextProxy``
|
||||
(``invisible_core._udp_exit.measure_proxy_udp``): the TCP exit through that proxy, with the services of the core
|
||||
(``_geo._IP_ECHO_ENDPOINTS``), and the UDP exit beside it. The names are resolved by the PROXY (remote DNS: the host's own resolver is
|
||||
never asked), through the gateway of THAT context and no other. The DoH e2e declare this discovery away (their subject is the roads
|
||||
of the BROWSER, and the asserts on the CONNECTs of a gateway would otherwise see the core's three names), so this test keeps what
|
||||
the declaration hides: the discovery goes through the gateway of the context, by name, only to the services of the core, and a
|
||||
gateway that refuses them never makes the measurement say ``coherent``.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from invisible_core import _geo, _udp_exit
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
#: The services of the core, in the order it asks them (https, so port 443).
|
||||
ECHO = [(url.split("//", 1)[1], 443) for url in _geo._IP_ECHO_ENDPOINTS]
|
||||
SERVICES = {url.split("//", 1)[1] for url in _geo._IP_ECHO_ENDPOINTS + _geo._IPV6_ECHO_ENDPOINTS}
|
||||
|
||||
|
||||
def test_the_exit_of_a_context_is_asked_to_its_own_gateway_by_name(gateway):
|
||||
mine = gateway("gw-mine")
|
||||
other = gateway("gw-other")
|
||||
command = _udp_exit.context_proxy_command(mine.proxy)
|
||||
assert command is not None
|
||||
assert mine.connects[:len(ECHO)] == ECHO, "the discovery goes through the gateway of the context, by name, in the core's order"
|
||||
assert {host for host, _port in mine.connects} <= SERVICES, (
|
||||
"only the services of the core are asked through it: %s" % (mine.connects,))
|
||||
assert other.connects == [], "the gateway of another context never sees it: %s" % (other.connects,)
|
||||
|
||||
|
||||
def test_a_gateway_that_refuses_the_services_never_gives_a_coherent_udp(gateway):
|
||||
gw = gateway("gw-refusing")
|
||||
command = _udp_exit.context_proxy_command(gw.proxy)
|
||||
assert command["type"] == "socks"
|
||||
assert gw.refused[:len(ECHO)] == ECHO, "the gateway refused the services: %s" % (gw.refused,)
|
||||
assert command["udp"] != "coherent", "a measurement that could not run is never coherent: %s" % (command,)
|
||||
@@ -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,233 @@
|
||||
"""The two knobs of the FakeDoh used by `test_doh_under_stress_e2e.py`: a latency on every answer and a first query that
|
||||
is refused. Tested with plain Python clients, on HTTP/1.1 and on h2, like `test_the_fake_doh_answers.py`.
|
||||
|
||||
* `delay_s` / `delay_names`: each answer is held that long after its QUERY arrived (not only the connection set-up), and
|
||||
over h2 the answers of one connection are held independently, so the A and the AAAA of one lookup both come back after
|
||||
the delay, not one after the other (the second after twice the delay would turn a 2 s latency into a 4 s one);
|
||||
* `fail_first`: the first query of each type for a name is refused as `close` (no answer: an h2 stream reset or a closed
|
||||
HTTP/1.1 connection), `http503` or `servfail`; every later one is served; the other names are untouched.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ssl
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
import _doh_servers as ds
|
||||
from _doh_servers import DOH_HOST, DOH_PATH, FakeDoh, QTYPE_A, QTYPE_AAAA, encode_query
|
||||
from test_the_fake_doh_answers import NAMES, _h1_request, _tls, read_response
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
DELAY = 0.6
|
||||
#: Slack for a loaded machine: the answer must not come EARLIER than the delay, and not much later.
|
||||
LATE = 1.5
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------- clients
|
||||
def _h1_post(tls, name, qtype=QTYPE_A):
|
||||
started = time.monotonic()
|
||||
status, _headers, body = _h1_request(tls, "POST", DOH_PATH, encode_query(name, qtype), "application/dns-message")
|
||||
return status, body, time.monotonic() - started
|
||||
|
||||
|
||||
def _h2_exchange(doh, messages):
|
||||
"""Send every message as its own POST stream at once on one h2 connection. Returns one entry per message, in order:
|
||||
``("reset", seconds)`` or ``(status, body, seconds)``, seconds counted from the moment all streams were sent."""
|
||||
h2_config = pytest.importorskip("h2.config")
|
||||
h2_connection = pytest.importorskip("h2.connection")
|
||||
h2_events = pytest.importorskip("h2.events")
|
||||
tls = _tls(("127.0.0.1", doh.port), alpn=["h2", "http/1.1"])
|
||||
assert tls.selected_alpn_protocol() == "h2"
|
||||
conn = h2_connection.H2Connection(config=h2_config.H2Configuration(client_side=True, header_encoding="utf-8"))
|
||||
conn.initiate_connection()
|
||||
ids = []
|
||||
for message in messages:
|
||||
stream_id = conn.get_next_available_stream_id()
|
||||
conn.send_headers(stream_id, [(":method", "POST"), (":scheme", "https"), (":authority", DOH_HOST),
|
||||
(":path", DOH_PATH), ("accept", "application/dns-message"),
|
||||
("content-type", "application/dns-message"),
|
||||
("content-length", str(len(message)))])
|
||||
conn.send_data(stream_id, message, end_stream=True)
|
||||
ids.append(stream_id)
|
||||
tls.sendall(conn.data_to_send())
|
||||
started = time.monotonic()
|
||||
status, body, done = {}, {i: b"" for i in ids}, {}
|
||||
tls.settimeout(10)
|
||||
try:
|
||||
while len(done) < len(ids):
|
||||
data = tls.recv(65536)
|
||||
assert data, "the server closed the connection"
|
||||
for event in conn.receive_data(data):
|
||||
if isinstance(event, h2_events.ResponseReceived):
|
||||
status[event.stream_id] = dict(event.headers)[":status"]
|
||||
elif isinstance(event, h2_events.DataReceived):
|
||||
body[event.stream_id] += event.data
|
||||
conn.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
|
||||
elif isinstance(event, h2_events.StreamEnded):
|
||||
done[event.stream_id] = ("answer", time.monotonic() - started)
|
||||
elif isinstance(event, h2_events.StreamReset):
|
||||
done[event.stream_id] = ("reset", time.monotonic() - started)
|
||||
tls.sendall(conn.data_to_send())
|
||||
finally:
|
||||
tls.close()
|
||||
out = []
|
||||
for i in ids:
|
||||
kind, seconds = done[i]
|
||||
out.append(("reset", seconds) if kind == "reset" else (status[i], body[i], seconds))
|
||||
return out
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------- the defaults
|
||||
def test_the_defaults_change_nothing():
|
||||
with FakeDoh(NAMES, h2=False) as doh:
|
||||
assert (doh.delay_s, doh.delay_names, doh.fail_first) == (0.0, {}, {})
|
||||
tls = _tls(("127.0.0.1", doh.port), alpn=["http/1.1"])
|
||||
try:
|
||||
status, body, took = _h1_post(tls, "page-a.test")
|
||||
finally:
|
||||
tls.close()
|
||||
assert status == 200 and read_response(body)[4] and took < DELAY
|
||||
(answer,) = doh.answers
|
||||
assert (answer.name, answer.qtype, answer.via, answer.outcome) == ("page-a.test", QTYPE_A, "direct", "answered")
|
||||
assert answer.delay < DELAY
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------- latency
|
||||
def test_every_answer_over_http1_is_held_for_the_delay():
|
||||
with FakeDoh(NAMES, h2=False, delay_s=DELAY) as doh:
|
||||
tls = _tls(("127.0.0.1", doh.port), alpn=["http/1.1"])
|
||||
try:
|
||||
first = _h1_post(tls, "page-a.test")
|
||||
second = _h1_post(tls, "other.test", QTYPE_AAAA)
|
||||
finally:
|
||||
tls.close()
|
||||
for status, body, took in (first, second):
|
||||
assert status == 200 and DELAY - 0.05 <= took < DELAY + LATE, took
|
||||
assert read_response(first[1])[4], "the answer is the normal one, only late"
|
||||
assert [round(a.delay, 1) for a in doh.answers] == [round(DELAY, 1)] * 2
|
||||
assert all(a.delay >= DELAY - 0.05 for a in doh.answers)
|
||||
|
||||
|
||||
def test_every_answer_over_h2_is_held_for_the_delay_and_the_a_and_the_aaaa_wait_together():
|
||||
with FakeDoh(NAMES, delay_s=DELAY) as doh:
|
||||
a, aaaa = _h2_exchange(doh, [encode_query("page-a.test", QTYPE_A), encode_query("page-a.test", QTYPE_AAAA)])
|
||||
for status, _body, took in (a, aaaa):
|
||||
assert status == "200" and DELAY - 0.05 <= took < 2 * DELAY + 0.3, (
|
||||
"both answers are held in parallel: %.2f s, not %.2f s" % (took, 2 * DELAY))
|
||||
assert read_response(a[1])[4] and not read_response(aaaa[1])[4]
|
||||
assert {x.qtype for x in doh.answers_for("page-a.test")} == {QTYPE_A, QTYPE_AAAA}
|
||||
assert all(x.delay >= DELAY - 0.05 for x in doh.answers)
|
||||
|
||||
|
||||
def test_the_delay_of_a_name_only_holds_that_name_and_the_names_under_it():
|
||||
with FakeDoh(NAMES, delay_names={"page-a.test": DELAY}) as doh:
|
||||
slow, fast, below = _h2_exchange(doh, [encode_query("page-a.test"), encode_query("other.test"),
|
||||
encode_query("_80._https.page-a.test", QTYPE_A)])
|
||||
assert slow[2] >= DELAY - 0.05 and below[2] >= DELAY - 0.05
|
||||
assert fast[0] == "200" and fast[2] < DELAY, "an unrelated name is not held: %.2f s" % fast[2]
|
||||
|
||||
|
||||
def test_the_delay_can_be_changed_while_the_server_runs():
|
||||
with FakeDoh(NAMES, h2=False) as doh:
|
||||
tls = _tls(("127.0.0.1", doh.port), alpn=["http/1.1"])
|
||||
try:
|
||||
assert _h1_post(tls, "page-a.test")[2] < DELAY
|
||||
doh.delay_s = DELAY
|
||||
assert _h1_post(tls, "page-a.test")[2] >= DELAY - 0.05
|
||||
finally:
|
||||
tls.close()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ first refused
|
||||
def test_an_unknown_failure_kind_is_refused_at_construction():
|
||||
with pytest.raises(ValueError):
|
||||
FakeDoh(NAMES, fail_first={"page-a.test": "explode"})
|
||||
|
||||
|
||||
def test_http503_once_over_http1_then_the_name_is_served_and_other_names_never_fail():
|
||||
with FakeDoh(NAMES, h2=False, fail_first={"page-a.test": "http503"}) as doh:
|
||||
tls = _tls(("127.0.0.1", doh.port), alpn=["http/1.1"])
|
||||
try:
|
||||
assert _h1_post(tls, "other.test")[0] == 200
|
||||
assert _h1_post(tls, "page-a.test")[0] == 503, "the first query of the name is refused"
|
||||
assert _h1_post(tls, "page-a.test")[0] == 200, "the second one is served"
|
||||
assert _h1_post(tls, "page-a.test")[0] == 200
|
||||
finally:
|
||||
tls.close()
|
||||
assert [a.outcome for a in doh.answers_for("page-a.test")] == ["http503", "answered", "answered"]
|
||||
assert len(doh.queries_for("page-a.test")) == 3, "a refused query is still a query"
|
||||
|
||||
|
||||
def test_servfail_once_is_a_dns_answer_with_rcode_2():
|
||||
with FakeDoh(NAMES, h2=False, fail_first={"page-a.test": "servfail"}) as doh:
|
||||
tls = _tls(("127.0.0.1", doh.port), alpn=["http/1.1"])
|
||||
try:
|
||||
status, body, _took = _h1_post(tls, "page-a.test")
|
||||
_i, _f, rcode, name, answers = read_response(body)
|
||||
assert (status, rcode, name, answers) == (200, ds.RCODE_SERVFAIL, "page-a.test", [])
|
||||
assert read_response(_h1_post(tls, "page-a.test")[1])[4], "the second one has its address"
|
||||
finally:
|
||||
tls.close()
|
||||
|
||||
|
||||
def test_close_once_over_http1_ends_the_connection_without_an_answer():
|
||||
with FakeDoh(NAMES, h2=False, fail_first={"page-a.test": "close"}) as doh:
|
||||
tls = _tls(("127.0.0.1", doh.port), alpn=["http/1.1"])
|
||||
try:
|
||||
with pytest.raises((AssertionError, OSError, ssl.SSLError)):
|
||||
_h1_post(tls, "page-a.test")
|
||||
finally:
|
||||
tls.close()
|
||||
tls = _tls(("127.0.0.1", doh.port), alpn=["http/1.1"])
|
||||
try:
|
||||
assert _h1_post(tls, "page-a.test")[0] == 200
|
||||
finally:
|
||||
tls.close()
|
||||
assert [a.outcome for a in doh.answers_for("page-a.test")] == ["close", "answered"]
|
||||
|
||||
|
||||
def test_close_once_over_h2_resets_the_stream_and_keeps_the_connection():
|
||||
with FakeDoh(NAMES, fail_first={"page-a.test": "close"}) as doh:
|
||||
first, = _h2_exchange(doh, [encode_query("page-a.test")])
|
||||
second, = _h2_exchange(doh, [encode_query("page-a.test")])
|
||||
assert first[0] == "reset" and second[0] == "200"
|
||||
assert [a.outcome for a in doh.answers_for("page-a.test")] == ["close", "answered"]
|
||||
|
||||
|
||||
def test_the_first_query_of_each_type_is_refused_so_a_whole_first_lookup_fails():
|
||||
"""A and AAAA of the first lookup both fail, whichever arrives first; the second lookup is served in full."""
|
||||
with FakeDoh(NAMES, fail_first={"page-a.test": "http503"}) as doh:
|
||||
first = _h2_exchange(doh, [encode_query("page-a.test", QTYPE_A), encode_query("page-a.test", QTYPE_AAAA)])
|
||||
second = _h2_exchange(doh, [encode_query("page-a.test", QTYPE_A), encode_query("page-a.test", QTYPE_AAAA)])
|
||||
assert [r[0] for r in first] == ["503", "503"]
|
||||
assert [r[0] for r in second] == ["200", "200"]
|
||||
|
||||
|
||||
def test_a_refusal_can_be_slow_too():
|
||||
with FakeDoh(NAMES, delay_s=DELAY, fail_first={"page-a.test": "http503"}) as doh:
|
||||
(refused,) = _h2_exchange(doh, [encode_query("page-a.test")])
|
||||
assert refused[0] == "503" and refused[2] >= DELAY - 0.05
|
||||
assert doh.answers_for("page-a.test")[0].delay >= DELAY - 0.05
|
||||
|
||||
|
||||
def test_a_gateway_hands_the_knobs_over_with_the_connection():
|
||||
"""Through a DohGateway the FakeDoh is the same object: the delay holds on the tunnelled road too."""
|
||||
from _doh_servers import DohGateway
|
||||
from test_the_fake_doh_answers import _socks_connect
|
||||
with FakeDoh(NAMES, h2=False, delay_s=DELAY) as doh, DohGateway("gw1", doh) as gw:
|
||||
s, code = _socks_connect(gw.port, ds.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)
|
||||
try:
|
||||
status, _body, took = _h1_post(tls, "page-a.test")
|
||||
finally:
|
||||
tls.close()
|
||||
assert status == 200 and took >= DELAY - 0.05
|
||||
assert doh.answers[0].via == "gw1"
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
"""The server and the judge of the HTTP/3 e2e work, without a browser (hermetic, loopback).
|
||||
|
||||
A retail Firefox (Windows 159, DoH forced like our core, 15 sessions per condition) never reads h3 at the first visit
|
||||
behind a proxy: with UDP free h2/h2/h3 in 9, h2/h2/h2 in 4, h2/h3/h3 in 2; with UDP blocked h2/h2/h2 in 15 of 15 with no delay of
|
||||
the load; with no proxy and the native DNS (loopback) h2, h3, h3. The e2e visits the page 3 times with no proxy and 5 times
|
||||
behind any proxy and asserts that. These tests hold what it stands on: the local server really speaks HTTP/2 on its TCP port (if it
|
||||
spoke HTTP/1.1 the first visit could never read ``h2``), says ``Alt-Svc: h3`` there, and answers the same document over HTTP/3;
|
||||
and the function that judges the visits names what is wrong.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import socket
|
||||
import ssl
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
import _udp_line as line
|
||||
from _h3_server import PAGE, H3Server
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
# -- the server ---------------------------------------------------------------------------------------------------------
|
||||
def _tls_client(server, 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((server.address, server.port), timeout=10)
|
||||
return context.wrap_socket(raw, server_hostname=server.address)
|
||||
|
||||
|
||||
def _h2_get(server, path):
|
||||
import h2.config
|
||||
import h2.connection
|
||||
import h2.events
|
||||
|
||||
tls = _tls_client(server, ["h2", "http/1.1"])
|
||||
try:
|
||||
assert tls.selected_alpn_protocol() == "h2", "the TCP side did not negotiate h2"
|
||||
conn = h2.connection.H2Connection(config=h2.config.H2Configuration(client_side=True, header_encoding="utf-8"))
|
||||
conn.initiate_connection()
|
||||
conn.send_headers(1, [(":method", "GET"), (":authority", server.address), (":scheme", "https"), (":path", path)],
|
||||
end_stream=True)
|
||||
tls.sendall(conn.data_to_send())
|
||||
headers, body, ended = {}, b"", False
|
||||
while not ended:
|
||||
data = tls.recv(65536)
|
||||
assert data, "the server closed the connection before the end of the stream"
|
||||
for event in conn.receive_data(data):
|
||||
if isinstance(event, h2.events.ResponseReceived):
|
||||
headers = dict(event.headers)
|
||||
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
|
||||
out = conn.data_to_send()
|
||||
if out:
|
||||
tls.sendall(out)
|
||||
return headers, body
|
||||
finally:
|
||||
tls.close()
|
||||
|
||||
|
||||
def test_the_tcp_side_speaks_http2_and_says_where_h3_is():
|
||||
with H3Server("127.0.0.1") as server:
|
||||
headers, body = _h2_get(server, "/?v=1")
|
||||
assert headers[":status"] == "200"
|
||||
assert headers["alt-svc"] == 'h3=":%d"; ma=3600' % server.port
|
||||
assert headers["content-type"].startswith("text/html")
|
||||
assert body == PAGE
|
||||
assert server.tcp_alpn == ["h2"] and server.tcp_requests == ["/?v=1"]
|
||||
|
||||
|
||||
def test_a_second_request_on_the_same_connection_is_answered_too():
|
||||
with H3Server("127.0.0.1") as server:
|
||||
for path in ("/?v=1", "/?v=2"):
|
||||
assert _h2_get(server, path)[1] == PAGE
|
||||
assert server.tcp_requests == ["/?v=1", "/?v=2"]
|
||||
|
||||
|
||||
def test_a_client_that_offers_only_http1_is_answered_with_the_alt_svc_too():
|
||||
with H3Server("127.0.0.1") as server:
|
||||
tls = _tls_client(server, ["http/1.1"])
|
||||
try:
|
||||
tls.sendall(b"GET /?v=1 HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n")
|
||||
data = b""
|
||||
while True:
|
||||
chunk = tls.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
finally:
|
||||
tls.close()
|
||||
assert data.startswith(b"HTTP/1.1 200 OK") and data.endswith(PAGE)
|
||||
assert ('Alt-Svc: h3=":%d"; ma=3600' % server.port).encode() in data
|
||||
assert server.tcp_alpn == ["http/1.1"]
|
||||
|
||||
|
||||
def test_the_same_document_is_answered_over_http3_and_the_peer_is_recorded():
|
||||
from aioquic.asyncio.client import connect
|
||||
from aioquic.asyncio.protocol import QuicConnectionProtocol
|
||||
from aioquic.h3.connection import H3_ALPN, H3Connection
|
||||
from aioquic.h3.events import DataReceived, HeadersReceived
|
||||
from aioquic.quic.configuration import QuicConfiguration
|
||||
|
||||
class Client(QuicConnectionProtocol):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.http = None
|
||||
self.status, self.body = None, b""
|
||||
self.finished = asyncio.Event()
|
||||
|
||||
def quic_event_received(self, event):
|
||||
if self.http is None:
|
||||
return
|
||||
for http_event in self.http.handle_event(event):
|
||||
if isinstance(http_event, HeadersReceived):
|
||||
self.status = dict(http_event.headers).get(b":status")
|
||||
elif isinstance(http_event, DataReceived):
|
||||
self.body += http_event.data
|
||||
if http_event.stream_ended:
|
||||
self.finished.set()
|
||||
|
||||
async def get(self, authority, path):
|
||||
self.http = H3Connection(self._quic)
|
||||
stream = self._quic.get_next_available_stream_id()
|
||||
self.http.send_headers(stream, [(b":method", b"GET"), (b":scheme", b"https"),
|
||||
(b":authority", authority.encode()), (b":path", path.encode())], end_stream=True)
|
||||
self.transmit()
|
||||
await asyncio.wait_for(self.finished.wait(), 10)
|
||||
|
||||
async def fetch(server):
|
||||
configuration = QuicConfiguration(is_client=True, alpn_protocols=H3_ALPN, verify_mode=ssl.CERT_NONE)
|
||||
async with connect(server.address, server.port, configuration=configuration, create_protocol=Client) as client:
|
||||
await client.get("%s:%d" % (server.address, server.port), "/?v=2")
|
||||
return client.status, client.body
|
||||
|
||||
with H3Server("127.0.0.1") as server:
|
||||
status, body = asyncio.run(fetch(server))
|
||||
assert status == b"200" and body == PAGE
|
||||
assert server.quic_peers == ["127.0.0.1"] and server.h3_requests == ["/?v=2"]
|
||||
|
||||
|
||||
# -- the sequence a retail Firefox reads, and the judge -------------------------------------------------------------------
|
||||
H2 = ["h2"] * 5
|
||||
FAST = [900, 300, 310, 305, 290]
|
||||
PROXY_ROADS = ("socks5_coherent", "socks5_no_udp", "socks5_mismatched", "socks5_unmeasured", "http_proxy")
|
||||
H2_ROADS = ("socks5_no_udp", "socks5_mismatched", "socks5_unmeasured", "http_proxy")
|
||||
|
||||
|
||||
def test_the_number_of_visits_of_each_road():
|
||||
assert line.visits_for("direct") == 3
|
||||
for road in PROXY_ROADS:
|
||||
assert line.visits_for(road) == 5, road
|
||||
|
||||
|
||||
def test_with_no_proxy_the_sequence_is_h2_h3_h3_and_nothing_else():
|
||||
assert line.judge_visits("direct", ["h2", "h3", "h3"], [900, 300, 310]) == []
|
||||
for wrong in (["h2", "h2", "h3"], ["h2", "h2", "h2"], ["h3", "h3", "h3"], ["h2", "h3", "h2"]):
|
||||
assert line.judge_visits("direct", wrong, [900, 300, 310]), wrong
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sequence", [
|
||||
["h2", "h2", "h3", "h3", "h3"], # the commonest retail sequence (9 of 15)
|
||||
["h2", "h3", "h3", "h3", "h3"], # retail, 2 of 15
|
||||
["h2", "h2", "h2", "h2", "h3"], # h3 as late as the fifth visit
|
||||
["h2", "h2", "h2", "h3", "h3"],
|
||||
])
|
||||
def test_behind_a_gateway_with_udp_free_h3_may_come_at_any_visit_after_the_first(sequence):
|
||||
assert line.judge_visits("socks5_coherent", sequence, FAST) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sequence", [
|
||||
["h3", "h3", "h3", "h3", "h3"], # h3 at visit 1
|
||||
["h3", "h2", "h3", "h3", "h3"],
|
||||
["h2", "h2", "h2", "h2", "h2"], # never h3 in five visits: the engine refuses h3 behind the proxy
|
||||
["h2", "h3", "h2", "h3", "h3"], # h3 goes back to h2
|
||||
["h2", "h2", "h3", "h3", "h2"],
|
||||
])
|
||||
def test_behind_a_gateway_with_udp_free_these_sequences_are_errors(sequence):
|
||||
assert line.judge_visits("socks5_coherent", sequence, FAST), sequence
|
||||
|
||||
|
||||
def test_h3_on_the_first_visit_is_an_error_and_says_so_on_every_road():
|
||||
assert any("visit 1 read h3" in p for p in line.judge_visits("direct", ["h3", "h3", "h3"], [900, 300, 310]))
|
||||
for road in PROXY_ROADS:
|
||||
problems = line.judge_visits(road, ["h3", "h3", "h3", "h3", "h3"], FAST)
|
||||
assert any("visit 1 read h3" in p for p in problems), (road, problems)
|
||||
|
||||
|
||||
def test_the_judge_names_what_the_retail_reads():
|
||||
problems = line.judge_visits("socks5_coherent", H2, FAST)
|
||||
assert len(problems) == 1 and "none of the 5 visits read h3" in problems[0] and "9 of 15" in problems[0], problems
|
||||
problems = line.judge_visits("socks5_no_udp", ["h2", "h2", "h3", "h3", "h3"], FAST)
|
||||
assert any("15 of 15" in p for p in problems), problems
|
||||
|
||||
|
||||
def test_h3_where_udp_is_dropped_is_an_error():
|
||||
for road in H2_ROADS:
|
||||
for sequence in (["h2", "h2", "h3", "h3", "h3"], ["h2", "h2", "h2", "h2", "h3"], ["h2", "h3", "h3", "h3", "h3"]):
|
||||
assert line.judge_visits(road, sequence, FAST), (road, sequence)
|
||||
assert line.judge_visits(road, H2, FAST) == [], road
|
||||
|
||||
|
||||
def test_an_unknown_road_is_refused():
|
||||
for call in (line.expected_protocols, line.visits_for):
|
||||
with pytest.raises(KeyError):
|
||||
call("socks5_maybe")
|
||||
|
||||
|
||||
def test_a_later_load_that_waits_for_a_fallback_is_an_error_where_udp_is_dropped_and_only_there():
|
||||
slow = [900, 900 + line.LOAD_MARGIN_MS + 1, 310, 305, 290]
|
||||
problems = line.judge_visits("socks5_no_udp", H2, slow)
|
||||
assert len(problems) == 1 and "visit 2 loaded" in problems[0], problems
|
||||
assert line.judge_visits("socks5_no_udp", H2, [900, 900 + line.LOAD_MARGIN_MS, 310, 305, 290]) == []
|
||||
for number in (3, 4, 5): # every later visit is judged, not only the second
|
||||
walls = list(FAST)
|
||||
walls[number - 1] = 900 + line.LOAD_MARGIN_MS + 1
|
||||
problems = line.judge_visits("http_proxy", H2, walls)
|
||||
assert len(problems) == 1 and "visit %d loaded" % number in problems[0], (number, problems)
|
||||
# where UDP is free the loads are not judged (an h3 handshake has its own cost)
|
||||
assert line.judge_visits("socks5_coherent", ["h2", "h2", "h3", "h3", "h3"], slow) == []
|
||||
assert line.judge_visits("direct", ["h2", "h3", "h3"], [900, 900 + line.LOAD_MARGIN_MS + 1, 310]) == []
|
||||
|
||||
|
||||
def test_a_series_of_the_wrong_length_is_an_error():
|
||||
assert line.judge_visits("direct", ["h2", "h3"], [900, 300])
|
||||
assert line.judge_visits("direct", ["h2", "h3", "h3"], [900, 300])
|
||||
assert line.judge_visits("socks5_coherent", ["h2", "h2", "h3"], [900, 300, 310])
|
||||
assert line.judge_visits("socks5_coherent", ["h2", "h2", "h3", "h3", "h3"], [900, 300, 310])
|
||||
assert line.judge_visits("socks5_no_udp", ["h2", "h2", "h2"], [900, 300, 310])
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------ the first visit is h2 by fixture
|
||||
# The retail reads h3 at the first visit when the DNS answer carries the HTTPS record (type 65): the third retail run did in 3
|
||||
# sessions of 15. The e2e expects h2 first only because the fixture has no such record.
|
||||
def test_a_page_reached_by_an_address_has_no_https_record_to_wait_for():
|
||||
assert line.no_https_record("192.0.2.1") == []
|
||||
assert line.no_https_record("[2001:db8::1]") == []
|
||||
|
||||
|
||||
def test_a_page_reached_by_a_name_may_have_one_and_the_check_says_so():
|
||||
problems = line.no_https_record("site.test")
|
||||
assert problems and "HTTPS record" in problems[0]
|
||||
|
||||
|
||||
def test_the_fake_doh_never_serves_a_type_65_with_data_and_the_check_reads_what_it_served():
|
||||
import _doh_servers as doh_servers
|
||||
|
||||
server = doh_servers.FakeDoh({"site.test": "192.0.2.1"})
|
||||
try:
|
||||
query = doh_servers.parse_query(doh_servers.encode_query("site.test", doh_servers.QTYPE_HTTPS))
|
||||
message = doh_servers.answer_for({"site.test": "192.0.2.1"}, query)
|
||||
assert int.from_bytes(message[6:8], "big") == 0, "a type 65 answer with data: the h2-first expectation no longer holds"
|
||||
assert server.https_served == []
|
||||
assert line.no_https_record("192.0.2.1", server) == []
|
||||
server.https_served.append("site.test") # a FakeDoh that learned to serve the record
|
||||
problems = line.no_https_record("192.0.2.1", server)
|
||||
assert problems and "site.test" in problems[0]
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
# -- the relay of the gateway: a send that fails is said, and a relay that leaves from the host's address works ----------------
|
||||
# The e2e once read "the server saw QUIC from []" on Windows: the relay sent from 127.0.0.1 to an address of its own host (WinError 10051),
|
||||
# the send ran in a timer that ignored every OSError, and the relay had still logged the datagram as carried.
|
||||
def _associate(gateway):
|
||||
"""A SOCKS5 UDP ASSOCIATE on ``gateway`` with no credentials: the control connection (kept open) and the relay's address."""
|
||||
control = socket.create_connection(("127.0.0.1", gateway.port), timeout=5)
|
||||
control.sendall(b"\x05\x01\x00")
|
||||
assert control.recv(2) == b"\x05\x00"
|
||||
control.sendall(b"\x05\x03\x00\x01\x00\x00\x00\x00\x00\x00")
|
||||
reply = b""
|
||||
while len(reply) < 10:
|
||||
reply += control.recv(10 - len(reply))
|
||||
assert reply[1] == 0, "the association was refused: %r" % reply
|
||||
return control, (socket.inet_ntoa(reply[4:8]), int.from_bytes(reply[8:10], "big"))
|
||||
|
||||
|
||||
def _wrapped(host, port, payload):
|
||||
return b"\x00\x00\x00\x01" + socket.inet_aton(host) + port.to_bytes(2, "big") + payload
|
||||
|
||||
|
||||
def test_a_send_the_relay_cannot_make_is_recorded_and_the_report_of_the_e2e_says_it():
|
||||
import test_http3_through_the_proxy_e2e as e2e
|
||||
from _socks_servers import coherent
|
||||
|
||||
with coherent() as gateway:
|
||||
assert gateway.send_errors == []
|
||||
|
||||
def refused():
|
||||
raise OSError(10051, "A socket operation was attempted to an unreachable network")
|
||||
|
||||
gateway._later(refused, "the datagram to 203.0.113.9:443")
|
||||
assert len(gateway.send_errors) == 1 and gateway.send_errors[0].startswith("the datagram to 203.0.113.9:443: OSError")
|
||||
class Server:
|
||||
tcp_alpn, quic_peers = ["h2"], []
|
||||
said = e2e._report("socks5_coherent", ["h2"], [1], Server, gateway)
|
||||
assert "sends of the relay that failed" in said and "10051" in said
|
||||
|
||||
|
||||
def test_a_relay_that_leaves_from_the_address_of_the_host_reaches_a_server_on_it_and_is_told_by_its_port():
|
||||
from _host_address import this_host_address
|
||||
from _socks_servers import coherent
|
||||
|
||||
host = this_host_address()
|
||||
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
server.bind((host, 0))
|
||||
server.settimeout(5)
|
||||
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
client.bind((host, 0)) # an engine's UDP sockets are bound to an interface
|
||||
with coherent(relay_host=host, exit_host=host) as gateway:
|
||||
gateway.forward_only_to = {host}
|
||||
control, relay = _associate(gateway)
|
||||
try:
|
||||
client.sendto(_wrapped(host, server.getsockname()[1], b"quic" * 300), relay)
|
||||
data, peer = server.recvfrom(4096)
|
||||
assert data == b"quic" * 300
|
||||
assert peer[0] == host and peer[1] in gateway.exit_ports, "the relay's port is not in exit_ports: %s" % (gateway.exit_ports,)
|
||||
direct = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
direct.bind((host, 0))
|
||||
direct.sendto(b"direct", server.getsockname())
|
||||
data, peer = server.recvfrom(4096)
|
||||
assert data == b"direct" and peer[1] not in gateway.exit_ports, "a client that came direct looks like the relay"
|
||||
direct.close()
|
||||
# the browser's own QUIC to a public address is recorded as carried and goes nowhere: the lab stays closed
|
||||
client.sendto(_wrapped("203.0.113.9", 443, b"background"), relay)
|
||||
time.sleep(0.3)
|
||||
assert ("203.0.113.9", 443) in {(h, p) for h, p, _d in gateway.datagrams}
|
||||
assert gateway.send_errors == [], gateway.send_errors
|
||||
finally:
|
||||
control.close()
|
||||
client.close()
|
||||
server.close()
|
||||
|
||||
|
||||
def test_the_fake_stun_of_a_relay_that_leaves_from_the_address_of_the_host_answers_through_the_relay():
|
||||
from _host_address import this_host_address
|
||||
from _socks_servers import MEASURE_NUMBER, STUN_PORT, coherent
|
||||
|
||||
host = this_host_address()
|
||||
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
client.bind((host, 0))
|
||||
client.settimeout(5)
|
||||
with coherent(relay_host=host, exit_host=host) as gateway:
|
||||
control, relay = _associate(gateway)
|
||||
try:
|
||||
request = b"\x00\x01\x00\x00\x21\x12\xa4\x42" + b"txid-of-12by"
|
||||
client.sendto(_wrapped(MEASURE_NUMBER, STUN_PORT, request), relay)
|
||||
answer, _peer = client.recvfrom(4096)
|
||||
assert answer[3] == 1 and socket.inet_ntoa(answer[4:8]) == MEASURE_NUMBER and int.from_bytes(answer[8:10], "big") == STUN_PORT
|
||||
assert answer[10:12] == b"\x01\x01", "not a STUN Binding success: %r" % answer[10:20]
|
||||
assert gateway.send_errors == [], gateway.send_errors
|
||||
finally:
|
||||
control.close()
|
||||
client.close()
|
||||
@@ -0,0 +1,81 @@
|
||||
"""The address of this host that the relay of an e2e test binds to is computed by ONE helper, and a host with no default
|
||||
route (a container or a CI runner without a network, a laptop offline) SKIPS the test instead of erroring, before any
|
||||
server of the test has started (it used to raise OSError in the middle of the construction of the chain, after the TURN
|
||||
server, the resolver and the page were listening)."""
|
||||
import types
|
||||
|
||||
import pytest
|
||||
|
||||
import _host_address
|
||||
import _turn_chain
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
class _Probe:
|
||||
"""A UDP socket of a host whose routing table is ``address`` (a string), or empty (None)."""
|
||||
def __init__(self, address):
|
||||
self.address, self.closed = address, False
|
||||
|
||||
def connect(self, _target):
|
||||
if self.address is None:
|
||||
raise OSError(10051, "Network is unreachable")
|
||||
|
||||
def getsockname(self):
|
||||
return (self.address, 40000)
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
def _host_with(monkeypatch, address):
|
||||
probes = []
|
||||
|
||||
def make(*_args):
|
||||
probes.append(_Probe(address))
|
||||
return probes[-1]
|
||||
monkeypatch.setattr(_host_address, "socket", types.SimpleNamespace(socket=make, AF_INET=2, SOCK_DGRAM=2))
|
||||
return probes
|
||||
|
||||
|
||||
def test_a_host_with_a_default_route_gives_the_address_it_sends_from(monkeypatch):
|
||||
probes = _host_with(monkeypatch, "192.168.7.20")
|
||||
assert _host_address.this_host_address() == "192.168.7.20"
|
||||
assert all(p.closed for p in probes)
|
||||
|
||||
|
||||
def test_a_host_with_no_default_route_skips_the_test(monkeypatch):
|
||||
probes = _host_with(monkeypatch, None)
|
||||
with pytest.raises(pytest.skip.Exception, match="no default route"):
|
||||
_host_address.this_host_address()
|
||||
assert all(p.closed for p in probes)
|
||||
|
||||
|
||||
def test_the_chain_asks_the_address_before_it_starts_any_server(monkeypatch):
|
||||
started = []
|
||||
for name in ("TurnServer", "FakeDoh", "Page"):
|
||||
monkeypatch.setattr(_turn_chain, name, lambda *a, _n=name, **k: started.append(_n))
|
||||
_host_with(monkeypatch, None)
|
||||
monkeypatch.setattr(_turn_chain, "this_host_address", _host_address.this_host_address)
|
||||
with pytest.raises(pytest.skip.Exception, match="no default route"):
|
||||
_turn_chain.Chain()
|
||||
assert started == [], "a server was started before the address of this host was known: %s" % started
|
||||
|
||||
|
||||
def test_the_chain_with_a_relay_host_of_its_own_does_not_ask_for_the_address(monkeypatch):
|
||||
def boom():
|
||||
raise AssertionError("asked")
|
||||
monkeypatch.setattr(_turn_chain, "this_host_address", boom)
|
||||
chain = _turn_chain.Chain(relay_host="127.0.0.1")
|
||||
try:
|
||||
assert chain.relay_host == "127.0.0.1"
|
||||
finally:
|
||||
chain.close()
|
||||
|
||||
|
||||
def test_there_is_one_copy_of_the_helper():
|
||||
import pathlib
|
||||
here = pathlib.Path(__file__).parent
|
||||
for name in ("_turn_chain.py", "test_http3_through_the_proxy_e2e.py", "test_webrtc_realness.py"):
|
||||
text = (here / name).read_text(encoding="utf-8")
|
||||
assert '"192.0.2.1"' not in text, "%s has its own copy of the probe of the default route" % name
|
||||
@@ -0,0 +1,76 @@
|
||||
"""E2E: the engine never reads the host's hosts file (drivers\\etc\\hosts, /etc/hosts), with a proxy or without.
|
||||
|
||||
WHY. Firefox reads that file once, in the first moments of the parent process, to keep the names it holds out of the DoH
|
||||
(`network.trr.exclude-etc-hosts`, default true in Mozilla's build). A name found there is then answered by the host: with a
|
||||
proxy that is a name leaving by the machine's resolver, and with or without a proxy it is a value taken from the host
|
||||
(the file is the host's, not the persona's). The engine declares `network.trr.exclude-etc-hosts` false by default, so the read
|
||||
(DNSServiceBase::DoReadEtcHostsFile, which returns before building the path when the pref is false) never happens.
|
||||
|
||||
HOW IT IS SEEN. A late attach of a debugger cannot prove it (the read is at start-up, before any attach), so the browser is
|
||||
launched with MOZ_LOG=sync,nsHostResolver:5 and MOZ_LOG_FILE=<dir>/moz-%PID.log (one file per process): the line the engine
|
||||
writes when it reads the file is "Reading hosts file at <path>" (DNSServiceBase.cpp:121). The test asserts that no log of any
|
||||
process of the browser contains it, and, as a control that the logging worked, that the parent process logged the start of
|
||||
its resolver ("nsHostResolver::Init"). The environment of the test process reaches the browser through the product's launch
|
||||
(the diagnostic runs of the owner pass MOZ_LOG the same way).
|
||||
|
||||
Red on an engine whose default is true (the round-2 binary reads it twice per parent process); green on one with the
|
||||
default false (commit fd21b34813 of the engine).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import os
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from test_doh_through_the_proxy_e2e import ( # noqa: F401 (the hermetic session is autouse and imported by name; the
|
||||
# other fixtures of the DoH e2e are in conftest.py)
|
||||
_hermetic_session, _launch, _page_in, _text)
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
_READ = b"Reading hosts file at"
|
||||
_STARTED = b"nsHostResolver::Init"
|
||||
#: Start-up tasks are in the first seconds; the page load and this pause let them all happen before the browser is closed.
|
||||
SETTLE_S = 4.0
|
||||
|
||||
|
||||
def _logs_of(directory):
|
||||
return sorted(glob.glob(os.path.join(str(directory), "moz-*.log*")))
|
||||
|
||||
|
||||
def _count(path, needle):
|
||||
with open(path, "rb") as f:
|
||||
return sum(1 for line in f if needle in line)
|
||||
|
||||
|
||||
def _report(directory):
|
||||
rows = []
|
||||
for path in _logs_of(directory):
|
||||
rows.append("%s: started=%d reads=%d" % (os.path.basename(path), _count(path, _STARTED), _count(path, _READ)))
|
||||
return "\n ".join(rows) or "(no log file was written)"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_a_proxy", [True, False], ids=["launch_proxy", "no_proxy"])
|
||||
def test_the_hosts_file_of_the_host_is_never_read(with_a_proxy, firefox_binary, doh, pages, gateway, watcher, tmp_path,
|
||||
monkeypatch):
|
||||
logs = tmp_path / "moz"
|
||||
logs.mkdir()
|
||||
monkeypatch.setenv("MOZ_LOG", "sync,nsHostResolver:5")
|
||||
monkeypatch.setenv("MOZ_LOG_FILE", str(logs / "moz-%PID.log"))
|
||||
gw = gateway("gw") if with_a_proxy else None
|
||||
with _launch(firefox_binary, gw.proxy if gw else None) as browser:
|
||||
context, page = _page_in(browser)
|
||||
page.goto("about:blank")
|
||||
time.sleep(SETTLE_S)
|
||||
context.close()
|
||||
watcher.stop()
|
||||
|
||||
report = _report(logs)
|
||||
started = [p for p in _logs_of(logs) if _count(p, _STARTED)]
|
||||
assert started, ("the control failed: no process logged the start of its resolver, so the logging did not work and an "
|
||||
"empty result would prove nothing\n " + report)
|
||||
reading = [p for p in _logs_of(logs) if _count(p, _READ)]
|
||||
assert reading == [], ("the browser read the host's hosts file ('Reading hosts file at ...'): the default of "
|
||||
"network.trr.exclude-etc-hosts must be false\n " + report)
|
||||
@@ -0,0 +1,209 @@
|
||||
"""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())
|
||||
# One byte at a time, so that not a byte of what follows the head is taken from the tunnel: a relay that sends the
|
||||
# 200 and the first bytes of the far side together (a server that writes and closes at once) would otherwise lose them here.
|
||||
data = b""
|
||||
while b"\r\n\r\n" not in data:
|
||||
chunk = s.recv(1)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
lines = data.decode().split("\r\n\r\n")[0].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_what_follows_the_head_of_a_connect_answer_is_left_for_the_caller():
|
||||
"""The answer and the first bytes of the tunnel can reach the socket in one segment (the far side writes and
|
||||
closes at once): the caller reads them after the head, none was swallowed with it."""
|
||||
listener = socket.socket()
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen(1)
|
||||
|
||||
def serve():
|
||||
c, _ = listener.accept()
|
||||
while b"\r\n\r\n" not in c.recv(4096):
|
||||
pass
|
||||
c.sendall(b"HTTP/1.1 200 Connection established\r\n\r\nhello")
|
||||
c.close()
|
||||
|
||||
threading.Thread(target=serve, daemon=True).start()
|
||||
|
||||
class Stub:
|
||||
port = listener.getsockname()[1]
|
||||
|
||||
s, status, _h = _connect_raw(Stub, "198.51.100.1:443")
|
||||
try:
|
||||
assert status.split()[1] == "200"
|
||||
assert s.recv(10) == b"hello"
|
||||
finally:
|
||||
s.close()
|
||||
listener.close()
|
||||
|
||||
|
||||
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,208 @@
|
||||
"""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 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 _udp_ask_at(address: str, port: int, name: str) -> bytes:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s.settimeout(3)
|
||||
try:
|
||||
s.sendto(ds.encode_query(name, ds.QTYPE_A, 0x004D), (address, port))
|
||||
return s.recvfrom(4096)[0]
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
|
||||
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_goes_to_the_next_loopback_address_when_the_first_has_its_port_taken():
|
||||
"""On a hosted runner something can hold 127.0.0.1:53 (or a wildcard of it): the trap takes the first loopback address
|
||||
of TRAP_ADDRESSES it can bind, says which, and that is the address a resolv.conf is written with (run 43146661635: the
|
||||
trap could not bind and eight tests ended in error at setup)."""
|
||||
import _leaks
|
||||
|
||||
holder_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
holder_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
holder_tcp.bind(("127.0.0.1", 0))
|
||||
port = holder_tcp.getsockname()[1]
|
||||
try:
|
||||
holder_udp.bind(("127.0.0.1", port))
|
||||
except OSError:
|
||||
raise
|
||||
holder_tcp.listen(1)
|
||||
# port != 0 is the case of port 53: the addresses are tried in order
|
||||
with ResolverTrap(port=port, rewrite_resolv_conf=False) as trap:
|
||||
assert trap.address != "127.0.0.1" and trap.address in _leaks.TRAP_ADDRESSES, trap.address
|
||||
assert _udp_ask_at(trap.address, port, "leak.test")[3] & 0xF == ds.RCODE_REFUSED
|
||||
finally:
|
||||
holder_tcp.close()
|
||||
holder_udp.close()
|
||||
|
||||
|
||||
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, **_kw: 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
|
||||
@@ -0,0 +1,193 @@
|
||||
"""The judges and the gateway of the realness suite (``test_realness_behind_a_declared_exit_e2e.py``), held to what they say.
|
||||
|
||||
No browser: golden reads for the judges (each red case is one the e2e must catch), and the gateway and the site with a plain
|
||||
socket client, so that "a connection the gateway did not open is a leak" is shown to work before a browser is trusted with it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import socket
|
||||
import struct
|
||||
|
||||
import pytest
|
||||
|
||||
import _realness_support as rs
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
EXIT = rs.EXITS["germany"]
|
||||
HOST_LAN = "192.168.1.20"
|
||||
GOOD_SDP = "v=0\r\no=- 1 0 IN IP4 0.0.0.0\r\nc=IN IP4 0.0.0.0\r\n"
|
||||
MDNS_HOST = "candidate:0 1 UDP 2122252543 1460e928-16b3-4c66-80ad-04abcdef0000.local 54551 typ host"
|
||||
SRFLX = "candidate:1 1 UDP 1686052863 %s 58555 typ srflx raddr 0.0.0.0 rport 0"
|
||||
|
||||
|
||||
def _probe(*lines, sdp=GOOD_SDP):
|
||||
return {"candidates": list(lines), "sdp": sdp + "".join("a=%s\r\n" % line for line in lines), "errors": []}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------- the table
|
||||
def test_every_declared_exit_is_a_public_ipv4_address_of_its_own():
|
||||
addresses = list(rs.EXITS.values())
|
||||
assert len(set(addresses)) == len(addresses) >= 6
|
||||
for address in addresses:
|
||||
parsed = ipaddress.ip_address(address)
|
||||
assert parsed.version == 4 and parsed.is_global, address
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------- webrtc
|
||||
def test_a_coherent_gather_with_mdns_hosts_and_the_exit_as_srflx_is_clean():
|
||||
assert rs.webrtc_problems(_probe(MDNS_HOST, SRFLX % EXIT), EXIT, {HOST_LAN, "127.0.0.1"}) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("probe, fragment", [
|
||||
(_probe("candidate:0 1 UDP 2122252543 %s 54551 typ host" % HOST_LAN), "not mDNS"),
|
||||
(_probe(MDNS_HOST, SRFLX % rs.EXITS["japan"]), "server-reflexive"),
|
||||
(_probe(MDNS_HOST, "candidate:2 1 UDP 2122252542 2001:db8::7 54552 typ host"), "IPv6"),
|
||||
(_probe(MDNS_HOST, sdp="v=0\r\nc=IN IP4 0.0.0.0\r\na=ice-ufrag:x\r\na=candidate:9 1 UDP 1 10.0.0.8 5 typ host raddr "
|
||||
"10.0.0.8 rport 5\r\n"), "private"),
|
||||
({"candidates": [], "sdp": GOOD_SDP, "errors": [{"code": 701}]}, "no candidate"),
|
||||
], ids=["raw_lan_host", "srflx_is_not_the_exit", "ipv6_behind_ipv4", "private_address_in_the_sdp", "no_candidate"])
|
||||
def test_a_gather_that_shows_the_host_or_disagrees_with_the_exit_is_named(probe, fragment):
|
||||
problems = rs.webrtc_problems(probe, EXIT, {HOST_LAN})
|
||||
assert problems and any(fragment in p for p in problems), problems
|
||||
|
||||
|
||||
def test_an_address_of_this_machines_interfaces_in_the_sdp_is_named_even_when_it_is_not_private():
|
||||
public_own = rs.EXITS["japan"] # an interface can carry a public address: the exit of this test is another one
|
||||
problems = rs.webrtc_problems(_probe(MDNS_HOST, sdp=GOOD_SDP + "a=x-note:%s\r\n" % public_own), EXIT, {public_own})
|
||||
assert any("interfaces" in p for p in problems), problems
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------------- zone
|
||||
def test_the_offsets_of_a_zone_at_the_two_instants_follow_its_daylight_saving():
|
||||
assert rs.expected_offsets("Asia/Kolkata") == [330, 330]
|
||||
assert rs.expected_offsets("America/Los_Angeles") == [-480, -420]
|
||||
assert rs.expected_offsets("Australia/Melbourne") == [660, 600] # the southern hemisphere runs the other way
|
||||
assert rs.expected_offsets("Asia/Tokyo") == [540, 540]
|
||||
|
||||
|
||||
def _read(zone, **override):
|
||||
read = {"zone": zone, "offsets_by_date": rs.expected_offsets(zone), "offsets_by_intl": rs.expected_offsets(zone),
|
||||
"language": "de", "languages": ["de", "en-US", "en"], "intl": "de"}
|
||||
read.update(override)
|
||||
return read
|
||||
|
||||
|
||||
def test_a_page_and_a_worker_that_say_the_zone_of_the_exit_are_clean():
|
||||
assert rs.timezone_problems({"page": _read("Europe/Berlin"), "worker": _read("Europe/Berlin")}, "Europe/Berlin") == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("worker, fragment", [
|
||||
(_read("Europe/London"), "worker: Intl says"),
|
||||
(_read("Europe/Berlin", offsets_by_date=[0, 0]), "worker: offsets_by_date"),
|
||||
(_read("Europe/Berlin", offsets_by_intl=[120, 60]), "worker: offsets_by_intl"),
|
||||
], ids=["worker_zone", "clock_offset", "intl_offset"])
|
||||
def test_a_worker_that_keeps_another_zone_or_offset_is_named(worker, fragment):
|
||||
problems = rs.timezone_problems({"page": _read("Europe/Berlin"), "worker": worker}, "Europe/Berlin")
|
||||
assert any(fragment in p for p in problems), problems
|
||||
|
||||
|
||||
def test_the_older_canonical_name_of_a_zone_is_the_zone():
|
||||
both = {"page": _read("Asia/Calcutta"), "worker": _read("Asia/Kolkata")}
|
||||
assert rs.timezone_problems(both, "Asia/Kolkata") == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------- language
|
||||
HEADER = "de,en-US;q=0.7,en;q=0.3"
|
||||
HEADERS = {"/": HEADER, "/fetch": HEADER, "/worker-fetch": HEADER}
|
||||
|
||||
|
||||
def test_a_language_everything_agrees_on_and_the_country_speaks_is_clean():
|
||||
reads = {"page": _read("Europe/Berlin"), "worker": _read("Europe/Berlin")}
|
||||
assert rs.language_problems(reads, HEADERS, "DE") == []
|
||||
|
||||
|
||||
def test_a_country_that_is_not_in_the_table_is_checked_for_agreement_only():
|
||||
reads = {"page": _read("Europe/Berlin"), "worker": _read("Europe/Berlin")}
|
||||
assert rs.language_problems(reads, HEADERS, "ZZ") == []
|
||||
assert rs.language_problems(reads, HEADERS, None) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change, fragment", [
|
||||
(lambda reads, headers: reads["worker"].update(languages=["en-US", "en"]), "worker: languages"),
|
||||
(lambda reads, headers: reads["worker"].update(intl="en-US"), "worker: the Intl locale"),
|
||||
(lambda reads, headers: reads["page"].update(language="en-US"), "navigator.language"),
|
||||
(lambda reads, headers: headers.update({"/worker-fetch": "en-US,en;q=0.5"}), "/worker-fetch: Accept-Language"),
|
||||
(lambda reads, headers: headers.update({"/fetch": None}), "carried no Accept-Language"),
|
||||
], ids=["worker_languages", "worker_intl", "navigator_language", "worker_header", "no_header"])
|
||||
def test_a_read_that_disagrees_with_the_others_is_named(change, fragment):
|
||||
reads = {"page": _read("Europe/Berlin"), "worker": _read("Europe/Berlin")}
|
||||
headers = dict(HEADERS)
|
||||
change(reads, headers)
|
||||
problems = rs.language_problems(reads, headers, "DE")
|
||||
assert any(fragment in p for p in problems), problems
|
||||
|
||||
|
||||
def test_a_language_the_country_does_not_speak_is_named():
|
||||
reads = {"page": _read("Asia/Tokyo", language="ru", languages=["ru", "en"], intl="ru"),
|
||||
"worker": _read("Asia/Tokyo", language="ru", languages=["ru", "en"], intl="ru")}
|
||||
headers = {path: "ru,en;q=0.5" for path in HEADERS}
|
||||
problems = rs.language_problems(reads, headers, "JP")
|
||||
assert any("not plausible for JP" in p for p in problems), problems
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------ the gateway and the site
|
||||
def _ask(s):
|
||||
s.sendall(b"GET /ip HTTP/1.0\r\nHost: x\r\nAccept-Language: de\r\n\r\n")
|
||||
data = b""
|
||||
while True:
|
||||
chunk = s.recv(4096)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
return data.split(b"\r\n\r\n", 1)[1].decode()
|
||||
|
||||
|
||||
def _get_ip_through(gateway_port, site_port):
|
||||
s = socket.create_connection(("127.0.0.1", gateway_port), timeout=10)
|
||||
try:
|
||||
s.sendall(b"\x05\x01\x00")
|
||||
assert s.recv(2) == b"\x05\x00"
|
||||
s.sendall(b"\x05\x01\x00\x01" + socket.inet_aton("127.0.0.1") + struct.pack("!H", site_port))
|
||||
reply = b""
|
||||
while len(reply) < 10:
|
||||
reply += s.recv(10 - len(reply))
|
||||
assert reply[1] == 0, reply
|
||||
return _ask(s)
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
|
||||
def test_the_site_tells_a_connection_of_the_gateway_from_a_direct_one(doh):
|
||||
gateway = rs.ExitGateway("exit", doh, tcp_exit=EXIT, udp_exit=EXIT)
|
||||
site = rs.Site(gateway)
|
||||
try:
|
||||
assert _get_ip_through(gateway.port, site.port) == EXIT
|
||||
direct = socket.create_connection(("127.0.0.1", site.port), timeout=10)
|
||||
try:
|
||||
assert _ask(direct).startswith("DIRECT 127.0.0.1")
|
||||
finally:
|
||||
direct.close()
|
||||
verdicts = [a.via_gateway for a in site.arrivals]
|
||||
assert verdicts == [True, False], site.arrivals
|
||||
problems = rs.ip_problems(EXIT, site.arrivals, [], EXIT, gateway.connects, site.port)
|
||||
assert any("did not open" in p for p in problems), problems
|
||||
assert site.headers_of("/ip") == {"/ip": "de"}
|
||||
finally:
|
||||
site.close()
|
||||
gateway.close()
|
||||
|
||||
|
||||
def test_a_run_through_the_gateway_only_is_clean_and_a_wrong_address_is_named(doh):
|
||||
gateway = rs.ExitGateway("exit", doh, tcp_exit=EXIT, udp_exit=EXIT)
|
||||
site = rs.Site(gateway)
|
||||
try:
|
||||
seen = _get_ip_through(gateway.port, site.port)
|
||||
assert rs.ip_problems(seen, site.arrivals, [], EXIT, gateway.connects, site.port) == []
|
||||
assert any("declared exit" in p for p in rs.ip_problems("192.0.2.1", site.arrivals, [], EXIT, gateway.connects, site.port))
|
||||
assert any("past the gateway" in p for p in rs.ip_problems(seen, site.arrivals, ["192.0.2.9:443"], EXIT,
|
||||
gateway.connects, site.port))
|
||||
finally:
|
||||
site.close()
|
||||
gateway.close()
|
||||
@@ -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,105 @@
|
||||
"""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
|
||||
from _leaks import ResolverTrap
|
||||
|
||||
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 _conftest():
|
||||
# the shared fixtures live in tests/conftest.py (the lint of F811: no file re-declares an imported fixture)
|
||||
here = str(Path(__file__).resolve().parent)
|
||||
if here not in sys.path:
|
||||
sys.path.insert(0, here)
|
||||
return importlib.import_module("conftest")
|
||||
|
||||
|
||||
def _fixture_body(module):
|
||||
fixture = _conftest().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(ResolverTrap, "available", False)
|
||||
monkeypatch.setattr(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(ResolverTrap, "available", True)
|
||||
|
||||
def busy(self):
|
||||
raise OSError("Address already in use")
|
||||
|
||||
monkeypatch.setattr(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(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(ResolverTrap, "available", False)
|
||||
monkeypatch.setattr(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)
|
||||
|
||||
|
||||
def test_a_closed_trap_gives_its_port_back_at_once():
|
||||
"""The threads that answer on the trap's sockets end BEFORE the sockets are closed. On Linux a close() from another thread
|
||||
does not wake a thread blocked in accept()/recvfrom(): the kernel kept the socket, still bound, so the port stayed taken after
|
||||
the test and the next trap went to 127.0.0.2, then 127.0.0.3 ... until none of the eight was left ("Address already in use" on
|
||||
all of them, run 43164943499). The old code fails here on Linux; no root is needed (a free port, no resolv.conf)."""
|
||||
first = ResolverTrap(port=0, rewrite_resolv_conf=False)
|
||||
first.__enter__()
|
||||
port = first.port
|
||||
assert port and first.address == "127.0.0.1"
|
||||
first.__exit__(None, None, None)
|
||||
again = ResolverTrap(port=port, rewrite_resolv_conf=False)
|
||||
try:
|
||||
again.__enter__()
|
||||
assert again.address == "127.0.0.1", (
|
||||
"the port %d of the closed trap was still taken: the second trap had to go to %s" % (port, again.address))
|
||||
finally:
|
||||
again.__exit__(None, 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,277 @@
|
||||
"""The position the core declares for a session reaches the engine for EVERY context, and the user's own wins.
|
||||
|
||||
The core computes the position (``SessionGeo.geolocation_override()``: latitude, longitude, accuracy) from the exit
|
||||
and the seed. This package carries it as the standard ``geolocation`` context option, in the session's context defaults,
|
||||
so ``Browser.setGeolocationOverride`` is sent for the default context, for each ``new_context``/``new_page`` and for each
|
||||
context a remote client opens; a ``geolocation=`` given by the caller replaces it; and the permission is never granted
|
||||
here (the engine answers only a page that was granted).
|
||||
|
||||
Hermetic: the engine is a recording connection, the geo step answers a made-up exit at 45.0 / 9.0.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import pathlib
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_core import SessionGeo, decide_session_locale
|
||||
from invisible_core._geoposition import declared_position
|
||||
from invisible_core.juggler.connection import EventListeners
|
||||
from invisible_playwright import InvisiblePlaywright, _session
|
||||
from invisible_playwright._juggler import remote
|
||||
from invisible_playwright._juggler.server import BrowserDispatcher, Server
|
||||
from invisible_playwright.async_api import InvisiblePlaywright as AsyncInvisiblePlaywright
|
||||
|
||||
_PKG = pathlib.Path(__file__).resolve().parent.parent / "src" / "invisible_playwright"
|
||||
EXIT = (45.0, 9.0)
|
||||
|
||||
|
||||
def _geo_of(seed):
|
||||
p = declared_position(seed, *EXIT)
|
||||
return SessionGeo("Europe/Rome", "203.0.113.7", p.latitude, p.longitude,
|
||||
decide_session_locale("it-IT"), p.accuracy)
|
||||
|
||||
|
||||
def _past_geo(cls, seed=42, geo=None):
|
||||
"""A session past the geo step of __enter__, without the network."""
|
||||
obj = cls(seed=seed, timezone="Europe/Rome", locale="it-IT")
|
||||
geo = geo if geo is not None else _geo_of(seed)
|
||||
obj._timezone, obj._locale = geo.timezone, geo.locale
|
||||
obj._geolocation = geo.geolocation_override()
|
||||
return obj
|
||||
|
||||
|
||||
class _Connection(EventListeners):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.sent = []
|
||||
|
||||
def startup_send(self, method, params=None):
|
||||
return self.send(method, params, timeout=None)
|
||||
|
||||
def send(self, method, params=None, session=None, timeout=30):
|
||||
self.sent.append((method, params))
|
||||
return {"browserContextId": "CTX-%d" % len(self.sent)}
|
||||
|
||||
|
||||
def _dispatcher():
|
||||
conn = _Connection()
|
||||
return conn, BrowserDispatcher(Server(), None, conn, "151.0")
|
||||
|
||||
|
||||
def _overrides(conn):
|
||||
return [p for m, p in conn.sent if m == "Browser.setGeolocationOverride"]
|
||||
|
||||
|
||||
def _protocol_params(kwargs):
|
||||
"""The session's defaults in the protocol's spelling, as the remote server and the Playwright client both give them."""
|
||||
return {("timezoneId" if k == "timezone_id" else k): v for k, v in kwargs.items()}
|
||||
|
||||
|
||||
# -- the defaults carry the declaration --------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("cls", [InvisiblePlaywright, AsyncInvisiblePlaywright])
|
||||
def test_the_context_defaults_carry_the_declared_position(cls):
|
||||
session = _past_geo(cls)
|
||||
want = declared_position(42, *EXIT).as_override()
|
||||
assert session._default_context_kwargs()["geolocation"] == want
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("cls", [InvisiblePlaywright, AsyncInvisiblePlaywright])
|
||||
def test_when_the_coordinates_are_unavailable_the_defaults_carry_nothing(cls):
|
||||
no_point = SessionGeo("Europe/Rome", "203.0.113.7", locale=decide_session_locale("it-IT"))
|
||||
session = _past_geo(cls, geo=no_point)
|
||||
assert "geolocation" not in session._default_context_kwargs()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_session_that_has_not_decided_yet_declares_nothing():
|
||||
assert "geolocation" not in InvisiblePlaywright(seed=42)._default_context_kwargs()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_two_seeds_get_different_positions_and_one_seed_the_same():
|
||||
a1 = _past_geo(InvisiblePlaywright, 1)._default_context_kwargs()["geolocation"]
|
||||
a2 = _past_geo(InvisiblePlaywright, 1)._default_context_kwargs()["geolocation"]
|
||||
b = _past_geo(InvisiblePlaywright, 2)._default_context_kwargs()["geolocation"]
|
||||
assert a1 == a2 and a1 != b
|
||||
|
||||
|
||||
# -- the command: the default context and every new context ----------------------------------------------------
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_default_context_gets_the_override_with_exactly_three_keys():
|
||||
"""`launch_persistent_context` takes the defaults as context options and addresses the default context by absence."""
|
||||
conn, browser = _dispatcher()
|
||||
session = _past_geo(InvisiblePlaywright)
|
||||
browser._apply_context_options(None, _protocol_params(session._default_context_kwargs()))
|
||||
(params,) = _overrides(conn)
|
||||
assert "browserContextId" not in params, "the default context is addressed by absence"
|
||||
assert set(params) == {"geolocation"}
|
||||
assert set(params["geolocation"]) == {"latitude", "longitude", "accuracy"}
|
||||
assert params["geolocation"] == declared_position(42, *EXIT).as_override()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_new_context_gets_the_override_for_its_own_id():
|
||||
conn, browser = _dispatcher()
|
||||
session = _past_geo(InvisiblePlaywright)
|
||||
browser.op_new_context(_protocol_params(session._default_context_kwargs()))
|
||||
(params,) = _overrides(conn)
|
||||
assert params["browserContextId"].startswith("CTX-")
|
||||
assert params["geolocation"] == declared_position(42, *EXIT).as_override()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_permission_is_not_granted_by_us():
|
||||
conn, browser = _dispatcher()
|
||||
session = _past_geo(InvisiblePlaywright)
|
||||
browser.op_new_context(_protocol_params(session._default_context_kwargs()))
|
||||
assert not [m for m, _ in conn.sent if m in ("Browser.grantPermissions", "Browser.setPermissions")]
|
||||
assert "permissions" not in session._default_context_kwargs()
|
||||
|
||||
|
||||
# -- the sync and the async wrappers: new_context and new_page ---------------------------------------------------
|
||||
|
||||
class _StubContext:
|
||||
def new_page(self, **kw):
|
||||
return object()
|
||||
|
||||
def add_cookies(self, cookies):
|
||||
pass
|
||||
|
||||
|
||||
class _StubBrowser:
|
||||
def __init__(self):
|
||||
self.context_kwargs, self.page_kwargs = [], []
|
||||
|
||||
def new_context(self, **kw):
|
||||
self.context_kwargs.append(kw)
|
||||
return _StubContext()
|
||||
|
||||
def new_page(self, **kw):
|
||||
self.page_kwargs.append(kw)
|
||||
page = type("_Page", (), {})()
|
||||
page.context = _StubContext()
|
||||
return page
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_new_context_and_new_page_get_the_declared_position():
|
||||
session = _past_geo(InvisiblePlaywright)
|
||||
browser = _StubBrowser()
|
||||
session._patch_new_context_defaults(browser)
|
||||
browser.new_context()
|
||||
browser.new_page()
|
||||
want = declared_position(42, *EXIT).as_override()
|
||||
assert browser.context_kwargs[0]["geolocation"] == want
|
||||
assert browser.page_kwargs[0]["geolocation"] == want
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_geolocation_given_by_the_user_wins():
|
||||
session = _past_geo(InvisiblePlaywright)
|
||||
browser = _StubBrowser()
|
||||
session._patch_new_context_defaults(browser)
|
||||
mine = {"latitude": 10.0, "longitude": 20.0}
|
||||
browser.new_context(geolocation=mine)
|
||||
browser.new_page(geolocation=mine)
|
||||
assert browser.context_kwargs[0]["geolocation"] == mine
|
||||
assert browser.page_kwargs[0]["geolocation"] == mine
|
||||
# ... and the next context, which names none, is back on the declared one: nothing leaks from the previous.
|
||||
browser.new_context()
|
||||
assert browser.context_kwargs[1]["geolocation"] == declared_position(42, *EXIT).as_override()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_user_geolocation_reaches_the_engine_instead_of_the_declared_one():
|
||||
conn, browser = _dispatcher()
|
||||
session = _past_geo(InvisiblePlaywright)
|
||||
params = _protocol_params(session._default_context_kwargs())
|
||||
params["geolocation"] = {"latitude": 10.0, "longitude": 20.0, "accuracy": 5}
|
||||
browser.op_new_context(params)
|
||||
(sent,) = _overrides(conn)
|
||||
assert sent["geolocation"] == {"latitude": 10.0, "longitude": 20.0, "accuracy": 5}
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_context_that_closes_leaves_no_override_for_the_next():
|
||||
"""Each context carries its own id: the first (user's) and the second (declared) never share a command."""
|
||||
conn, browser = _dispatcher()
|
||||
session = _past_geo(InvisiblePlaywright)
|
||||
mine = {"latitude": 10.0, "longitude": 20.0, "accuracy": 5}
|
||||
first = _protocol_params(session._default_context_kwargs())
|
||||
first["geolocation"] = mine
|
||||
browser.op_new_context(first)
|
||||
browser.op_new_context(_protocol_params(session._default_context_kwargs()))
|
||||
one, two = _overrides(conn)
|
||||
assert one["browserContextId"] != two["browserContextId"]
|
||||
assert one["geolocation"] == mine
|
||||
assert two["geolocation"] == declared_position(42, *EXIT).as_override()
|
||||
|
||||
|
||||
# -- the served browser: a remote client's context gets the session defaults ------------------------------------------
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_remote_clients_context_gets_the_declared_position_and_its_own_wins():
|
||||
session = _past_geo(InvisiblePlaywright)
|
||||
defaults = remote._context_defaults(session, None)
|
||||
assert defaults["geolocation"] == declared_position(42, *EXIT).as_override()
|
||||
|
||||
class _Browser:
|
||||
guid = "browser"
|
||||
|
||||
endpoint = remote.RemoteEndpoint.__new__(remote.RemoteEndpoint)
|
||||
endpoint.context_defaults = dict(defaults)
|
||||
endpoint.context_options_override = False
|
||||
endpoint.browser = _Browser()
|
||||
endpoint._pages = iter(range(10))
|
||||
plain = endpoint._prepared({"guid": "browser", "method": "newContext", "params": {}})
|
||||
assert plain["params"]["geolocation"] == defaults["geolocation"]
|
||||
mine = {"latitude": 10.0, "longitude": 20.0}
|
||||
own = endpoint._prepared({"guid": "browser", "method": "newContext", "params": {"geolocation": mine}})
|
||||
assert own["params"]["geolocation"] == mine
|
||||
page = endpoint._prepared({"guid": "browser", "method": "newPage", "params": {}})
|
||||
assert page["params"]["geolocation"] == defaults["geolocation"]
|
||||
|
||||
|
||||
# -- the geo step is asked WITH the seed, in every entry --------------------------------------------------------
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_every_call_to_the_geo_step_hands_it_the_session_seed():
|
||||
"""Without the seed the core declares nothing, so a call site that forgets it is a session with no position."""
|
||||
sites = []
|
||||
for path in _PKG.rglob("*.py"):
|
||||
if "_pw" in path.relative_to(_PKG).parts:
|
||||
continue
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"))
|
||||
for node in ast.walk(tree):
|
||||
if not isinstance(node, ast.Call):
|
||||
continue
|
||||
name = getattr(node.func, "id", getattr(node.func, "attr", ""))
|
||||
if name in ("prepare_session_geo", "session_geo"):
|
||||
sites.append((path.name, node.lineno, any(k.arg == "seed" for k in node.keywords)))
|
||||
# asyncio.to_thread(prepare_session_geo, ...): the function is an argument
|
||||
if name == "to_thread" and node.args and getattr(node.args[0], "id", "") == "prepare_session_geo":
|
||||
sites.append((path.name, node.lineno, any(k.arg == "seed" for k in node.keywords)))
|
||||
assert len(sites) >= 4, sites
|
||||
assert [s for s in sites if not s[2]] == [], sites
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_session_geo_step_passes_the_seed_to_the_core(monkeypatch):
|
||||
import invisible_core
|
||||
seen = {}
|
||||
|
||||
def fake(timezone, proxy, locale, *, seed=None):
|
||||
seen["seed"] = seed
|
||||
return _geo_of(7)
|
||||
|
||||
# conftest's autouse patch replaced `_session.session_geo` with a fixed answer: undo it, the real one is under test.
|
||||
monkeypatch.undo()
|
||||
monkeypatch.setattr(invisible_core, "prepare_session_geo", fake)
|
||||
_session.session_geo("auto", None, "auto", seed=7)
|
||||
assert seen["seed"] == 7
|
||||
@@ -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,113 @@
|
||||
"""The helpers the e2e tests of the UDP line share work, without a browser (hermetic, loopback).
|
||||
|
||||
The core measures the UDP exit of a SOCKS5 proxy before it declares it (``invisible_core._udp_exit``), from the servers of the
|
||||
launch parameter ``udp_stun_servers``. An e2e that expects the engine to use a relay is only as good as the measurement that
|
||||
precedes it: if the gateway of the test did not answer the Binding the way the core asks it (a STUN request wrapped in the
|
||||
SOCKS5 UDP header, to an IPv4 literal, through the ASSOCIATE), the road would be declared ``no`` and the engine would never
|
||||
send the page's UDP there, and the e2e would fail for a reason that is not the product's. These tests hold the gateways of
|
||||
``_socks_servers`` and the chain of ``_turn_chain`` to the real measurement of the core, and the helper that builds the list
|
||||
to its form.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
|
||||
import pytest
|
||||
|
||||
import _turn_chain as chain_mod
|
||||
from _socks_servers import EXIT, MEASURE_NUMBER, STUN_NUMBER, STUN_PORT, coherent, mismatched, silent_udp, tcp_only
|
||||
from _udp_line import declared_udp, egress_by_proxy, measure_servers
|
||||
from invisible_core import _geo, _udp_exit
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fresh(monkeypatch):
|
||||
monkeypatch.setattr(_udp_exit, "_cache", {})
|
||||
|
||||
|
||||
def test_the_measure_servers_are_ip_port_ipv4_literals_that_the_core_takes():
|
||||
for gateway in (coherent(), tcp_only(), mismatched(), silent_udp()):
|
||||
with gateway:
|
||||
servers = measure_servers(gateway)
|
||||
assert servers and all(isinstance(entry, str) for entry in servers)
|
||||
for entry in servers:
|
||||
host, _, port = entry.rpartition(":")
|
||||
assert ipaddress.ip_address(host).version == 4, entry
|
||||
assert 1 <= int(port) <= 65535, entry
|
||||
assert _udp_exit.stun_servers(servers), "the core refused the list the helper builds"
|
||||
|
||||
|
||||
def test_the_measure_server_is_not_the_one_the_page_asks():
|
||||
"""So that what the measurement sent through the relay is never mistaken for what the page sent."""
|
||||
with coherent() as gateway:
|
||||
assert measure_servers(gateway) == ["%s:%d" % (MEASURE_NUMBER, STUN_PORT)]
|
||||
assert MEASURE_NUMBER != STUN_NUMBER
|
||||
|
||||
|
||||
def test_the_helper_refuses_a_name_or_a_bad_port():
|
||||
class Named:
|
||||
measure_servers = ["stun.example.test:3478"]
|
||||
|
||||
class Ported:
|
||||
measure_servers = ["198.51.100.6:0"]
|
||||
|
||||
for gateway in (Named(), Ported()):
|
||||
with pytest.raises(ValueError):
|
||||
measure_servers(gateway)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("make, verdict", [
|
||||
(lambda: coherent(), "coherent"),
|
||||
(lambda: coherent(user="alice", password="s3cret"), "coherent"),
|
||||
(lambda: mismatched(), "no"),
|
||||
(lambda: tcp_only(), "no"),
|
||||
(lambda: silent_udp(), "unmeasured"),
|
||||
], ids=["coherent", "coherent_with_credentials", "mismatched", "tcp_only", "silent_udp"])
|
||||
def test_the_gateway_answers_the_core_measurement_the_way_its_name_says(make, verdict):
|
||||
"""The real measurement of the core, against the gateway, asked at the server the helper hands out."""
|
||||
with make() as gateway:
|
||||
got = _udp_exit.measure_udp_exit(gateway.proxy, gateway.tcp_exit, udp_stun_servers=measure_servers(gateway),
|
||||
budget=1.5)
|
||||
assert got == verdict
|
||||
if gateway.udp == "relay":
|
||||
asked = {host for host, _port, _payload in gateway.datagrams}
|
||||
assert asked == {MEASURE_NUMBER}, "the measurement asked %s; the page's server is not its business" % asked
|
||||
|
||||
|
||||
def test_the_chain_answers_the_core_measurement_coherent():
|
||||
"""The road of the whole-chain e2e (TURN by name, DoH, page): its relay answers a Binding to the helper's server with the
|
||||
address its datagrams leave from, which is its TCP exit."""
|
||||
with chain_mod.Chain(rtt_ms=0, relay_host="127.0.0.1") as chain:
|
||||
assert chain.tcp_exit == chain_mod.EXIT_HOST
|
||||
got = _udp_exit.measure_udp_exit(chain.proxy, chain.tcp_exit, udp_stun_servers=measure_servers(chain), budget=1.5)
|
||||
assert got == "coherent"
|
||||
# And the TCP exit the e2e hands the core is the chain's own: with any other address it would read ``no``.
|
||||
other = _udp_exit.measure_udp_exit(chain.proxy, EXIT, udp_stun_servers=measure_servers(chain), budget=1.5)
|
||||
assert other == "no"
|
||||
|
||||
|
||||
def test_each_proxy_has_the_tcp_exit_of_its_own_gateway():
|
||||
with coherent(exit_ip="203.0.113.7") as first, coherent(exit_ip="198.51.100.77") as second:
|
||||
discover = egress_by_proxy(first, second)
|
||||
assert discover(first.proxy) == "203.0.113.7"
|
||||
assert discover(dict(second.proxy, username="x")) == "198.51.100.77"
|
||||
assert discover(first.proxy, timeout=3) == "203.0.113.7"
|
||||
with pytest.raises(AssertionError):
|
||||
discover({"server": "socks5://127.0.0.1:1"})
|
||||
with pytest.raises(AssertionError):
|
||||
discover(None)
|
||||
assert egress_by_proxy(first, direct="192.0.2.9")(None) == "192.0.2.9"
|
||||
|
||||
|
||||
def test_what_the_launch_declared_is_what_the_core_measured_and_an_absent_measurement_is_not_unmeasured(monkeypatch):
|
||||
with silent_udp() as mute, coherent(exit_ip="198.51.100.77") as good:
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(mute, good))
|
||||
with pytest.raises(AssertionError):
|
||||
declared_udp(mute.proxy, measure_servers(mute)) # nothing measured yet
|
||||
assert _udp_exit.measure_proxy_udp(good.proxy, measure_servers(good)) == "coherent"
|
||||
assert declared_udp(good.proxy, measure_servers(good)) == "coherent"
|
||||
# a measurement the launch made with ANOTHER list is not this one
|
||||
with pytest.raises(AssertionError):
|
||||
declared_udp(good.proxy, ["198.51.100.8:3478"])
|
||||
@@ -0,0 +1,90 @@
|
||||
"""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
|
||||
from _udp_line import declared_udp, egress_by_proxy, measure_servers
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
#: Loopback goes through the proxy too (as in test_doh_through_the_proxy_e2e.py), so the road of the page is observable.
|
||||
#:
|
||||
#: ⛔ `media.peerconnection.ice.loopback`: the gateway's datagrams leave from 127.0.0.2 (so that a TURN server hearing 127.0.0.1 proves a
|
||||
#: browser that went around it), hence the TURN server tells the browser, in the XOR-MAPPED-ADDRESS of its answer, that its address is
|
||||
#: 127.0.0.2. A retail Firefox throws that answer away as "bogus" (a loopback mapped address, `nr_stun_transport_addr_check` in
|
||||
#: stun_client_ctx.cpp, unless the ICE context allows loopback: turn_client_ctx.cpp, flag set by this pref in nricectx.cpp): it keeps
|
||||
#: retransmitting the same Allocate and never gathers (measured on the giro 3 binary: the gateway delivered the 401 and then the success
|
||||
#: within 5 ms, the browser read both from the relay's socket and retransmitted the Allocate 5 times in 2 s; the same chain with the pref
|
||||
#: passes at 130 ms). It is the lab's address, not a behaviour of the product: on the real network the mapped address is the exit's.
|
||||
PREFS = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": "",
|
||||
"media.peerconnection.ice.loopback": True}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def gateway(monkeypatch):
|
||||
with chain_mod.Chain(rtt_ms=130) as chain:
|
||||
# The probe of the core that asks for the TCP exit goes nowhere (the world has no network but the gateway): it is told
|
||||
# the exit of the chain, the address its datagrams leave from. The core's UDP measurement that follows is NOT replaced:
|
||||
# it asks the chain's relay for a STUN Binding for real and compares what comes back with that exit, so the road
|
||||
# is declared ``coherent`` by measurement and the engine sends the page's UDP to the relay.
|
||||
try:
|
||||
from invisible_core import _geo
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(chain), 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
|
||||
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, udp_stun_servers=measure_servers(gateway),
|
||||
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")
|
||||
declared = declared_udp(gateway.proxy, measure_servers(gateway))
|
||||
assert declared == "coherent", "the core did not measure the chain's UDP coherent (%s): the engine would not use the relay" % declared + gateway.explain(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)
|
||||
@@ -0,0 +1,164 @@
|
||||
"""A TURN server reached over TCP is really tried, as a retail Firefox tries it.
|
||||
|
||||
The connection's local address is the DECLARED one (the interface list is declared, never read from the host), which is not an
|
||||
address of this machine. The TCP socket that talks to a TURN server was bound to it, the bind failed, the socket closed before it
|
||||
connected, and the page heard `icecandidateerror` 701 within milliseconds, with the gathering complete, without a single packet
|
||||
having left (measured on the firefox-63 candidate, direct and behind a SOCKS5 gateway: the server saw no connection at all).
|
||||
|
||||
A retail Firefox connects, sends its Allocate request, and hears 701 when the server closes: here the stand-in server accepts,
|
||||
reads, and closes the connection N milliseconds after it accepted it. So:
|
||||
|
||||
* the server sees a connection and the request (the network was tried, direct and through the gateway);
|
||||
* the page hears 701 no sooner than N milliseconds after the accept (it waited for the server, it did not give up on its own);
|
||||
* the gathering does not complete before that error.
|
||||
|
||||
Hermetic: the server listens on this machine's address (a loopback TURN server is refused by Firefox itself, retail too), the page is
|
||||
local, the gateway relays TCP only. Red on an engine before webrtc/declared-network "WebrtcTCPSocket binds the wildcard".
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import pytest
|
||||
|
||||
from _socks_servers import Socks5TcpOnly
|
||||
from test_webrtc_realness import _e2e_binary, _launch # noqa: F401
|
||||
|
||||
# Bound to the engine that carries the UDP line: red before the declared network (firefox-63): skips on the published engine; runs on the candidate.
|
||||
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
|
||||
|
||||
DECLARED = "v4=192.168.31.7;v6=0;p6="
|
||||
N_MS = 800
|
||||
WAIT_MS = 3000
|
||||
SLACK_MS = 150
|
||||
|
||||
|
||||
def _host_ip():
|
||||
"""The address this machine uses to leave: nothing is sent, the kernel only chooses the route."""
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
s.connect(("192.0.2.1", 9))
|
||||
ip = s.getsockname()[0]
|
||||
except OSError as exc:
|
||||
pytest.fail("this machine has no address but loopback (%s): the test needs one for the TURN stand-in" % exc, pytrace=False)
|
||||
finally:
|
||||
s.close()
|
||||
if ip.startswith("127."):
|
||||
pytest.fail("the only address of this machine is loopback: the test needs one for the TURN stand-in", pytrace=False)
|
||||
return ip
|
||||
|
||||
|
||||
class _TurnTcp:
|
||||
"""Accepts TCP connections, reads what comes, closes N ms after the accept."""
|
||||
|
||||
def __init__(self, n_ms):
|
||||
self.n_ms, self.accepts, self.bytes_in = n_ms, [], 0
|
||||
self._s = socket.socket()
|
||||
self._s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
self._s.bind(("0.0.0.0", 0))
|
||||
self._s.listen(16)
|
||||
self.port = self._s.getsockname()[1]
|
||||
threading.Thread(target=self._serve, daemon=True).start()
|
||||
|
||||
def _serve(self):
|
||||
while True:
|
||||
try:
|
||||
conn, _ = self._s.accept()
|
||||
except OSError:
|
||||
return
|
||||
self.accepts.append(time.time() * 1000)
|
||||
threading.Thread(target=self._hold, args=(conn,), daemon=True).start()
|
||||
|
||||
def _hold(self, conn):
|
||||
end = time.time() + self.n_ms / 1000
|
||||
conn.settimeout(0.05)
|
||||
while time.time() < end:
|
||||
try:
|
||||
data = conn.recv(4096)
|
||||
if not data:
|
||||
break
|
||||
self.bytes_in += len(data)
|
||||
except socket.timeout:
|
||||
pass
|
||||
except OSError:
|
||||
break
|
||||
try:
|
||||
conn.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
self._s.close()
|
||||
|
||||
|
||||
_JS = """async ([url, waitMs]) => {
|
||||
const ev = [];
|
||||
const pc = new RTCPeerConnection({iceServers: [{urls: url, username: 'u', credential: 'c'}]});
|
||||
pc.addEventListener('icecandidateerror', e => ev.push(['error', Date.now(), e.errorCode]));
|
||||
pc.addEventListener('icegatheringstatechange', () => ev.push(['gathering', Date.now(), pc.iceGatheringState]));
|
||||
pc.createDataChannel('x');
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
await new Promise(r => setTimeout(r, waitMs));
|
||||
pc.close();
|
||||
return ev;
|
||||
}"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def local_page():
|
||||
class H(BaseHTTPRequestHandler):
|
||||
timeout = 5
|
||||
|
||||
def do_GET(self):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html")
|
||||
self.end_headers()
|
||||
self.wfile.write(b"<html><body>turn</body></html>")
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
httpd = ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
httpd.daemon_threads = True
|
||||
threading.Thread(target=httpd.serve_forever, daemon=True).start()
|
||||
yield "http://127.0.0.1:%d/" % httpd.server_address[1]
|
||||
httpd.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("through_socks5", [False, True], ids=["direct", "socks5"])
|
||||
def test_a_turn_server_over_tcp_is_connected_to_and_waited_for(local_page, monkeypatch, through_socks5):
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.fail("no patched binary: set STEALTHFOX_E2E_BINARY", pytrace=False)
|
||||
monkeypatch.setenv("STEALTHFOX_WEBRTC_NETWORK", DECLARED)
|
||||
turn = _TurnTcp(N_MS)
|
||||
socks = Socks5TcpOnly() if through_socks5 else None
|
||||
kw = {}
|
||||
if socks:
|
||||
monkeypatch.setenv("STEALTHFOX_WEBRTC_PUBLIC_IP", "203.0.113.7")
|
||||
kw = {"proxy": {"server": "socks5://127.0.0.1:%d" % socks.port},
|
||||
"extra_prefs": {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": "",
|
||||
"media.peerconnection.ice.obfuscate_host_addresses": True}}
|
||||
try:
|
||||
with _launch(binary_path=binary, seed=7, **kw) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto(local_page, wait_until="domcontentloaded", timeout=60000)
|
||||
events = page.evaluate(_JS, ["turn:%s:%d?transport=tcp" % (_host_ip(), turn.port), WAIT_MS])
|
||||
finally:
|
||||
turn.close()
|
||||
if socks:
|
||||
socks.close()
|
||||
|
||||
assert turn.accepts, "the TURN server never saw a connection: the network was not tried (events: %r)" % events
|
||||
assert turn.bytes_in > 0, "the connection carried nothing: no Allocate request was sent"
|
||||
errors = [e for e in events if e[0] == "error"]
|
||||
assert errors and errors[0][2] == 701, "expected the 701 of a server that closed: %r" % events
|
||||
first_accept = turn.accepts[0]
|
||||
assert errors[0][1] >= first_accept + N_MS - SLACK_MS, \
|
||||
"701 came %d ms after the accept, the server held the connection for %d ms: %r" % (
|
||||
errors[0][1] - first_accept, N_MS, events)
|
||||
complete = [e for e in events if e[0] == "gathering" and e[2] == "complete"]
|
||||
assert not complete or complete[0][1] >= errors[0][1] - 50, "the gathering completed before the TURN error: %r" % events
|
||||
@@ -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):
|
||||
|
||||
+350
-217
@@ -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
|
||||
@@ -32,6 +30,10 @@ from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler, HTTPServer
|
||||
|
||||
import pytest
|
||||
|
||||
from _host_address import this_host_address
|
||||
from _socks_servers import MEASURE_NUMBER, STUN_PORT, Socks5TcpOnly
|
||||
from _udp_line import declared_udp, egress_by_proxy, measure_servers
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
# Pure SDP / ICE-candidate helpers (no I/O) - the heart of the sentinels.
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
@@ -240,27 +242,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
|
||||
|
||||
@@ -278,115 +267,8 @@ def test_no_orphan_prefs_in_baseline():
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
# Fake-proxy infrastructure for e2e: a tiny TCP-only SOCKS5 server.
|
||||
# Fake-proxy infrastructure for e2e: a tiny TCP-only SOCKS5 server (Socks5TcpOnly, in _socks_servers.py).
|
||||
# ──────────────────────────────────────────────────────────────────────────
|
||||
class _Socks5TcpOnly:
|
||||
"""Minimal SOCKS5: no-auth, CONNECT (TCP) relayed, UDP ASSOCIATE refused.
|
||||
|
||||
Reproduces a residential TCP-only proxy: pages load over TCP, but WebRTC's
|
||||
UDP path is dead - which (for a no-camera page in default_address_only mode)
|
||||
is exactly what made the default-route probe fail and ICE return zero
|
||||
candidates before Fix C.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self._srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
self._srv.bind(("127.0.0.1", 0))
|
||||
self._srv.listen(16)
|
||||
self.port = self._srv.getsockname()[1]
|
||||
self.udp_associate_attempts = 0
|
||||
self._stop = False
|
||||
self._t = threading.Thread(target=self._serve, daemon=True)
|
||||
self._t.start()
|
||||
|
||||
def _serve(self):
|
||||
while not self._stop:
|
||||
try:
|
||||
conn, _ = self._srv.accept()
|
||||
except OSError:
|
||||
break
|
||||
threading.Thread(target=self._handle, args=(conn,), daemon=True).start()
|
||||
|
||||
def _recv_exact(self, sock, n):
|
||||
buf = b""
|
||||
while len(buf) < n:
|
||||
chunk = sock.recv(n - len(buf))
|
||||
if not chunk:
|
||||
return None
|
||||
buf += chunk
|
||||
return buf
|
||||
|
||||
def _handle(self, conn):
|
||||
try:
|
||||
head = self._recv_exact(conn, 2)
|
||||
if not head or head[0] != 0x05:
|
||||
conn.close()
|
||||
return
|
||||
nmethods = head[1]
|
||||
self._recv_exact(conn, nmethods)
|
||||
conn.sendall(b"\x05\x00") # no-auth
|
||||
req = self._recv_exact(conn, 4)
|
||||
if not req:
|
||||
conn.close()
|
||||
return
|
||||
ver, cmd, _, atyp = req
|
||||
if atyp == 0x01:
|
||||
addr = socket.inet_ntoa(self._recv_exact(conn, 4))
|
||||
elif atyp == 0x03:
|
||||
ln = self._recv_exact(conn, 1)[0]
|
||||
addr = self._recv_exact(conn, ln).decode("ascii", "ignore")
|
||||
elif atyp == 0x04:
|
||||
addr = socket.inet_ntop(socket.AF_INET6, self._recv_exact(conn, 16))
|
||||
else:
|
||||
conn.close()
|
||||
return
|
||||
port = struct.unpack("!H", self._recv_exact(conn, 2))[0]
|
||||
if cmd != 0x01: # not CONNECT (e.g. UDP ASSOCIATE) → refuse
|
||||
self.udp_associate_attempts += 1
|
||||
conn.sendall(b"\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00") # cmd not supported
|
||||
conn.close()
|
||||
return
|
||||
try:
|
||||
upstream = socket.create_connection((addr, port), timeout=15)
|
||||
except OSError:
|
||||
conn.sendall(b"\x05\x04\x00\x01\x00\x00\x00\x00\x00\x00") # host unreachable
|
||||
conn.close()
|
||||
return
|
||||
conn.sendall(b"\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00") # success
|
||||
self._relay(conn, upstream)
|
||||
except Exception:
|
||||
try:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _relay(self, a, b):
|
||||
try:
|
||||
while True:
|
||||
r, _, _ = select.select([a, b], [], [], 30)
|
||||
if not r:
|
||||
break
|
||||
for s in r:
|
||||
data = s.recv(65536)
|
||||
if not data:
|
||||
return
|
||||
(b if s is a else a).sendall(data)
|
||||
finally:
|
||||
for s in (a, b):
|
||||
try:
|
||||
s.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
self._stop = True
|
||||
try:
|
||||
self._srv.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# Same per-event probe CreepJS runs (kept tiny; raw string = one escape level).
|
||||
_PROBE_JS = r"""async () => {
|
||||
const pc = new RTCPeerConnection({iceCandidatePoolSize:1, iceServers:[{urls:[
|
||||
@@ -416,35 +298,6 @@ def _e2e_binary():
|
||||
return None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def socks5_tcp_only():
|
||||
srv = _Socks5TcpOnly()
|
||||
yield srv
|
||||
srv.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def local_https_page():
|
||||
"""A trivial localhost page (used by the no-proxy srflx test)."""
|
||||
class H(BaseHTTPRequestHandler):
|
||||
#: A silent socket no longer pins a thread down: after five seconds it drops.
|
||||
timeout = 5
|
||||
def do_GET(self):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html")
|
||||
self.end_headers()
|
||||
self.wfile.write(b"<html><body>wrtc</body></html>")
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
httpd = ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
httpd.daemon_threads = True
|
||||
threading.Thread(target=httpd.serve_forever, daemon=True).start()
|
||||
yield f"http://127.0.0.1:{httpd.server_address[1]}/"
|
||||
httpd.shutdown()
|
||||
|
||||
|
||||
def _launch(**extra):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
@@ -453,20 +306,29 @@ def _launch(**extra):
|
||||
# discovery through the (fake) proxy - irrelevant here, we inject the
|
||||
# egress IP directly and want the launch deterministic/offline.
|
||||
"timezone": "America/New_York",
|
||||
# Where the core measures the UDP exit of a SOCKS5 proxy from (an explicit launch parameter, never the public
|
||||
# defaults in a hermetic test): a documentation address only the relay of a test gateway answers.
|
||||
"udp_stun_servers": ["%s:%d" % (MEASURE_NUMBER, STUN_PORT)],
|
||||
"extra_prefs": {"media.peerconnection.ice.obfuscate_host_addresses": True}}
|
||||
kw.update(extra)
|
||||
return InvisiblePlaywright(**kw)
|
||||
|
||||
|
||||
def _launch_behind(gateway, **extra):
|
||||
"""The launch behind a test gateway: its proxy, and the STUN server its relay answers for the measurement of its UDP
|
||||
exit (``udp_stun_servers``). ONE place for every e2e that needs the relay."""
|
||||
return _launch(proxy=gateway.proxy, udp_stun_servers=measure_servers(gateway), **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)."""
|
||||
@pytest.mark.usefixtures("the_udp_line")
|
||||
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 +336,365 @@ 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};
|
||||
}"""
|
||||
|
||||
|
||||
# The two prefs that decide where ICE runs are LOCKED to the retail value by the engine (toolkit/xre/nsAppRunner.cpp, after the user
|
||||
# prefs are loaded): a caller that asks for the ICE in the process of the page, or for no socket process, gets the socket process all the
|
||||
# same, and the srflx is born through the relay. Both rows below are such callers; the first is the default.
|
||||
_ICE_PREFS = [
|
||||
{}, # the engine's default: ICE in the socket process
|
||||
{"media.peerconnection.mtransport_process": False}, # a caller asks for the ICE in the process of the page: locked
|
||||
{"network.process.enabled": False}, # a caller asks for no socket process: locked
|
||||
]
|
||||
_ICE_IDS = ["ice_in_the_socket_process", "the_caller_asks_for_ice_in_the_content_process_and_the_lock_wins",
|
||||
"the_caller_asks_for_no_socket_process_and_the_lock_wins"]
|
||||
|
||||
|
||||
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, WEB_ADDRESS, 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=this_host_address(), 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", egress_by_proxy(gateway))
|
||||
extra_prefs = {"media.peerconnection.ice.obfuscate_host_addresses": True, **ice_prefs}
|
||||
with _launch_behind(gateway, binary_path=binary, 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://%s/" % WEB_ADDRESS) # by address: the browser resolves names itself
|
||||
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.
|
||||
|
||||
ICE runs in the socket process (the sockets are NrSocket's, where the layer is attached) whatever the caller asks:
|
||||
`media.peerconnection.mtransport_process` and `network.process.enabled` are locked to their retail value by the engine,
|
||||
so a caller who sets either to false (rows 2 and 3) gets the same srflx through the relay as the default. 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 = this_host_address()
|
||||
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:
|
||||
# Each gateway reports the TCP exit of its own: the context proxy is measured against ITS exit, not the session's.
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(first, second))
|
||||
extra_prefs = {"media.peerconnection.ice.obfuscate_host_addresses": True}
|
||||
with _launch_behind(first, binary_path=binary, 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 = this_host_address()
|
||||
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", egress_by_proxy(session, context))
|
||||
extra_prefs = {"media.peerconnection.ice.obfuscate_host_addresses": True}
|
||||
with _launch_behind(session, binary_path=binary, 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}")
|
||||
|
||||
|
||||
def _gather_where_the_udp_is_dropped(gateway, monkeypatch, measured):
|
||||
"""Launch behind ``gateway`` (a SOCKS5 proxy whose UDP is not coherent), gather with a STUN server only its relay could
|
||||
reach, and say what the target must look like: a retail Windows at home on a network that blocks UDP.
|
||||
|
||||
The core measured the proxy before the launch declared it, and it is ``measured`` (``no`` or ``unmeasured``): the engine
|
||||
sends the page's UDP nowhere, not to the relay and not direct, so the STUN request retransmits and ends in 701 in nICEr's
|
||||
own time. The page gets host candidates and 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)."""
|
||||
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 = f"stun:{STUN_NUMBER}:{STUN_PORT}"
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(gateway))
|
||||
extra_prefs = {"media.peerconnection.ice.obfuscate_host_addresses": True}
|
||||
with _launch_behind(gateway, binary_path=binary, extra_prefs=extra_prefs) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto("about:blank")
|
||||
res = page.evaluate(_RELAY_PROBE_JS, stun)
|
||||
carried = [(host, port) for host, port, _payload in gateway.datagrams]
|
||||
declared = declared_udp(gateway.proxy, measure_servers(gateway))
|
||||
assert declared == measured, f"the core declared udp={declared} for this proxy, the measurement is {measured}"
|
||||
assert (STUN_NUMBER, STUN_PORT) not in carried, (
|
||||
f"the engine sent the page's UDP to a relay that was not measured coherent: {carried}")
|
||||
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")
|
||||
|
||||
|
||||
@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 (reply 7). The core measures it ``no``: the target is a
|
||||
retail Windows at home on a network that blocks UDP (see :func:`_gather_where_the_udp_is_dropped`)."""
|
||||
from _socks_servers import tcp_only
|
||||
with tcp_only(user="alice", password="s3cret") as gateway:
|
||||
_gather_where_the_udp_is_dropped(gateway, monkeypatch, "no")
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.usefixtures("the_udp_line")
|
||||
def test_a_proxy_whose_udp_leaves_from_another_address_gives_no_srflx_at_all(monkeypatch):
|
||||
"""⛔ THE KNOWN-BAD INPUT: a gateway that grants UDP ASSOCIATE and answers STUN, but with an address that is not its TCP
|
||||
exit: the classic leak (a srflx that is not the address of the page's HTTP). The core measures it ``no`` and the engine
|
||||
treats it as a router that drops UDP: the relay is granted but the page's datagrams never go to it."""
|
||||
from _socks_servers import mismatched
|
||||
with mismatched(user="alice", password="s3cret", relay_host=this_host_address()) as gateway:
|
||||
_gather_where_the_udp_is_dropped(gateway, monkeypatch, "no")
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.usefixtures("the_udp_line")
|
||||
def test_a_proxy_whose_relay_never_answers_gives_no_srflx_at_all(monkeypatch):
|
||||
"""⛔ THE KNOWN-BAD INPUT: a gateway that grants UDP ASSOCIATE and carries datagrams, but no STUN server ever answers (a
|
||||
router that drops UDP behind a working handshake). The measurement ends within its budget in ``unmeasured``: not a
|
||||
refusal, but the engine acts on ``coherent`` only, so the page is where it is on a network that blocks UDP."""
|
||||
from _socks_servers import silent_udp
|
||||
with silent_udp(user="alice", password="s3cret", relay_host=this_host_address()) as gateway:
|
||||
_gather_where_the_udp_is_dropped(gateway, monkeypatch, "unmeasured")
|
||||
|
||||
|
||||
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.
|
||||
@@ -745,3 +875,6 @@ def test_a_burst_of_silent_probes_rejects_the_session():
|
||||
assert _session.ProxyEgressNonVerificabile is not _session.ProxyEgressDrifted, (
|
||||
"unmeasurable and drifted are two different diagnoses and must be "
|
||||
"distinguished by type too, or a catch cannot react differently")
|
||||
# what goes unconfirmed is the timezone and the locale decided from the egress: the engine declares no egress address
|
||||
doc = " ".join(_session.ProxyEgressNonVerificabile.__doc__.split())
|
||||
assert "timezone" in doc and "locale" in doc and "an address" not in doc, doc
|
||||
Reference in new issue
Block a user