Compare commits

...
Author SHA1 Message Date
feder-cr d4bee3cb19 ci(hunt): linux-3 becomes linux-3-loaded: 4 background loops of the security state's generation during the main run of every round (temporary) 2026-11-22 15:41:01 +01:00
feder-cr 7ae04457ef ci(hunt): this branch runs its own workflow: three Linux whole-suite copies, 3 rounds each, cores read by gdb (temporary) 2026-11-22 14:21:59 +01:00
feder-cr ca142970a2 Merge remote-tracking branch 'origin/char69/cores' into hunt/intermittent-68-suite-cores
# Conflicts:
#	ci/required-suites.json
2026-11-22 14:20:52 +01:00
feder-cr e44b2d623c ci(hunt): the fourth Linux copy becomes linux-secstate: tests/test_security_state_engine_e2e.py alone, 40 rounds, cores and gdb texts kept per round 2026-11-22 13:41:35 +01:00
feder-cr c7b8c4533e test(fakeweb p2): a round that does not idle keeps the whole in-flight list, what the lifecycle held open at the expiry, and each open request's history on the Juggler wire (+4 unit tests) 2026-11-22 13:40:18 +01:00
feder-cr 17a38797c5 Merge origin/tests/characterization-69 (10d15eee) into the suite hunt branch 2026-11-22 13:33:36 +01:00
feder-cr dd227e72b9 ci: a hunt for the intermittent e2e of firefox-68 in the whole suite (8 jobs, rounds), on the hunt branch only 2026-11-22 13:29:37 +01:00
feder-cr 0f06f39c14 Merge origin/tests/characterization-69 into the suite hunt branch 2026-11-22 13:25:09 +01:00
feder-cr 8a57737969 tests: the popup's recorder binds the error text before the lambda that writes it (F821) 2026-11-22 13:22:54 +01:00
feder-cr 72c7e6acf6 tests: the far-away gateway gather saves, when it fails, where the page's STUN request went
Evidence only (webrtc-far-away-<ice row>-<rtt>): the gateway's control connections and datagrams with their times and addresses,
the page's candidates, ICE errors and gathering states, the timings, the Juggler wire and the addresses of the runner.
Assertions, waits and deadlines are unchanged.
2026-11-22 13:12:02 +01:00
feder-cr e461d9d763 test(h3 lab): the residual case of the QUIC-first order is measured: a client that starts a QUIC handshake and vanishes holds the TCP of its IP until the QUIC idle timeout (+1 unit test) 2026-11-22 13:07:46 +01:00
feder-cr 365df5d90f test(read after goto): the test saves, when it fails, the client's view of every request and navigation, the Juggler wire, the engine's trace and the server's record of the requests it served 2026-11-22 13:06:26 +01:00
feder-cr aa078c0ff9 test(popup): the server-side recorder passes every call through unchanged and a recording error never reaches the server 2026-11-22 13:06:00 +01:00
feder-cr 2ab0b97072 test(popup): the 25 s popup saves, when it fails, the engine's wire and trace, what the server sent to the client and did with the target, what the client heard and the destination's record 2026-11-22 13:05:59 +01:00
feder-cr 5e70b513ce tests: the two-connections loopback test keeps what the lab heard on the mDNS group, packet by packet, when it fails
A passive listener (tests/_mdns_listener.py) joins 224.0.0.251:5353 on 127.0.0.1, the interface the engine's responder joins, before each launch and records every packet with its time, source, query or response, names and addresses. It never sends or answers, shares the port with the engine's socket and never raises. No assertion, wait or deadline changes.
2026-11-22 13:05:59 +01:00
feder-cr c0683e010b tests: the two-connections loopback test keeps the mDNS and mtransport logs and the page's ICE timeline when it fails
On failure the test saves the engine's own log of the failing launch (mdns_service and mtransport, MOZ_LOG_FILE in the evidence folder), the timings and the page's timeline of every launch up to it: each icecandidate of both connections, every ice and connection state change, when each addIceCandidate was called and settled. No assertion, wait or deadline changes.
2026-11-22 13:05:59 +01:00
feder-cr 525832571f tests: the no-proxy HTTP/3 test keeps the engine's HTTP log, the lab server's record and the visit timings when it fails
On failure the test saves the engine's own log of the launch (nsHttp and the neqo_glue, neqo_http3 and neqo_transport modules, MOZ_LOG_FILE in the evidence folder), the lab server's record of every TCP and QUIC connection (start, handshake, each request with its path, close and reason) and the url, protocol, goto time and read time of each visit. No assertion, wait or deadline changes.
2026-11-22 13:05:55 +01:00
feder-cr e68597cdb8 ci: the unit file of the lab server's QUIC-first order is in the rows of the whole unit suite (+5 tests) 2026-11-22 12:54:59 +01:00
feder-cr 59186492f3 test(h3 lab): LF line endings for the new test file, as the rest of the repository 2026-11-22 12:54:43 +01:00
feder-cr 9ef9ae651c test(h3 lab): the TLS of a TCP connection waits for the QUIC handshake in progress of the same client, as a real network orders them (QUIC 1 RTT, TCP+TLS 2) 2026-11-22 12:54:27 +01:00
feder-cr 13ecefb579 test(h3 lab): the QUIC connection of a client is ready before its TCP+TLS one while its QUIC handshake is in progress (red on the current server) 2026-11-22 12:53:30 +01:00
feder-cr 93239a1a10 tests: the save-on-failure helper of the e2e (tests/_evidence_on_failure.py as on tests/characterization-69 bc6d861f, unchanged), for the journey's evidence 2026-11-22 12:50:09 +01:00
feder-cr 42c344a180 test(fakeweb): a failure of the journey's request log is never the client's 2026-11-22 12:49:55 +01:00
feder-cr 261883cfd5 test(fakeweb): the journey saves, when it fails, the site's record of each request, the client's log of every request event per step and each step's in-flight list 2026-11-22 12:49:55 +01:00
19 changed files with 2312 additions and 106 deletions

No files matched your search

@@ -0,0 +1,457 @@
# ─────────────────────────────────────────────────────────────────────────────
# intermittent-68-suite-cores-hunt.yml - a HUNT for the intermittent e2e of firefox-68, in the context that reproduces them: the WHOLE e2e suite, on the load
# of the whole suite, with the cores of any crash read by gdb. It is NOT a gate, it is never merged to main (it lives on the branch
# `hunt/intermittent-68-suite-cores` and is deleted with it), and no result of it counts as green for anything: a green hunt proves nothing about a release,
# a red one is evidence to read.
#
# What it runs. The Linux job of .github/workflows/e2e.yml on this branch, as that file runs it, ROUNDS (3) times in sequence per job, and it never stops at a
# red: three identical copies (the whole suite under xvfb-run without the root and the sandbox files, then the root step and the sandbox step, as e2e.yml
# runs them). No Windows, no one-file security-state job. Left out on purpose: the gate that waits for the core on the index. Same runner, same install, same
# security state, same fetch, same GeoIP database, same scripts/run_e2e.py with its own width (-n), its own deadline and no rerun of any kind.
# The job linux-3-loaded also runs, DURING the main run of every round, 4 background loops of tests/test_security_state_engine_e2e.py::
# test_the_engine_generates_the_security_state_it_is_given (see "THE BACKGROUND LOOPS" in the step): the -11 of the generation did not happen alone, only
# inside the suite. A red iteration, or a core of a background engine, makes the job red; the summary lists node, iteration and engine exit code.
# What this branch adds to the tests: tests/conftest.py raises RLIMIT_CORE and, after a test that fails, tests/_crash_cores.py has gdb read every core in
# $INVPW_CORE_DIR (gdb, kernel.core_pattern and INVPW_CORE_DIR are set in the system-deps step, as in e2e.yml); the gdb texts are in
# invpw-evidence/cores/<test>/, which moves with invpw-evidence into round-N.
#
# Each round leaves, in $RUNNER_TEMP/hunt/round-N/: the junit of the round, the evidence the tests save on failure (invpw-evidence, with the gdb texts of
# the cores), the watchdog file, the log of the round and the junit of the root and sandbox steps. The browsers left over are closed between rounds.
# hunt-summary.md (also in the job summary) has one line per round (passed, failed, errors, skipped) and the failed node ids with the first line of each
# message. A job is red when any round has a failure or an error, when a round produced no junit, or when the shell broke.
#
# Triggered ONLY by a push to `hunt/intermittent-68-suite-cores`: no schedule, no dispatch, no pull request.
# ─────────────────────────────────────────────────────────────────────────────
name: intermittent 68 suite cores hunt
on:
push:
branches: [hunt/intermittent-68-suite-cores]
permissions:
contents: read
# A newer push to the hunt branch replaces the run it supersedes.
concurrency:
group: intermittent-68-suite-cores-hunt-${{ github.ref }}
cancel-in-progress: true
# Engine and GeoIP downloads go through the release API with this token (as every workflow that runs tests).
env:
GITHUB_TOKEN: ${{ github.token }}
jobs:
hunt:
name: suite cores hunt ${{ matrix.label }}
runs-on: ubuntu-24.04
# Up to 6 rounds of the whole suite plus the install: the ceiling is the longest a hosted job may run.
timeout-minutes: 360
strategy:
fail-fast: false
max-parallel: 3
matrix:
include:
- label: linux-1
temp: /tmp
- label: linux-2
temp: /tmp
- label: linux-3-loaded
temp: /tmp
load: secstate-x4
env:
TEMP: ${{ matrix.temp }}
TMP: ${{ matrix.temp }}
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: Install wrapper + test deps (+ Playwright ONLY as a system tool)
run: |
python -m pip install --upgrade pip
python -m pip install ".[dev]"
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
- name: System deps (xvfb + Firefox runtime libs)
run: |
sudo apt-get update
sudo apt-get install -y xvfb
sudo apt-get install -y strace
sudo apt-get install -y gdb
mkdir -p "$RUNNER_TEMP/invpw-cores"
sudo sysctl -w kernel.core_pattern="$RUNNER_TEMP/invpw-cores/core.%e.%p"
echo "INVPW_CORE_DIR=$RUNNER_TEMP/invpw-cores" >> "$GITHUB_ENV"
sudo "$(which python)" -m playwright install-deps firefox
# The loaded job: 4 background loops run the engine from their own copy of its folder (/tmp/ffbg-K), and the name of a core carries the path of the executable
# (%E, slashes as '!'), so that the core of a background engine is told from the cores of the main run: tests/_crash_cores.py leaves the first to the loops.
- name: Core names carry the executable's path (loaded job)
if: matrix.load == 'secstate-x4'
run: sudo sysctl -w kernel.core_pattern="$RUNNER_TEMP/invpw-cores/core.%E.%p"
# The security state is a ready directory of the repository (ci/security-state/, a result with no data, the sha256 in ci/security-state.pin.json): with
# STEALTHFOX_SECURITY_STATE set the core neither downloads nor generates one. BEFORE `fetch`, which makes the state present (it would download and generate it).
- name: The security state (a fixed directory of the repository)
run: python scripts/ci_lab_security_state.py set --pin ci/security-state.pin.json
- name: Fetch the published firefox binary
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
# The GeoIP database made by the repository, as in e2e.yml (no download, the same bytes every run).
- name: The GeoIP database (made by the repository, same bytes every run)
run: python scripts/ci_lab_geoip.py build
- name: The suite, round after round
env:
PYTHONUNBUFFERED: "1"
# The number of rounds: the matrix's (40 for the one-file job), else 3, and never more than 6 for the whole suite or 100 for the one file (the script clamps it).
HUNT_ROUNDS: ${{ matrix.rounds || '3' }}
# `suite`: the e2e of e2e.yml (the Linux job or the Windows part); `secstate`: only tests/test_security_state_engine_e2e.py, on Linux.
HUNT_MODE: ${{ matrix.mode || 'suite' }}
# The loaded job (matrix.load): this many background loops of the generation of the security state run during the main run of every round; else none.
HUNT_BG: ${{ matrix.load == 'secstate-x4' && '4' || '0' }}
# No new round starts after this many seconds of the step, so that the artifact is uploaded before the job's ceiling.
HUNT_BUDGET_S: "19000"
HUNT_LABEL: ${{ matrix.label }}
# The watchdog of tests/conftest.py, as e2e.yml sets it for the run of the runner user (the junit of the run is written beside it).
HUNT_WATCHDOG: ${{ runner.temp }}/e2e-watchdog.log
# The Linux job of e2e.yml: the root files and the sandbox file are left out of the run and run in their own steps.
ROOT_FILES: tests/test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py
ROOT_NODES: tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick
SANDBOX_FILES: tests/test_the_socket_process_is_sandboxed_e2e.py
ROOT_TESTS: "7"
SANDBOX_TESTS: "1"
run: |
# A step of a hunt that breaks must never end green: any error stops it, and the trap below turns a stop before the verdict into a red step.
set -euo pipefail
finished=0
trap 'if [ "$finished" != 1 ]; then echo "::error::the hunt step stopped before its verdict"; exit 1; fi' EXIT
if [ -z "${FF:-}" ] || [ ! -e "$FF" ]; then echo "::error::no engine binary (FF='${FF:-}')"; exit 1; fi
rounds="${HUNT_ROUNDS:-3}"
case "$rounds" in ''|*[!0-9]*) echo "::warning::HUNT_ROUNDS='$rounds' is not a number: 3 rounds"; rounds=3;; esac
if [ "$rounds" -lt 1 ]; then rounds=3; fi
most=6
if [ "$HUNT_MODE" = "secstate" ]; then most=100; fi
if [ "$rounds" -gt "$most" ]; then echo "::warning::HUNT_ROUNDS=$rounds is more than $most: $most rounds"; rounds=$most; fi
hunt="$RUNNER_TEMP/hunt"
mkdir -p "$hunt"
extras=()
if [ "$RUNNER_OS" = "Windows" ]; then
mapfile -t ARGS < <(tr -d '\r' < "$RUNNER_TEMP/e2e_args.txt")
elif [ "$HUNT_MODE" = "suite" ]; then
# What the restriction on user namespaces was, to put it back after the sandbox step of every round.
USERNS0="$(sysctl -n kernel.apparmor_restrict_unprivileged_userns 2>/dev/null || echo 1)"
extras=("root-e2e.xml=$ROOT_TESTS" "sandbox-e2e.xml=$SANDBOX_TESTS")
fi
# The reading of one round: "tests failures errors skipped junit-files problems" on the first line, then one line per red test (node id, first line of
# the message) and one per problem (a junit that is not there or not readable, an extra with the wrong number of tests).
cat > "$hunt/read_round.py" <<'PY'
import glob, os, sys, xml.etree.ElementTree as ET
sys.stdout.reconfigure(newline="\n")
rd = sys.argv[1]
exact = dict(a.split("=", 1) for a in sys.argv[2:])
files = sorted(glob.glob(os.path.join(rd, "e2e-junit-*.xml")))
problems, reds = [], []
tests = failures = errors = skipped = 0
if not files:
problems.append("no e2e-junit-*.xml in the round")
for name in sorted(exact):
path = os.path.join(rd, name)
if not os.path.exists(path):
problems.append("%s is not there" % name)
else:
files.append(path)
for path in files:
try:
root = ET.parse(path).getroot()
except Exception as exc:
problems.append("%s is not readable: %r" % (os.path.basename(path), exc))
continue
count = 0
for case in root.iter("testcase"):
count += 1
tests += 1
if case.find("skipped") is not None:
skipped += 1
for kind in ("failure", "error"):
bad = case.find(kind)
if bad is None:
continue
if kind == "failure":
failures += 1
else:
errors += 1
message = (bad.get("message") or bad.text or "").strip().splitlines()
reds.append("%s::%s [%s] | %s" % (case.get("classname"), case.get("name"), kind, (message[0] if message else "")[:300]))
want = exact.get(os.path.basename(path))
if want is not None and count != int(want):
problems.append("%s has %d tests, exactly %s were demanded" % (os.path.basename(path), count, want))
print(tests, failures, errors, skipped, len(files), len(problems))
for line in reds:
print("FAIL " + line)
for line in problems:
print("PROBLEM " + line)
PY
# Every browser left by a round is closed before the next one starts (and after the last).
reap() {
if [ "$RUNNER_OS" = "Windows" ]; then
powershell -NoProfile -Command "Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue" > /dev/null 2>&1 || true
else
pkill -9 -f "$(dirname "$FF")" > /dev/null 2>&1 || true
pkill -9 -f '[/]tmp/ffbg-' > /dev/null 2>&1 || true
sudo pkill -9 -f '[/]opt/ff' > /dev/null 2>&1 || true
pkill -9 Xvfb > /dev/null 2>&1 || true
fi
}
# THE BACKGROUND LOOPS (loaded job only): while the main run of a round goes on, HUNT_BG copies of the generation of the security state loop, each one pytest
# (-n 0) after the other until the round's main run ends. A loop has its own copy of the engine folder (/tmp/ffbg-K: the name of its cores says so), its own
# basetemp (the work dir of the test and the engine's profile are under it), its own RUNNER_TEMP (the evidence the test saves) and no INVPW_CORE_DIR (the hooks
# of tests/conftest.py touch nothing): after each iteration the loop reads and deletes the cores of ITS engine with gdb itself (tests/_crash_cores.py gdb_text).
cat > "$hunt/bg_cores.py" <<'PY'
import os, sys
from pathlib import Path
sys.path.insert(0, "tests")
import _crash_cores
coredir, mark, into = sys.argv[1], sys.argv[2], Path(sys.argv[3])
if coredir and os.path.isdir(coredir):
for core in sorted(p for p in Path(coredir).glob("core*") if p.is_file() and mark in p.name):
into.mkdir(parents=True, exist_ok=True)
print(_crash_cores.gdb_text(core, into))
core.unlink()
PY
cat > "$hunt/bg_loop.sh" <<'SH'
#!/usr/bin/env bash
# bg_loop.sh K ROUND_DIR STOP_FILE HUNT_DIR: one pytest after the other of the generation test until STOP_FILE exists. FF and INVPW_CORE_DIR come from the step.
k=$1; rd=$2; stop=$3; hunt=$4
d="$rd/secstate-bg-$k"
mkdir -p "$d"
bin="/tmp/ffbg-$k/$(basename "$FF")"
node="tests/test_security_state_engine_e2e.py::test_the_engine_generates_the_security_state_it_is_given"
n=0
while [ ! -e "$stop" ]; do
n=$((n + 1))
it="$d/it-$n"
mkdir -p "$it/rt"
echo "$n" > "$d/current"
t0=$SECONDS
env -u INVPW_CORE_DIR -u GEOIP_USED_OUT -u PYTEST_ADDOPTS RUNNER_TEMP="$it/rt" INVPW_TEST_WATCHDOG_FILE="$it/watchdog.log" \
STEALTHFOX_E2E_BINARY="$bin" INVPW_BINARY_PATH="$bin" \
python -u -m pytest "$node" -m e2e -n 0 -o addopts='' -o junit_family=xunit2 -q -p no:cacheprovider -p no:rerunfailures -rs \
--basetemp="$it/base" --junitxml="$it/e2e-junit-bg.xml" > "$it/log.txt" 2>&1
code=$?
secs=$((SECONDS - t0))
python "$hunt/bg_cores.py" "$INVPW_CORE_DIR" "!ffbg-$k!" "$it/cores" > "$it/cores.txt" 2>&1
ncores=$(grep -c '^core ' "$it/cores.txt")
python "$hunt/read_round.py" "$it" 2>&1 | tr -d '\r' > "$it/read.txt"
read -r t f e s files problems < <(head -1 "$it/read.txt")
state=green
if [ "$code" -ne 0 ] || [ "${t:-x}" != 1 ] || [ "${f:-x}" != 0 ] || [ "${e:-x}" != 0 ] || [ "${s:-x}" != 0 ] || [ "${problems:-x}" != 0 ]; then state=RED; fi
if [ "$ncores" -gt 0 ]; then state=RED; fi
engine=$(grep -o 'exit code -\?[0-9]*' "$it/read.txt" | head -1)
case "$engine" in *" -11") engine="$engine (SIGSEGV)";; esac
printf '%s\t%s\tpytest exit %s\t%s s\t%s\t%s cores\n' "$n" "$state" "$code" "$secs" "${engine:-no engine exit code in the message}" "$ncores" >> "$d/bg.tsv"
if [ "$state" = RED ]; then
echo "bg-$k iteration $n: RED, pytest exit $code, ${engine:-no engine exit code in the message}, $ncores core(s), $secs s, $node | $(grep -m1 '^FAIL\|^PROBLEM' "$it/read.txt" | cut -c1-300)" >> "$d/red.txt"
else
rm -rf "$it/base"
fi
rm -f "$d/current"
done
SH
bg_n="${HUNT_BG:-0}"
case "$bg_n" in ''|*[!0-9]*) bg_n=0;; esac
bg_pids=()
if [ "$bg_n" -gt 0 ]; then
for k in $(seq 1 "$bg_n"); do rm -rf "/tmp/ffbg-$k"; cp -a "$(dirname "$FF")" "/tmp/ffbg-$k"; done
fi
bg_start() {
local rd=$1 k
[ "$bg_n" -gt 0 ] || return 0
rm -f "$rd/bg-stop"
bg_pids=()
for k in $(seq 1 "$bg_n"); do
setsid xvfb-run -a bash "$hunt/bg_loop.sh" "$k" "$rd" "$rd/bg-stop" "$hunt" > "$rd/bg-$k.log" 2>&1 &
bg_pids+=("$!")
done
}
# The main run has ended: no new iteration, the one in progress ends by itself (a generation lasts a few seconds; at most 420 s are waited), then the loops that
# are still there are killed with their group. Nothing outlives the round.
bg_stop() {
local rd=$1 waited=0 pid alive
[ "$bg_n" -gt 0 ] || return 0
touch "$rd/bg-stop"
while [ "$waited" -lt 420 ]; do
alive=0
for pid in "${bg_pids[@]}"; do if kill -0 "$pid" 2>/dev/null; then alive=1; fi; done
if [ "$alive" = 0 ]; then break; fi
sleep 3
waited=$((waited + 3))
done
for pid in "${bg_pids[@]}"; do
if kill -0 "$pid" 2>/dev/null; then
echo "::warning::a background loop (pid $pid) was still running $waited s after the end of the main run: killed"
echo "a background loop (pid $pid) was killed $waited s after the end of the main run" >> "$rd/bg-killed.txt"
kill -TERM -- "-$pid" 2>/dev/null; sleep 2; kill -KILL -- "-$pid" 2>/dev/null
fi
wait "$pid" 2>/dev/null
done
bg_pids=()
pkill -9 -f '[/]tmp/ffbg-' > /dev/null 2>&1
# The cores of a background engine that a killed iteration left.
python "$hunt/bg_cores.py" "${INVPW_CORE_DIR:-}" '!ffbg-' "$rd/bg-leftover-cores" > "$rd/bg-leftover-cores.txt" 2>&1
}
# The count of the loops of a round: bg_iters, bg_red, and the lines for the summary in $1/bg-summary.txt.
bg_read() {
local rd=$1 k d
bg_iters=0; bg_red=0
: > "$rd/bg-summary.txt"
[ "$bg_n" -gt 0 ] || return 0
for k in $(seq 1 "$bg_n"); do
d="$rd/secstate-bg-$k"
local it=0 red=0
if [ -f "$d/bg.tsv" ]; then it=$(wc -l < "$d/bg.tsv"); red=$(grep -c "RED" "$d/bg.tsv" || true); fi
bg_iters=$((bg_iters + it)); bg_red=$((bg_red + red))
echo "secstate loop $k: $it iterations, $red red" >> "$rd/bg-summary.txt"
if [ -f "$d/red.txt" ]; then sed 's/^/ RED /' "$d/red.txt" >> "$rd/bg-summary.txt"; fi
if [ -f "$d/current" ]; then echo " iteration $(cat "$d/current") was cut at the end of the round (not counted)" >> "$rd/bg-summary.txt"; fi
done
if [ -s "$rd/bg-killed.txt" ]; then sed 's/^/ /' "$rd/bg-killed.txt" >> "$rd/bg-summary.txt"; fi
if [ -s "$rd/bg-leftover-cores.txt" ] && grep -q '^core ' "$rd/bg-leftover-cores.txt"; then
bg_red=$((bg_red + 1)); sed 's/^/ RED leftover /' "$rd/bg-leftover-cores.txt" >> "$rd/bg-summary.txt"
fi
if [ "$bg_iters" -eq 0 ]; then bg_red=$((bg_red + 1)); echo " RED no iteration of any loop ended in the round: not measured" >> "$rd/bg-summary.txt"; fi
}
# The run of the runner user, as e2e.yml runs it: Linux, the whole suite without the root and the sandbox files; Windows, the files of the part.
run_main() {
if [ "$RUNNER_OS" = "Windows" ]; then
INVPW_TEST_WATCHDOG_FILE="$HUNT_WATCHDOG" python -u scripts/run_e2e.py "$FF" "${ARGS[@]}"
elif [ "$HUNT_MODE" = "secstate" ]; then
# The one file, as e2e.yml runs it (the whole file, the engine in its generate mode, under xvfb), on the serial path of run_e2e.py: one pytest.
INVPW_TEST_WATCHDOG_FILE="$HUNT_WATCHDOG" xvfb-run -a python -u scripts/run_e2e.py "$FF" tests/test_security_state_engine_e2e.py -n 1
else
local IGNORE=() DESELECT=() f nodeid
for f in $ROOT_FILES $SANDBOX_FILES; do IGNORE+=("--ignore=$f"); done
for nodeid in $ROOT_NODES; do DESELECT+=("--deselect=$nodeid"); done
INVPW_TEST_WATCHDOG_FILE="$HUNT_WATCHDOG" xvfb-run -a python -u scripts/run_e2e.py "$FF" "${IGNORE[@]}" "${DESELECT[@]}"
fi
}
# THE ROOT STEP of e2e.yml (wrapper.e2e.udp.exit), after the run of the runner user.
run_root() {
sudo rm -rf /opt/ff
sudo cp -a "$(dirname "$FF")" /opt/ff
sudo chown -R root:root /opt/ff
sudo chmod -R go+rX /opt/ff
local ROOT_FF="/opt/ff/$(basename "$FF")"
local JUNIT="${RUNNER_TEMP}/root-e2e.xml"
sudo -H -E env -u PYTEST_ADDOPTS -u XDG_RUNTIME_DIR INVPW_REQUIRE_TRAP=1 "PATH=$PATH" INVPW_BINARY_PATH="$ROOT_FF" STEALTHFOX_E2E_BINARY="$ROOT_FF" \
python -m pytest $ROOT_FILES $ROOT_NODES -m e2e -o addopts='' -o junit_family=xunit2 -q -p no:cacheprovider -p no:rerunfailures -rs --junitxml="$JUNIT"
}
# THE SANDBOX STEP of e2e.yml (wrapper.e2e.udp.sandbox), after the root step.
run_sandbox() {
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
local JUNIT="${RUNNER_TEMP}/sandbox-e2e.xml"
xvfb-run -a env -u PYTEST_ADDOPTS INVPW_BINARY_PATH="$FF" STEALTHFOX_E2E_BINARY="$FF" \
python -m pytest $SANDBOX_FILES -m e2e -o addopts='' -o junit_family=xunit2 -q -p no:cacheprovider -p no:rerunfailures -rs --junitxml="$JUNIT"
}
{
echo "## $HUNT_LABEL"
echo ""
if [ "$HUNT_MODE" = "secstate" ]; then what="tests/test_security_state_engine_e2e.py alone"; else what="The whole e2e of e2e.yml on this branch"; fi
echo "$what, $rounds rounds in sequence. A hunt, not a gate: nothing here counts as green."
echo ""
} > "$hunt/hunt-summary.md"
rounds_run=0; rounds_red=0
for n in $(seq 1 "$rounds"); do
if [ "$SECONDS" -gt "${HUNT_BUDGET_S:-19000}" ]; then
echo "::warning::time budget reached after $rounds_run rounds of $rounds: no new round"
echo "- time budget reached after $rounds_run rounds of $rounds: no new round" >> "$hunt/hunt-summary.md"
break
fi
rd="$hunt/round-$n"
mkdir -p "$rd"
log="$rd/round.log"
t0=$SECONDS
echo "::group::round $n/$rounds"
code_main=-; code_root=-; code_sandbox=-
set +e
bg_start "$rd"
run_main 2>&1 | tee "$log"
code_main=${PIPESTATUS[0]}
bg_stop "$rd"
if [ "$RUNNER_OS" = "Linux" ] && [ "$HUNT_MODE" = "suite" ]; then
run_root 2>&1 | tee -a "$log"
code_root=${PIPESTATUS[0]}
# Whatever root wrote under the evidence folder is the runner's again.
sudo chown -R "$(id -u):$(id -g)" "$RUNNER_TEMP/root-e2e.xml" "$RUNNER_TEMP/invpw-evidence" > /dev/null 2>&1
run_sandbox 2>&1 | tee -a "$log"
code_sandbox=${PIPESTATUS[0]}
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns="$USERNS0" > /dev/null 2>&1
{
echo "-- files owned by root under the runner's home and /tmp"; sudo find /home/runner /tmp -maxdepth 3 -user root 2>/dev/null | head -40
echo "-- /etc/resolv.conf"; cat /etc/resolv.conf
echo "-- lo"; ip -4 addr show lo
} >> "$log" 2>&1
fi
reap
# The leg ran with the pinned GeoIP database (the step of e2e.yml, once per round here).
geoip_ok=1
python scripts/ci_lab_geoip.py evidence --out "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" > /dev/null 2>> "$log" || geoip_ok=0
python scripts/ci_lab_geoip.py verify --evidence "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" --used "$GEOIP_USED_OUT" >> "$log" 2>&1 || geoip_ok=0
set -e
echo "::endgroup::"
# What this round left, moved aside so that the next one does not overwrite it.
shopt -s nullglob
for item in "$RUNNER_TEMP"/e2e-junit-*.xml "$RUNNER_TEMP/root-e2e.xml" "$RUNNER_TEMP/sandbox-e2e.xml" "$HUNT_WATCHDOG" "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json"; do
if [ -e "$item" ]; then mv "$item" "$rd/"; fi
done
if [ -d "$RUNNER_TEMP/invpw-evidence" ]; then mv "$RUNNER_TEMP/invpw-evidence" "$rd/invpw-evidence"; fi
# A core file the engine left (the test deletes the ones it reads) and the gdb texts beside it, kept with the round that made them.
if [ -n "${INVPW_CORE_DIR:-}" ] && [ -d "$INVPW_CORE_DIR" ] && [ -n "$(ls -A "$INVPW_CORE_DIR")" ]; then
mkdir -p "$rd/invpw-cores"
find "$INVPW_CORE_DIR" -mindepth 1 -maxdepth 1 -exec mv -t "$rd/invpw-cores" {} +
fi
shopt -u nullglob
# Python writes CRLF on Windows: every line read back loses its carriage return before it is used in an arithmetic expression.
python "$hunt/read_round.py" "$rd" "${extras[@]}" | tr -d '\r' > "$rd/round-read.txt"
read -r t f e s files problems < <(head -1 "$rd/round-read.txt")
for number in "$t" "$f" "$e" "$s" "$files" "$problems"; do
case "$number" in ''|*[!0-9]*) echo "::error::round $n: the junit read gave '$t $f $e $s $files $problems', not six numbers"; exit 1;; esac
done
rounds_run=$((rounds_run + 1))
bg_read "$rd"
red=0
if [ "$bg_red" -gt 0 ]; then red=1; fi
if [ $((f + e)) -gt 0 ] || [ "$problems" -gt 0 ] || [ "$code_main" -ne 0 ] || [ "$geoip_ok" -ne 1 ]; then red=1; fi
if [ "$red" -eq 1 ]; then rounds_red=$((rounds_red + 1)); verdict=RED; else verdict=green; fi
line="round $n/$rounds: $verdict - passed $((t - f - e - s)), failed $f, errors $e, skipped $s (tests $t in $files junit files; exit main=$code_main root=$code_root sandbox=$code_sandbox; geoip ok=$geoip_ok; $((SECONDS - t0)) s)"
echo "$line"
{
echo "- $line"
tail -n +2 "$rd/round-read.txt" | sed 's/^/ - /'
sed 's/^/ - /' "$rd/bg-summary.txt"
} >> "$hunt/hunt-summary.md"
tail -n +2 "$rd/round-read.txt"
cat "$rd/bg-summary.txt"
done
cat "$hunt/hunt-summary.md"
# Red means FOUND, and also NOT MEASURED: a red round, or no round at all.
finished=1
if [ "$rounds_run" -eq 0 ]; then echo "::error::no round ran"; exit 1; fi
if [ "$rounds_red" -ne 0 ]; then echo "::error::$rounds_red of $rounds_run rounds are red"; exit 1; fi
- name: The counts in the job summary
if: always()
run: |
if [ -f "$RUNNER_TEMP/hunt/hunt-summary.md" ]; then cat "$RUNNER_TEMP/hunt/hunt-summary.md" >> "$GITHUB_STEP_SUMMARY"; fi
# Everything of every round, and what a round that did not end (a kill at the ceiling) left where it was.
- name: Upload what the hunt found (every round)
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: suite-hunt-${{ matrix.label }}-${{ github.run_id }}
path: |
${{ runner.temp }}/hunt
${{ runner.temp }}/invpw-evidence
${{ runner.temp }}/e2e-junit-*.xml
${{ runner.temp }}/root-e2e.xml
${{ runner.temp }}/sandbox-e2e.xml
${{ runner.temp }}/e2e-watchdog.log
if-no-files-found: warn
retention-days: 14
+2 -2
View File
@@ -14,8 +14,8 @@
{"id": "wrapper.e2e.fakeweb", "giro": "G2", "os": ["linux", "windows"], "min_tests": 4, "exact": true, "tests": ["tests/test_fakeweb_p2_e2e.py", "tests/test_fakeweb_p4_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The fake web, offline: our browser on the hard pages (profile P2: a reused routed page reaches networkidle every time, also under a load of three other browsers; the other site is another process) and on the 17-step journey of a person (profile P4), each judged against what stock Firefox does, as tests/fakeweb/pages.json declares it. 4 = 3 + 1. Stock itself is held to that declaration, and compared with ours step by step, by scripts/run_fakeweb.py in .github/workflows/fakeweb.yml. Needs the candidate binary (STEALTHFOX_E2E_BINARY)."},
{"id": "wrapper.e2e.fontconfig", "giro": "G2", "os": ["linux"], "min_tests": 2, "exact": true, "tests": ["tests/test_the_parent_reads_the_bundle_from_fontconfig_s_cache_linux_e2e.py"], "marker": "e2e", "needs_root": false, "linux_only": "Fontconfig exists only on Linux: the parent of the engine shows <GRE>/fonts to it (FcConfigAppFontAddDir) to rebuild a font from a path and a face index. On Windows DirectWrite opens the file from its path, with no folder to scan and no cache to read, so this test has no Windows counterpart.", "note": "2 = (1) the stand-in that runs the engine under strace stays in the engine's place, as the core launches it (the leader of a process group of its own): a fake engine with a child, no browser; the process the launcher holds lives as long as the fake engine, and the group killed holds strace and the child (the stand-in that exec'd setsid forked and exited 0 at once: candidate 44161687675); (2) the warm launch of the parent reads the bundle from fontconfig's cache and does not scan it again (from firefox-66, engine_at_least). Two launches under strace with the same XDG_CACHE_HOME of the test, the first cold and the second warm: the cold parent opens every font file of <GRE>/fonts (the folder as the disk lists it) before any page and fontconfig writes its cache; the warm parent does not open every one of them, and it opens a *.cache-* file of fontconfig (a few files are opened to be used, so the verdict asks about the whole folder, as a scan does). Scan and drawing are told apart by position: only what the parent opens before the first page counts (the opens that draw are written as after_startup). Evidence in RUNNER_TEMP/invpw-evidence/fontconfig-cache: the interval and the number of opens of the bundle, the names of the files of the bundle each launch opened before the first page, the size of the cache file, the VmRSS of the parent after about:blank and after a page with every family, and a third launch with gfx.bundled-fonts.activate=0 (the behaviour before), which is evidence only. Needs strace on the runner: without it both are red, not skipped. No threshold."},
{"id": "wrapper.unit.compositing", "giro": "G1", "os": ["linux", "windows"], "min_tests": 30, "exact": true, "tests": ["tests/test_the_page_bytes_reference_compares_decoded_pixels.py"], "marker": "unit", "needs_root": false, "note": "The helpers of wrapper.e2e.compositing on known inputs, no browser: the PNG compared on decoded pixels (another deBG chunk and compression are the same, one pixel is not, every scanline filter), the comparison with a reference (changed, missing and extra keys named, the entry to record), the type of an engine process, an engine process known by its executable and not by the name it gives itself (Linux), and the CPU of a window, and the shape of the committed Windows reference, and the box cut out of a screenshot (its pixels, a box outside the picture refused, written as a PNG and read back, two boxes told apart by a pixel that is named, the pixels that are not grey)."},
{"id": "wrapper.unit.all.linux", "giro": "G1", "os": ["linux"], "min_tests": 2301, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_generation_of_the_security_state_keeps_its_evidence.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_read_whose_probe_ran_out_is_the_callers_timeout.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_suite_run.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_goto_follows_the_base_url.py", "tests/test_hook_wiring.py", "tests/test_imports.py", "tests/test_integration.py", "tests/test_juggler_event_buffer.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py", "tests/test_juggler_lives_in_the_core.py", "tests/test_juggler_posix_pipe.py", "tests/test_juggler_transport.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_launch_counters_run_on_github.py", "tests/test_launcher_config.py", "tests/test_launcher_helpers.py", "tests/test_motion_never_hides_a_programming_error.py", "tests/test_moving_page_model.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_no_legacy_in_the_wrapper.py", "tests/test_no_override_leaves_the_persona_scheme.py", "tests/test_no_thread_is_started_on_the_reader.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/testLine truncated
{"id": "wrapper.unit.all.windows", "giro": "G1", "os": ["windows"], "min_tests": 2302, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_generation_of_the_security_state_keeps_its_evidence.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_read_whose_probe_ran_out_is_the_callers_timeout.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_suite_run.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_goto_follows_the_base_url.py", "tests/test_hook_wiring.py", "tests/test_imports.py", "tests/test_integration.py", "tests/test_juggler_event_buffer.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py", "tests/test_juggler_lives_in_the_core.py", "tests/test_juggler_transport.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_launch_counters_run_on_github.py", "tests/test_launcher_config.py", "tests/test_launcher_helpers.py", "tests/test_motion_never_hides_a_programming_error.py", "tests/test_moving_page_model.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_no_legacy_in_the_wrapper.py", "tests/test_no_override_leaves_the_persona_scheme.py", "tests/test_no_thread_is_started_on_the_reader.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pin.py", "tests/test_pin_dicts_Line truncated
{"id": "wrapper.unit.all.linux", "giro": "G1", "os": ["linux"], "min_tests": 2311, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_generation_of_the_security_state_keeps_its_evidence.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_read_whose_probe_ran_out_is_the_callers_timeout.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_suite_run.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_goto_follows_the_base_url.py", "tests/test_hook_wiring.py", "tests/test_imports.py", "tests/test_integration.py", "tests/test_juggler_event_buffer.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py", "tests/test_juggler_lives_in_the_core.py", "tests/test_juggler_posix_pipe.py", "tests/test_juggler_transport.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_launch_counters_run_on_github.py", "tests/test_launcher_config.py", "tests/test_launcher_helpers.py", "tests/test_motion_never_hides_a_programming_error.py", "tests/test_moving_page_model.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_no_legacy_in_the_wrapper.py", "tests/test_no_override_leaves_the_persona_scheme.py", "tests/test_no_thread_is_started_on_the_reader.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/testLine truncated
{"id": "wrapper.unit.all.windows", "giro": "G1", "os": ["windows"], "min_tests": 2312, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_generation_of_the_security_state_keeps_its_evidence.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_read_whose_probe_ran_out_is_the_callers_timeout.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_suite_run.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_goto_follows_the_base_url.py", "tests/test_hook_wiring.py", "tests/test_imports.py", "tests/test_integration.py", "tests/test_juggler_event_buffer.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py", "tests/test_juggler_lives_in_the_core.py", "tests/test_juggler_transport.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_launch_counters_run_on_github.py", "tests/test_launcher_config.py", "tests/test_launcher_helpers.py", "tests/test_motion_never_hides_a_programming_error.py", "tests/test_moving_page_model.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_no_legacy_in_the_wrapper.py", "tests/test_no_override_leaves_the_persona_scheme.py", "tests/test_no_thread_is_started_on_the_reader.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pin.py", "tests/test_pin_dicts_Line truncated
{"id": "wrapper.e2e.securitystate", "giro": "G2", "os": ["linux", "windows"], "min_tests": 4, "exact": true, "tests": ["tests/test_security_state_engine_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The security state the core declares, against the engine: the engine launched directly in its generate mode makes what it is given (the contract's result, security_state/ with the bytes of the full filter and of the delta, the core's own validation of it); a normal launch declares no pref of the mode and re-imports nothing; a certificate that Mozilla's CRLite test data say is revoked in a delta is refused at the first navigation (SEC_ERROR_REVOKED_CERTIFICATE) while a valid one loads, and the revoked one loads when the ready directory has no data; a ready directory with no or an empty security_state/ starts. Certificates made on the run (a fresh root trusted in cert9.db by the engine's own xpcshell, Mozilla's default test key as the key of CN=int), servers on loopback, no network. Red on firefox-67 (no generate mode)."},
{"id": "wrapper.e2e.suite.linux.1", "giro": "G2", "os": ["linux"], "min_tests": 376, "exact": true, "tests": ["tests/test_a_closed_browser_leaves_the_others_alone_e2e.py", "tests/test_a_context_that_ends_leaves_no_process_e2e.py", "tests/test_a_cors_preflight_is_not_a_request_of_the_page_e2e.py", "tests/test_a_declared_webgl_extension_survives_its_use_e2e.py", "tests/test_a_granted_permission_is_the_one_the_page_asks_for_e2e.py", "tests/test_a_launch_without_a_session_gets_one_e2e.py", "tests/test_a_left_documents_body_is_evicted_e2e.py", "tests/test_a_mouse_click_makes_one_mousemove_on_its_point_e2e.py", "tests/test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_screenshot_draws_the_text_of_the_bundled_fonts_as_the_content_does_e2e.py", "tests/test_a_served_browser_answers_a_plain_client_e2e.py", "tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_turn_name_over_tcp_goes_through_the_proxy_of_the_context_e2e.py", "tests/test_accept_language_on_the_wire_e2e.py", "tests/test_browser_output_is_drained.py", "tests/test_click_rhythm.py", "tests/test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py", "tests/test_control_a_selects_all_in_a_field_e2e.py", "tests/test_cross_origin_iframe.py", "tests/test_declared_host_network_e2e.py", "tests/test_detectors_e2e.py", "tests/test_e2e.py", "tests/test_element_handle_actions.py", "tests/test_element_screenshot_e2e.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_file_chooser.py", "tests/test_fingerprint_surface.py", "tests/test_fission_frames_history_and_processes_e2e.py", "tests/test_fission_frames_workers_storage_and_special_frames_e2e.py", "tests/test_frames_outlive_the_back_forward_cache_e2e.py", "tests/test_goto_networkidle_after_spa_e2e.py", "tests/test_goto_script_redirect_e2e.py", "tests/test_hidden_display_linux.py", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_the_ice_name_of_a_context_goes_by_the_proxy_of_that_context", "tests/test_ignore_https_errors_e2e.py", "tests/test_injected_node_surface.py", "tests/test_juggler_connection.py", "tests/test_juggler_posix_pipe.py", "tests/test_juggler_transport.py", "tests/test_navigation_across_processes_e2e.py", "tests/test_navigation_response.py", "tests/test_networkidle_reaches_the_client_e2e.py", "tests/test_oop_frame_element.py", "tests/test_oop_frame_geometry.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pointer_position.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_preload_newtab_turns_the_privileged_about_process_off_e2e.py", "tests/test_realness_behind_a_declared_exit_e2e.py", "tests/test_resolver_race_e2e.py", "tests/test_route_header_order_e2e.py", "tests/test_same_document_goto_e2e.py", "tests/test_screencast.py", "tests/test_screencast_stop_e2e.py", "tests/test_screenshot_looks_where_you_are.py", "tests/test_security_state_engine_e2e.py", "tests/test_service_worker.py", "tests/test_service_worker_controller_e2e.py", "tests/test_set_offline_e2e.py", "tests/test_shadow_trusted_input.py", "tests/test_strict_and_force.py", "tests/test_the_callers_code_is_not_counted_e2e.py", "tests/test_the_device_enumeration_takes_the_declared_time_e2e.py", "tests/test_the_engine_is_born_in_the_job_e2e.py::test_a_launch_scans_no_process_of_the_machine", "tests/test_the_engine_is_born_in_the_job_e2e.py::test_after_close_no_process_of_the_session_is_left", "tests/test_the_hosts_file_of_the_host_is_never_read_e2e.py", "tests/test_trial_does_not_act.py", "tests/test_turn_over_tcp_is_tried_for_real_e2e.py", "tests/test_ua_widget_not_selectable.py", "tests/test_voices_e2e.py", "tests/test_wait_for_function.py", "tests/test_webgl_draws_on_the_engine_s_own_gl_e2e.py", "tests/test_webgl_noise_active.py", "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_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server", "tests/test_webrtc_realness.py::test_a_host_with_ipv6_addresses_gathers_through_an_ipv4_relay", "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_relay_never_answers_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_not_blocked_behind_tcp_only_socks", "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_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context", "tests/test_webrtc_realness.py::test_two_contexts_with_two_proxies_each_gets_the_srflx_of_its_own"], "marker": "e2e", "needs_root": false, "windows_twin"Line truncated
{"id": "wrapper.e2e.suite.linux.2", "giro": "G2", "os": ["linux"], "min_tests": 411, "exact": true, "tests": ["tests/test_a_click_waits_for_the_navigation_it_plans_e2e.py", "tests/test_a_context_init_script_runs_once_e2e.py", "tests/test_a_drag_keeps_its_buttons_pressed_e2e.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_goto_to_a_response_with_no_document_ends_e2e.py", "tests/test_a_keepalive_request_reaches_the_client_e2e.py", "tests/test_a_latin_letter_on_a_cyrillic_persona_e2e.py", "tests/test_a_page_cannot_probe_the_juggler_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_pointer_event_is_handled_before_the_call_returns_e2e.py", "tests/test_a_request_says_what_it_is_e2e.py", "tests/test_a_worker_comes_back_with_its_page_from_the_cache_e2e.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_isolated_page_and_the_next_e2e.py", "tests/test_bypass_csp_e2e.py", "tests/test_caller_world_handles_e2e.py", "tests/test_canvas_reads_as_drawn.py", "tests/test_canvas_render_stealth.py", "tests/test_context_locale_e2e.py", "tests/test_context_proxy_only_resolves_by_doh_e2e.py", "tests/test_doh_through_the_proxy_e2e.py", "tests/test_doh_under_stress_e2e.py", "tests/test_download_is_intercepted_e2e.py", "tests/test_drag_motion.py", "tests/test_expose_binding_e2e.py", "tests/test_fakeweb_p4_e2e.py", "tests/test_fingerprint_consistency.py", "tests/test_fission_frames_dialogs_downloads_popups_e2e.py", "tests/test_fission_frames_route_and_bindings_e2e.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fission_iframe_crash_e2e.py", "tests/test_fission_strategy1_bench.py", "tests/test_goto_to_the_same_url_e2e.py", "tests/test_http3_through_the_proxy_e2e.py", "tests/test_input_is_born_before_the_page_sees_it_e2e.py", "tests/test_juggler_actions.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py::test_a_javascript_that_THROWS_arrives_as_an_error_not_as_None", "tests/test_juggler_injected.py::test_actionability_DISTINGUISHES_instead_of_always_saying_yes", "tests/test_juggler_injected.py::test_reads_that_make_no_sense_are_REJECTED", "tests/test_juggler_injected.py::test_states_DISCRIMINATE_instead_of_always_saying_true", "tests/test_juggler_injected.py::test_the_DOM_READING_group", "tests/test_juggler_injected.py::test_the_selector_engines_respond", "tests/test_juggler_injected.py::test_the_text_reads", "tests/test_juggler_lifecycle_e2e.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_long_session_e2e.py", "tests/test_mouse.py", "tests/test_mouse_events_keep_their_values_e2e.py", "tests/test_new_page_defaults.py", "tests/test_popup_destinations_e2e.py", "tests/test_popup_pages.py", "tests/test_proxy_http_auth_e2e.py", "tests/test_proxy_reaches_the_browser.py", "tests/test_proxy_socks_auth_e2e.py", "tests/test_requestless_navigation.py", "tests/test_route_abort_code.py", "tests/test_route_e2e.py", "tests/test_route_post_data_e2e.py", "tests/test_route_sends_a_navigation_elsewhere_e2e.py", "tests/test_route_superseded_e2e.py", "tests/test_same_document_navigation.py", "tests/test_screenshot_of_text_returns_linux_e2e.py", "tests/test_scroll_into_view.py", "tests/test_scroll_only_if_needed_e2e.py", "tests/test_service_workers_blocked.py", "tests/test_set_input_files_payloads.py", "tests/test_software_compositing_is_declared_e2e.py", "tests/test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py", "tests/test_the_callers_code_runs_once_e2e.py", "tests/test_the_close_returns_when_the_browser_has_exited_e2e.py", "tests/test_the_favicon_stays_out_of_sight_e2e.py", "tests/test_the_font_list_is_the_bundle_e2e.py", "tests/test_the_parent_reads_the_bundle_from_fontconfig_s_cache_linux_e2e.py", "tests/test_the_scheme_is_the_personas_e2e.py", "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_typing_a_character_without_a_key_e2e.py", "tests/test_wait_for_timeout.py", "tests/test_web_fonts_of_closed_contexts_e2e.py"], "marker": "e2e", "needs_root": false, "windows_twin": "wrapper.e2e.suite.windows.2", "note": "Part 2 of the whole e2e suite of the wrapper (every test that opens the browser: what e2e.yml runs on the published engine), on the engine under test, as two passes through scripts/ci_suite_run.py (4 browsers at once, then the wall_clock tests alone; no rerun). The files of the 2 rows of linux are the files of tests/ that tests/test_the_e2e_suite_is_accounted_for.py holds one by one: a file whole when every test of it is here, else its tests by name. Partition from the junits of runs 44942540063 and 44985244053, test time balanced (about 564 s of estimated wall time, 4 browsers). A new file is added by hand to a row of each system and the minimum of the row goes up by hand. Left out of every row, with the reason in the accounting test: the files and tests of wrapLine truncated
+2 -1
View File
@@ -96,7 +96,8 @@ def _cores():
where = os.environ.get("INVPW_CORE_DIR")
if not where or not Path(where).is_dir():
return None, []
return Path(where), sorted((path for path in Path(where).glob("core*") if path.is_file()), key=lambda path: path.stat().st_mtime)
# A core of a background engine of the hunt (/tmp/ffbg-K, the executable's path is in the core's name) is read by the loop that owns it, never by the run's hooks.
return Path(where), sorted((path for path in Path(where).glob("core*") if path.is_file() and "!ffbg-" not in path.name), key=lambda path: path.stat().st_mtime)
def executable_of(core, command):
+31
View File
@@ -0,0 +1,31 @@
"""``FailureEvidence`` that also keeps a folder of extra files (the engine's own log of the launch, a lab server's record, a page's timeline).
The test writes whatever it wants to keep into ``evidence.files`` while it runs. When the body fails, the folder is copied next to the
rest of the evidence (``<evidence folder>/files/``) and ``meta.json`` lists it; when the body passes, it is deleted with the rest.
Nothing else differs from ``tests/_evidence_on_failure.py``.
"""
from __future__ import annotations
import json
import shutil
from _evidence_on_failure import FailureEvidence
class FailureEvidenceWithFiles(FailureEvidence):
def __init__(self, name: str):
super().__init__(name)
#: Under the helper's own temporary folder: removed with it when the body passes.
self.files = self.work / "files"
self.files.mkdir(parents=True, exist_ok=True)
def _save(self, exc_type, exc) -> None:
super()._save(exc_type, exc)
if self.saved_to is None or not self.files.exists():
return
shutil.copytree(self.files, self.saved_to / "files", dirs_exist_ok=True)
meta_path = self.saved_to / "meta.json"
meta = json.loads(meta_path.read_text(encoding="utf-8"))
meta["files"] = sorted(p.name for p in self.saved_to.iterdir())
meta["extra_files"] = sorted(str(p.relative_to(self.files)).replace("\\", "/") for p in self.files.rglob("*") if p.is_file())
meta_path.write_text(json.dumps(meta, indent=1), encoding="utf-8")
+141 -14
View File
@@ -7,6 +7,13 @@ later one read `h3` (retail Firefox 159, native DNS in loopback: h2, h3, h3; beh
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.
A client that has a QUIC handshake in progress toward the server is served its next TCP connection only once that handshake has ended (``_QuicFirst``): a real network completes
QUIC in 1 round trip and TCP+TLS in 2, and a browser takes the first connection that is ready.
It also keeps its own record of what it saw (``H3Server.record``, ``write_record``): per TCP connection its accept, the ALPN, every request
path and its end, per QUIC connection its first datagram, its handshake, every request and its end (with the reason), each with ``m``
(``time.perf_counter()`` of the test process) and ``t`` (``time.time()``). It only listens: no answer depends on it.
Needs `aioquic` and `h2` (pip install aioquic h2; the dev extra installs both).
"""
from __future__ import annotations
@@ -14,14 +21,17 @@ from __future__ import annotations
import asyncio
import datetime
import ipaddress
import itertools
import json
import socket
import socketserver
import ssl
import sys
import tempfile
import threading
import time
from pathlib import Path
from typing import List, Tuple
from typing import Dict, List, Tuple
from _ports import bind_tcp_and_hold_udp
@@ -50,6 +60,50 @@ def _certificate(address: str, directory: 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 _QuicFirst:
"""Keeps the order of a real network between the two connections a browser opens to one server: QUIC is ready after 1 round trip and TCP+TLS after 2, so the QUIC one is
taken. The Python QUIC server of the lab needs longer than TCP+TLS under load and would invert that. For a peer address that has a QUIC handshake in progress toward the
server, the TLS of a new TCP connection from that address waits until the handshake has ended. It waits for an event, never for a time: ``ended`` is called when the
handshake completes (the client has had its connection ready for a round trip by then), fails, or the connection terminates (the idle timeout is one of them), and
``release_all`` when the server closes. With no handshake in progress for the address nothing is held.
The residual case: a client that starts a QUIC handshake and vanishes without a CONNECTION_CLOSE leaves its handshake in progress, so the TCP connections of the same
IP are held until the QUIC idle timeout ends the connection (aioquic: 60 s by default, ``H3Server(quic_idle_timeout=...)``). A real network does not hold the TCP of a
client for that long, but a client of the lab that opens QUIC and goes away is not one a test of the lab depends on; it is measured, with the order asserted and not a
duration, in tests/test_the_h3_lab_server_lets_quic_finish_first.py."""
def __init__(self):
self._changed = threading.Condition()
self._in_progress: Dict[str, int] = {}
self._closed = False
def began(self, peer: str) -> None:
with self._changed:
self._in_progress[peer] = self._in_progress.get(peer, 0) + 1
def ended(self, peer: str) -> None:
with self._changed:
left = self._in_progress.get(peer, 0) - 1
if left > 0:
self._in_progress[peer] = left
else:
self._in_progress.pop(peer, None)
self._changed.notify_all()
def hold(self, peer: str, held: List[str]) -> None:
"""Returns at once when no QUIC handshake of ``peer`` is in progress; otherwise records the hold in ``held`` and returns when none is."""
with self._changed:
if peer not in self._in_progress or self._closed:
return
held.append(peer)
self._changed.wait_for(lambda: self._closed or peer not in self._in_progress)
def release_all(self) -> None:
with self._changed:
self._closed = True
self._changed.notify_all()
class _TcpServer(socketserver.ThreadingTCPServer):
# On Windows SO_REUSEADDR is "share the port": with a number the picker drew (tests/_ports.py) it would bind over a listener that is there.
allow_reuse_address = sys.platform != "win32"
@@ -71,29 +125,36 @@ class _TcpHandler(socketserver.BaseRequestHandler):
def handle(self):
owner = self.server.owner
cid = "tcp-%d" % next(owner._ids)
owner.note("tcp_accept", conn=cid, peer=list(self.client_address[:2]))
reason = "handler ended"
try:
owner._quic_first.hold(self.client_address[0], owner.tcp_held)
self.request.settimeout(10)
tls = owner._tls.wrap_socket(self.request, server_side=True)
except (ssl.SSLError, OSError):
except (ssl.SSLError, OSError) as exc:
owner.note("tcp_handshake_failed", conn=cid, error=repr(exc))
return
try:
tls.settimeout(60)
alpn = tls.selected_alpn_protocol() or "http/1.1"
owner.tcp_alpn.append(alpn)
owner.note("tcp_handshake_done", conn=cid, alpn=alpn)
if alpn == "h2":
self._h2(tls, owner)
reason = self._h2(tls, owner, cid)
else:
self._http1(tls, owner)
except (ssl.SSLError, OSError):
pass
reason = self._http1(tls, owner, cid)
except (ssl.SSLError, OSError) as exc:
reason = "error: %r" % (exc,)
finally:
owner.note("tcp_close", conn=cid, reason=reason)
try:
tls.close()
except OSError:
pass
@staticmethod
def _h2(tls, owner):
def _h2(tls, owner, cid):
import h2.config
import h2.connection
import h2.events
@@ -105,15 +166,16 @@ class _TcpHandler(socketserver.BaseRequestHandler):
while True:
data = tls.recv(65536)
if not data:
return
return "the client closed the connection (EOF)"
try:
events = conn.receive_data(data)
except h2.exceptions.ProtocolError:
except h2.exceptions.ProtocolError as exc:
tls.sendall(conn.data_to_send())
return
return "h2 protocol error: %r" % (exc,)
for event in events:
if isinstance(event, h2.events.RequestReceived):
owner.tcp_requests.append(dict(event.headers).get(":path", ""))
owner.note("tcp_request", conn=cid, stream=event.stream_id, path=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),
@@ -122,13 +184,13 @@ class _TcpHandler(socketserver.BaseRequestHandler):
elif isinstance(event, h2.events.DataReceived):
conn.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
elif isinstance(event, h2.events.ConnectionTerminated):
return
return "h2 GOAWAY from the client (error code %s)" % (event.error_code,)
out = conn.data_to_send()
if out:
tls.sendall(out)
@staticmethod
def _http1(tls, owner):
def _http1(tls, owner, cid):
head = b""
while b"\r\n\r\n" not in head:
chunk = tls.recv(4096)
@@ -140,18 +202,20 @@ class _TcpHandler(socketserver.BaseRequestHandler):
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))
return "answered, Connection: close"
class H3Server:
"""TCP+TLS (HTTP/2) and QUIC (HTTP/3) on one port of `address`."""
def __init__(self, address: str):
def __init__(self, address: str, quic_idle_timeout: float = None):
"""``quic_idle_timeout`` (seconds) is the QUIC idle timeout of the server; None keeps aioquic's default (60 s)."""
from aioquic.asyncio.protocol import QuicConnectionProtocol
from aioquic.asyncio.server import QuicServer
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
from aioquic.quic.events import ConnectionTerminated, HandshakeCompleted, ProtocolNegotiated
self.address = address
#: The address each QUIC connection came from.
@@ -164,6 +228,12 @@ class H3Server:
self.tcp_requests: List[str] = []
#: The ALPN each TCP connection negotiated ("h2", or "http/1.1").
self.tcp_alpn: List[str] = []
#: The peer address of each TCP connection whose TLS was held until a QUIC handshake of that address had ended (see ``_QuicFirst``).
self.tcp_held: List[str] = []
self._quic_first = _QuicFirst()
#: The server's own record of what it saw, in order (``note``): a list of dicts, each with ``m``, ``t`` and ``kind``.
self.record: List[dict] = []
self._ids = itertools.count(1)
self._dir = tempfile.TemporaryDirectory()
cert, key = _certificate(address, Path(self._dir.name))
@@ -186,8 +256,47 @@ class H3Server:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._http = None
#: The address whose handshake this connection holds open in ``_quic_first``; None before its first datagram and once the handshake has ended.
self._handshaking = None
self._began = False
self._cid = "quic-%d" % next(server._ids)
self._datagrams = 0
self._last_datagram_m = None
def datagram_received(self, data, addr):
self._datagrams += 1
self._last_datagram_m = round(time.perf_counter(), 6)
if self._datagrams == 1:
server.note("quic_first_datagram", conn=self._cid, peer=list(addr[:2]), bytes=len(data))
# The first datagram of a peer is the start of its handshake: it is registered before the server answers it.
if not self._began:
self._began = True
self._handshaking = addr[0]
server._quic_first.began(addr[0])
super().datagram_received(data, addr)
# A close (the peer's, or ours after a failed handshake) ends the handshake before the event of the end of the connection.
if self._quic._close_event is not None:
self._handshake_ended()
def _handshake_ended(self):
if self._handshaking is not None:
peer, self._handshaking = self._handshaking, None
server._quic_first.ended(peer)
def quic_event_received(self, event):
if isinstance(event, (HandshakeCompleted, ConnectionTerminated)):
self._handshake_ended()
kind = type(event).__name__
if isinstance(event, ProtocolNegotiated):
server.note("quic_protocol_negotiated", conn=self._cid, alpn=event.alpn_protocol, datagrams=self._datagrams)
elif kind == "HandshakeCompleted":
server.note("quic_handshake_done", conn=self._cid, alpn=getattr(event, "alpn_protocol", None),
datagrams=self._datagrams)
elif kind == "ConnectionTerminated":
server.note("quic_close", conn=self._cid, error_code=event.error_code, frame_type=event.frame_type,
reason=event.reason_phrase, datagrams=self._datagrams, last_datagram_m=self._last_datagram_m)
elif kind == "StreamReset":
server.note("quic_stream_reset", conn=self._cid, stream=event.stream_id, error_code=event.error_code)
if isinstance(event, ProtocolNegotiated):
self._http = H3Connection(self._quic)
peer = self._quic._network_paths[0].addr
@@ -198,6 +307,7 @@ class H3Server:
if isinstance(http_event, HeadersReceived):
headers = dict(http_event.headers)
server.h3_requests.append(headers.get(b":path", b"").decode())
server.note("quic_request", conn=self._cid, stream=http_event.stream_id, path=server.h3_requests[-1])
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"*")])
@@ -205,6 +315,8 @@ class H3Server:
self.transmit()
configuration = QuicConfiguration(is_client=False, alpn_protocols=H3_ALPN)
if quic_idle_timeout is not None:
configuration.idle_timeout = quic_idle_timeout
configuration.load_cert_chain(str(cert), str(key))
self._loop = asyncio.new_event_loop()
started = threading.Event()
@@ -236,7 +348,22 @@ class H3Server:
def url(self) -> str:
return "https://%s:%d/" % (self.address, self.port)
def note(self, kind: str, **fields) -> None:
"""One line of the server's record: ``m`` is ``time.perf_counter()`` of this process, ``t`` the wall clock. Never raises."""
try:
self.record.append({"m": round(time.perf_counter(), 6), "t": round(time.time(), 4), "kind": kind, **fields})
except Exception:
pass
def write_record(self, path) -> None:
"""The record as JSON lines (what the failure evidence of a test keeps)."""
with open(path, "w", encoding="utf-8") as out:
for line in list(self.record):
out.write(json.dumps(line, default=str) + "\n")
def close(self) -> None:
self._quic_first.release_all()
self.note("server_close", quic_connections=len(self.quic_peers), tcp_connections=len(self.tcp_alpn))
self._tcp.shutdown()
self._tcp.server_close()
if not self._loop.is_closed():
+165
View File
@@ -0,0 +1,165 @@
"""A passive listener on the mDNS group (224.0.0.251, UDP 5353): what the lab heard of the engine's responder, packet by packet.
Failure evidence of ``tests/test_declared_host_network_e2e.py``. The engine's responder (dom/media/webrtc/transport/mdns_service/src/lib.rs) is
not heard in a release build: its ``trace!`` lines are compiled out (``release_max_level_info``), so the lab listens to the group itself.
IT ONLY LISTENS. It never sends a packet, never answers, never sets a multicast interface or the loop flag (those are the sender's), and it never raises:
every refusal (a bind, a join, a read, a parse) is written into its own record and the test goes on unchanged.
HOW IT BINDS, against the engine's own socket (lib.rs:124-135): the engine makes a UDP socket with SO_REUSEADDR, SO_REUSEPORT where the system has it
(not on Windows) and binds 0.0.0.0:5353. Both sockets here set the same options, so two sockets share the port and each receives every datagram sent
to the group, and the listener takes nothing from the engine:
* Linux: SO_REUSEADDR and SO_REUSEPORT, bound to the group address 224.0.0.251:5353. A socket bound to a multicast address receives only datagrams
addressed to that group, never a unicast one, so it cannot take a datagram that was meant for the engine's wildcard socket.
* Windows: SO_REUSEADDR, bound to 0.0.0.0:5353 (a multicast address cannot be bound there). The listener is started BEFORE the browser is launched, so the
engine's socket is the later one: Windows gives a unicast datagram to the socket bound last, and the engine's responder sends and answers on the group
address only (lib.rs: ``send_to(&buf, mdns_addr)``).
It joins the group on the interfaces the engine joins on: ``mdns_service_start`` is given ``nr_stealth_mdns_interfaces()``, which is ``"127.0.0.1;"``
(dom/media/webrtc/transport/nr_stealth_network.cpp:229), and the engine joins each address it is given (lib.rs:138-145) and sends through the first
(lib.rs:150-153). So the listener joins on 127.0.0.1 and nothing else.
The record (``write``): JSON lines, the first line ``{"kind": "listener", ...}`` (how the bind and the join went, and the packet counts), then one
line per packet: ``m`` (``time.perf_counter()`` of the test process, the scale of the page timeline once joined by the launch's ``started_m``), ``t`` (wall
clock), ``src`` ([address, port]), ``bytes``, ``kind`` (``query``, ``response`` or ``unparsed``), ``id``, ``questions`` ([{name, type, unicast_bit}]) and
``answers`` ([{name, type, ttl, data}]) as read by a minimal DNS parse.
"""
from __future__ import annotations
import ipaddress
import json
import socket
import struct
import sys
import threading
import time
GROUP = "224.0.0.251"
#: The engine's group, and the one interface it joins on (nr_stealth_mdns_interfaces).
MDNS_ADDRESS = (GROUP, 5353)
JOIN_INTERFACE = "127.0.0.1"
_TYPES = {1: "A", 12: "PTR", 16: "TXT", 28: "AAAA", 33: "SRV", 255: "ANY"}
def _name(data: bytes, offset: int, depth: int = 0):
"""The domain name at ``offset`` (compression followed) and the offset after it in the record the name started in."""
labels, end, jumped = [], None, False
while True:
if offset >= len(data) or depth > 20:
raise ValueError("name out of range")
length = data[offset]
if length == 0:
offset += 1
break
if length & 0xC0 == 0xC0:
pointer = ((length & 0x3F) << 8) | data[offset + 1]
if end is None:
end = offset + 2
offset, jumped, depth = pointer, True, depth + 1
continue
labels.append(data[offset + 1: offset + 1 + length].decode("utf-8", "replace"))
offset += 1 + length
return ".".join(labels), (end if jumped else offset)
def parse(data: bytes) -> dict:
"""A DNS message, minimally: its id, whether it is a query or a response, the questions and the answers."""
identifier, flags, qd, an, ns, ar = struct.unpack("!6H", data[:12])
out = {"id": identifier, "kind": "response" if flags & 0x8000 else "query", "counts": [qd, an, ns, ar], "questions": [], "answers": []}
offset = 12
for _ in range(qd):
name, offset = _name(data, offset)
qtype, qclass = struct.unpack("!HH", data[offset: offset + 4])
offset += 4
out["questions"].append({"name": name, "type": _TYPES.get(qtype, qtype), "unicast_bit": bool(qclass & 0x8000)})
for _ in range(an + ns + ar):
name, offset = _name(data, offset)
rtype, _rclass, ttl, length = struct.unpack("!HHIH", data[offset: offset + 10])
offset += 10
raw = data[offset: offset + length]
if rtype == 1 and length == 4:
value = str(ipaddress.IPv4Address(raw))
elif rtype == 28 and length == 16:
value = str(ipaddress.IPv6Address(raw))
else:
value = raw.hex()
out["answers"].append({"name": name, "type": _TYPES.get(rtype, rtype), "ttl": ttl, "data": value})
offset += length
return out
class MdnsListener:
def __init__(self):
self.packets = []
#: What happened to the listener itself: the bind, the join, a read or a parse that failed. Never raised.
self.status = []
self._socket = None
self._thread = None
self._stop = threading.Event()
def start(self) -> "MdnsListener":
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if sys.platform != "win32" and hasattr(socket, "SO_REUSEPORT"):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
sock.bind((GROUP if sys.platform != "win32" else "0.0.0.0", MDNS_ADDRESS[1]))
self.status.append({"what": "bound", "address": sock.getsockname()[0], "port": sock.getsockname()[1]})
except Exception as exc:
self.status.append({"what": "bind failed: the listener hears nothing", "error": repr(exc)})
return self
try:
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(GROUP) + socket.inet_aton(JOIN_INTERFACE))
self.status.append({"what": "joined", "group": GROUP, "interface": JOIN_INTERFACE})
except Exception as exc:
self.status.append({"what": "join failed", "group": GROUP, "interface": JOIN_INTERFACE, "error": repr(exc)})
try:
sock.settimeout(0.2)
self._socket = sock
self._thread = threading.Thread(target=self._run, name="mdns-listener", daemon=True)
self._thread.start()
except Exception as exc:
self.status.append({"what": "no reader thread", "error": repr(exc)})
return self
def _run(self) -> None:
sock = self._socket
while not self._stop.is_set():
try:
data, source = sock.recvfrom(9000)
except socket.timeout:
continue
except Exception as exc:
if not self._stop.is_set():
self.status.append({"what": "read failed: the listener stops", "error": repr(exc)})
return
record = {"m": round(time.perf_counter(), 6), "t": round(time.time(), 4), "src": [source[0], source[1]], "bytes": len(data)}
try:
record.update(parse(data))
except Exception as exc:
record.update(kind="unparsed", error=repr(exc), hex=data[:64].hex())
self.packets.append(record)
def stop(self) -> None:
self._stop.set()
try:
if self._socket is not None:
self._socket.close()
except Exception:
pass
if self._thread is not None:
self._thread.join()
def summary(self) -> dict:
kinds = {}
for packet in list(self.packets):
kinds[packet["kind"]] = kinds.get(packet["kind"], 0) + 1
return {"packets": len(self.packets), "by_kind": kinds, "status": list(self.status)}
def write(self, path) -> None:
with open(path, "w", encoding="utf-8") as out:
out.write(json.dumps(dict(kind="listener", group=GROUP, join_interface=JOIN_INTERFACE, **self.summary()), default=str) + "\n")
for packet in list(self.packets):
out.write(json.dumps(packet, default=str) + "\n")
+11
View File
@@ -12,6 +12,11 @@ def _landing(url: str) -> str:
_SENT: dict = {}
#: An optional hook for the evidence a failing test leaves: called as ``note(what, **fields)`` where `_goto` sends, hears the answer and hears the error.
#: The test module sets it; it only listens and changes no wait or assertion.
note = None
def forget(page) -> None:
_SENT.pop(id(page), None)
@@ -38,10 +43,16 @@ def _goto(page, url, *, the_page_before_may_move, our_page_may_stop_ours, **kwar
from invisible_playwright.sync_api import Error
before = _SENT.get(id(page), frozenset()) if the_page_before_may_move else frozenset()
if note:
note("goto", url=url, before=sorted(before))
try:
page.goto(url, **kwargs)
if note:
note("goto-answered", url=url)
except Error as e:
text = str(e)
if note:
note("goto-raised", url=url, error=text[:300])
if "NS_BINDING_ABORTED" in text:
ends = tuple(_landing(u) for u in sorted(before | ({url} if our_page_may_stop_ours else frozenset())))
assert ends, e
+67 -4
View File
@@ -22,6 +22,8 @@ User: alice / secret.
import html
import json
import secrets
import select
import socket
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -31,6 +33,8 @@ from urllib.parse import parse_qs, urlencode, urlsplit
from fakeweb import sites
CACHE_PAGES = "no-cache"
#: Most records kept per start(): a long run of the site is not a memory leak.
MAX_RECORDS = 50000
STATE = None # the State of the running site (set by start): the walk tells it the current step
USER, PASSWORD = "alice", "secret"
N_ARTICLES = 30
@@ -365,6 +369,17 @@ class State:
self.walk = 0
self.cond = threading.Condition()
self.released = set()
#: What the server itself saw, in order, for a test that saves it when it fails (`start(...)[2].state.records`; nothing else reads
#: it): one `accept` per TCP connection and one `request` per request, with `time.perf_counter()` of this process as `m_*` (the
#: scale of the client's log) and `time.time()` as `t_*`; for a held request (`/hold`) also when the hold began and ended, why
#: it ended, and when the server first saw the browser's end of the connection closed.
self.records = []
def note(self, record):
with self.lock:
if len(self.records) < MAX_RECORDS:
self.records.append(record)
return record
def set_step(self, n):
with self.cond:
@@ -388,13 +403,17 @@ class State:
self.released.add(rid)
self.cond.notify_all()
def hold(self, rid, until=0, failsafe=90.0):
def hold(self, rid, until=0, failsafe=90.0, watch=None):
"""Block until /release?id=rid arrives, or the walk reaches step `until`; the failsafe only
keeps a lost event from blocking a thread forever."""
keeps a lost event from blocking a thread forever. Returns why it ended (`released`, `step`, `failsafe`);
`watch`, if given, is called every half second while waiting (it only looks)."""
end = time.time() + failsafe
with self.cond:
while rid not in self.released and not (until and self.step >= until) and time.time() < end:
self.cond.wait(0.5)
if watch is not None:
watch()
return "released" if rid in self.released else "step" if (until and self.step >= until) else "failsafe"
def record(self, idx, method, path, q):
"""Server-side log: what the server saw, tagged with the walk step that was current."""
@@ -425,6 +444,11 @@ class Site(ThreadingHTTPServer):
self.idx = idx
self.state = state
def process_request(self, request, client_address):
self.state.note({"ev": "accept", "t": round(time.time(), 4), "m": round(time.perf_counter(), 6), "site": self.idx,
"peer": client_address[1]})
super().process_request(request, client_address)
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
@@ -451,6 +475,11 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers()
if body and self.command != "HEAD":
self.wfile.write(body)
rec = getattr(self, "_rec", None)
if rec is not None:
rec["status"] = code
rec["t_answer"] = round(time.time(), 4)
rec["m_answer"] = round(time.perf_counter(), 6)
def _html(self, text, code=200, headers=()):
self._send(code, "text/html; charset=utf-8", text.encode(), headers, cache=CACHE_PAGES)
@@ -460,10 +489,32 @@ class Handler(BaseHTTPRequestHandler):
def _guard(self, fn):
# Browsers abort requests on purpose; a dropped socket is not an error here.
state = self.server.state
rec = self._rec = state.note({
"ev": "request", "t_arrive": round(time.time(), 4), "m_arrive": round(time.perf_counter(), 6), "site": self.server.idx,
"peer": self.client_address[1], "method": self.command, "path": self.path, "walk": state.walk, "step": state.step,
"status": None, "t_answer": None, "m_answer": None, "t_done": None, "m_done": None, "error": None})
try:
fn()
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, TimeoutError):
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, TimeoutError) as exc:
rec["error"] = type(exc).__name__
self.close_connection = True
except BaseException as exc:
rec["error"] = type(exc).__name__
raise
finally:
rec["t_done"] = round(time.time(), 4)
rec["m_done"] = round(time.perf_counter(), 6)
def _peer_closed(self):
"""Whether the browser has closed its end of this connection (a peek: nothing is read from it)."""
try:
readable, _w, _x = select.select([self.connection], [], [], 0)
return bool(readable) and self.connection.recv(1, socket.MSG_PEEK) == b""
except (BlockingIOError, InterruptedError):
return False
except (OSError, ValueError):
return True
def do_GET(self):
self._guard(self._get)
@@ -570,7 +621,18 @@ class Handler(BaseHTTPRequestHandler):
return self._send(200, "text/plain", b"ok", cache="no-store")
if p == "/hold":
until = int(q.get("until", ["0"])[0] or 0)
self.server.state.hold(q.get("id", [""])[0], until)
rec = self._rec
def watch():
if rec.get("m_peer_closed_seen") is None and self._peer_closed():
rec["t_peer_closed_seen"] = round(time.time(), 4)
rec["m_peer_closed_seen"] = round(time.perf_counter(), 6)
rec["t_hold_start"], rec["m_hold_start"] = round(time.time(), 4), round(time.perf_counter(), 6)
rec["hold_until_step"], rec["m_peer_closed_seen"] = until, None
rec["hold_ended_by"] = self.server.state.hold(q.get("id", [""])[0], until, watch=watch)
rec["t_hold_end"], rec["m_hold_end"], rec["step_at_hold_end"] = round(time.time(), 4), round(time.perf_counter(), 6), self.server.state.step
watch()
return self._send(200, "application/json", b'{"held":true}', cache="no-store")
if p == "/stream":
# headers and 10 of 20 body bytes at once; the rest after a short wait
@@ -635,6 +697,7 @@ def start(ports=(8321, 8322), bind="127.0.0.1", public_host="127.0.0.1", other_h
s.shutdown()
s.server_close()
stop.state = state # the server's own record (`state.records`), kept after stop()
global STATE
STATE = state
return state.origins[0], state.origins[1], stop
+183 -7
View File
@@ -8,6 +8,8 @@ verdict is "same outcome as stock".
"""
from __future__ import annotations
import json
import re
import time
BLOCKED = ("image", "media")
@@ -17,8 +19,9 @@ def install_route(context):
context.route("**/*", lambda route: route.abort() if route.request.resource_type in BLOCKED else route.continue_())
def navigate(page, url, *, idle_timeout_ms, client_log=None):
"""`client_log`, a list (default None: nothing kept), gets one entry per event the client heard (wall time `t`, time.time(), and `m`, time.perf_counter()):
def navigate(page, url, *, idle_timeout_ms, client_log=None, lifecycle_probe=None):
"""`lifecycle_probe`, a function (default None: nothing), is called the moment the wait for networkidle expires and its answer is kept in `lifecycle_open`
of the cell (`lifecycle_open_requests`). `client_log`, a list (default None: nothing kept), gets one entry per event the client heard (wall time `t`, time.time(), and `m`, time.perf_counter()):
the navigation's start and end, and every request, its response and its end. A test that saves evidence when it fails passes it."""
rec = {"idle": False, "err": None, "seconds": None}
# The requests the client has heard of and not yet heard the end of: a navigation that does not idle says who is still in flight
@@ -64,7 +67,15 @@ def navigate(page, url, *, idle_timeout_ms, client_log=None):
except Exception as exc: # recorded, the run goes on: the verdict compares outcomes
text = str(exc).strip()
rec["err"] = (text.splitlines()[0] if text else repr(exc))[:200]
rec["in_flight"] = list(open_requests.values())[:30]
# First thing at the expiry, before anything else is read: what the served browser's own lifecycle holds as open is what keeps networkidle away.
if lifecycle_probe is not None:
rec["expired_at"] = {"t": round(time.time(), 4), "m": round(time.perf_counter(), 6)}
try:
rec["lifecycle_open"] = lifecycle_probe()
except Exception as problem: # the evidence never changes the outcome it is about
rec["lifecycle_open"] = [{"error": repr(problem)}]
# The WHOLE list, not a head of it: what is left open is the question.
rec["in_flight"] = list(open_requests.values())
finally:
for event, handler in (("request", started), ("response", answered), ("requestfinished", ended), ("requestfailed", ended)):
try:
@@ -76,7 +87,168 @@ def navigate(page, url, *, idle_timeout_ms, client_log=None):
return rec
def drive(browser, origin, patterns, repetitions, idle_timeout_ms=10000, client_log=None):
def lifecycle_open_requests(server):
"""What the in-process server of a served browser (`launch_server()`) holds as OPEN, per page: the lifecycle's own map of the requests it waits the end of
(`Lifecycle._open`: request id -> (owner frame, navigation)), each with what the lifecycle knows of its owner frame, and the frame tree. A client cannot
read it: the test reaches the lifecycle through the registry of the server (`RemoteServer._endpoint.server._objects`, whose `Page` objects are the
`PageDispatcher`s, each with its `lifecycle`). Read-only; the lifecycle's lock is taken for at most two seconds, and the dump says when it was not."""
pages = []
for obj in list(server._endpoint.server._objects.values()):
if getattr(obj, "TYPE", None) != "Page":
continue
try:
lifecycle = obj.lifecycle
except Exception:
continue
locked = lifecycle._cv.acquire(timeout=2)
try:
frames = dict(lifecycle.frames)
held = list(lifecycle._open.items())
main = lifecycle.main_frame
tree = lifecycle.frame_tree()
finally:
if locked:
lifecycle._cv.release()
opened = []
for rid, (owner, navigation) in held:
frame = frames.get(owner or main)
opened.append({"rid": rid, "owner": owner, "navigation": navigation, "owner_is_known": (owner in frames) if owner else None,
"owner_url": frame.url if frame else None, "owner_parent": frame.parent if frame else None,
"owner_navigation": frame.navigation if frame else None, "owner_states": sorted(frame.states) if frame else None})
pages.append({"page": obj.guid, "main_frame": main, "lock_taken": locked, "open": opened, "frame_tree": tree})
return pages
# ---- the history of the requests still open, read from the Juggler wire (tests/_evidence_on_failure.py writes it) -----------------------------------
#: The commands that answer an intercepted request, and the events of a frame that matter around a request of it.
INTERCEPT_COMMANDS = ("Network.resumeInterceptedRequest", "Network.abortInterceptedRequest", "Network.fulfillInterceptedRequest")
FRAME_EVENTS = ("Page.frameAttached", "Page.frameDetached", "Page.navigationStarted", "Page.navigationCommitted", "Page.navigationAborted",
"Page.sameDocumentNavigation")
#: Seconds of a frame's events kept before a request and after it.
FRAME_WINDOW = (1.0, 20.0)
_FIELDS = ("requestId", "frameId", "url", "navigationId", "errorCode")
def _string_field(text, name):
found = re.search(r'"%s"\s*:\s*"((?:[^"\\]|\\.)*)"' % name, text)
return found.group(1) if found else None
def _wire_events(lines):
"""The records of the wire log (one JSON per line) as events: time, direction and the message; a message the log cut is read from the fields it still shows."""
events = []
for line in lines:
try:
record = json.loads(line)
except ValueError:
continue
text = record.get("msg") or ""
try:
msg = json.loads(text)
except ValueError:
msg = None
if not isinstance(msg, dict):
number = re.search(r'"id"\s*:\s*(\d+)', text)
msg = {"method": _string_field(text, "method"), "id": int(number.group(1)) if number else None,
"params": {name: _string_field(text, name) for name in _FIELDS}, "_cut": True}
events.append({"t": record.get("t"), "m": record.get("m"), "dir": record.get("dir") or "", "msg": msg})
return events
def _brief(msg, *names):
params = msg.get("params") or {}
return " ".join("%s=%s" % (n, params.get(n)) for n in names if params.get(n) is not None)
def open_requests_history(wire_lines, cells):
"""The text of `p2-open-requests-history.txt`: for each request id the lifecycle held open when a wait for networkidle expired (the `lifecycle_open` of
the cells), in time order, what the Juggler wire says of it: `requestWillBeSent` (frame, interception, address, navigation), each command that answered
the interception and its reply, `responseReceived`, `requestFinished` or `requestFailed` if any, and, around it, the `Page` events of its frame
(frameAttached/Detached, navigationStarted/Committed/Aborted): the history that says who ended it and who did not."""
events = _wire_events(wire_lines)
wanted = {}
for cell in cells or []:
for page in cell.get("lifecycle_open") or []:
for entry in page.get("open") or []:
wanted.setdefault(entry["rid"], []).append((cell, entry))
out = ["The requests the served browser's lifecycle held open when the wait for networkidle expired, and what the Juggler wire says of each.",
"t: wall clock (seconds since the epoch), m: perf_counter of the test process, +s: seconds from the request's requestWillBeSent. Around a request "
"the events of its frame are kept from %.0f s before to %.0f s after. A message longer than the wire log's limit is read from the fields "
"still readable (cut)." % FRAME_WINDOW, ""]
if not wanted:
out.append("No request was held open at an expiry (no cell was not idle, or the lifecycle could not be read).")
return "\n".join(out) + "\n"
by_request, replies = {}, {}
for ev in events:
msg = ev["msg"]
method = msg.get("method")
params = msg.get("params") if isinstance(msg.get("params"), dict) else {}
rid = params.get("requestId")
if rid is not None and method and method.startswith("Network."):
by_request.setdefault(rid, []).append(ev)
elif not method and msg.get("id") is not None and ev["dir"] == "in":
replies.setdefault(msg["id"], []).append(ev)
def line(ev, base, text):
t = ev["t"]
after = (" (+%.3fs)" % (t - base)) if (t is not None and base is not None) else ""
return " t=%s m=%s %s%s %s" % (t, ev["m"], ev["dir"].ljust(3), after, text)
def first_expiry(rid):
return min(((c.get("expired_at") or {}).get("t") or 0) for c, _e in wanted[rid])
for rid in sorted(wanted, key=first_expiry):
out.append("== request %s" % rid)
for cell, entry in wanted[rid]:
expired = cell.get("expired_at") or {}
out.append(" open at the expiry of round %s %s%s (t=%s m=%s): owner frame %s (known to the lifecycle: %s, url %s, its navigation %s, states %s), "
"the request's navigation %s" % (cell.get("round"), cell.get("pattern"), " (canary)" if cell.get("canary") else "",
expired.get("t"), expired.get("m"), entry.get("owner"), entry.get("owner_is_known"),
entry.get("owner_url"), entry.get("owner_navigation"), entry.get("owner_states"),
entry.get("navigation")))
mine = by_request.get(rid, [])
sent = [ev for ev in mine if ev["msg"].get("method") == "Network.requestWillBeSent"]
base = sent[0]["t"] if sent else None
frame = None
if not mine:
out.append(" not on the wire: its requestWillBeSent came before the wire was logged, or from another connection")
for ev in mine:
msg = ev["msg"]
method = msg["method"]
if method == "Network.requestWillBeSent":
frame = frame or (msg.get("params") or {}).get("frameId")
out.append(line(ev, base, "requestWillBeSent %s%s" % (_brief(msg, "frameId", "isIntercepted", "navigationId", "redirectedFrom", "method", "url"),
" (cut)" if msg.get("_cut") else "")))
elif method in INTERCEPT_COMMANDS:
out.append(line(ev, base, "%s sent, id=%s %s" % (method.split(".")[1], msg.get("id"), _brief(msg, "requestId"))))
answers = replies.get(msg.get("id"), [])
for reply in answers:
body = reply["msg"]
verdict = ("error " + json.dumps(body.get("error"), default=str)[:300]) if body.get("error") else "ok"
out.append(line(reply, base, " reply to id=%s: %s" % (msg.get("id"), verdict)))
if not answers:
out.append(" no reply to id=%s on the wire" % msg.get("id"))
else:
out.append(line(ev, base, "%s %s" % (method.split(".")[1], _brief(msg, "errorCode", "url"))))
if mine and not [ev for ev in mine if ev["msg"].get("method") in ("Network.requestFinished", "Network.requestFailed")]:
out.append(" no requestFinished or requestFailed for it on the wire")
if frame is not None and base is not None:
out.append(" events of its frame %s, %.0f s before to %.0f s after the request:" % ((frame,) + FRAME_WINDOW))
shown = 0
for ev in events:
msg = ev["msg"]
params = msg.get("params") if isinstance(msg.get("params"), dict) else {}
if msg.get("method") in FRAME_EVENTS and params.get("frameId") == frame and ev["t"] is not None \
and base - FRAME_WINDOW[0] <= ev["t"] <= base + FRAME_WINDOW[1]:
shown += 1
out.append(line(ev, base, "%s %s" % (msg["method"].split(".")[1], _brief(msg, "navigationId", "url", "parentFrameId", "errorText"))))
if not shown:
out.append(" none")
out.append("")
return "\n".join(out) + "\n"
def drive(browser, origin, patterns, repetitions, idle_timeout_ms=10000, client_log=None, lifecycle_probe=None):
"""Every pattern `repetitions` times, each followed by the canary. Returns a list of cells."""
cells = []
context = browser.new_context()
@@ -86,7 +258,8 @@ def drive(browser, origin, patterns, repetitions, idle_timeout_ms=10000, client_
for rep in range(1, repetitions + 1):
for name in patterns:
for pattern, canary in ((name, False), ("quiet", True)):
cell = navigate(page, "%s/p/%s" % (origin, pattern), idle_timeout_ms=idle_timeout_ms, client_log=client_log)
cell = navigate(page, "%s/p/%s" % (origin, pattern), idle_timeout_ms=idle_timeout_ms, client_log=client_log,
lifecycle_probe=lifecycle_probe)
cell.update(round=rep, pattern=pattern, canary=canary, after=name if canary else None)
cells.append(cell)
finally:
@@ -97,11 +270,14 @@ def drive(browser, origin, patterns, repetitions, idle_timeout_ms=10000, client_
return cells
def run_on_candidate(sync_playwright, binary, origin, patterns, repetitions, **kw):
"""Our engine, served over the Playwright WebSocket and driven by the stock client."""
def run_on_candidate(sync_playwright, binary, origin, patterns, repetitions, lifecycle_dump=False, **kw):
"""Our engine, served over the Playwright WebSocket and driven by the stock client. With `lifecycle_dump`, a cell that does not idle keeps what the
server's lifecycle held open when its wait expired (`lifecycle_open_requests`)."""
from invisible_playwright._juggler.remote import launch_server
server = launch_server(headless=True, binary_path=binary, locale="en-US", timezone="Europe/Rome")
if lifecycle_dump:
kw["lifecycle_probe"] = lambda: lifecycle_open_requests(server)
try:
with sync_playwright() as p:
browser = p.firefox.connect(server.ws_endpoint)
+92 -8
View File
@@ -30,32 +30,98 @@ def install_route(context):
class Tracer:
"""The requests the client has heard of and not yet heard the end of (kept for the report; never compared). With
`events` (the runner's --trace) it also keeps every request event the client reports, per step, for the request-type check."""
`events` (the runner's --trace) it also keeps every request event the client reports, per step, for the request-type check.
With `log` (a list; a test that saves evidence when it fails gives it) it keeps, apart from that, one entry per event the client
hears (request, response, requestfinished, requestfailed, and the page's own framenavigated / domcontentloaded / load), each with
the step the walk is in (`self.step`, set by the walk), its wall time `t` and `time.perf_counter()` as `m`; it only listens."""
def __init__(self, context, events=False):
def __init__(self, context, events=False, log=None):
self.open = {}
self.events = [] if events else None
self.t0 = time.monotonic()
self.log = log
self.step = 0
self.detail = {}
context.on("request", self._started)
context.on("requestfinished", lambda r: self._ended(r, "finished"))
context.on("requestfailed", lambda r: self._ended(r, "failed"))
if log is not None:
context.on("response", self._answered)
context.on("page", self._page_opened)
def _started(self, r):
self.open[r] = "%s %s" % (r.resource_type, r.url.split("/", 3)[-1][:70])
self._event(r, "request")
entry = self._logged(r, "request")
if entry is not None:
self.detail[r] = {k: entry[k] for k in ("step", "m", "type", "method", "url", "frame")}
def _ended(self, r, kind):
self.open.pop(r, None)
self.detail.pop(r, None)
self._event(r, kind)
more = {}
if kind == "failed" and self.log is not None:
try:
more["failure"] = str(r.failure)[:200]
except Exception:
more["failure"] = None
self._logged(r, "requestfinished" if kind == "finished" else "requestfailed", **more)
def _event(self, r, kind):
if self.events is not None:
self.events.append({"ev": kind, "type": r.resource_type, "method": r.method,
"url": "/" + r.url.split("/", 3)[-1][:90], "t": round(time.monotonic() - self.t0, 3)})
def _logged(self, r, kind, **more):
"""One entry of the log; a failure of the recording is never the client's (the walk goes on, the entry is missing)."""
if self.log is None:
return None
try:
try:
frame = r.frame.url[:160]
except Exception:
frame = None
entry = {"ev": kind, "step": self.step, "t": round(time.time(), 4), "m": round(time.perf_counter(), 6), "req": id(r),
"type": r.resource_type, "method": r.method, "url": r.url[:200], "frame": frame}
entry.update(more)
self.log.append(entry)
return entry
except Exception:
return None
def _answered(self, response):
try:
self._logged(response.request, "response", status=response.status)
except Exception:
pass
def _page_opened(self, page):
try:
for name in ("framenavigated", "domcontentloaded", "load"):
page.on(name, lambda arg, name=name: self._page_event(page, name, arg))
self._page_event(page, "page", None)
except Exception:
pass
def _page_event(self, page, name, arg):
try:
url = (arg.url if name == "framenavigated" else page.url)[:200]
except Exception:
url = None
try:
self.log.append({"ev": name, "step": self.step, "t": round(time.time(), 4), "m": round(time.perf_counter(), 6), "page": id(page), "url": url})
except Exception:
pass
def snapshot(self):
return sorted(self.open.values())[:12]
def in_flight(self):
"""What the client counts as in flight now, with how long (`age_s`) and from which step (`step`); `log` only."""
now = time.perf_counter()
return [dict(d, age_s=round(now - d["m"], 3)) for d in sorted(self.detail.values(), key=lambda d: d["m"])]
def take_events(self):
taken, self.events = self.events, []
return taken
@@ -326,13 +392,20 @@ def snapshot(j, pg, rec):
rec["url"] = j.norm(pg.url)
def run_round(j, tracer, round_no, idle_timeout_ms):
def run_round(j, tracer, round_no, idle_timeout_ms, step_log=None):
"""`step_log`, a list (default None: nothing kept), receives each step's record as soon as it is done, with the moments of the step
(`m_*`: time.perf_counter(), the scale of the client log and of the site's record) and what the client counted as in flight when
`networkidle` returned or gave up: for a test that saves evidence when it fails. Never compared."""
out = []
walk = journey_site.STATE.begin_walk() # the site tags what it sees with the walk, stock and ours both use steps 1..N
for n, (name, method) in enumerate(STEPS, 1):
j.extra = {}
tracer.step = n
m_before_set_step = time.perf_counter()
journey_site.STATE.set_step(n) # a held response of the site is released when the walk reaches its step
rec = {"round": round_no, "n": n, "name": name, "ok": False, "error": None}
if step_log is not None:
rec["m_step_start"], rec["t_step_start"] = round(m_before_set_step, 6), round(time.time(), 4)
t0 = time.monotonic()
pg, cleanup = j.page, None
try:
@@ -340,12 +413,19 @@ def run_round(j, tracer, round_no, idle_timeout_ms):
rec["ok"] = True
except Exception as exc:
rec["error"] = first_line(exc)
if step_log is not None:
rec["m_action_end"] = round(time.perf_counter(), 6)
try:
pg.wait_for_load_state("networkidle", timeout=idle_timeout_ms)
rec["idle"] = True
except Exception:
except Exception as exc:
rec["idle"] = False
if step_log is not None:
rec["idle_error"] = first_line(exc)
rec["open_at_idle_end"] = tracer.snapshot() # for the report, not compared
if step_log is not None:
rec["m_idle_end"], rec["t_idle_end"] = round(time.perf_counter(), 6), round(time.time(), 4)
rec["in_flight_at_idle_end"] = tracer.in_flight()
if tracer.events is not None:
rec["client_events"] = tracer.take_events()
snapshot(j, pg, rec)
@@ -359,6 +439,8 @@ def run_round(j, tracer, round_no, idle_timeout_ms):
rec["error"] = rec["error"] or ("cleanup: " + first_line(exc))
rec["seconds"] = round(time.monotonic() - t0, 2)
out.append(rec)
if step_log is not None:
step_log.append(rec)
if tracer.events is not None:
# read once, at the end: a request fired on pagehide reaches the server after its step's own work is done
time.sleep(0.5)
@@ -367,9 +449,11 @@ def run_round(j, tracer, round_no, idle_timeout_ms):
return out
def drive(browser, origin_a, origin_o, rounds=1, idle_timeout_ms=15000, trace=False):
def drive(browser, origin_a, origin_o, rounds=1, idle_timeout_ms=15000, trace=False, client_log=None, step_log=None):
"""`rounds` walks, each in a fresh context and a fresh page. Returns the step records. `trace`: keep, per step, the request
events the client reported and the hits the server saw (for the report; never compared)."""
events the client reported and the hits the server saw (for the report; never compared). `client_log` and `step_log`, two lists
(default None: nothing kept), are filled as the walk goes with what the client heard (`Tracer`) and with each step's record
(`run_round`): for a test that saves evidence when it fails."""
records = []
for r in range(1, rounds + 1):
context = browser.new_context()
@@ -377,9 +461,9 @@ def drive(browser, origin_a, origin_o, rounds=1, idle_timeout_ms=15000, trace=Fa
context.set_default_timeout(TIMEOUT_MS)
context.set_default_navigation_timeout(TIMEOUT_MS)
install_route(context)
tracer = Tracer(context, events=trace)
tracer = Tracer(context, events=trace, log=client_log)
page = context.new_page()
records += run_round(Journey(context, page, origin_a, origin_o), tracer, r, idle_timeout_ms)
records += run_round(Journey(context, page, origin_a, origin_o), tracer, r, idle_timeout_ms, step_log)
finally:
try:
context.close()
+4
View File
@@ -52,6 +52,7 @@ import time
import types
import pytest
import _moving_page
from _moving_page import _goto, _landing, forget
from _evidence_on_failure import FailureEvidence
@@ -70,6 +71,9 @@ def _note(what: str, **fields) -> None:
_CLIENT_LOG.append({"t": round(time.time(), 4), "m": round(time.perf_counter(), 6), "what": what, **fields})
_moving_page.note = _note
def _replace_after_load(ms: int, cross_site: bool) -> bytes:
target = ("location.origin.replace('127.0.0.1','localhost')+'/landed'+location.search"
if cross_site else "'/landed'+location.search")
@@ -11,12 +11,15 @@ was applied after the page was announced), and the one that answers after 25 s w
"""
from __future__ import annotations
import json
import threading
import time
from http.server import BaseHTTPRequestHandler
from types import SimpleNamespace
import pytest
from _evidence_on_failure import WIRE_LIMIT, FailureEvidence
from _servers import LocalServer
pytestmark = pytest.mark.e2e
@@ -27,15 +30,30 @@ class _Handler(BaseHTTPRequestHandler):
pass
def do_GET(self):
# The destination's own record, for a test that saves evidence when it fails (`server.records`): it only listens.
rec = {"ev": "request", "t_arrive": round(time.time(), 4), "m_arrive": round(time.perf_counter(), 6), "peer": self.client_address[1],
"path": self.path, "status": None, "m_slept": None, "m_answer": None, "m_done": None, "error": None}
records = getattr(self.server, "records", None)
if records is not None:
with self.server.records_lock:
records.append(rec)
try:
self._get(rec)
finally:
rec["m_done"] = round(time.perf_counter(), 6)
def _get(self, rec):
path, _, query = self.path.partition("?")
if path == "/nocontent":
self.send_response(204)
self.send_header("Content-Length", "0")
self.end_headers()
rec["status"] = 204
return
if path == "/slow":
ms = int(query.split("ms=")[1].split("&")[0]) if "ms=" in query else 0
time.sleep(ms / 1000.0)
rec["m_slept"] = round(time.perf_counter(), 6)
body = b"<!doctype html><html><head><title>slow</title></head><body>slow</body></html>"
else:
body = (b"<!doctype html><html><head><title>opener</title></head><body>"
@@ -52,21 +70,29 @@ class _Handler(BaseHTTPRequestHandler):
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
except OSError: # the browser left before a slow answer
pass
rec["status"] = 200
rec["m_answer"] = round(time.perf_counter(), 6)
except OSError as exc: # the browser left before a slow answer
rec["error"] = type(exc).__name__
@pytest.fixture
def site():
def site_server():
srv = LocalServer(("127.0.0.1", 0), _Handler)
srv.records, srv.records_lock = [], threading.Lock()
threading.Thread(target=srv.serve_forever, daemon=True).start()
try:
yield "http://127.0.0.1:%d/" % srv.server_address[1]
yield srv
finally:
srv.shutdown()
srv.server_close()
@pytest.fixture
def site(site_server):
return "http://127.0.0.1:%d/" % site_server.server_address[1]
def _stock_client(module):
import importlib
@@ -132,14 +158,205 @@ def test_a_slow_popup_is_reported_with_the_address_of_its_destination(firefox_bi
_drive(mode, firefox_binary, body)
class _ServerSideLog:
"""What OUR server says to the client and how it decides to, recorded from the test, with nothing changed in `src`: the methods are
wrapped at their class and put back at the end. `messages`: every protocol message the server hands to the client (a served browser:
`RemoteClient.post`, the text sent on the WebSocket; in-process: `InProcessTransport.emit_message`, the dict). `steps`: the adoption of
each engine target (`_Adoption`: attached, every note it makes, with the engine's own event names) and the two calls that decide when
the client hears of a page (`PageDispatcher.wait_until_ready`, `PageDispatcher.announce`). Both carry `t` and `m` like the engine's wire."""
LIMIT = 20000
def __init__(self):
self.messages, self.steps, self.problems = [], [], []
self._lock = threading.Lock()
self._patch = pytest.MonkeyPatch()
def _add(self, where, record):
try:
record["t"], record["m"] = round(time.time(), 4), round(time.perf_counter(), 6)
with self._lock:
if len(where) < self.LIMIT:
where.append(record)
except Exception:
pass
def _sent(self, via, message):
try:
text = message if isinstance(message, str) else json.dumps(message, default=str)
parsed = json.loads(text) if isinstance(message, str) else message
params = parsed.get("params") or {}
self._add(self.messages, {"via": via, "len": len(text), "cut": len(text) > WIRE_LIMIT, "guid": parsed.get("guid"),
"method": parsed.get("method"), "id": parsed.get("id"),
"create_type": params.get("type") if parsed.get("method") == "__create__" else None,
"msg": text[:WIRE_LIMIT]})
except Exception:
pass
def _step(self, event, /, **more):
# `event` is positional-only: a wrapped call records a field called `what` (the adoption's note) and must not collide with it.
record = {"ev": event}
record.update(more)
self._add(self.steps, record)
def _record(self, make):
"""Run `make`, which records something about a call the server makes; a failure of the recording is noted in the evidence and
never reaches the server."""
try:
make()
except BaseException as exc:
with self._lock:
if len(self.problems) < 20:
self.problems.append("recording failed: %r" % (exc,))
def install(self):
log = self
def wrap(owner, name, make):
try:
self._patch.setattr(owner, name, make(getattr(owner, name)))
except Exception as exc: # the rest is still recorded; the problem is saved with it
self.problems.append("%s.%s not wrapped: %r" % (getattr(owner, "__name__", owner), name, exc))
try:
from invisible_playwright._juggler import remote, server, transport
except Exception as exc:
self.problems.append("the server modules could not be imported: %r" % (exc,))
return
# Every wrapper takes (*args, **kwargs) and passes them on unchanged: whatever the real code passes, positional or keyword, reaches
# the wrapped method as it was. What a wrapper reads from the call is read inside `_record`, which never raises.
def post(original):
def wrapper(*args, **kwargs):
log._record(lambda: log._sent("RemoteClient.post", args[1] if len(args) > 1 else kwargs.get("text")))
return original(*args, **kwargs)
return wrapper
def emit_message(original):
def wrapper(*args, **kwargs):
log._record(lambda: log._sent("InProcessTransport.emit_message", args[1] if len(args) > 1 else kwargs.get("message")))
return original(*args, **kwargs)
return wrapper
def adoption_init(original):
def wrapper(*args, **kwargs):
result = original(*args, **kwargs)
adoption = args[0]
log._record(lambda: log._step("adoption_attached", target=adoption.target_id, opener=adoption.opener is not None,
context=adoption.context_id))
return result
return wrapper
def adoption_note(original):
def wrapper(*args, **kwargs):
adoption = args[0]
log._record(lambda: log._step("adoption_note", target=adoption.target_id, state=adoption.state,
what=args[1] if len(args) > 1 else kwargs.get("what")))
return original(*args, **kwargs)
return wrapper
def wait_until_ready(original):
def wrapper(*args, **kwargs):
page = args[0]
log._record(lambda: log._step("wait_until_ready_begin", page=page.guid))
try:
result = original(*args, **kwargs)
except BaseException as exc:
error = repr(exc)[:300]
log._record(lambda: log._step("wait_until_ready_failed", page=page.guid, error=error))
raise
log._record(lambda: log._step("wait_until_ready_end", page=page.guid))
return result
return wrapper
def announce(original):
def wrapper(*args, **kwargs):
page = args[0]
log._record(lambda: log._step("announce_begin", page=page.guid))
try:
return original(*args, **kwargs)
finally:
log._record(lambda: log._step("announce_end", page=page.guid))
return wrapper
wrap(remote.RemoteClient, "post", post)
wrap(transport.InProcessTransport, "emit_message", emit_message)
wrap(server._Adoption, "__init__", adoption_init)
wrap(server._Adoption, "note", adoption_note)
wrap(server.PageDispatcher, "wait_until_ready", wait_until_ready)
wrap(server.PageDispatcher, "announce", announce)
def uninstall(self):
self._patch.undo()
#: What each extra file of the evidence of the test below holds, field by field (written into its meta.json).
_EXTRA_FILES = {
"server-to-client.jsonl": "every protocol message OUR server handed to the client, in order: t (time.time()), m (time.perf_counter(), the scale "
"of every other file), via (RemoteClient.post for a served browser, InProcessTransport.emit_message in-process), "
"guid and method (the event or the __create__ it carries; id for a reply), create_type (the type a __create__ makes: "
"Page, Frame, ...), len, cut (msg was cut at %d characters), msg (the message as JSON text)" % WIRE_LIMIT,
"server-adoption-steps.jsonl": "what the server did with each engine target and when it told the client: t, m, ev = adoption_attached "
"(target, opener, context), adoption_note (target, state, what = the engine's event names Page.frameAttached/"
"navigationCommitted/ready/... without the 'Page.', and the adoption's own steps building/waiting/announced), "
"wait_until_ready_begin / _end / _failed (page = the Page guid), announce_begin / announce_end (page = the Page "
"guid; the `page` event is sent between them), and `problems` lines if a wrapper could not be installed",
"client-events.jsonl": "what the stock client heard, in order: t, m, ev = click, page_event (url = popup.url read in the handler of the context's "
"page event), then for that popup framenavigated (url, main = the main frame), domcontentloaded, load, close (url), and "
"expect_popup_returned (url, took_s, the time since the click)",
}
def _save_extra(folder, files, problems):
"""Add the files of the server's side to the evidence folder `FailureEvidence` saved, and say in its meta.json what each holds."""
for name, records in files.items():
with open(folder / name, "w", encoding="utf-8") as out:
for record in records:
out.write(json.dumps(record, default=str) + "\n")
meta_path = folder / "meta.json"
meta = json.loads(meta_path.read_text(encoding="utf-8"))
meta["files"] = sorted(set(meta.get("files", [])) | set(files))
meta["extra_files"] = _EXTRA_FILES
meta["extra_problems"] = problems
meta["note"] = ("client-request-log.jsonl is empty here (the destination has one request; the client's own events are client-events.jsonl); "
"fakeweb-server-record.jsonl is the destination's record: t_arrive/m_arrive when the request came, m_slept when its wait "
"ended, m_answer when the answer was written, status, error")
meta_path.write_text(json.dumps(meta, indent=1), encoding="utf-8")
@pytest.mark.parametrize("mode", MODES)
def test_a_popup_whose_destination_answers_after_25_seconds_is_reported_then(firefox_binary, site, mode):
def test_a_popup_whose_destination_answers_after_25_seconds_is_reported_then(firefox_binary, site, site_server, mode):
"""When it fails it saves, under `invpw-evidence/popup-25s-<mode>/`, the order in which the engine and then our server told the popup's
story: the engine's Juggler wire and trace (`juggler-wire.jsonl`, `juggler-engine-trace/`), what our server sent to the client
(`server-to-client.jsonl`), what it did with the target (`server-adoption-steps.jsonl`), what the client heard (`client-events.jsonl`),
the destination's record (`fakeweb-server-record.jsonl`) and a summary (`cells.json`)."""
client_events = []
summary = {"mode": mode}
def mark(ev, **more):
client_events.append(dict({"ev": ev, "t": round(time.time(), 4), "m": round(time.perf_counter(), 6)}, **more))
def watch_popups(ctx):
def on_page(popup):
mark("page_event", url=popup.url)
summary["url_at_page_event"] = popup.url
popup.on("framenavigated", lambda frame: mark("framenavigated", url=frame.url, main=frame.parent_frame is None))
popup.on("domcontentloaded", lambda p: mark("domcontentloaded", url=p.url))
popup.on("load", lambda p: mark("load", url=p.url))
popup.on("close", lambda p: mark("close", url=p.url))
ctx.on("page", on_page)
def body(ctx, page):
page.goto(site, wait_until="load", timeout=30000)
watch_popups(ctx)
t0 = time.monotonic()
mark("click")
with page.expect_popup(timeout=45000) as info:
page.click("#open25000")
took = time.monotonic() - t0
mark("expect_popup_returned", url=info.value.url, took_s=round(took, 3))
summary["took_s"] = round(took, 3)
# The lower bound is the server's: it answers after 25 s, so a popup announced before 24 s was announced
# before it was ready. There is no upper bound of ours: the limit above is expect_popup's 45 s (a popup
# dropped at 20 s, the defect this test is red on, ends in its timeout).
@@ -147,7 +364,25 @@ def test_a_popup_whose_destination_answers_after_25_seconds_is_reported_then(fir
assert info.value.url == site + "slow?ms=25000"
info.value.close()
_drive(mode, firefox_binary, body)
evidence = FailureEvidence("popup-25s-" + mode)
evidence.watch_server(SimpleNamespace(state=SimpleNamespace(lock=site_server.records_lock, records=site_server.records)))
evidence.note_cells(summary)
side = _ServerSideLog()
try:
with evidence:
side.install()
evidence.arm()
_drive(mode, firefox_binary, body)
finally:
side.uninstall()
if evidence.saved_to is not None:
try:
_save_extra(evidence.saved_to, {"server-to-client.jsonl": side.messages,
"server-adoption-steps.jsonl": side.steps + [{"ev": "problem", "what": w} for w in side.problems],
"client-events.jsonl": client_events}, side.problems)
except Exception as problem: # the evidence never hides the failure it is about
import sys
sys.stderr.write("popup evidence: the server's side could not be saved: %r\n" % (problem,))
@pytest.mark.parametrize("mode", MODES)
+104 -31
View File
@@ -25,11 +25,17 @@ retail and died with no usable interface. Hermetic: a local TCP-only SOCKS5 prox
"""
from __future__ import annotations
import json
import os
import shutil
import statistics
import time
import pytest
from _e2e_verdicts import MDNS_RETRY_MS, opened_at_the_retry_problem
from _evidence_with_files import FailureEvidenceWithFiles
from _mdns_listener import MdnsListener
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")]
@@ -64,24 +70,45 @@ _GATHER_JS = r"""async () => {
}"""
# Two connections on one page, connected to each other in script (the loopback test many demos use).
# ``events`` is the page's own timeline for the failure evidence (``at``: ``performance.now()`` since the start of the script, ``origin``:
# ``performance.timeOrigin``, so the wall clock of an event is ``origin + at``): every ``icecandidate`` of both connections with the candidate string,
# every state change, when each ``addIceCandidate`` was called and when it settled. It only listens: nothing waits on it.
_LOOPBACK_JS = r"""async () => {
const t0 = performance.now();
const events = [];
const at = (what, extra) => { events.push(Object.assign({at: Math.round((performance.now() - t0) * 10) / 10, what}, extra || {})); };
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(() => {}); };
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)}));
};
pc1.onicecandidate = e => { if (e.candidate) add(pc2, 'pc2', e.candidate); };
pc2.onicecandidate = e => { if (e.candidate) add(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;
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'); };
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}); };
await pc1.setLocalDescription(await pc1.createOffer());
at('pc1 local description set');
await pc2.setRemoteDescription(pc1.localDescription);
await pc2.setLocalDescription(await pc2.createAnswer());
at('pc2 local description set');
await pc1.setRemoteDescription(pc2.localDescription);
at('pc1 remote description set');
// Until the channel has opened and echoed, for 30 s (the deadline of the wait). The loop also keeps the longest time it 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;
@@ -92,13 +119,20 @@ _LOOPBACK_JS = r"""async () => {
stalled = Math.max(stalled, now - last);
last = now;
}
at('wait over', {opened, echoed});
// The road the connection took, read from the browser's own statistics: the nominated pair, and the protocol of each end.
let pair = null;
const pairs = [];
try {
const stats = await pc1.getStats();
const byId = {};
stats.forEach(r => { byId[r.id] = r; });
stats.forEach(r => {
if (r.type === 'candidate-pair') {
const l = byId[r.localCandidateId] || {}, rm = byId[r.remoteCandidateId] || {};
pairs.push({state: r.state, nominated: r.nominated, local: [l.protocol, l.candidateType, l.address, l.port],
remote: [rm.protocol, rm.candidateType, rm.address, rm.port], requestsSent: r.requestsSent, responsesReceived: r.responsesReceived});
}
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,
@@ -107,7 +141,7 @@ _LOOPBACK_JS = r"""async () => {
});
} catch (e) {}
pc1.close(); pc2.close();
return {opened, echoed, pair, gathered, stalled: Math.round(stalled)};
return {opened, echoed, pair, gathered, stalled: Math.round(stalled), events, pairs, origin: performance.timeOrigin, started_at: Math.round(t0 * 10) / 10};
}"""
# Retail 159 on Windows, 12 cold launches (``captures/mdns-loopback/retail-159-win-12``): 37-52 ms in ten of twelve, two
@@ -117,14 +151,28 @@ _LOOPBACK_JS = r"""async () => {
# 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
# What the engine logs for the failure evidence of the loopback test, by its own names (MOZ_LOG; the file is MOZ_LOG_FILE, one per process and
# per launch). ``mdns_service::*`` is the Rust crate of the mDNS responder (dom/media/webrtc/transport/mdns_service/src/lib.rs, crate ``mdns_service``,
# which logs with the ``log`` macros at the crate root, so the module path is ``mdns_service``): a Rust module reaches MOZ_LOG only by a name that
# contains ``::`` (xpcom/base/Logging.cpp, ``LogModule::SetLevel`` calls ``set_rust_log_level`` only then). ``mtransport`` is the module of nICEr's own
# log and of the transport layers (``MOZ_MTLOG_MODULE("mtransport")``, dom/media/webrtc/transport/nricectx.cpp:100, nriceresolver.cpp:67 ...), ML_DEBUG is level 5.
# The engine's ``log`` crate is built with ``release_max_level_info`` (toolkit/library/rust/shared/Cargo.toml:41): a release engine keeps the info, warn and
# error lines of the responder (the ``warn!`` of a failed send, a bad packet, an interface it could not use), not its ``trace!`` lines (questions, answers,
# registrations). ``timestamp`` writes the wall clock (UTC) on each line, ``sync`` writes each line at once, ``rotate:30`` keeps at most 30 MB per process.
MDNS_MOZ_LOG = "timestamp,sync,rotate:30,mdns_service::*:5,mtransport:5"
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."""
def _session(declaration, socks, page_url, monkeypatch, seed, script, engine_log=None):
"""One proxied launch with the declaration in the environment; runs ``script`` on the page and returns the result.
``engine_log``: a folder where the engine writes its own log of this launch (failure evidence, ``MDNS_MOZ_LOG``)."""
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
monkeypatch.setenv(NETWORK_ENV, declaration)
if engine_log is not None:
os.makedirs(engine_log, exist_ok=True)
monkeypatch.setenv("MOZ_LOG", MDNS_MOZ_LOG)
monkeypatch.setenv("MOZ_LOG_FILE", os.path.join(engine_log, "engine-%PID.log"))
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:
@@ -231,29 +279,54 @@ def test_two_connections_on_one_page_connect_in_the_time_of_retail(local_https_p
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))
problem = opened_at_the_retry_problem(res["opened"], res["stalled"], MDNS_RETRY_MS)
assert problem is None, "run %d: %s" % (n, problem)
launches = []
# Failure evidence (tests/_evidence_with_files.py): per launch, the engine's own log (the mDNS responder and mtransport), kept only for the launch that
# fails; and ``launches.json``, the timings and the page's timeline of EVERY launch up to it (the loop stops at the first red).
with FailureEvidenceWithFiles("declared-host-two-connections-open-in-time") as evidence:
try:
for n in range(5):
log_dir = evidence.files / ("engine-log-run-%d" % n)
launch = {"run": n, "seed": 100 + n, "moz_log": MDNS_MOZ_LOG, "started_m": round(time.perf_counter(), 6),
"started_t": round(time.time(), 4)}
launches.append(launch)
# The lab's own ear on the mDNS group (tests/_mdns_listener.py), started BEFORE the browser so that the engine's socket is the later one:
# it only listens, and what it heard of this launch is ``mdns-wire-run-N.jsonl`` (``m`` is the scale of ``started_m`` above).
listener = MdnsListener().start()
try:
res = _session(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch, 100 + n,
lambda page: page.evaluate(_LOOPBACK_JS), engine_log=str(log_dir))
finally:
launch.update(returned_m=round(time.perf_counter(), 6), returned_t=round(time.time(), 4))
listener.stop()
listener.write(evidence.files / ("mdns-wire-run-%d.jsonl" % n))
launch["mdns_wire"] = listener.summary()
page_timeline = {key: res.pop(key, None) for key in ("events", "pairs", "origin", "started_at")}
launch.update(opened=res["opened"], echoed=res["echoed"], stalled=res["stalled"], pair=res["pair"], gathered=res["gathered"],
page=page_timeline)
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))
problem = opened_at_the_retry_problem(res["opened"], res["stalled"], MDNS_RETRY_MS)
assert problem is None, "run %d: %s" % (n, problem)
# This launch is right: its engine log is no evidence of anything.
shutil.rmtree(log_dir, ignore_errors=True)
finally:
(evidence.files / "launches.json").write_text(json.dumps(launches, indent=1, default=str), encoding="utf-8")
times = sorted(r["opened"] for r in runs)
low, high = RETAIL_MEDIAN_WINDOW_MS
with capsys.disabled():
+32 -3
View File
@@ -12,6 +12,7 @@ from __future__ import annotations
import importlib
import json
import pathlib
import sys
import pytest
@@ -26,6 +27,34 @@ HARD = ["leaving_beacons_subframe", "leaving_beacons", "cancel_among_beacons"]
REPETITIONS = 10
class P2Evidence(FailureEvidence):
"""What a round that does not reach networkidle leaves, on top of the helper's own files: `p2-not-idle.json` (each such cell with its WHOLE in-flight list:
type, method, url, frame url, seconds from the navigation's start; and what the served browser's lifecycle held open when the wait expired) and
`p2-open-requests-history.txt` (the history of each of those open requests on the Juggler wire, `profile_p2.open_requests_history`). It only reads what the
helper already saved; a failure of its own is written to stderr and never hides the failure of the test."""
def _save(self, exc_type, exc, kept: str = "") -> None:
self.saved_to = None
super()._save(exc_type, exc, kept)
target = self.saved_to
if target is None:
return
try:
cells = self.cells or []
not_idle = [{key: cell.get(key) for key in ("round", "pattern", "canary", "after", "err", "seconds", "expired_at", "in_flight", "lifecycle_open")}
for cell in cells if not cell.get("idle")]
(target / "p2-not-idle.json").write_text(json.dumps(not_idle, indent=1, default=str), encoding="utf-8")
wire = target / "juggler-wire.jsonl"
lines = wire.read_text(encoding="utf-8").splitlines() if wire.exists() else []
(target / "p2-open-requests-history.txt").write_text(profile_p2.open_requests_history(lines, cells), encoding="utf-8")
meta_path = target / "meta.json"
meta = json.loads(meta_path.read_text(encoding="utf-8"))
meta["files"] = sorted(p.name for p in target.iterdir())
meta_path.write_text(json.dumps(meta, indent=1), encoding="utf-8")
except Exception as problem:
sys.stderr.write("p2 evidence: could not be written: %r\n" % (problem,))
def _stock_client():
"""The stock Playwright client (a pinned dev dependency), imported by name: the fork's guard forbids a static import."""
try:
@@ -135,7 +164,7 @@ def test_the_page_that_leaves_with_beacons_reaches_networkidle_every_time_under_
import tempfile
import time
with FailureEvidence("fakeweb-leaving-beacons-under-load") as evidence:
with P2Evidence("fakeweb-leaving-beacons-under-load") as evidence:
loader = pathlib.Path(__file__).resolve().parent / "fakeweb" / "loader.py"
ready_dir = pathlib.Path(tempfile.mkdtemp(prefix="fakeweb-loaders-"))
ready = [ready_dir / ("loader-%d.ready" % i) for i in range(LOADERS)]
@@ -148,7 +177,7 @@ def test_the_page_that_leaves_with_beacons_reaches_networkidle_every_time_under_
assert wait_until(lambda: all(mark.exists() for mark in ready), 180, lambda: time.sleep(0.25)), "the loaders did not start loading: %s" % [m.name for m in ready if not m.exists()]
evidence.arm()
cells = profile_p2.run_on_candidate(_stock_client(), firefox_binary, origin, ["leaving_beacons_subframe"], 10,
client_log=evidence.client_log)
client_log=evidence.client_log, lifecycle_dump=True)
evidence.note_cells(cells)
finally:
stop()
@@ -163,7 +192,7 @@ def test_the_page_that_leaves_with_beacons_reaches_networkidle_every_time_under_
assert len(cells) == 20, "the run made %d navigations, not 20" % len(cells)
return
bad = ["round %d%s: %s -- in flight: %s" % (c["round"], " (canary)" if c["canary"] else "", c["err"],
[(r["type"], r["method"], r["frame"]) for r in c.get("in_flight", [])[:3]])
[(r["type"], r["method"], r["frame"], r["url"], r["t"]) for r in c.get("in_flight", [])])
for c in cells if not c["idle"]]
assert not bad, "%d of %d navigations did not reach networkidle under load:%s" % (
len(bad), len(cells), "".join("\n " + line for line in bad[:6]))
+21 -10
View File
@@ -15,6 +15,7 @@ import pathlib
import pytest
from _evidence_on_failure import FailureEvidence
from fakeweb import journey_site, profile_p4
pytestmark = pytest.mark.e2e
@@ -32,14 +33,24 @@ def _stock_client():
def test_the_journey_succeeds_on_every_step_and_idles_where_stock_does(firefox_binary):
"""When it fails it saves, under `invpw-evidence/fakeweb-journey-idles-where-stock-does/`, what answers whether the browser sent the
request a step holds, when the site received and answered it, and what the client heard of it before `networkidle` returned:
`fakeweb-server-record.jsonl` (the site's own record), `client-request-log.jsonl` (every request event the client heard, with the step),
`cells.json` (each step's record with `in_flight_at_idle_end`), `juggler-wire.jsonl` and `juggler-engine-trace/`."""
not_idle = json.loads((HERE / "pages.json").read_text(encoding="utf-8"))["journey_p4"]["not_idle_steps"]
origin_a, origin_o, stop = journey_site.start((0, 0))
try:
steps = profile_p4.run_on_candidate(_stock_client(), firefox_binary, origin_a, origin_o, 1)
finally:
stop()
failed = ["step %d (%s): %s" % (s["n"], s["name"], s["error"]) for s in steps if not s["ok"]]
assert not failed, "steps that did not succeed:\n " + "\n ".join(failed)
wrong = ["step %d (%s): %s" % (s["n"], s["name"], "idle, stock holds a request here" if s["idle"] else
"not idle, open: %s" % s["open_at_idle_end"]) for s in steps if s["idle"] != (s["n"] not in not_idle)]
assert not wrong, "networkidle differs from the declared outcome of stock Firefox:\n " + "\n ".join(wrong)
with FailureEvidence("fakeweb-journey-idles-where-stock-does") as evidence:
origin_a, origin_o, stop = journey_site.start((0, 0))
evidence.watch_server(stop)
step_log = []
evidence.note_cells(step_log)
try:
evidence.arm()
steps = profile_p4.run_on_candidate(_stock_client(), firefox_binary, origin_a, origin_o, 1,
client_log=evidence.client_log, step_log=step_log)
finally:
stop()
failed = ["step %d (%s): %s" % (s["n"], s["name"], s["error"]) for s in steps if not s["ok"]]
assert not failed, "steps that did not succeed:\n " + "\n ".join(failed)
wrong = ["step %d (%s): %s" % (s["n"], s["name"], "idle, stock holds a request here" if s["idle"] else
"not idle, open: %s" % s["open_at_idle_end"]) for s in steps if s["idle"] != (s["n"] not in not_idle)]
assert not wrong, "networkidle differs from the declared outcome of stock Firefox:\n " + "\n ".join(wrong)
+48 -8
View File
@@ -44,12 +44,14 @@ carries ``Alt-Svc: h3`` (tests/_h3_server.py).
"""
from __future__ import annotations
import json
import os
import socket
import time
import pytest
from _evidence_with_files import FailureEvidenceWithFiles
from _host_address import this_host_address
from _waits import wait_until
from _udp_line import (declared_udp, egress_by_proxy, expected_protocols, judge_visits, measure_servers, no_https_record,
@@ -66,6 +68,14 @@ PAUSE_MS = 2000
#: The roads where QUIC can reach the server, so a QUIC connection of the browser is what its Alt-Svc turns into.
_UDP_FREE_ROADS = ("direct", "socks5_coherent")
_NAV_JS = "() => performance.getEntriesByType('navigation')[0].nextHopProtocol"
#: What the engine logs for the failure evidence of the no-proxy test, by its own names (MOZ_LOG; the file is MOZ_LOG_FILE, one per process).
#: ``nsHttp`` is the HTTP stack of the engine (``gHttpLog``, netwerk/protocol/http/nsHttpHandler.cpp:146): Alt-Svc, Http3Session, the transaction
#: and the connection manager. The three Rust crates of HTTP/3 are named by their module path with ``::*``: ``neqo_glue`` (netwerk/socket/neqo_glue),
#: ``neqo_http3`` and ``neqo_transport`` (third_party/rust/neqo-*). A Rust module reaches MOZ_LOG only by a name that contains ``::`` (xpcom/base/Logging.cpp,
#: ``LogModule::SetLevel`` calls ``set_rust_log_level`` only then) and the engine's ``log`` crate is built with ``release_max_level_info``
#: (toolkit/library/rust/shared/Cargo.toml:41): a release engine keeps their info, warn and error lines, not their debug and trace ones.
#: ``timestamp`` writes the wall clock (UTC) on each line, ``sync`` writes each line at once, ``rotate:30`` keeps at most 30 MB per process.
H3_MOZ_LOG = "timestamp,sync,rotate:30,nsHttp:5,neqo_glue::*:5,neqo_http3::*:5,neqo_transport::*:5"
def _binary():
@@ -96,6 +106,13 @@ def _visits(road, server, monkeypatch, discover, **launch):
from invisible_playwright import InvisiblePlaywright
monkeypatch.setattr(_geo, "discover_egress_ip", discover)
# Failure evidence, only listening: a folder for the engine's own log of this launch, and a list this function fills, visit by visit.
engine_log = launch.pop("engine_log", None)
visit_log = launch.pop("visit_log", None)
if engine_log is not None:
os.makedirs(engine_log, exist_ok=True)
monkeypatch.setenv("MOZ_LOG", H3_MOZ_LOG)
monkeypatch.setenv("MOZ_LOG_FILE", os.path.join(engine_log, "engine-%PID.log"))
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
@@ -109,16 +126,25 @@ def _visits(road, server, monkeypatch, discover, **launch):
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()
seen = {"visit": visit, "url": url, "goto_started_m": round(time.perf_counter(), 6), "goto_started_t": round(time.time(), 4)}
if visit_log is not None:
visit_log.append(seen)
page.goto(url, wait_until="load", timeout=60000)
walls.append(round((time.monotonic() - started) * 1000))
seen.update(goto_ms=walls[-1], goto_done_m=round(time.perf_counter(), 6), quic_connections_after_goto=len(server.quic_peers))
if road in _UDP_FREE_ROADS:
# The Alt-Svc of the document is absorbed when the browser has made its own QUIC connection to the server (the
# server sees it): the next visit reads h3 from then on, and not before. Waited for as a condition with a
# deadline, not slept for: on a loaded machine that connection comes later than any pause. A road whose UDP
# leads nowhere has nothing to wait for (every visit is h2 and no QUIC arrives): it keeps the pause.
wait_until(lambda: server.quic_peers, 30, lambda: page.wait_for_timeout(100))
quic_seen = wait_until(lambda: server.quic_peers, 30, lambda: page.wait_for_timeout(100))
seen.update(wait_for_quic_ok=quic_seen, wait_for_quic_done_m=round(time.perf_counter(), 6))
page.wait_for_timeout(PAUSE_MS) # let the later resources settle
protocols.append(page.evaluate(_NAV_JS))
seen["read_started_m"] = round(time.perf_counter(), 6)
protocol = page.evaluate(_NAV_JS)
seen.update(protocol=protocol, read_done_m=round(time.perf_counter(), 6), quic_connections_at_read=len(server.quic_peers),
tcp_alpn_at_read=list(server.tcp_alpn))
protocols.append(protocol)
return protocols, walls
@@ -137,12 +163,26 @@ 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"
# On failure: the engine's own HTTP and HTTP/3 log of the launch, the lab server's record of every TCP and QUIC connection, and the
# protocol, the goto time and the read time of each visit (``files/``, ``tests/_evidence_with_files.py``). The times of the server record and
# of the visits are ``time.perf_counter()`` (``m``) of this process; the engine's log has the wall clock.
with FailureEvidenceWithFiles("h3-no-proxy-h2-h3-h3") as evidence:
with H3Server(this_host_address()) as server:
visit_log = []
try:
assert not no_https_record(server.address), no_https_record(server.address)
protocols, walls = _visits("direct", server, monkeypatch, egress_by_proxy(direct=EXIT_DIRECT),
engine_log=str(evidence.files / "engine-log"), visit_log=visit_log)
# On a real network QUIC completes in 1 RTT and TCP+TLS in 2, so a browser with an Alt-Svc mapping takes QUIC; the lab server
# keeps that order (its TCP+TLS waits for the QUIC handshake of the same client, tests/_h3_server.py), so visits 2 and 3 read h3.
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"
finally:
server.write_record(evidence.files / "h3-server-record.jsonl")
(evidence.files / "visits.json").write_text(json.dumps(
{"alt_svc": server.alt_svc, "address": server.address, "port": server.port, "moz_log": H3_MOZ_LOG, "visits": visit_log},
indent=1, default=str), encoding="utf-8")
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):
@@ -0,0 +1,224 @@
"""The lab's HTTP/3 server finishes the QUIC handshake of a client before it finishes the TLS of a TCP connection of the same client (no browser, loopback).
A real network gives QUIC the lead: QUIC is ready after 1 round trip and TCP+TLS after 2, and a browser that holds an Alt-Svc mapping opens both and takes the FIRST that is
ready. The lab server in Python completed the QUIC handshake in 49-73 ms against 6-22 ms for TCP+TLS, so under load the TCP connection won and the visits that had to read h3
read h2 (``test_a_page_with_no_proxy_reads_h2_then_h3_then_h3``, 2 red copies in 200; the engine's own log said ``HandleConnectionResult id=1 isUDP=0`` and closed the QUIC
session). The server restores the order of a real network by an event, never by a timer: for a peer address that has a QUIC handshake in progress toward it, the TLS of a new
TCP connection from that address waits until that handshake has ended (completed, failed, or the connection terminated).
The known-bad input is the interleaving that lost: a QUIC handshake of a peer is in progress (the test holds the packets that finish it) and a TCP connection of the same peer arrives.
The test judges the ORDER the client sees, not a duration: the QUIC connection is ready for the client before the TCP+TLS connection is.
"""
from __future__ import annotations
import socket
import ssl
import threading
import time
import pytest
from _h3_server import H3Server
from _waits import wait_until
pytestmark = pytest.mark.unit
#: The bound of every wait of this file (a wait for something that must happen: it ends the test when the server hangs, it judges no speed).
DEADLINE = 30
class _QuicClient:
"""A QUIC client by hand, over a UDP socket the test owns, so that the test decides when each packet of the server is read: the handshake finishes when the test lets it."""
def __init__(self, server, source="127.0.0.1"):
from aioquic.h3.connection import H3_ALPN
from aioquic.quic.configuration import QuicConfiguration
from aioquic.quic.connection import QuicConnection
self.server_addr = (server.address, server.port)
self.quic = QuicConnection(configuration=QuicConfiguration(is_client=True, alpn_protocols=H3_ALPN, verify_mode=ssl.CERT_NONE))
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind((source, 0))
self.sock.settimeout(DEADLINE)
#: The packets of the server that arrived and that the client has not read yet.
self.unread = []
self.ready = False
def send_first_flight(self):
self.quic.connect(self.server_addr, now=time.monotonic())
self.flush()
def flush(self):
for data, addr in self.quic.datagrams_to_send(now=time.monotonic()):
self.sock.sendto(data, addr)
def server_has_answered(self):
"""Blocks (with the deadline) until a packet of the server arrived: the server has seen the first flight, so a handshake of this peer is in progress there."""
self.unread.append(self.sock.recv(65536))
def read_until_ready(self, order):
"""The client reads what the server sent, and answers, until its QUIC handshake is complete: the moment a browser takes this connection. It writes ``quic_ready`` in ``order`` then,
before its last packet (the one that lets the server finish) leaves."""
from aioquic.quic.events import HandshakeCompleted
while not self.ready:
data = self.unread.pop(0) if self.unread else self.sock.recv(65536)
self.quic.receive_datagram(data, self.server_addr, now=time.monotonic())
while True:
event = self.quic.next_event()
if event is None:
break
if isinstance(event, HandshakeCompleted):
self.ready = True
order.append("quic_ready")
self.flush()
def close(self):
self.sock.close()
def _tcp_tls(server, order, done, source="127.0.0.1"):
"""A TCP+TLS client on its own thread: when its handshake is complete it writes ``tcp_tls`` in ``order`` and sets ``done``."""
def run():
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
context.set_alpn_protocols(["h2", "http/1.1"])
raw = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
raw.bind((source, 0))
raw.settimeout(DEADLINE)
try:
raw.connect((server.address, server.port))
tls = context.wrap_socket(raw, server_hostname=server.address)
order.append("tcp_tls")
tls.close()
except OSError as error:
order.append("tcp_tls failed: %r" % (error,))
finally:
raw.close()
done.set()
thread = threading.Thread(target=run, daemon=True)
thread.start()
return thread
def _held_or_done(server, done):
"""The TCP connection is either held by the server or finished: a fact of the server's own record, never a pause."""
held = lambda: getattr(server, "tcp_held", []) # noqa: E731 - a server that holds nothing has no record
assert wait_until(lambda: held() or done.is_set(), DEADLINE, lambda: done.wait(0.01)), "the TCP connection was neither held nor served"
def test_the_quic_connection_is_ready_before_the_tcp_one_when_the_quic_handshake_is_in_progress():
"""Known-bad: the old server finished the TLS of the TCP connection while the QUIC handshake of the same client was still in progress, so the TCP connection was ready first."""
with H3Server("127.0.0.1") as server:
client = _QuicClient(server)
order, done = [], threading.Event()
try:
client.send_first_flight()
client.server_has_answered()
_tcp_tls(server, order, done)
_held_or_done(server, done)
client.read_until_ready(order)
assert done.wait(DEADLINE), "the TCP connection was never served after the QUIC handshake"
finally:
client.close()
assert order == ["quic_ready", "tcp_tls"], (
"the TCP+TLS connection was ready before the QUIC connection of the same client: %s (a browser takes the first that is ready and reads h2)" % order)
def test_a_tcp_connection_with_no_quic_handshake_in_progress_is_not_held():
with H3Server("127.0.0.1") as server:
order, done = [], threading.Event()
_tcp_tls(server, order, done)
assert done.wait(DEADLINE), "the TCP connection was held with no QUIC handshake in progress"
assert order == ["tcp_tls"], order
assert getattr(server, "tcp_held", []) == [], "the server held a TCP connection with no QUIC handshake in progress"
def test_a_quic_handshake_that_ends_without_completing_lets_the_tcp_connection_go_on():
"""The QUIC side ends by the peer closing it before the handshake is done: nothing is waited for after that."""
with H3Server("127.0.0.1") as server:
client = _QuicClient(server)
order, done = [], threading.Event()
try:
client.send_first_flight()
client.server_has_answered()
_tcp_tls(server, order, done)
_held_or_done(server, done)
client.quic.close()
client.flush()
assert done.wait(DEADLINE), "the TCP connection stayed held after the QUIC handshake was closed by the peer"
finally:
client.close()
assert order == ["tcp_tls"], order
def test_a_quic_connection_the_server_terminates_lets_the_tcp_connection_go_on():
"""The event aioquic gives the server at the end of a connection that never completed (the idle timeout is one of them) releases the TCP connection too."""
from aioquic.quic.events import ConnectionTerminated
with H3Server("127.0.0.1") as server:
client = _QuicClient(server)
order, done = [], threading.Event()
try:
client.send_first_flight()
client.server_has_answered()
_tcp_tls(server, order, done)
_held_or_done(server, done)
def terminate():
for protocol in set(server._quic._protocols.values()):
protocol.quic_event_received(ConnectionTerminated(error_code=0, frame_type=None, reason_phrase="idle timeout"))
server._loop.call_soon_threadsafe(terminate)
assert done.wait(DEADLINE), "the TCP connection stayed held after the server's QUIC connection terminated"
finally:
client.close()
assert order == ["tcp_tls"], order
def test_a_quic_handshake_of_another_address_holds_nothing():
"""The peer addresses of TCP and QUIC differ behind some proxies: then nothing is held, and nothing can hang."""
with H3Server("127.0.0.1") as server:
client = _QuicClient(server)
order, done = [], threading.Event()
try:
client.send_first_flight()
client.server_has_answered()
_tcp_tls(server, order, done, source="127.0.0.2")
assert done.wait(DEADLINE), "a TCP connection of another address was held by a QUIC handshake of this one"
assert getattr(server, "tcp_held", []) == []
finally:
client.close()
assert order == ["tcp_tls"], order
def test_a_client_that_starts_a_quic_handshake_and_vanishes_holds_the_tcp_connection_until_the_quic_idle_timeout():
"""The residual case of the order (``_QuicFirst``): the client sends its first QUIC flight and then nothing (no CONNECTION_CLOSE). A TCP+TLS connection from the same IP is
held, and it goes on only when the server's QUIC idle timeout ends that QUIC connection. The order is asserted, not a duration: the server's QUIC idle timeout is set to about 1 s
only to keep the test short (the default is 60 s)."""
with H3Server("127.0.0.1", quic_idle_timeout=1.0) as server:
order = []
ended = server._quic_first.ended
def ended_after_noting(peer):
# Written before the TCP connection is released, so the order of the two lines is the order of the facts.
order.append("quic_terminated")
ended(peer)
server._quic_first.ended = ended_after_noting
client = _QuicClient(server)
done = threading.Event()
try:
client.send_first_flight()
client.server_has_answered()
_tcp_tls(server, order, done)
assert wait_until(lambda: server.tcp_held, DEADLINE, lambda: done.wait(0.01)), "the TCP connection was not held by the QUIC handshake in progress"
assert done.wait(DEADLINE), "the TCP connection was never served after the QUIC idle timeout"
finally:
client.close()
closed = [line for line in server.record if line["kind"] == "quic_close"]
assert order == ["quic_terminated", "tcp_tls"], (
"the TCP+TLS connection went on before the QUIC connection of the vanished client was terminated, or the QUIC one was never terminated: %s" % order)
assert closed and "idle" in str(closed[0]["reason"]).lower(), "the QUIC connection did not end by the idle timeout: %s" % closed
+100
View File
@@ -0,0 +1,100 @@
"""What the fake web's P2 case keeps when a round does not reach networkidle (no browser): the requests the served browser's lifecycle holds open, and their history on the
Juggler wire.
The lifecycle's open requests are read through the registry of the in-process server (`RemoteServer._endpoint.server._objects`, the `PageDispatcher`s, their
`lifecycle`), from a real `Lifecycle` driven by the events a page's engine sends. The history text (`p2-open-requests-history.txt`) is read from a wire log in the format of
`tests/_evidence_on_failure.py`. Known-bad input: a request whose resume was sent and never answered, whose frame was detached, and that no end ever came for: the text
must say all three, and must not list a request that ended.
"""
from __future__ import annotations
import json
from types import SimpleNamespace
import pytest
from invisible_core.juggler.connection import EventListeners
from invisible_core.juggler.lifecycle import Lifecycle
from fakeweb import profile_p2
pytestmark = pytest.mark.unit
def _server_of(*lifecycles):
objects = {"page@%d" % n: SimpleNamespace(TYPE="Page", guid="page@%d" % n, lifecycle=lc) for n, lc in enumerate(lifecycles)}
objects["browser"] = SimpleNamespace(TYPE="Browser", guid="browser")
return SimpleNamespace(_endpoint=SimpleNamespace(server=SimpleNamespace(_objects=objects)))
def _lifecycle():
lifecycle = Lifecycle(EventListeners(), "session")
lifecycle._on_event("Page.frameAttached", {"frameId": "main", "parentFrameId": None})
lifecycle._on_event("Page.navigationCommitted", {"frameId": "main", "navigationId": "nav-1", "url": "http://a.test/p/x", "name": ""})
lifecycle._on_event("Page.frameAttached", {"frameId": "sub", "parentFrameId": "main"})
return lifecycle
def _sent(rid, frame, navigation=None, intercepted=True):
return {"requestId": rid, "frameId": frame, "navigationId": navigation, "isIntercepted": intercepted, "method": "POST", "url": "http://o.test/beacon"}
def test_the_lifecycle_open_requests_are_read_with_their_owner_frame_and_navigation():
lifecycle = _lifecycle()
lifecycle._on_event("Network.requestWillBeSent", _sent("r-open", "sub", "nav-9"))
lifecycle._on_event("Network.requestWillBeSent", _sent("r-done", "main"))
lifecycle._on_event("Network.requestFinished", {"requestId": "r-done"})
pages = profile_p2.lifecycle_open_requests(_server_of(lifecycle))
assert len(pages) == 1 and pages[0]["lock_taken"] and pages[0]["main_frame"] == "main"
held = {e["rid"]: e for e in pages[0]["open"]}
assert list(held) == ["r-open"], held
assert held["r-open"]["owner"] == "sub" and held["r-open"]["navigation"] == "nav-9" and held["r-open"]["owner_is_known"] is True
assert held["r-open"]["owner_parent"] == "main"
assert pages[0]["frame_tree"]["main"]["url"] == "http://a.test/p/x"
def _wire(*records):
return [json.dumps({"t": t, "m": t - 1000, "dir": d, "len": len(msg), "cut": cut, "msg": msg}) for t, d, msg, cut in records]
def test_the_history_of_an_open_request_has_its_start_its_resume_without_a_reply_and_its_frame_events():
sent = json.dumps({"method": "Network.requestWillBeSent", "params": _sent("r-open", "sub", "nav-9"), "sessionId": "s"})
resume = json.dumps({"id": 7, "method": "Network.resumeInterceptedRequest", "params": {"requestId": "r-open"}, "sessionId": "s"})
detached = json.dumps({"method": "Page.frameDetached", "params": {"frameId": "sub"}, "sessionId": "s"})
other = json.dumps({"method": "Page.navigationCommitted", "params": {"frameId": "elsewhere", "url": "http://x/"}})
done_sent = json.dumps({"method": "Network.requestWillBeSent", "params": _sent("r-done", "main")})
done_end = json.dumps({"method": "Network.requestFinished", "params": {"requestId": "r-done"}})
lines = _wire((1000.0, "in", sent, False), (1000.1, "out", resume, False), (1000.5, "in", detached, False), (1000.6, "in", other, False),
(1000.7, "in", done_sent, False), (1000.8, "in", done_end, False))
lifecycle = _lifecycle()
lifecycle._on_event("Network.requestWillBeSent", _sent("r-open", "sub", "nav-9"))
cell = {"round": 3, "pattern": "leaving_beacons_subframe", "canary": False, "expired_at": {"t": 1011.0, "m": 11.0},
"lifecycle_open": profile_p2.lifecycle_open_requests(_server_of(lifecycle))}
text = profile_p2.open_requests_history(lines, [cell])
assert "== request r-open" in text and "r-done" not in text
assert "open at the expiry of round 3 leaving_beacons_subframe" in text and "owner frame sub" in text
assert "requestWillBeSent frameId=sub isIntercepted=True navigationId=nav-9" in text
assert "resumeInterceptedRequest sent, id=7 requestId=r-open" in text and "no reply to id=7 on the wire" in text
assert "no requestFinished or requestFailed for it on the wire" in text
assert "frameDetached" in text and "elsewhere" not in text
def test_a_reply_and_an_end_are_in_the_history_and_a_cut_message_is_read_from_its_fields():
# longer than the wire log's limit: the log keeps its head, which is no JSON, with the fields that matter in it
sent = json.dumps({"method": "Network.requestWillBeSent", "params": dict(_sent("r1", "main", "nav-1"), postData="x" * 6000)})[:4000]
resume = json.dumps({"id": 4, "method": "Network.resumeInterceptedRequest", "params": {"requestId": "r1"}})
reply = json.dumps({"id": 4, "result": {}})
failed = json.dumps({"method": "Network.requestFailed", "params": {"requestId": "r1", "errorCode": "NS_BINDING_ABORTED"}})
committed = json.dumps({"method": "Page.navigationCommitted", "params": {"frameId": "main", "navigationId": "nav-2", "url": "http://a.test/p/quiet"}})
lines = _wire((50.0, "in", sent, True), (50.1, "out", resume, False), (50.2, "in", reply, False), (50.4, "in", failed, False), (50.5, "in", committed, False))
cell = {"round": 1, "pattern": "quiet", "canary": True, "lifecycle_open": [{"open": [{"rid": "r1", "owner": "main", "navigation": "nav-1"}]}]}
text = profile_p2.open_requests_history(lines, [cell])
assert "requestWillBeSent frameId=main navigationId=nav-1" in text and "(cut)" in text
assert "reply to id=4: ok" in text and "requestFailed errorCode=NS_BINDING_ABORTED" in text
assert "no requestFinished or requestFailed" not in text
assert "navigationCommitted navigationId=nav-2 url=http://a.test/p/quiet" in text
def test_a_run_with_nothing_open_says_so():
assert "No request was held open" in profile_p2.open_requests_history([], [{"round": 1, "idle": True}])
cell = {"round": 2, "lifecycle_open": [{"error": "RuntimeError()"}]}
assert "No request was held open" in profile_p2.open_requests_history([], [cell])
+387 -12
View File
@@ -25,11 +25,15 @@ import re
import select
import socket
import struct
import subprocess
import sys
import threading
import time
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler, HTTPServer
import pytest
from _evidence_on_failure import FailureEvidence
from _host_address import this_host_address
from _socks_servers import MEASURE_NUMBER, STUN_NUMBER, STUN_PORT, Socks5TcpOnly
from _udp_line import bench_report, declared_udp, declared_udp_or_absent, egress_by_proxy, measure_servers
@@ -389,27 +393,45 @@ def test_not_blocked_behind_tcp_only_socks(socks5_tcp_only, local_https_page):
# 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();
// What the page saw, with its time (``ms`` from the offer, ``wall`` the epoch clock the test's own record shares): the evidence of a
// failed gather. It is also left on ``window`` so that a test whose evaluation did not return can still read it. It changes nothing.
const events = window.__relayEvents = [];
const note = (kind, data) => {
try { events.push(Object.assign({kind, ms: Math.round((performance.now() - t0) * 10) / 10, wall: Date.now()}, data || {})); } catch (e) {}
};
const pc = new RTCPeerConnection({iceServers: [{urls: [stun]}]});
pc.createDataChannel('');
const cands = [], errors = [], at = {};
note('start', {state: pc.iceGatheringState});
pc.addEventListener('icegatheringstatechange', () => note('icegatheringstatechange', {state: pc.iceGatheringState}));
pc.addEventListener('icecandidate', e => {
try {
const c = e.candidate;
note('icecandidate', c ? {candidate: c.candidate, type: c.type, protocol: c.protocol, address: c.address, port: c.port,
relatedAddress: c.relatedAddress, relatedPort: c.relatedPort, url: e.url} : {end: true});
} catch (x) {}
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); });
pc.addEventListener('icecandidateerror', e => {
note('icecandidateerror', {errorCode: e.errorCode, errorText: e.errorText, url: e.url, address: e.address, port: e.port});
errors.push({code: e.errorCode, text: e.errorText, url: e.url}); at.error = Math.round(performance.now() - t0);
});
await pc.setLocalDescription(await pc.createOffer());
note('setLocalDescription returned', {state: pc.iceGatheringState});
await new Promise(resolve => {
const timer = setTimeout(resolve, 30000);
const timer = setTimeout(() => { note('the 30 s wait for the end of the gathering ran out'); resolve(); }, 30000);
pc.addEventListener('icegatheringstatechange', () => {
if (pc.iceGatheringState === 'complete') { at.complete = Math.round(performance.now() - t0); clearTimeout(timer); resolve(); }
});
});
const sdp = (pc.localDescription && pc.localDescription.sdp) || '';
note('closing', {state: pc.iceGatheringState});
try { pc.close(); } catch (e) {}
return {candidates: cands, errors, sdp, at_ms: at};
return {candidates: cands, errors, sdp, at_ms: at, events};
}"""
@@ -425,9 +447,344 @@ _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):
# What a failed gather leaves for a reader (tests/_evidence_on_failure.py): where the page's STUN request went. Nothing here changes an
# assertion, a wait or a deadline: the gateway of the test and its sockets are listened to, never steered.
class _Journal:
"""A record the evidence saves as ``<name>.jsonl`` (``lock``, ``records``). ``t`` is the wall clock (seconds since the epoch), ``m`` the
``perf_counter`` of this process; a record that carries its own time says ``m=None``."""
def __init__(self):
self.lock = threading.Lock()
self.records = []
def add(self, **fields):
fields.setdefault("t", round(time.time(), 4))
fields.setdefault("m", round(time.perf_counter(), 6))
with self.lock:
self.records.append(fields)
def _interfaces_of_this_runner(relay_host):
"""Every address this runner has, as the several ways to ask give it (a failure of one is said, not raised): what the hostname
resolves to, the interfaces of ``psutil`` when it is installed, and the system's own listing (``ipconfig /all`` or ``ip addr``)."""
found = {"relay_host_this_host_address": relay_host}
try:
name = socket.gethostname()
found["hostname"] = name
found["getaddrinfo_of_the_hostname"] = sorted({"%s %s" % (info[0].name, info[4][0]) for info in socket.getaddrinfo(name, None)})
except Exception as problem:
found["getaddrinfo_error"] = repr(problem)
try:
import psutil
found["psutil_net_if_addrs"] = {nic: [{"family": a.family.name, "address": a.address, "netmask": a.netmask} for a in addrs]
for nic, addrs in psutil.net_if_addrs().items()}
except Exception as problem:
found["psutil"] = "not read: %r" % (problem,)
command = ["ipconfig", "/all"] if sys.platform == "win32" else ["ip", "-o", "addr"]
try:
done = subprocess.run(command, capture_output=True, text=True, errors="replace", timeout=30)
found["listing_command"] = " ".join(command)
found["listing"] = done.stdout[:30000]
except Exception as problem:
found["listing_error"] = "%s: %r" % (" ".join(command), problem)
return found
class _Watch:
"""The record of one gather behind a gateway of the test, kept only when ``evidence`` (a ``FailureEvidence``) is given; with none every
method is the plain call. It wraps the OBJECT of the gateway and the ``socket`` name of ``tests/_socks_servers.py`` (not the file), so that
the failed gather says, with times, for each control connection what the client sent and what the gateway answered (the greeting, the
authentication, the ASSOCIATE with the address the client declared, the BND address and port), and for each datagram on the relay and on
the exit sockets where it came from, where it went and whether the gateway skipped, dropped or carried it. The Gateway has no source
filter: it takes the datagram of any address and answers the last one it heard (the cells say so)."""
def __init__(self, gateway, monkeypatch, evidence, relay_host):
self.gateway = gateway
self.evidence = evidence
self.active = evidence is not None
self.relay_host = relay_host
if not self.active:
return
self.cells = evidence.cells if evidence.cells is not None else {}
evidence.note_cells(self.cells)
self.control, self.udp, self.page = _Journal(), _Journal(), _Journal()
evidence.note_records("gateway-control-connections", self.control)
evidence.note_records("gateway-udp-datagrams", self.udp)
evidence.note_records("page-view", self.page)
self.bnd_ports = set()
self._reads = threading.local()
self.cells["relay_host"] = relay_host
self._wrap_the_gateway(monkeypatch)
self._wrap_the_sockets(monkeypatch)
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
if self.active:
try:
self.snapshot()
except Exception as problem: # the evidence never hides the failure it is about
sys.stderr.write("gateway evidence: could not be taken: %r\n" % (problem,))
return False
# ---- the clocks ---------------------------------------------------------------------------------------------------------
def _gw(self):
"""Seconds from the start of the gateway (``Gateway.t0``): the scale of its ``requests``, ``accepted``, ``associations`` and ``datagram_log``."""
return round(time.monotonic() - self.gateway.t0, 4)
def _conn(self):
return getattr(self.gateway._local, "index", -1)
def _kind_of(self, ip):
if ip.startswith("127."):
return "loopback"
if ip == self.relay_host:
return "the host address of the runner (this_host_address(), where the relay listens)"
return "another address"
# ---- the control connections --------------------------------------------------------------------------------------------------
def _wrap_the_gateway(self, monkeypatch):
gateway, control, reads, watch = self.gateway, self.control, self._reads, self
import _socks_servers as servers
original_recv_exact = servers._recv_exact
def recv_exact(s, n):
data = original_recv_exact(s, n)
sink = getattr(reads, "sink", None)
if sink is not None:
sink.append(data)
return data
monkeypatch.setattr(servers, "_recv_exact", recv_exact)
original_handle, original_greet = gateway._handle, gateway._greet
original_read_address = type(gateway)._read_address
original_send, original_connect = gateway._send, gateway._connect
original_associate, original_route, original_deliver = gateway._associate, gateway._route, gateway._deliver
def handle(c):
reads.sink, reads.address, reads.cmd = [], None, None
started = time.monotonic()
try:
peer, local = c.getpeername(), c.getsockname()
except OSError as problem:
peer = local = repr(problem)
control.add(event="control connection accepted", conn=watch._conn(), gw=watch._gw(), client=str(peer), gateway_end=str(local))
try:
return original_handle(c)
finally:
control.add(event="control connection closed", conn=watch._conn(), gw=watch._gw(), lasted_s=round(time.monotonic() - started, 4),
bytes_read_from_the_client_hex=[r.hex() for r in reads.sink])
def greet(c):
ok = original_greet(c)
sink = reads.sink
record = {"event": "greeting and authentication done", "ok": ok, "conn": watch._conn(), "gw": watch._gw(),
"gateway_wants_credentials": gateway.user is not None}
try:
record["methods_offered_by_the_client"] = list(sink[1])
if gateway.user is not None and len(sink) >= 7:
record["user_sent"] = sink[4].decode("utf-8", "replace")
record["password_length_sent"] = len(sink[6])
except Exception as problem:
record["decode_error"] = repr(problem)
control.add(**record)
return ok
def read_address(c):
host, port = original_read_address(c)
header = next((r for r in reversed(reads.sink) if len(r) == 3 and r[0] == 5), b"")
reads.cmd = {1: "CONNECT", 3: "UDP ASSOCIATE"}.get(header[1], "command %d" % header[1]) if len(header) == 3 else "unknown"
reads.address = "%s:%d" % (host, port)
control.add(event="request", command=reads.cmd, address_declared_by_the_client=reads.address, conn=watch._conn(), gw=watch._gw())
return host, port
def connect(c, host, port):
control.add(event="CONNECT handled", target="%s:%d" % (host, port), conn=watch._conn(), gw=watch._gw())
return original_connect(c, host, port)
def associate(c):
control.add(event="UDP ASSOCIATE handled", address_declared_by_the_client=getattr(reads, "address", None),
associations_so_far=len(gateway.associations), conn=watch._conn(), gw=watch._gw())
return original_associate(c)
def send(c, data):
asked = watch._gw()
kind = getattr(gateway._local, "kind", None)
try:
original_send(c, data)
except BaseException as problem:
control.add(event="answer could not be sent", kind=kind, error=repr(problem), hex=data.hex(), conn=watch._conn(),
asked_gw=asked, gw=watch._gw())
raise
record = {"event": "answer sent", "kind": kind, "hex": data.hex(), "conn": watch._conn(), "asked_gw": asked, "gw": watch._gw()}
if len(data) == 2:
record["what"] = ("method selection (0x00 none, 0x02 user/password, 0xff none acceptable)" if data[0] == 5 else
"authentication status (0x00 accepted)")
record["value"] = data[1]
elif len(data) == 10 and data[0] == 5 and data[3] == 1:
host, port = socket.inet_ntoa(data[4:8]), struct.unpack("!H", data[8:10])[0]
record.update(what="reply (REP 0 = succeeded)", rep=data[1], bnd="%s:%d" % (host, port))
if kind == "associate" and data[1] == 0:
watch.bnd_ports.add(port)
control.add(**record)
def route(host, dport, atyp, payload, out_port, answer):
routed = original_route(host, dport, atyp, payload, out_port, answer)
what = {"event": "datagram dropped by the route (nothing is sent on)" if routed is None else "datagram routed", "gw": watch._gw(),
"destination_in_the_header": "%s:%d" % (host, dport), "atyp": atyp, "payload_len": len(payload), "exit_socket_port": out_port}
if routed is not None:
what["sent_on_to"] = "%s:%d" % routed[0]
what["answer_will_be_reported_as"] = None if routed[1] is None else "%s:%d" % routed[1]
watch.udp.add(source="gateway", **what)
return routed
def deliver(relay, to, host, port, payload):
watch.udp.add(source="gateway", event="answer handed to the relay socket for the client", gw=watch._gw(), to=str(to),
reported_as_coming_from="%s:%d" % (host, port), payload_len=len(payload), payload_head_hex=payload[:2].hex())
return original_deliver(relay, to, host, port, payload)
for name, function in (("_handle", handle), ("_greet", greet), ("_read_address", read_address), ("_send", send),
("_connect", connect), ("_associate", associate), ("_route", route), ("_deliver", deliver)):
setattr(gateway, name, function)
# ---- the datagrams ----------------------------------------------------------------------------------------------------------
def _wrap_the_sockets(self, monkeypatch):
"""The datagram sockets the gateway opens from now on (the relay of each association and its exit socket) report every ``recvfrom``
and ``sendto``: the ``socket`` name of ``tests/_socks_servers.py`` stands for a module whose ``socket`` class does."""
watch, gateway, real = self, self.gateway, socket
import _socks_servers as servers
class Listening(real.socket):
def _role(self):
try:
local = self.getsockname()
except OSError:
return None, "closed"
if local[1] in gateway.exit_ports:
return local, "exit socket (leaves for the world)"
if local[1] in watch.bnd_ports:
return local, "relay socket (the BND address the client was told)"
return local, "datagram socket"
def recvfrom(self, *args):
try:
data, peer = super().recvfrom(*args)
except ConnectionResetError as problem:
if self.type == real.SOCK_DGRAM:
watch.udp.add(source="socket", event="recvfrom raised ConnectionResetError", gw=watch._gw(), error=repr(problem),
local=str(self._role()[0]))
raise
if self.type == real.SOCK_DGRAM and data:
local, role = self._role()
record = {"event": "datagram received", "gw": watch._gw(), "on": role, "local": ("%s:%d" % local) if local else None,
"source": "%s:%d" % peer, "source_kind": watch._kind_of(peer[0]), "len": len(data), "head_hex": data[:24].hex()}
if role.startswith("relay"):
skipped = len(data) < 10 or data[2] != 0
record["skipped_by_the_gateway"] = skipped
record["why"] = ("shorter than 10 bytes" if len(data) < 10 else "FRAG is not 0") if skipped else None
record["source_refused_as_foreign"] = False # the Gateway has no source filter: see the cells
watch.udp.add(source="socket", **record)
return data, peer
def sendto(self, data, *args):
try:
sent = super().sendto(data, *args)
except OSError as problem:
if self.type == real.SOCK_DGRAM and data:
watch.udp.add(source="socket", event="sendto failed", gw=watch._gw(), error=repr(problem), destination=str(args[-1]),
len=len(data), local=str(self._role()[0]))
raise
if self.type == real.SOCK_DGRAM and data:
local, role = self._role()
watch.udp.add(source="socket", event="datagram sent", gw=watch._gw(), on=role, local=("%s:%d" % local) if local else None,
destination="%s:%d" % args[-1], len=len(data), head_hex=data[:24].hex())
return sent
class Module:
socket = Listening
def __getattr__(self, name):
return getattr(real, name)
monkeypatch.setattr(servers, "socket", Module())
# ---- the launch and the page ------------------------------------------------------------------------------------------------
def arm(self):
"""Before the browser is launched: the engine's trace and the Juggler wire."""
if self.active:
self.evidence.arm()
def launched(self, session):
"""What the core declared for this session, read from the object the launch made."""
if not self.active:
return
seed = getattr(session, "seed", None)
self.cells["seed"] = seed
try:
from invisible_core import network_to_declare
self.cells["network_the_core_declares_to_the_engine (STEALTHFOX_WEBRTC_NETWORK)"] = network_to_declare(seed)
except Exception as problem:
self.cells["network_the_core_declares_to_the_engine"] = "not read: %r" % (problem,)
def evaluate(self, page, script, argument):
"""``page.evaluate`` and, when the evidence is kept, the page's own view of the gather as ``page-view.jsonl``."""
if not self.active:
return page.evaluate(script, argument)
self.page.add(source="test", event="page.evaluate of the gather starts", stun=argument, wall_ms=round(time.time() * 1000), gw=self._gw())
try:
res = page.evaluate(script, argument)
except BaseException as problem:
self.page.add(source="test", event="page.evaluate raised", error=repr(problem), gw=self._gw())
try:
for event in page.evaluate("() => window.__relayEvents || []"):
self.page.add(source="page", t=event.get("wall", 0) / 1000.0, m=None, **event)
except Exception as again:
self.page.add(source="test", event="the page's events could not be read back", error=repr(again))
raise
self.page.add(source="test", event="page.evaluate of the gather returned", wall_ms=round(time.time() * 1000), gw=self._gw())
for event in res.get("events", []):
self.page.add(source="page", t=event.get("wall", 0) / 1000.0, m=None, **event)
self.cells["page_result"] = {key: value for key, value in res.items() if key != "events"}
return res
def snapshot(self):
"""The gateway's own lists, taken before it closes (times in seconds from its start; ``wall0`` is that instant on the wall clock)."""
gateway = self.gateway
self.cells["gateway"] = {
"wall0_epoch_seconds_of_the_gateway_start": gateway.wall0,
"udp": gateway.udp, "wants_credentials": gateway.user is not None, "rtt_s": gateway.rtt,
"relay_host (BND.ADDR it answers)": gateway.relay_host, "exit_host (source of the datagrams it sends on)": gateway.exit_host,
"fake_stun_address": list(gateway.stun.address), "fake_stun_requests_answered": gateway.stun.requests,
"tcp_exit": gateway.tcp_exit,
"accepted_control_connections_s": list(gateway.accepted),
"requests (s, connection, kind, detail)": [list(r) for r in gateway.requests],
"connects": [list(c) for c in gateway.connects],
"associates": gateway.associates,
"associations (start, end in s)": [list(a) for a in gateway.associations],
"exit_ports": list(gateway.exit_ports),
"bnd_ports_told_to_the_client": sorted(self.bnd_ports),
"datagram_log (host, port, atyp, s)": [list(d) for d in gateway.datagram_log],
"datagram_via (host, port, association, s)": [list(d) for d in gateway.datagram_via],
"datagrams_carried (host, port, payload length, head hex)": [[h, p, len(d), d[:24].hex()] for h, p, d in gateway.datagrams],
"send_errors": list(gateway.send_errors),
"source_filter": ("none: Gateway._associate keeps the source address of the last well-formed datagram as the client and answers "
"it; no datagram is refused as foreign by its source address. What it does not carry: a datagram shorter than "
"10 bytes or with FRAG != 0 (skipped), one the route drops (stun_answers False, forward_only_to); both are in "
"gateway-udp-datagrams.jsonl."),
}
try:
self.cells["declared_udp_of_the_core_for_this_proxy"] = declared_udp_or_absent(gateway.proxy)
except Exception as problem:
self.cells["declared_udp_of_the_core_for_this_proxy"] = "not read: %r" % (problem,)
def _gather_behind_a_coherent_gateway(monkeypatch, credentials, ice_prefs, rtt_ms, evidence=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."""
its relay reaches, and say whether the page's request took the relay and what the gather looked like. With `evidence` (a
`FailureEvidence`) the gateway, its sockets, the page and the launch are also recorded for it (`_Watch`); nothing else differs."""
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
@@ -438,16 +795,20 @@ def _gather_behind_a_coherent_gateway(monkeypatch, credentials, ice_prefs, rtt_m
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:
relay_host = this_host_address()
with coherent(user=user, password=password, relay_host=relay_host, rtt_ms=rtt_ms) as gateway, _Watch(gateway, monkeypatch, evidence, relay_host) as watch:
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:
watch.arm()
launched = _launch_behind(gateway, binary_path=binary, extra_prefs=extra_prefs)
watch.launched(launched)
with launched as browser:
page = browser.new_context().new_page()
page.goto("about:blank")
res = page.evaluate(_RELAY_PROBE_JS, stun)
res = watch.evaluate(page, _RELAY_PROBE_JS, stun)
carried = [(host, port) for host, port, _payload in gateway.datagrams]
stun_requests = gateway.stun.requests
associates = gateway.associates
@@ -504,10 +865,24 @@ def test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_it
"""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
ice_id = _ICE_IDS[_ICE_PREFS.index(ice_prefs)]
# When it fails it saves, under `invpw-evidence/webrtc-far-away-<ice row>-<rtt>/`, where the page's STUN request went: `cells.json` (the
# gateway's own lists, the page's result, `timings_ms_from_the_offer`, the verdict, the addresses of the runner and the network the core
# declares), `gateway-control-connections.jsonl`, `gateway-udp-datagrams.jsonl`, `page-view.jsonl`, `juggler-wire.jsonl` and
# `juggler-engine-trace/`. The assertion below is the one it always was.
with FailureEvidence("webrtc-far-away-%s-%d" % (ice_id, rtt_ms)) as evidence:
cells = {"test": "far-away gateway", "rtt_ms": rtt_ms, "ice_prefs": ice_prefs, "ice_row": ice_id}
evidence.note_cells(cells)
try:
took_the_relay, verdict, _timings = _gather_behind_a_coherent_gateway(
monkeypatch, ("alice", "s3cret"), ice_prefs, rtt_ms, evidence=evidence)
cells["timings_ms_from_the_offer"] = _timings
cells["verdict"] = verdict
print(f"[gather] rtt {rtt_ms} ms, {ice_id}: {_timings}")
assert took_the_relay, "the page's STUN request did not take the relay. " + verdict
except BaseException:
cells["interfaces_of_the_runner"] = _interfaces_of_this_runner(cells.get("relay_host"))
raise
_START_A_GATHER_JS = r"""async (stun) => {