tests: the UDP chain by name is judged by rounds of the gateway and the association it left on, not by the tick of the page or two launches
This commit is contained in:
1 parent
6576bc18ad
commit
d81c23ee83
6 files changed
+236
-42
No files matched your search
@@ -38,3 +38,42 @@ def cold_association_problem(associations: Sequence[Sequence[Optional[float]]],
|
||||
"was born at %.3f s: a cold association, made from scratch (ready before the birth: %s)"
|
||||
% (at, index, associations[index][1] and round(associations[index][1], 3), born, ready))
|
||||
return None
|
||||
|
||||
|
||||
#: The serial rounds of the gateway that the road of a TURN server written as a NAME is designed to cost, from the first CONNECT of
|
||||
#: the DoH to the Allocate that is answered with credentials (a ROUND is one round trip of the gateway, ``rtt``): the reply of the
|
||||
#: CONNECT (1), the TLS flight and the DoH question (2), the first Allocate answered 401 (1) and the second one reaching the TURN
|
||||
#: server (1/2): four and a half, and one more for a second question asked of the DoH before the allocation. What the gateway adds
|
||||
#: to every step is the same on every machine, so a count of rounds is the same on every machine: a handshake that waits for another
|
||||
#: (the associations made one after the other, a DoH connection made for every question) adds rounds, a slow machine does not.
|
||||
TURN_CHAIN_ROUNDS = 6
|
||||
|
||||
|
||||
def turn_chain_problem(born: float, connect_at: Sequence[float], allocated_at: Optional[float], rtt: float,
|
||||
associations: Sequence[Sequence[Optional[float]]],
|
||||
via: Iterable[Tuple[str, int, int, float]], host: str,
|
||||
rounds: int = TURN_CHAIN_ROUNDS) -> Optional[str]:
|
||||
"""What is wrong with the road of a TURN server written as a name, or None. Every time is in seconds from the start of the
|
||||
gateway, read off its own stamps: the page's tick decides nothing.
|
||||
|
||||
``born`` is the birth of the PeerConnection; ``connect_at`` the arrival of each CONNECT to the DoH; ``allocated_at`` the moment
|
||||
the TURN server answered the first Allocate that carried credentials (None: it never did); ``rtt`` the round trip of the
|
||||
gateway; ``associations``, ``via`` and ``host`` as for :func:`cold_association_problem` (``host`` is the address of the TURN
|
||||
server: the datagrams of the allocation are the ones judged).
|
||||
|
||||
Two promises. The allocation is answered within ``rounds`` rounds of the gateway and one round more, counted from the first
|
||||
CONNECT to the DoH after the birth (from the birth when the DoH connection of the page was kept: nothing before it is a round
|
||||
of the gateway, so a machine that is slow to start asking does not move it). And the Allocate leaves on an association that was
|
||||
ready before the birth: a handshake made after it costs two rounds more that nobody asked for, and a gateway whose handshakes
|
||||
wait for each other costs them over and over."""
|
||||
if allocated_at is None:
|
||||
return "the TURN server never answered an Allocate that carried credentials"
|
||||
began = min((t for t in connect_at if t >= born), default=born)
|
||||
spent = allocated_at - began
|
||||
budget = (rounds + 1) * rtt
|
||||
if spent > budget:
|
||||
return ("the allocation was answered %.3f s after the road began (the first CONNECT to the DoH after the birth of the "
|
||||
"PeerConnection at %.3f s, or the birth), %.1f rounds of the gateway (%.0f ms each); the design costs %d and one "
|
||||
"more is allowed: a handshake waited for another"
|
||||
% (spent, began, spent / rtt if rtt else float("inf"), rtt * 1000, rounds))
|
||||
return cold_association_problem(associations, via, host, born)
|
||||
+22
-5
@@ -40,7 +40,7 @@ import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
from _doh_servers import DohGateway, FakeDoh
|
||||
from _doh_servers import DOH_TARGETS, DohGateway, FakeDoh
|
||||
from _host_address import this_host_address
|
||||
from _socks_servers import WHOAMI4, Gateway
|
||||
|
||||
@@ -55,6 +55,8 @@ EXIT_HOST = "127.0.0.2"
|
||||
#: The exit of a lab that a browser accepts as a real one: a documentation address (RFC 5737, TEST-NET-2, like the TURN server's) that
|
||||
#: the host holds on its loopback interface (`lab_exit_address`). A mapped address in 127/8 is thrown away by nICEr as bogus.
|
||||
LAB_EXIT = "198.51.100.9"
|
||||
#: The path of an empty page of the page server (no PeerConnection): see :attr:`Page.warm_url`.
|
||||
WARM_PATH = "/warm"
|
||||
MAGIC = 0x2112A442
|
||||
PASSWORD = "qwerty"
|
||||
REALM = "hermetic"
|
||||
@@ -182,6 +184,8 @@ class Chain(DohGateway):
|
||||
self.turn = TurnServer()
|
||||
self.doh = FakeDoh({TURN_NAME: TURN_IP, PAGE_NAME: "127.0.0.1"})
|
||||
self.page = Page(self)
|
||||
#: When each CONNECT to the DoH arrived, seconds from ``t0`` (the clock of ``associations`` and ``datagram_via``).
|
||||
self.doh_connect_at: List[float] = []
|
||||
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)
|
||||
@@ -193,6 +197,8 @@ class Chain(DohGateway):
|
||||
self.page.close()
|
||||
|
||||
def _connect(self, c, host, port) -> None:
|
||||
if (host, port) in DOH_TARGETS:
|
||||
self.doh_connect_at.append(time.monotonic() - self.t0)
|
||||
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
|
||||
@@ -257,7 +263,7 @@ class Chain(DohGateway):
|
||||
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"
|
||||
why = ("the allocation succeeded but the page read no server-reflexive candidate: the association handshakes 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]
|
||||
@@ -275,8 +281,11 @@ const finish = (s) => { status = s; window.__result.status = s; window.__done =
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
mark('dom');
|
||||
// the tick of a leak test: 2 seconds after the page starts. It stops the moment a srflx arrives, before the POST: what the
|
||||
// test asks is whether the srflx came before the tick, not whether the POST came back within it.
|
||||
// test asks is whether the srflx came before the tick, not whether the POST came back within it. The tick is the model of the
|
||||
// page and decides nothing: a srflx that comes after it is still read and posted (`late`), and the test judges the road by the
|
||||
// stamps of the gateway, the DoH and the TURN server.
|
||||
const tick = setInterval(() => { if (status === 'PENDING') { mark('tick'); finish('TIMEOUT'); } clearInterval(tick); }, 2000);
|
||||
window.__result.born = Date.now();
|
||||
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');
|
||||
@@ -285,12 +294,14 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
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' || window.__result.srflx) return;
|
||||
if (e.candidate.candidate.indexOf(' typ srflx ') < 0 || window.__result.srflx) return;
|
||||
window.__result.late = status !== 'PENDING';
|
||||
clearInterval(tick);
|
||||
mark('srflx');
|
||||
window.__result.srflx = e.candidate.candidate;
|
||||
const r = await fetch('/verdict', {method: 'POST', body: JSON.stringify({srflx: e.candidate.candidate})});
|
||||
mark('posted');
|
||||
window.__result.posted = true;
|
||||
finish((await r.json()).ok ? 'DONE' : 'REFUSED');
|
||||
};
|
||||
pc.createOffer().then((o) => pc.setLocalDescription(o));
|
||||
@@ -315,7 +326,8 @@ class Page:
|
||||
|
||||
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()
|
||||
body = (b"<!doctype html><meta charset=utf-8><title>warm</title>" if self.path == WARM_PATH else
|
||||
(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)))
|
||||
@@ -346,5 +358,10 @@ class Page:
|
||||
def url(self) -> str:
|
||||
return "http://%s:%d/" % (PAGE_NAME, self.port)
|
||||
|
||||
@property
|
||||
def warm_url(self) -> str:
|
||||
"""An empty page of the same server: opened first, it makes the browser learn the proxy and fill its pool of associations."""
|
||||
return "http://%s:%d%s" % (PAGE_NAME, self.port, WARM_PATH)
|
||||
|
||||
def close(self) -> None:
|
||||
self.httpd.shutdown()
|
||||
@@ -39,12 +39,13 @@ def test_every_test_that_compares_a_near_and_a_far_duration_runs_in_the_serial_g
|
||||
assert unserial(FILE.read_text(encoding="utf-8")) == []
|
||||
|
||||
|
||||
def test_the_known_test_is_found():
|
||||
def test_no_test_of_the_file_compares_a_near_and_a_far_duration_any_more():
|
||||
tree = ast.parse(FILE.read_text(encoding="utf-8"))
|
||||
found = sorted(n.name for n in tree.body if isinstance(n, ast.FunctionDef) and _compares_near_and_far(n))
|
||||
# The first-candidate test no longer compares a near and a far gather: it holds the far gateway's handshake and waits for the
|
||||
# host candidate (tests/test_the_timing_of_the_e2e_tests_is_the_browsers_not_the_runners.py), so it is not here any more.
|
||||
assert found == ["test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server"], found
|
||||
# Neither of the two known tests does: the first-candidate test holds the far gateway's handshake and waits for the host
|
||||
# candidate, and the gather after a page judges the association the datagram left on and the order of the candidates
|
||||
# (tests/test_the_timing_of_the_e2e_tests_is_the_browsers_not_the_runners.py). A new comparison is found by the guard above.
|
||||
assert found == [], found
|
||||
|
||||
|
||||
def test_a_comparison_without_the_marker_is_refused():
|
||||
|
||||
@@ -199,3 +199,88 @@ def test_a_frame_that_is_painted_late_is_waited_for_and_one_never_painted_is_red
|
||||
with pytest.raises(AssertionError) as red:
|
||||
module.painted_shot(_Page(), lambda: b"png", [((5, 5), pink)], seconds=0.3)
|
||||
assert "never painted" in str(red.value) and "(255, 255, 255)" in str(red.value)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# the road of a TURN server written as a name costs rounds of the gateway
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
RTT = 0.13
|
||||
TURN_BORN = 10.0
|
||||
#: #0 the core's probe, #1 and #2 the pool of the engine (granted before the birth), #3 .. #5 made after it, one after the other
|
||||
TURN_ASSOCIATIONS = [[0.1, 0.3], [9.0, 9.26], [9.1, 9.36], [10.1, 10.36], [10.4, 10.66], [10.7, 10.96]]
|
||||
|
||||
|
||||
def _turn(allocated_rounds, connect=10.02, via=1, associations=TURN_ASSOCIATIONS, rounds=None, born=TURN_BORN):
|
||||
from _e2e_verdicts import TURN_CHAIN_ROUNDS, turn_chain_problem
|
||||
allocated = None if allocated_rounds is None else connect + allocated_rounds * RTT
|
||||
return turn_chain_problem(born, [connect], allocated, RTT, associations, [("198.51.100.7", 3478, via, connect + 0.3)],
|
||||
"198.51.100.7", TURN_CHAIN_ROUNDS if rounds is None else rounds)
|
||||
|
||||
|
||||
def test_a_road_that_costs_what_the_design_costs_is_green_at_the_speed_of_any_machine():
|
||||
assert _turn(4.5) is None
|
||||
assert _turn(6.95) is None # the rounds of the design and one more: the edge
|
||||
# the machine took five seconds to ask the DoH at all, and the browser is slow in everything it does before the first CONNECT:
|
||||
# no round of the gateway is in that time, so it is not counted
|
||||
assert _turn(4.5, connect=15.0) is None
|
||||
|
||||
|
||||
def test_gateway_handshakes_that_wait_for_each_other_are_red_even_when_the_machine_is_quick():
|
||||
# the associations made one after the other after the birth (2 rounds each), the Allocate waiting for the last: 11 rounds
|
||||
problem = _turn(4.5 + 3 * 2, via=5)
|
||||
assert problem and "rounds of the gateway" in problem and "a handshake waited for another" in problem
|
||||
|
||||
|
||||
def test_one_round_more_than_the_design_allows_is_red_and_the_edge_is_not():
|
||||
assert _turn(7.0 - 0.05) is None
|
||||
problem = _turn(7.0 + 0.1)
|
||||
assert problem and "7.1 rounds" in problem
|
||||
assert _turn(8.0, rounds=7) is None and _turn(8.1, rounds=7) # the design says how many: it is a parameter, not a clock
|
||||
|
||||
|
||||
def test_an_allocation_on_an_association_made_after_the_birth_is_red_within_the_budget_too():
|
||||
problem = _turn(4.5, via=3)
|
||||
assert problem and "a cold association" in problem and "association #3" in problem
|
||||
|
||||
|
||||
def test_an_allocation_that_never_came_is_red():
|
||||
assert "never answered an Allocate" in _turn(None)
|
||||
|
||||
|
||||
def test_the_road_is_counted_from_the_birth_when_the_doh_connection_of_the_page_was_kept():
|
||||
from _e2e_verdicts import turn_chain_problem
|
||||
# no CONNECT to the DoH after the birth (the connection that loaded the page answered the question): counted from the birth
|
||||
assert turn_chain_problem(TURN_BORN, [3.0], TURN_BORN + 3.0 * RTT, RTT, TURN_ASSOCIATIONS,
|
||||
[("198.51.100.7", 3478, 1, 10.2)], "198.51.100.7") is None
|
||||
assert "rounds of the gateway" in turn_chain_problem(TURN_BORN, [3.0], TURN_BORN + 7.5 * RTT, RTT, TURN_ASSOCIATIONS,
|
||||
[("198.51.100.7", 3478, 1, 10.2)], "198.51.100.7")
|
||||
|
||||
|
||||
def test_the_chain_stamps_the_connects_to_the_doh_and_only_those():
|
||||
import _turn_chain as chain_mod
|
||||
from _doh_servers import DOH_BOOTSTRAP
|
||||
from test_the_udp_chain_helper import _socks_connect
|
||||
with chain_mod.Chain(rtt_ms=0, relay_host="127.0.0.1") as chain:
|
||||
assert chain.doh_connect_at == []
|
||||
s, code = _socks_connect(chain, "192.0.2.77", 9) # refused: no DoH
|
||||
s.close()
|
||||
assert chain.doh_connect_at == []
|
||||
s, code = _socks_connect(chain, DOH_BOOTSTRAP, 443)
|
||||
s.close()
|
||||
assert code == 0 and len(chain.doh_connect_at) == 1 and 0 <= chain.doh_connect_at[0] < 30
|
||||
|
||||
|
||||
def test_the_turn_page_reports_its_birth_reads_a_srflx_after_its_tick_and_has_an_empty_twin():
|
||||
import _turn_chain as chain_mod
|
||||
page = chain_mod.PAGE_HTML
|
||||
assert "window.__result.born = Date.now()" in page[:page.index("new RTCPeerConnection")]
|
||||
handler = page[page.index("pc.onicecandidate"):]
|
||||
guard = handler[:handler.index("clearInterval(tick)")]
|
||||
assert "status !== 'PENDING' ||" not in guard and "window.__result.late = status !== 'PENDING'" in guard
|
||||
assert "window.__result.posted = true" in handler
|
||||
with chain_mod.Chain(rtt_ms=0, relay_host="127.0.0.1") as chain:
|
||||
assert chain.page.warm_url.endswith(chain_mod.WARM_PATH)
|
||||
import urllib.request
|
||||
body = urllib.request.urlopen("http://127.0.0.1:%d%s" % (chain.page.port, chain_mod.WARM_PATH), timeout=10).read()
|
||||
assert b"RTCPeerConnection" not in body and b"warm" in body
|
||||
@@ -3,7 +3,8 @@
|
||||
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 the moment the srflx arrives (before the POST made for
|
||||
it, so the verdict does not depend on the POST coming back within the tick); the server compares the address of that srflx with the source the TURN server saw for the allocation.
|
||||
it); the server compares the address of that srflx with the source the TURN server saw for the allocation. The tick is the model of
|
||||
the page and decides nothing here: the verdict is read off the stamps of the gateway, the DoH and the TURN server (see below).
|
||||
|
||||
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
|
||||
@@ -16,7 +17,11 @@ What the product must do, to be what a retail Firefox is with no proxy at all (t
|
||||
* 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.
|
||||
* and all of it costs a number of ROUNDS of the gateway (a round is one round trip of it, 130 ms here), not a number of
|
||||
milliseconds: from the first CONNECT to the DoH after the birth of the PeerConnection to the Allocate the TURN server answered
|
||||
with credentials, `TURN_CHAIN_ROUNDS` and one more at most, and the Allocate leaves on an association made BEFORE the birth
|
||||
(`_e2e_verdicts.turn_chain_problem`). A handshake that waits for another, or an association made from scratch, adds rounds
|
||||
on every machine; a slow machine adds none. The page is waited for until its srflx is posted (30 s), not until its tick.
|
||||
|
||||
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
|
||||
@@ -32,7 +37,9 @@ import pytest
|
||||
|
||||
import _turn_chain as chain_mod
|
||||
from _doh_servers import DOH_PROVIDER_PREFS
|
||||
from _e2e_verdicts import turn_chain_problem
|
||||
from _udp_line import declared_udp, egress_by_proxy, measure_servers
|
||||
from _waits import wait_until
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
@@ -103,20 +110,40 @@ def _walk(gateway, firefox_binary, engine_at_least, prefs):
|
||||
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()
|
||||
# An empty page first, through the proxy: Firefox learns the proxy there and its pool makes the associations. The
|
||||
# PeerConnection is born once the gateway has granted one (the first granted is the core's own probe, no association of the
|
||||
# engine), so "ready before the birth" is a fact of the road and not a race with the load of the machine.
|
||||
page.goto(gateway.page.warm_url, wait_until="domcontentloaded", timeout=60000)
|
||||
wait_until(lambda: len([a for a in gateway.associations if a[1] is not None]) >= 2, 30, lambda: page.wait_for_timeout(50))
|
||||
page.goto(gateway.page.url, wait_until="domcontentloaded", timeout=60000)
|
||||
# The tick of the page is its model and decides nothing: the page is waited for until it has posted its srflx (30 s).
|
||||
try:
|
||||
page.wait_for_function("window.__done === true", timeout=9000)
|
||||
page.wait_for_function("window.__result.posted === true", timeout=30000)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
try:
|
||||
page.wait_for_function("window.__result.candidates.some(c => c.indexOf(' typ relay ') >= 0)", timeout=3000)
|
||||
page.wait_for_function("window.__result.candidates.some(c => c.indexOf(' typ relay ') >= 0)", timeout=30000)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
result = page.evaluate("window.__result")
|
||||
# what the road looked like, read before anything else asks the gateway for an association (the declared_udp below does)
|
||||
t0, wall0 = gateway.t0, gateway.wall0
|
||||
born = (result.get("born") or wall0 * 1000.0) / 1000.0 - wall0 # the asserts below name a page that never ran
|
||||
associations = [list(a) for a in gateway.associations]
|
||||
via = list(gateway.datagram_via)
|
||||
connect_at = list(gateway.doh_connect_at)
|
||||
allocated_at = gateway.turn.allocations[0][3] - t0 if gateway.turn.allocations else None
|
||||
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)
|
||||
assert ok, "the page did not get a server-reflexive candidate that the TURN server saw (the page was waited for 30 s):" + gateway.explain(result)
|
||||
problem = turn_chain_problem(born, connect_at, allocated_at, gateway.rtt, associations, via, chain_mod.TURN_IP)
|
||||
seen = ("the page's tick of 2 s %s; associations %s; datagrams to the TURN server %s; CONNECTs to the DoH at %s s; the PeerConnection "
|
||||
"born at %.3f s; the allocation at %s s" % (
|
||||
"had passed (the srflx was late)" if result.get("late") else "had not passed", associations,
|
||||
[d for d in via if d[0] == chain_mod.TURN_IP], [round(t, 3) for t in connect_at], born,
|
||||
None if allocated_at is None else round(allocated_at, 3)))
|
||||
assert problem is None, "%s; %s%s" % (problem, seen, gateway.explain(result))
|
||||
# what the PAGE reads: a server-reflexive candidate that is the gateway's exit, and the relay of the TURN server it asked
|
||||
srflx = (result.get("srflx") or "").split()
|
||||
assert len(srflx) > 5 and srflx[4] == gateway.exit_ip, "the srflx of the page is not the exit of the gateway %s: %r" % (gateway.exit_ip, result.get("srflx"))
|
||||
|
||||
@@ -277,7 +277,14 @@ _PROBE_JS = r"""async () => {
|
||||
const cands = [];
|
||||
pc.addEventListener('icecandidate', e => { if (e.candidate && e.candidate.candidate) cands.push(e.candidate.candidate); });
|
||||
await pc.setLocalDescription(await pc.createOffer({offerToReceiveAudio:1, offerToReceiveVideo:1}));
|
||||
await new Promise(r => setTimeout(r, 3500));
|
||||
// until the gather says it is complete (what the page reads is the whole of it), or 25 s: the deadline of the wait, not a
|
||||
// window the verdict depends on
|
||||
await new Promise(resolve => {
|
||||
const timer = setTimeout(resolve, 25000);
|
||||
const done = () => { if (pc.iceGatheringState === 'complete') { clearTimeout(timer); resolve(); } };
|
||||
pc.addEventListener('icegatheringstatechange', done);
|
||||
done();
|
||||
});
|
||||
const sdp = (pc.localDescription && pc.localDescription.sdp) || '';
|
||||
try { pc.close(); } catch(e) {}
|
||||
return { candidates: cands, sdp };
|
||||
@@ -407,7 +414,7 @@ _ICE_IDS = ["ice_in_the_socket_process", "the_caller_asks_for_ice_in_the_content
|
||||
"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):
|
||||
def _gather_behind_a_coherent_gateway(monkeypatch, credentials, ice_prefs, rtt_ms):
|
||||
"""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()
|
||||
@@ -415,7 +422,7 @@ def _gather_behind_a_coherent_gateway(monkeypatch, credentials, ice_prefs, rtt_m
|
||||
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
|
||||
from _socks_servers import STUN_NUMBER, STUN_PORT, coherent
|
||||
stun = f"stun:{STUN_NUMBER}:{STUN_PORT}"
|
||||
user, password = credentials or (None, None)
|
||||
# The relay sits on the address of this host, as a real gateway's does: the engine's ICE sockets are bound to an
|
||||
@@ -428,12 +435,7 @@ def _gather_behind_a_coherent_gateway(monkeypatch, credentials, ice_prefs, rtt_m
|
||||
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)
|
||||
page.goto("about:blank")
|
||||
res = page.evaluate(_RELAY_PROBE_JS, stun)
|
||||
carried = [(host, port) for host, port, _payload in gateway.datagrams]
|
||||
stun_requests = gateway.stun.requests
|
||||
@@ -498,7 +500,7 @@ def test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_it
|
||||
|
||||
|
||||
_START_A_GATHER_JS = r"""async (stun) => {
|
||||
const g = window.__gather = {host: null, srflx: null, complete: false, candidates: [], errors: []};
|
||||
const g = window.__gather = {host: null, srflx: null, complete: false, candidates: [], errors: [], born: Date.now()};
|
||||
const t0 = performance.now();
|
||||
const pc = window.__pc = new RTCPeerConnection({iceServers: [{urls: [stun]}]});
|
||||
pc.createDataChannel('');
|
||||
@@ -564,27 +566,50 @@ def test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far
|
||||
"the srflx was not born through the relay once the gateway was let go. " + seen)
|
||||
|
||||
|
||||
@pytest.mark.wall_clock # its verdict compares two durations (near and far): the e2e run gives it the machine alone
|
||||
@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}")
|
||||
"""⛔ THE KNOWN-BAD INPUT: a gateway 250 ms away, a page loaded through it, and a while later the page asks for WebRTC.
|
||||
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: the STUN request of the page leaves on an
|
||||
association the gateway had granted before the PeerConnection was born, and the host candidate does not wait for the srflx.
|
||||
Both are facts the gateway and the page record, whatever the speed of the machine (a comparison with the same gather next to a
|
||||
gateway was a comparison of two launches of a browser): the gateway says which association carried the datagram, and the
|
||||
page orders its candidates. The page waits until the gateway has granted an association of the engine (30 s), not 2.5 s."""
|
||||
binary = _e2e_binary()
|
||||
if not binary:
|
||||
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
|
||||
from invisible_core import _geo
|
||||
|
||||
from _e2e_verdicts import cold_association_problem
|
||||
from _socks_servers import STUN_NUMBER, STUN_PORT, WEB_ADDRESS, coherent
|
||||
from _waits import wait_until, watch
|
||||
stun = f"stun:{STUN_NUMBER}:{STUN_PORT}"
|
||||
with coherent(user="alice", password="s3cret", relay_host=this_host_address(), rtt_ms=250) as gateway:
|
||||
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("http://%s/" % WEB_ADDRESS) # by address: the browser resolves names itself
|
||||
# the pool makes its associations: wait until the gateway has granted one of the engine's (the first granted is the
|
||||
# core's probe); the verdict names what it saw if none came
|
||||
wait_until(lambda: len([a for a in gateway.associations if a[1] is not None]) >= 2, 30,
|
||||
lambda: page.wait_for_timeout(50))
|
||||
page.evaluate(_START_A_GATHER_JS, stun)
|
||||
srflx = watch(lambda: page.evaluate("window.__gather.srflx"), lambda at: at is not None, 30,
|
||||
lambda: page.wait_for_timeout(50))
|
||||
gather = page.evaluate("window.__gather")
|
||||
associations = [list(a) for a in gateway.associations]
|
||||
via = list(gateway.datagram_via)
|
||||
born = gather["born"] / 1000.0 - gateway.wall0
|
||||
seen = (f"candidates: {gather['candidates']}; ICE errors: {gather['errors']}; associations (start, end) seen by the gateway: "
|
||||
f"{associations}; datagrams and the association each left on: {via}; srflx looks: {srflx.render()}")
|
||||
assert srflx.ok, "no srflx within 30 s behind a gateway 250 ms away. " + seen
|
||||
problem = cold_association_problem(associations, via, STUN_NUMBER, born)
|
||||
assert problem is None, f"{problem}. {seen}"
|
||||
assert gather["host"] is not None and gather["host"] < gather["srflx"], (
|
||||
f"the host candidate (at {gather['host']} ms) did not come before the srflx ({gather['srflx']} ms): it waited for the "
|
||||
f"road to the server. {seen}")
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
|
||||
Reference in new issue
Block a user