tests: a port of the ICE socket that another process holds on loopback blinds the checks of two connections (red on firefox-68 on Windows; firefox-69 binds it exclusively) (+1 test)

This commit is contained in:
feder-cr committed 2026-11-22 17:42:21 +01:00
1 parent 3946c6c024
commit e4f3dd2712
5 files changed
+342 -4

No files matched your search

+1 -1
View File
@@ -1,5 +1,5 @@
[
{"id": "wrapper.e2e.udp", "giro": "G2", "os": ["linux", "windows"], "min_tests": 43, "exact": true, "tests": ["tests/test_preload_newtab_turns_the_privileged_about_process_off_e2e.py", "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::test_a_turn_srflx_by_name_arrives_through_the_relay_when_the_exit_of_the_lab_is_loopback", "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). The chain by name is here in its variant with the lab's exit on loopback (127.0.0.2) and the pref `media.peerconnection.ice.loopback`, on Linux and Windows: the exit of the lab is loopback, and a loopback mapped address is thrown away by nICEr unless the ICE context allows it. The variant without the pref (an exit that is not loopback) is the suite wrapper.e2e.udp.exit, Linux only; the address added to the interface of the Windows runner is work of the release after firefox-63. The preload_newtab test (2) is here: seen green on Linux as root (Docker) and on Windows 10 runs of 10 (windows-2022, round 5 engine); it reads the engine's own process log."},
{"id": "wrapper.e2e.udp", "giro": "G2", "os": ["linux", "windows"], "min_tests": 44, "exact": true, "tests": ["tests/test_preload_newtab_turns_the_privileged_about_process_off_e2e.py", "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::test_a_turn_srflx_by_name_arrives_through_the_relay_when_the_exit_of_the_lab_is_loopback", "tests/test_declared_host_network_e2e.py", "tests/test_a_held_ice_port_blinds_the_loopback_checks_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). The chain by name is here in its variant with the lab's exit on loopback (127.0.0.2) and the pref `media.peerconnection.ice.loopback`, on Linux and Windows: the exit of the lab is loopback, and a loopback mapped address is thrown away by nICEr unless the ICE context allows it. The variant without the pref (an exit that is not loopback) is the suite wrapper.e2e.udp.exit, Linux only; the address added to the interface of the Windows runner is work of the release after firefox-63. The preload_newtab test (2) is here: seen green on Linux as root (Docker) and on Windows 10 runs of 10 (windows-2022, round 5 engine); it reads the engine's own process log."},
{"id": "wrapper.e2e.udp.exit", "giro": "G2", "os": ["linux"], "min_tests": 7, "exact": true, "tests": ["tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick", "tests/test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux only, and not collected on Windows: the exit of the lab is a documentation address (198.51.100.9) added to lo with `ip addr add`, which needs root and iproute2; a mapped address in 127/8 would be thrown away by nICEr as bogus (stun_client_ctx.cpp nr_stun_transport_addr_check) and the pref that allows it is off in a product. The page reads a srflx equal to the gateway exit and the relay of the TURN server, the TURN name resolved by the DoH through the proxy, in the tick of 2 s. On the Windows runner of GitHub (administrator, the network of the runner) it could run too: not yet. A skipped test would turn the verdict red, hence a suite of its own. Its twin with the lab's exit on loopback and the pref stays in wrapper.e2e.udp on both systems, so that Windows keeps the walk of the chain by name.", "linux_only": "The lab's exit is a documentation address the host must hold besides its loopback (nICEr throws away a mapped address in 127/8). Linux holds it on lo as root; Windows takes no extra address on its loopback pseudo-interface, and adding it to the runner's adapter took the runner off the network (runs 43314251547 and 43334169682 died in the test step). A Windows twin waits for a way that leaves the runner's network alone."},
{"id": "wrapper.e2e.udp.sandbox", "giro": "G2", "os": ["linux"], "min_tests": 13, "exact": true, "tests": ["tests/test_the_socket_process_is_sandboxed_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_a_gateway_without_udp_resolves_the_ice_name_then_ends_in_701"], "marker": "e2e", "needs_root": false, "note": "The browser WITH its sandbox, run by a normal user, as on any Linux that allows user namespaces. On the Ubuntu 24.04 runner AppArmor refuses them to a user, so every other non-root suite runs a browser WITHOUT the sandbox of its socket and content processes; the gate turns the restriction off for this leg (sysctl kernel.apparmor_restrict_unprivileged_userns=0) and the first test fails unless the socket and a tab process have a seccomp filter (Seccomp: 2). The three situations of the UDP line: A (a proxy that carries UDP: the srflx born through the relay), B (no proxy: the gather is real), C (a proxy with no UDP: the ICE server name goes by DoH through the proxy and the gather ends in 701). No root and no resolver trap needed.", "linux_only": "It reads the seccomp filter of the socket and tab processes in /proc. The Windows twin reads the sandbox token of the same processes (integrity level, restrictions) and needs a measurement of the retail Firefox's tokens first; until then Linux only."},
{"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)."},
+8
View File
@@ -11,5 +11,13 @@
"tests/test_a_page_that_moves_on_e2e.py": "a navigation that committed is not cut by the parent: goto answers on our own page, networkidle is reached on the one that replaced it",
"tests/test_fakeweb_p2_e2e.py": "under a load of other browsers the page that leaves with beacons reaches networkidle every round (the held cut of a committed navigation); on an older engine the run is made and not judged"
}
},
"firefox-69": {
"carries": [
"the ICE host port the engine draws is bound exclusively on Windows: another process cannot bind 127.0.0.1 on it"
],
"files": {
"tests/test_a_held_ice_port_blinds_the_loopback_checks_e2e.py": "the ICE port the engine draws is its alone: on Windows a second bind of 127.0.0.1 on it is refused (before, it took the checks of the pair and the connection opened late); on Linux the bind is refused on every engine"
}
}
}
+1
View File
@@ -19,6 +19,7 @@
{"file": "_turn_chain.py", "scope": "<module>.PAGE_HTML", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "The 2 s tick is the model of a leak test's page and decides nothing: a srflx that comes after it is still read and posted, the status of the page is final (DONE or REFUSED) in the same step that says `posted`, and the verdict is read from the stamps of the gateway, the DoH and the TURN server, never from when the tick fired."},
{"file": "_turn_chain.py", "scope": "<module>.TURN_PORT", "rule": "port", "nth": 1, "kind": "virtual-port", "reason": "A port number that nothing binds: the gateway of the test answers for the name or address by itself, so no worker can collide on it."},
{"file": "test_a_granted_permission_is_the_one_the_page_asks_for_e2e.py", "scope": "<module>.READ", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The timer of 30 s only ends a read of the position that never answers: the answer is a position or an error as soon as the engine gives one, and no verdict reads when the timer fired."},
{"file": "test_a_held_ice_port_blinds_the_loopback_checks_e2e.py", "scope": "<module>._START_JS", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The 5 ms step of the page's two waits, each with a deadline of 30 s: for the host UDP candidate of the first connection, and for the data channel to open and echo; the second loop keeps the longest time it did not run, so the time the connection took is judged only when the page itself was not stopped by the machine (`_e2e_verdicts.opened_at_the_retry_problem`)."},
{"file": "test_a_page_cannot_probe_the_juggler_e2e.py", "scope": "<module>._CHANNELS", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The 30 s of each channel are the deadline of its wait (`no answer` is a channel that stays silent). Every channel of a URL is asked at once and a name that is nowhere answers all of them, so on a healthy run no silence is waited for, and a stall of the machine cannot make one URL answer and the other not."},
{"file": "test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_e2e.py", "scope": "<module>._GATHER_JS", "rule": "js-timer", "nth": 1, "kind": "hang-detector", "reason": "The timer of 30 s is the deadline of the wait for the end of the ICE gathering: the wait ends when the page says `complete`, a gathering that never completes returns what it has and fails the assertions on the candidates, and no verdict reads when the timer fired."},
{"file": "test_a_page_that_moves_on_e2e.py", "scope": "_replace_after_load", "rule": "js-timer", "nth": 1, "kind": "stimulus", "reason": "The page's own timer moves the page 0, 50 or 300 ms after the load, and the reads made while it moves accept both states (the page before the move or the page it moved to) and never an engine error; nothing reads when the timer fired, and the waits that lead up to the reads have a deadline of 30 s."},
@@ -0,0 +1,328 @@
"""A port of the ICE socket that another process holds on loopback must not blind the checks of two connections on one page (red on firefox-68 on Windows).
The engine draws the host port of each connection at random in 49152-65535 and binds the WILDCARD address on it (``nr_stealth_network.cpp``), and a
connection that talks to its own peer is sent to ``127.0.0.1:<that port>``. On Windows a wildcard bind and a bind of ``127.0.0.1`` on the same port
coexist, and a datagram sent to ``127.0.0.1`` goes to the specific one: another program of the machine (here the way the lab's SOCKS5 server binds its
relay sockets, ``tests/_socks_servers.py``) that binds ``127.0.0.1:<port>`` takes every check and every answer of the pair, and the connection does not
open until it lets go and the checks that follow find the road again. Linux refuses the second bind. The engine from firefox-69 binds exclusively
(``SO_EXCLUSIVEADDRUSE``): whoever holds the port first makes the other bind fail, so a program that wants the port is refused and the engine's socket
is never blind.
The reproduction does not wait for a lucky draw. The page makes the two connections and sets the offer on the first (it knows its host port then); the
test binds ``127.0.0.1:<that port>`` the way the lab's server binds its sockets; the page goes on (answer, candidates) and waits for the pair to open.
* Windows, engine before firefox-69: the bind succeeds, the pair does not open while the socket is held, and, the socket let go 7 s after the page
started, it opens between 9 and 10 s (the seventh check of the connection that asks last leaves at about 9.4 s: ``stun_client_ctx.cpp``);
* Windows from firefox-69, and Linux whatever the engine: the bind is refused and the pair opens at once.
Nothing here changes the road: the held socket only reads (it never answers, never sends), the page reads ``getStats`` and never writes, and the lines
the engine logs are the ones the other launch tests keep (``tests/_evidence_with_files.py``).
"""
from __future__ import annotations
import json
import shutil
import socket
import sys
import threading
import time
import pytest
from _e2e_verdicts import MDNS_RETRY_MS, STALL_MS, opened_at_the_retry_problem
from _evidence_with_files import FailureEvidenceWithFiles, probe_machine
from _mdns_listener import MdnsListener
from test_declared_host_network_e2e import MDNS_MOZ_LOG, V4_ONLY, _session
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
#: The socket is let go this long after the page started (ms): the checks of a connection fail for good at 7.9 s, and the ones of the connection that asks
#: last go on to 9.4 s, so the pair that was blind opens after this, not at once.
RELEASE_AT_MS = 7000
#: Where the pair of an engine whose port is held opens (ms from the start of the page): the retry that follows the release. The window is of the
#: schedule of the checks, which the machine does not change; it is judged only on a run whose page was not stopped by the machine.
BLIND_OPENS_BETWEEN_MS = (9000, 10000)
#: A statistics snapshot of the held phase, this long before the socket is let go (ms): the checks sent with no response.
SNAPSHOT_BEFORE_RELEASE_MS = 500
# The same two connections as ``_LOOPBACK_JS`` of ``test_declared_host_network_e2e.py``, in two steps. The first makes them, sets the offer on pc1 and
# returns pc1's host UDP candidate (the address is a mDNS name, the port is real); the second goes on from there. A candidate waits until the other
# connection has the remote description (a real signaling channel delivers it then), because the second step starts a moment after the first.
# ``events`` is the page's timeline (``at`` since the start of the page), ``snapshots`` is what ``getStats`` says of both connections (every pair with the
# checks sent and answered); it only reads.
_START_JS = r"""async () => {
const t0 = performance.now();
const events = [];
const now = () => Math.round((performance.now() - t0) * 10) / 10;
const at = (what, extra) => { events.push(Object.assign({at: now(), what}, extra || {})); };
const steps = {};
const step = name => { steps[name] = now(); at(name); };
const tick = () => new Promise(r => setTimeout(r, 5));
const pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();
for (const [name, pc] of [['pc1', pc1], ['pc2', pc2]]) {
pc.addEventListener('icecandidate', e => at('icecandidate', {pc: name, candidate: e.candidate ? e.candidate.candidate : null}));
pc.addEventListener('iceconnectionstatechange', () => at('iceconnectionstatechange', {pc: name, state: pc.iceConnectionState}));
pc.addEventListener('connectionstatechange', () => at('connectionstatechange', {pc: name, state: pc.connectionState}));
pc.addEventListener('icegatheringstatechange', () => at('icegatheringstatechange', {pc: name, state: pc.iceGatheringState}));
pc.addEventListener('signalingstatechange', () => at('signalingstatechange', {pc: name, state: pc.signalingState}));
}
const add = (target, targetName, candidate) => {
at('addIceCandidate called', {to: targetName, candidate: candidate.candidate});
return target.addIceCandidate(candidate).then(
() => at('addIceCandidate resolved', {to: targetName, candidate: candidate.candidate}),
err => at('addIceCandidate rejected', {to: targetName, candidate: candidate.candidate, error: String(err)}));
};
const ready = {pc1: false, pc2: false};
const waiting = {pc1: [], pc2: []};
const deliver = (target, targetName, candidate) => { if (ready[targetName]) add(target, targetName, candidate); else waiting[targetName].push(candidate); };
const open = (target, targetName) => { ready[targetName] = true; for (const c of waiting[targetName].splice(0)) add(target, targetName, c); };
pc1.onicecandidate = e => { if (e.candidate) deliver(pc2, 'pc2', e.candidate); };
pc2.onicecandidate = e => { if (e.candidate) deliver(pc1, 'pc1', e.candidate); };
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, error = null;
dc.onopen = () => { opened = Math.round(performance.now() - t0); at('datachannel open'); dc.send('ping'); };
pc2.ondatachannel = ev => { at('datachannel announced on pc2'); ev.channel.onmessage = m => ev.channel.send('pong:' + m.data); };
dc.onmessage = m => { echoed = (m.data === 'pong:ping'); at('datachannel echo', {echoed}); };
const readStats = async pc => {
const stats = await pc.getStats();
const byId = {};
stats.forEach(r => { byId[r.id] = r; });
const view = r => r ? {id: r.id, candidateType: r.candidateType, address: r.address, port: r.port, protocol: r.protocol, priority: r.priority} : null;
const out = {local: [], remote: [], pairs: []};
stats.forEach(r => {
if (r.type === 'local-candidate') out.local.push(view(r));
if (r.type === 'remote-candidate') out.remote.push(view(r));
if (r.type === 'candidate-pair') {
out.pairs.push({id: r.id, state: r.state, nominated: r.nominated, requestsSent: r.requestsSent, responsesReceived: r.responsesReceived,
requestsReceived: r.requestsReceived, responsesSent: r.responsesSent, localCandidateId: r.localCandidateId,
remoteCandidateId: r.remoteCandidateId, local: view(byId[r.localCandidateId]), remote: view(byId[r.remoteCandidateId])});
}
});
return out;
};
const snapshot = async when => {
const one = {when, at: now()};
for (const [name, pc] of [['pc1', pc1], ['pc2', pc2]]) {
try { one[name] = await readStats(pc); } catch (e) { one[name] = {error: String(e)}; }
}
return one;
};
// The second step: from the holder's bind to the end of the wait. ``snapshotAt`` is the page time of the snapshot of the held phase (null: none).
const finish = async snapshotAt => {
let stalled = 0;
const snapshots = [];
try {
await pc2.setRemoteDescription(pc1.localDescription);
step('pc2 remote description set');
open(pc2, 'pc2');
await pc2.setLocalDescription(await pc2.createAnswer());
step('pc2 local description set');
await pc1.setRemoteDescription(pc2.localDescription);
step('pc1 remote description set');
open(pc1, 'pc1');
// Until the channel has opened and echoed, for 30 s (the deadline of the wait), keeping the longest time the loop did not run: a page that was
// stopped by the machine says so, and the time the connection took is not judged then (`_e2e_verdicts.opened_at_the_retry_problem`).
const deadline = performance.now() + 30000;
let last = performance.now();
let snapped = snapshotAt === null;
while (performance.now() < deadline && !(opened !== null && echoed)) {
await tick();
if (!snapped && now() >= snapshotAt) {
snapped = true;
snapshots.push(await snapshot('held'));
last = performance.now();
continue;
}
const t = performance.now();
stalled = Math.max(stalled, t - last);
last = t;
}
at('wait over', {opened, echoed});
} catch (e) {
error = String(e);
at('error', {error});
}
let pair = null;
try {
const final = await snapshot(error ? 'error' : 'wait over');
snapshots.push(final);
for (const p of (final.pc1 && final.pc1.pairs) || []) {
if (p.state === 'succeeded' && (p.nominated || !pair)) {
const l = p.local || {}, rm = p.remote || {};
pair = {local: l.protocol, remote: rm.protocol, localType: l.candidateType, remoteType: rm.candidateType, remoteAddress: rm.address || null};
}
}
} catch (e) {}
// Closed before the browser is: the engine prints a connection's timecard when the connection is destroyed.
try { pc1.close(); } catch (e) {}
try { pc2.close(); } catch (e) {}
return {opened, echoed, pair, gathered, stalled: Math.round(stalled), error, events, steps, snapshots, origin: performance.timeOrigin, started_at: Math.round(t0 * 10) / 10};
};
let first = null;
try {
await pc1.setLocalDescription(await pc1.createOffer());
step('pc1 local description set');
// The host UDP candidate of pc1: its port is the one the engine drew and bound.
const deadline = performance.now() + 30000;
while (performance.now() < deadline && !first) {
first = gathered.pc1.find(c => c.split(' ')[2].toLowerCase() === 'udp' && c.indexOf(' typ host') >= 0) || null;
if (!first) await tick();
}
at('first host udp candidate of pc1', {candidate: first});
} catch (e) {
error = String(e);
at('error', {error});
}
window.__heldPort = {finish};
return {candidate: first, port: first ? Number(first.split(' ')[5]) : null, error, started_wall_ms: performance.timeOrigin + t0};
}"""
_FINISH_JS = "async (snapshotAt) => window.__heldPort.finish(snapshotAt)"
class _Holder:
"""A UDP socket on ``127.0.0.1:<port>`` bound the way the lab's SOCKS5 server binds its relay sockets (``tests/_socks_servers.py``: a plain datagram
socket, no option, and on Windows the reset of an unreachable port switched off). It only reads: it never sends a datagram, and what it received is
its record. ``bind_error`` is the refusal, None when the bind succeeded."""
def __init__(self) -> None:
self.sock = None
self.bind_error = None
self.received = []
self.released_wall = None
self._lock = threading.Lock()
def take(self, port: int) -> bool:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.bind(("127.0.0.1", port))
except OSError as exc:
sock.close()
self.bind_error = {"errno": exc.errno, "winerror": getattr(exc, "winerror", None), "message": str(exc)}
return False
if hasattr(socket, "SIO_UDP_CONNRESET"):
sock.ioctl(socket.SIO_UDP_CONNRESET, False)
self.sock = sock
threading.Thread(target=self._read, args=(sock,), daemon=True).start()
return True
def _read(self, sock: socket.socket) -> None:
# Until the socket is closed by ``release`` (the read then fails). An error of the body ends the reading, never the test.
while True:
try:
data, peer = sock.recvfrom(65536)
except ConnectionResetError:
continue
except OSError:
return
self.received.append({"t": time.time(), "from": list(peer), "bytes": len(data), "stun": data[4:8] == b"\x21\x12\xa4\x42"})
def release(self) -> None:
with self._lock:
if self.sock is None:
return
sock, self.sock = self.sock, None
self.released_wall = time.time()
sock.close()
@pytest.mark.wall_clock
def test_a_held_ice_port_blinds_the_loopback_checks(local_https_page, socks5_tcp_only, monkeypatch, engine_reaches, capsys):
"""See the module. One cold launch; the verdict by system and by engine, none on a clock of the machine but the schedule of the checks.
It carries ``wall_clock``: the e2e run gives it the machine alone, so that no other worker's socket holds or takes the port it is about."""
windows = sys.platform == "win32"
engine_binds_exclusively = engine_reaches("firefox-69")
blind = windows and not engine_binds_exclusively
holder = _Holder()
launch = {"seed": 100, "windows": windows, "engine_binds_exclusively": engine_binds_exclusively, "moz_log": MDNS_MOZ_LOG}
with FailureEvidenceWithFiles("a-held-ice-port-blinds-the-loopback-checks") as evidence:
log_dir = evidence.files / "engine-log"
timer = None
def script(page):
nonlocal timer
started = page.evaluate(_START_JS)
launch["started"] = started
assert started["port"], "pc1 gathered no host UDP candidate: %r" % (started,)
launch["bound"] = holder.take(started["port"])
launch["bind_error"] = holder.bind_error
start_wall = started["started_wall_ms"]
# The release is `RELEASE_AT_MS` after the page started, on the wall clock both sides share.
delay = max(0.0, (start_wall + RELEASE_AT_MS) / 1000.0 - time.time())
timer = threading.Timer(delay, holder.release)
timer.daemon = True
if launch["bound"]:
timer.start()
snapshot_at = RELEASE_AT_MS - SNAPSHOT_BEFORE_RELEASE_MS if launch["bound"] else None
res = page.evaluate(_FINISH_JS, snapshot_at)
if (not res["echoed"] or res["opened"] is None or not res["pair"]
or opened_at_the_retry_problem(res["opened"], res["stalled"], MDNS_RETRY_MS) is not None):
probe_machine(evidence.files / "machine-run-0.txt")
return res
listener = MdnsListener().start()
launch.update(started_m=round(time.perf_counter(), 6), started_t=round(time.time(), 4))
res = None
try:
res = _session(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch, 100, script, engine_log=str(log_dir))
finally:
if timer is not None:
timer.cancel()
holder.release()
launch.update(returned_m=round(time.perf_counter(), 6), returned_t=round(time.time(), 4))
listener.stop()
listener.write(evidence.files / "mdns-wire-run-0.jsonl")
launch["mdns_wire"] = listener.summary()
start_wall = (launch.get("started") or {}).get("started_wall_ms")
launch["held"] = {
"released_at_page_ms": None if holder.released_wall is None or start_wall is None else round(holder.released_wall * 1000 - start_wall, 1),
"received": len(holder.received),
"received_stun": sum(1 for r in holder.received if r["stun"]),
"first_at_page_ms": None if not holder.received or start_wall is None else round(holder.received[0]["t"] * 1000 - start_wall, 1),
"last_at_page_ms": None if not holder.received or start_wall is None else round(holder.received[-1]["t"] * 1000 - start_wall, 1),
"peers": sorted({tuple(r["from"]) for r in holder.received}),
}
if res is not None:
launch["page"] = {key: res.pop(key, None) for key in ("events", "steps", "snapshots", "error", "origin", "started_at")}
launch.update(opened=res["opened"], echoed=res["echoed"], stalled=res["stalled"], pair=res["pair"], gathered=res["gathered"])
(evidence.files / "launches.json").write_text(json.dumps([launch], indent=1, default=str), encoding="utf-8")
# The bind of the other process: the whole difference between the engines and the systems.
if blind:
assert launch["bound"], ("firefox-68 on Windows must let another process bind 127.0.0.1 on the port its wildcard socket holds, "
"this one was refused: %r" % (launch["bind_error"],))
else:
assert not launch["bound"], ("the port of the ICE socket was bound a second time on 127.0.0.1 (%s): another process reads the checks "
"of the pair" % ("an engine that binds exclusively" if windows else "Linux"))
assert res["echoed"] and res["opened"] is not None, "the data channel did not open: %r" % (res,)
for side in ("pc1", "pc2"):
udp = [c for c in res["gathered"][side] if " typ host" in c and c.split(" ")[2].lower() == "udp"]
assert udp, "%s gathered no UDP host candidate: %r" % (side, res["gathered"][side])
pair = res["pair"]
assert pair, "the browser reports no nominated pair: %r" % (res,)
assert pair["local"] == "udp" and pair["remote"] == "udp", "the connection did not take UDP at both ends: %r" % (pair,)
assert pair["localType"] in ("host", "prflx") and pair["remoteType"] in ("host", "prflx"), "the pair is not direct and local: %r" % (pair,)
stopped = res["stalled"] >= STALL_MS
if blind:
released = launch["held"]["released_at_page_ms"]
assert released is not None, "the held socket was never let go: %r" % (launch["held"],)
assert res["opened"] >= released, ("the pair opened at %d ms, while the socket was still held (let go at %.0f ms): the held port does not "
"blind the checks" % (res["opened"], released))
if not stopped:
low, high = BLIND_OPENS_BETWEEN_MS
assert low <= res["opened"] <= high, ("the pair opened at %d ms, not between %d and %d ms after a release at %.0f ms"
% (res["opened"], low, high, released))
else:
problem = opened_at_the_retry_problem(res["opened"], res["stalled"], MDNS_RETRY_MS)
assert problem is None, problem
shutil.rmtree(log_dir, ignore_errors=True)
with capsys.disabled():
print("\n[measure] a held ICE port (%s, %s): bound=%s %s; the pair opened at %s ms (page stopped at most %s ms); the held socket was let go at %s ms and "
"received %s datagrams (%s STUN)" % (
"Windows" if windows else "Linux", "firefox-69 or later" if engine_binds_exclusively else "before firefox-69", launch["bound"],
launch["bind_error"] or "", res["opened"], res["stalled"], launch["held"]["released_at_page_ms"], launch["held"]["received"],
launch["held"]["received_stun"]))
+4 -3
View File
@@ -125,11 +125,12 @@ def test_every_test_waits_for_the_release_that_carries_its_property():
def test_the_release_being_made_carries_only_its_own_properties():
"""firefox-68 holds the tests of the property it carries (networkidle: the held cut of a committed navigation); no later release has a row until
a test waits for it."""
"""firefox-68 holds the tests of the property it carries (networkidle: the held cut of a committed navigation), firefox-69 the one of the ICE port the
engine draws (bound exclusively, so no other process reads the checks of the pair); no later release has a row until a test waits for it."""
registry = _registry()
assert sorted(registry) == ["firefox-68"]
assert sorted(registry) == ["firefox-68", "firefox-69"]
assert sorted(registry["firefox-68"]["files"]) == ["tests/test_a_page_that_moves_on_e2e.py", "tests/test_fakeweb_p2_e2e.py"]
assert sorted(registry["firefox-69"]["files"]) == ["tests/test_a_held_ice_port_blinds_the_loopback_checks_e2e.py"]
def test_a_test_of_the_accumulated_line_gated_on_the_release_being_made_is_named():