The server's UDP port does not see an engine that tries h3 through the relay of a gateway: it asks for a UDP ASSOCIATE or sends into the relay. relay_activity() is taken before the first visit (after the core's own measurement) and after the last; h3_attempts() reports what the engine asked of the gateway in between. A unit test covers a granted and a refused ASSOCIATE and a datagram into the relay; the unit rows of required-suites count it (+1 again).
255 lines
16 KiB
Python
255 lines
16 KiB
Python
"""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, Tuple
|
|
|
|
#: 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
|
|
|
|
|
|
#: What the core rendered into an engine proxy command during the running test, by proxy server: the ``udp`` of every
|
|
#: ``Browser.setBrowserProxy`` / ``Browser.setContextProxy`` it built, in order. The core keeps no verdict in memory, so
|
|
#: this is where a test reads what was declared: at the one place that writes it (see :func:`record_declared`).
|
|
DECLARED: Dict[str, List[str]] = {}
|
|
|
|
|
|
def record_declared(monkeypatch: Any) -> None:
|
|
"""Record, for the running test, the ``udp`` of every proxy command the core renders (autouse in ``conftest.py``).
|
|
|
|
It spies ``invisible_core._udp_exit._command``: the one function that builds the engine command from a proxy and a
|
|
verdict, whoever asks (the launch with the verdict the geo step made, a context after its own measurement). The spy
|
|
delegates, and changes nothing the engine is told."""
|
|
DECLARED.clear()
|
|
try:
|
|
from invisible_core import _udp_exit
|
|
except Exception: # noqa: BLE001 - the package is absent: the tests that need it say so
|
|
return
|
|
real = _udp_exit._command
|
|
|
|
def spy(proxy: Dict[str, Any], udp: Any) -> Optional[Dict[str, Any]]:
|
|
command = real(proxy, udp)
|
|
if command is not None and "udp" in command:
|
|
DECLARED.setdefault(proxy.get("server"), []).append(command["udp"])
|
|
return command
|
|
|
|
monkeypatch.setattr(_udp_exit, "_command", spy)
|
|
|
|
|
|
def declared_udp(proxy: Dict[str, Any]) -> str:
|
|
"""The ``udp`` the core declared to the engine for ``proxy``, the last one of this test: ``coherent``, ``no`` or
|
|
``unmeasured``. An AssertionError when nothing was declared for it, so ``unmeasured`` cannot be mistaken for an
|
|
absent declaration."""
|
|
declared = DECLARED.get(proxy.get("server"))
|
|
if not declared:
|
|
raise AssertionError("the core declared nothing for %r" % proxy.get("server"))
|
|
return declared[-1]
|
|
|
|
|
|
def declared_udp_or_absent(proxy: Dict[str, Any]) -> Optional[str]:
|
|
""":func:`declared_udp`, or None when nothing was declared for ``proxy`` (a report must say that, not raise)."""
|
|
try:
|
|
return declared_udp(proxy)
|
|
except AssertionError:
|
|
return None
|
|
|
|
|
|
def udp_measure_sentence(declared: Optional[str], rtt_ms: int) -> str:
|
|
"""What the core declared for the proxy of a bench, as a sentence of the verdict of a failed test. A measurement that is
|
|
not ``coherent`` is said outright: the engine then never sends the page's UDP to the relay, and the test fails for a reason
|
|
that is the measurement's (the budget of the core against the round trip of the gateway), not the page's."""
|
|
if declared == "coherent":
|
|
return "UDP verdict the core declared for this proxy: coherent"
|
|
if declared is None:
|
|
return ("the core measured nothing for this proxy: the UDP measure of the core did not finish in its budget "
|
|
"with rtt %d ms (no verdict was declared)" % rtt_ms)
|
|
return ("the UDP measure of the core did not finish coherent in its budget with rtt %d ms: it declared %r for this proxy, "
|
|
"so the engine had no relay to use" % (rtt_ms, declared))
|
|
|
|
|
|
def bench_report(gateway: Any, rtt_ms: int, declared: Optional[str]) -> str:
|
|
"""What the bench saw, as one string for the verdict of a failed test: the datagrams the relay carried with their times
|
|
(seconds from the start of the gateway), the sends that failed, the CONNECTs, the TCP connections accepted, the UDP
|
|
ASSOCIATEs and their start and end, and what the core declared for the proxy. Nothing here changes an outcome."""
|
|
log = ["%s:%d atyp=%d t=%.3fs" % (host, port, atyp, at) for host, port, atyp, at in list(gateway.datagram_log)]
|
|
associations = [[None if x is None else round(x, 3) for x in record] for record in list(gateway.associations)]
|
|
return ("%s; gateway send errors: %s; CONNECTs the gateway saw: %s; TCP connections it accepted: %d; "
|
|
"associations (start, end in s from its start): %s; datagram log with times: %s"
|
|
% (udp_measure_sentence(declared, rtt_ms), list(gateway.send_errors), list(gateway.connects),
|
|
len(gateway.accepted), associations, log))
|
|
|
|
|
|
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, with no attempt at h3 (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 relay_activity(gateway: Any) -> Tuple[int, int]:
|
|
"""What a SOCKS5 gateway of the tests has been asked for so far, as ``(UDP ASSOCIATE requests, datagrams its relay carried)``: the
|
|
requests answered or refused, the datagrams of every association. Taken twice (before the first visit, which is after the core's own
|
|
measurement of the gateway, and after the last), the difference is what the ENGINE asked of the relay while it visited the page."""
|
|
return int(gateway.associates), len(gateway.datagrams)
|
|
|
|
|
|
def h3_attempts(server: Any, gateway: Any = None, before: Optional[Tuple[int, int]] = None) -> List[str]:
|
|
"""What the test server (and, behind a SOCKS5 gateway, the gateway) says about a TRY at HTTP/3, as sentences; an empty list when nothing tried.
|
|
|
|
Behind a SOCKS5 gateway that is not coherent the engine does not carry UDP (nsSOCKSUDPIOLayer.cpp, ``StealthPutSocksUdpLayer``: the socket of an
|
|
HTTP/3 connection gets a layer that is ``Blocked``, no association is asked for): an engine that tried would ask the gateway for a UDP
|
|
ASSOCIATE (a refused one is a request too) or send a datagram to its relay, whether or not the datagram goes on to the server.
|
|
``gateway`` and ``before`` (:func:`relay_activity` taken before the first visit) add those two to the answer.
|
|
|
|
A retail Firefox on a network that drops UDP (and behind an HTTP proxy, which has no UDP at all) never tries HTTP/3: it reads h2 and
|
|
nothing is sent to the h3 port the Alt-Svc announces. An engine that TRIES sends its QUIC Initial there first, and then waits for
|
|
an answer that does not come before it falls back to h2: the wait is the tell, and the datagram is the attempt. The attempt is
|
|
read where it is born, as a datagram that reached the UDP port of ``server`` (``H3Server.udp_datagrams``, every datagram, with
|
|
or without a handshake), never as a duration: how long a fallback takes is the speed of the machine, whether it was tried is the engine."""
|
|
problems: List[str] = []
|
|
seen = list(getattr(server, "udp_datagrams", ()))
|
|
if seen:
|
|
problems.append("%d UDP datagrams reached the h3 port %s of the server, from %s: the engine tried HTTP/3 (and, where nothing answers, "
|
|
"waits for a timeout before the fallback to h2)" % (len(seen), getattr(server, "port", "?"), sorted(set(seen))))
|
|
if gateway is not None:
|
|
if before is None:
|
|
raise ValueError("a gateway is judged against what it had been asked before the first visit (relay_activity)")
|
|
associates, datagrams = (now - was for now, was in zip(relay_activity(gateway), before))
|
|
if associates:
|
|
problems.append("the engine asked the gateway for %d UDP ASSOCIATE while it visited the page: it tried to carry UDP (HTTP/3) "
|
|
"through a gateway that was not measured coherent" % associates)
|
|
if datagrams:
|
|
problems.append("%d datagrams went into the relay of the gateway while the page was visited: the engine tried HTTP/3 "
|
|
"through a gateway that was not measured coherent" % datagrams)
|
|
return problems
|
|
|
|
|
|
def judge_visits(road: str, protocols: Sequence[str]) -> 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, :func:`visits_for` entries. No duration is judged: that an h3 attempt
|
|
waited for a timeout is read as the attempt itself (:func:`h3_attempts`). 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 attempt at h3: :func:`h3_attempts`, read by the test)."""
|
|
problems: List[str] = []
|
|
protocols = list(protocols)
|
|
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 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))
|
|
return problems
|