Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
021e541314 | ||
|
|
7bff02b03d | ||
|
|
76c9a2dd9f | ||
|
|
c02384430d | ||
|
|
58f937a95f | ||
|
|
8f0e158c85 | ||
|
|
825418d95a | ||
|
|
b44bea2d0d | ||
|
|
716ff800ba | ||
|
|
917d01e558 | ||
|
|
978e395e84 | ||
|
|
a3acdd5585 | ||
|
|
6f20604b3e | ||
|
|
8d96daab6e | ||
|
|
5a532b621e | ||
|
|
10db4cf32a | ||
|
|
526cb06aa2 | ||
|
|
583cc601ec | ||
|
|
286a4f13c3 | ||
|
|
d184f4f895 | ||
|
|
60e8bda53f | ||
|
|
00d672f94a | ||
|
|
bc9dafef2d | ||
|
|
23ed3edc01 | ||
|
|
be2d1bacb5 | ||
|
|
47150e8218 | ||
|
|
5249f812ca | ||
|
|
1c01b2a80e | ||
|
|
71425ab1bd | ||
|
|
db8b56f998 | ||
|
|
933e5b220e | ||
|
|
5da9ce42ca | ||
|
|
340a1df516 |
No files matched your search
+165
-5
@@ -6,8 +6,7 @@
|
||||
# launched Firefox in true HEADLESS mode, which is content-process unstable on
|
||||
# the hosted runners (eval-CSP / context-destroyed). The stealth wrapper instead
|
||||
# launches Firefox HEADED on a real display; under `xvfb-run` (a virtual X
|
||||
# server) that's exactly what we get on a headless CI box - stable, and the same
|
||||
# thing webrtc-e2e.yml already relies on.
|
||||
# server) that's exactly what we get on a headless CI box - stable.
|
||||
#
|
||||
# Secret-free, so it's safe in public CI: the binary is the PUBLIC firefox-9
|
||||
# release (no token), and the webrtc e2e fake a local TCP-only SOCKS. The proxy
|
||||
@@ -34,6 +33,15 @@ on:
|
||||
- 'docs/**'
|
||||
- 'LICENSE'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
only:
|
||||
description: "Which job. `windows-control-a` runs only the Windows job of the keyboard shortcut (after the core of a release is on the index and its engine is published); `all` runs the whole workflow."
|
||||
required: false
|
||||
default: "all"
|
||||
type: choice
|
||||
options:
|
||||
- all
|
||||
- windows-control-a
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -75,7 +83,7 @@ jobs:
|
||||
e2e:
|
||||
name: e2e (linux, xvfb)
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true'
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 40
|
||||
steps:
|
||||
@@ -116,6 +124,13 @@ jobs:
|
||||
# The generator moved into the core with the module it writes (0.30.0),
|
||||
# so the check runs against the core this package installs.
|
||||
run: python -m invisible_core.juggler._gen_protocol --check --binary "$(dirname "$FF")"
|
||||
# The GeoIP database is made by the repository (scripts/ci_lab_geoip.py: the same bytes on every run, the sha256 in ci/geoip.json), never a
|
||||
# site and never a licensed file: without STEALTHFOX_GEOIP_MMDB the core asks GitHub which database is the latest on every call
|
||||
# (run 43211837926). The variable reaches every later step of the job.
|
||||
- name: The GeoIP database (made by the repository, same bytes every run)
|
||||
shell: bash
|
||||
run: python scripts/ci_lab_geoip.py build
|
||||
|
||||
- name: Run the full e2e suite under a virtual display, without the root ones
|
||||
# PYTHONUNBUFFERED, and it is not a nicety. Without it Python block-buffers
|
||||
# stdout when it is a pipe, and this step printed NOTHING for 39 minutes
|
||||
@@ -134,9 +149,11 @@ jobs:
|
||||
INVPW_TEST_WATCHDOG_FILE: ${{ runner.temp }}/e2e-watchdog.log
|
||||
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
|
||||
# The root ones are left out by name and run in the step below, as root: here, as the runner user, they errored.
|
||||
SANDBOX_FILES: tests/test_the_socket_process_is_sandboxed_e2e.py
|
||||
# The root ones are left out by name and run in the step below, as root: here, as the runner user, they errored. The sandbox one is left out
|
||||
# by name too and runs in its own step after them: it is red on a runner whose AppArmor refuses user namespaces to a normal user.
|
||||
run: |
|
||||
IGNORE=(); for f in $ROOT_FILES; do IGNORE+=("--ignore=$f"); done
|
||||
IGNORE=(); for f in $ROOT_FILES $SANDBOX_FILES; do IGNORE+=("--ignore=$f"); done
|
||||
DESELECT=(); for n in $ROOT_NODES; do DESELECT+=("--deselect=$n"); done
|
||||
xvfb-run -a python -u scripts/run_e2e.py "$FF" "${IGNORE[@]}" "${DESELECT[@]}"
|
||||
|
||||
@@ -175,6 +192,32 @@ jobs:
|
||||
if counts["tests"] != int(os.environ["ROOT_TESTS"]) or counts["failures"] or counts["errors"] or counts["skipped"]:
|
||||
sys.exit("the root e2e must be exactly %s tests, all passed: %s" % (os.environ["ROOT_TESTS"], counts))
|
||||
PY
|
||||
# THE SANDBOX E2E (wrapper.e2e.udp.sandbox), as the gate runs its first file: the browser WITH its sandbox, run by the runner user. On this runner AppArmor
|
||||
# refuses user namespaces to a normal user (kernel.apparmor_restrict_unprivileged_userns=1), so the browser of every other step starts WITHOUT the sandbox
|
||||
# of its socket and content processes, and tests/test_the_socket_process_is_sandboxed_e2e.py (which fails unless both have a seccomp filter) can only
|
||||
# be green after the restriction is turned off. It is left out of the run above by name (SANDBOX_FILES) so that it cannot fail on a runner without the
|
||||
# sysctl, and it runs here, after the run and the root step (whatever the sysctl changes cannot reach a launch of the run), as the runner user. Nothing
|
||||
# is skipped silently: the step reads its own junit and refuses anything but exactly that many tests, all passed.
|
||||
# tests/test_the_sandbox_e2e_runs_where_user_namespaces_are_on.py holds this step, the exclusion above and the order.
|
||||
- name: The sandbox e2e (wrapper.e2e.udp.sandbox), with unprivileged user namespaces on
|
||||
if: success() || failure()
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
SANDBOX_FILES: tests/test_the_socket_process_is_sandboxed_e2e.py
|
||||
SANDBOX_TESTS: "1"
|
||||
run: |
|
||||
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
|
||||
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" || true
|
||||
python - <<'PY'
|
||||
import os, sys, xml.etree.ElementTree as ET
|
||||
root = ET.parse(os.path.join(os.environ["RUNNER_TEMP"], "sandbox-e2e.xml")).getroot()
|
||||
suite = root if root.tag == "testsuite" else root.find("testsuite")
|
||||
counts = {k: int(suite.get(k, 0)) for k in ("tests", "failures", "errors", "skipped")}
|
||||
print("sandbox e2e:", counts)
|
||||
if counts["tests"] != int(os.environ["SANDBOX_TESTS"]) or counts["failures"] or counts["errors"] or counts["skipped"]:
|
||||
sys.exit("the sandbox e2e must be exactly %s tests, all passed: %s" % (os.environ["SANDBOX_TESTS"], counts))
|
||||
PY
|
||||
- name: What the root step left behind (diagnostic, decides nothing)
|
||||
if: always()
|
||||
run: |
|
||||
@@ -182,6 +225,15 @@ jobs:
|
||||
echo "-- /etc/resolv.conf"; cat /etc/resolv.conf || true
|
||||
echo "-- lo"; ip -4 addr show lo || true
|
||||
|
||||
# The leg ran with the pinned database, and the core never went past it to GitHub (tests/geoip_used.py wrote what it did).
|
||||
- name: The leg ran with the pinned GeoIP database
|
||||
if: always()
|
||||
shell: bash
|
||||
run: |
|
||||
python scripts/ci_lab_geoip.py evidence --out "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" > /dev/null
|
||||
python scripts/ci_lab_geoip.py verify --evidence "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" --used "$GEOIP_USED_OUT"
|
||||
|
||||
|
||||
# Runs ONLY if the full run above fails, and before 2026-08-13 it could not
|
||||
# exist: the hang was killed by the 40-minute ceiling, so the job came out
|
||||
# `cancelled` and the following steps did not start at all. With
|
||||
@@ -219,3 +271,111 @@ jobs:
|
||||
path: ${{ runner.temp }}/e2e-watchdog.log
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
|
||||
# ``Control+A`` selects all in a field, on the PUBLISHED engine and the core this package pins, on Windows, where the keyboard of a real
|
||||
# user is: the shortcut letter used to reach the browser as Control+Shift+A (invisible-core 63.66.0 fixes it). The e2e is red on the
|
||||
# keyboard that held Shift for the capital A (tests/test_control_a_selects_all_in_a_field_e2e.py: 5 ways to press it x an <input> and a
|
||||
# <textarea>, in-process and served to the stock Playwright client). Same gate as the Linux job: it is SKIPPED, with the reason in the
|
||||
# summary, until the core is on the index, and it runs unchanged after; `workflow_dispatch` with `only: windows-control-a` runs it alone.
|
||||
e2e-windows-control-a:
|
||||
name: e2e (windows, Control+A)
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true'
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 20
|
||||
# `run:` blocks are PowerShell on Windows unless said otherwise (e2e-hunt.yml had a ParserError on its first launch there).
|
||||
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 (the stock client is in the dev extra)
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install ".[dev]"
|
||||
- name: Fetch the published firefox binary
|
||||
run: echo "FF=$(python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
- name: The keyboard shortcut selects all (the browser opens on the runner's desktop, as in e2e-hunt.yml)
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
run: INVPW_BINARY_PATH="$FF" python -u -m pytest -m e2e -p no:cacheprovider -v tests/test_control_a_selects_all_in_a_field_e2e.py
|
||||
|
||||
# THE SAME e2e ON WINDOWS (Federico, 12/11: every test of the product runs on Linux AND Windows; where Windows behaves
|
||||
# differently the test adapts to the system). Before this, 562 of the 808 e2e had never run on Windows in any round. The census
|
||||
# of 12/11 (run 43307193708) took ~50 minutes in one job, so the files are split in four parts (the sorted list, every fourth
|
||||
# file: a split that does not move when a file is added elsewhere). Left out, by name, are the suites ci/required-suites.json
|
||||
# declares `linux_only` (the reason is on the row); tests/test_every_suite_runs_on_linux_and_windows.py holds both together.
|
||||
e2e-windows:
|
||||
name: e2e (windows, part ${{ matrix.part }})
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: windows-2022
|
||||
timeout-minutes: 40
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
part: [1, 2, 3, 4]
|
||||
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: Fetch the published firefox binary
|
||||
run: echo "FF=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
# The GeoIP database made by the repository, as on the Linux run (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 files of this part, without the linux_only suites
|
||||
run: |
|
||||
set -e
|
||||
python -m pytest --collect-only -q -m e2e -o addopts= -p no:cacheprovider 2>/dev/null | grep "::" | cut -d: -f1 | sort -u > "$RUNNER_TEMP/e2e_files.txt"
|
||||
python - "${{ matrix.part }}" "$RUNNER_TEMP" <<'PY'
|
||||
import json, os, sys
|
||||
part, tmp = int(sys.argv[1]), sys.argv[2]
|
||||
rows = json.load(open("ci/required-suites.json", encoding="utf-8"))
|
||||
left_out = [t for r in rows if r.get("linux_only") for t in r["tests"]]
|
||||
files = [l.strip() for l in open(os.path.join(tmp, "e2e_files.txt")) if l.strip()]
|
||||
files = [f for f in files if f not in left_out]
|
||||
mine = [f for i, f in enumerate(files) if i % 4 == part - 1]
|
||||
nodes = [t for t in left_out if "::" in t and t.split("::")[0] in mine]
|
||||
open(os.path.join(tmp, "e2e_args.txt"), "w").write("\n".join(mine + ["--deselect=" + n for n in nodes]) + "\n")
|
||||
print("%d e2e files, %d left out as linux_only, %d in part %d, %d node(s) deselected"
|
||||
% (len(files) + len([t for t in left_out if "::" not in t]), len(left_out), len(mine), part, len(nodes)))
|
||||
PY
|
||||
- name: Run this part of the e2e
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
INVPW_TEST_WATCHDOG_FILE: ${{ runner.temp }}/e2e-watchdog.log
|
||||
run: |
|
||||
mapfile -t ARGS < <(tr -d '\r' < "$RUNNER_TEMP/e2e_args.txt")
|
||||
python -u scripts/run_e2e.py "$FF" "${ARGS[@]}"
|
||||
- name: The leg ran with the pinned GeoIP database
|
||||
if: always()
|
||||
run: |
|
||||
python scripts/ci_lab_geoip.py evidence --out "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" > /dev/null
|
||||
python scripts/ci_lab_geoip.py verify --evidence "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" --used "$GEOIP_USED_OUT"
|
||||
- name: Close every Firefox left
|
||||
if: always()
|
||||
shell: pwsh
|
||||
run: |
|
||||
Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||
"left: " + @(Get-Process firefox -ErrorAction SilentlyContinue).Count
|
||||
- name: Upload the hang evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: e2e-watchdog-windows-${{ matrix.part }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: ${{ runner.temp }}/e2e-watchdog.log
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
@@ -196,8 +196,27 @@ jobs:
|
||||
# code no job has run.
|
||||
run: python -m pytest -q
|
||||
|
||||
# The three checks on the REAL GeoIP database, and only here (the release): the legs of the pull requests and of the gates launch with the database that
|
||||
# scripts/ci_lab_geoip.py makes (a few networks, the same bytes every run, no download), so what only the real one can show is looked at once per release:
|
||||
# the product's own road (no variable, cold cache, the latest database downloaded), the lab database against it for the six exits, and every
|
||||
# time_zone of the database known to the runner's tz database. See the docstring of scripts/ci_real_geoip_check.py.
|
||||
real-geoip-database:
|
||||
needs: already-published
|
||||
if: needs.already-published.outputs.present != 'yes'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- name: Install the wrapper (its core comes from the index)
|
||||
run: python -m pip install -e . maxminddb
|
||||
- name: The real GeoIP database - the product's road, the lab database against it, every zone known
|
||||
run: python scripts/ci_real_geoip_check.py
|
||||
|
||||
upload:
|
||||
needs: [already-published, gate]
|
||||
needs: [already-published, gate, real-geoip-database]
|
||||
if: needs.already-published.outputs.present != 'yes'
|
||||
runs-on: ubuntu-latest
|
||||
environment: pypi # the trust relationship lives HERE, behind the gate
|
||||
|
||||
@@ -173,15 +173,15 @@ jobs:
|
||||
# untested until 2026-08-01, and the user who opened issue #51 was on
|
||||
# 3.14. test_marker_vocabulary.py compares this list to the floor.
|
||||
python: ["3.11", "3.12", "3.13", "3.14"]
|
||||
# Windows runners are the scarce, 2x-cost, slow-to-schedule ones, and a
|
||||
# burst of pushes queues them for a long time. Run the FULL Python range
|
||||
# on ubuntu (cheap, fast) and cover Windows on 3.12 only - this is a
|
||||
# pure-Python package, the OS-specific surface is tiny. The python LIST
|
||||
# above stays complete so test_marker_vocabulary still sees every version.
|
||||
# The FULL Python range on ubuntu; Windows on the two ends of the range,
|
||||
# 3.11 and 3.14 (Federico, 12/11: every test on Linux AND Windows; the
|
||||
# ends are where a version-specific difference shows first). The runners
|
||||
# are free for this public repository; the account runs 20 jobs at once.
|
||||
# The python LIST above stays complete so test_marker_vocabulary still
|
||||
# sees every version.
|
||||
exclude:
|
||||
- { os: windows-latest, python: "3.11" }
|
||||
- { os: windows-latest, python: "3.12" }
|
||||
- { os: windows-latest, python: "3.13" }
|
||||
- { os: windows-latest, python: "3.14" }
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -222,12 +222,27 @@ jobs:
|
||||
run: |
|
||||
python -m ruff check --select F821,F811,F601 --no-cache --output-format concise .
|
||||
|
||||
# The GeoIP database is made by the repository (scripts/ci_lab_geoip.py: the same bytes on every run, the sha256 in ci/geoip.json), never a
|
||||
# site and never a licensed file: without STEALTHFOX_GEOIP_MMDB the core asks GitHub which database is the latest on every call
|
||||
# (run 43211837926). The variable reaches every later step of the job.
|
||||
- name: The GeoIP database (made by the repository, same bytes every run)
|
||||
shell: bash
|
||||
run: python scripts/ci_lab_geoip.py build
|
||||
|
||||
- name: Run pytest
|
||||
shell: bash
|
||||
run: |
|
||||
set -o pipefail # or tee would swallow pytest's exit code
|
||||
pytest tests/ -v --tb=short -rs | tee tests-report.txt
|
||||
|
||||
# The leg ran with the pinned database, and the core never went past it to GitHub (tests/geoip_used.py wrote what it did).
|
||||
- name: The leg ran with the pinned GeoIP database
|
||||
if: always()
|
||||
shell: bash
|
||||
run: |
|
||||
python scripts/ci_lab_geoip.py evidence --out "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" > /dev/null
|
||||
python scripts/ci_lab_geoip.py verify --evidence "$(dirname "$GEOIP_USED_OUT")/geoip-evidence.json" --used "$GEOIP_USED_OUT"
|
||||
|
||||
# This repo has the largest suite of the three and was the only one with
|
||||
# no floor. pytest's exit code cannot distinguish "everything passed"
|
||||
# from "the marker expression deselected everything", and `addopts`
|
||||
|
||||
@@ -94,12 +94,12 @@ jobs:
|
||||
- uses: actions/setup-python@v5
|
||||
with: { python-version: '3.11' }
|
||||
|
||||
# Only what the TEST needs. The package under test is installed by the
|
||||
# Only what the TEST needs (and `uv`, for the wait below to ask uv, which the release test installs the package with). The package under test is installed by the
|
||||
# test itself, into a venv it creates, from the index - installing it
|
||||
# here as well would put a second copy on the path and the assertions
|
||||
# would be reading the wrong one.
|
||||
- name: Test harness only
|
||||
run: python -m pip install --upgrade pip pytest packaging
|
||||
run: python -m pip install --upgrade pip pytest packaging uv
|
||||
|
||||
# PyPI does not serve a new version to pip the instant twine finishes, and
|
||||
# this workflow runs on the ledger pull request, which the publish run
|
||||
@@ -115,9 +115,11 @@ jobs:
|
||||
# started later, was green). Those are three different pages of the index, and
|
||||
# the job only needs the one pip installs from.
|
||||
#
|
||||
# So the question asked here is pip's own: `pip download invisible-playwright==X`,
|
||||
# the same client, the same index, no cache. Bounded at ten minutes: a forgotten
|
||||
# publish still fails, and it fails HERE, saying that the index does not have the
|
||||
# So the question asked here is the INSTALLERS' own, both: the upgrade test installs with pip, the release test with uv (the README's
|
||||
# way in), so each round asks `pip download invisible-playwright==X` AND `uv pip compile` of it (no cache, nothing installed), and the
|
||||
# job goes on only after three rounds in a row in which both said yes, 15 s apart (one yes proves that one request saw the version, not
|
||||
# that the next is served by the same node of the index); a no restarts the count and a call that does not answer in two minutes is
|
||||
# a no. Bounded at ten minutes: a forgotten publish still fails, and it fails HERE, saying that the index does not have the
|
||||
# version, instead of three steps later as a test that compares two versions.
|
||||
#
|
||||
# Only on the ledger pull request. A scheduled or dispatched run is not
|
||||
@@ -134,21 +136,40 @@ jobs:
|
||||
deadline = time.monotonic() + 600
|
||||
deadline = min(deadline, time.monotonic() + float(os.environ.get("INDEX_WAIT_SECONDS", "600")))
|
||||
poll = float(os.environ.get("INDEX_WAIT_POLL", "15"))
|
||||
n = 0
|
||||
need = int(os.environ.get("INDEX_WAIT_CONFIRMATIONS", "3"))
|
||||
call_limit = float(os.environ.get("INDEX_WAIT_CALL_SECONDS", "120"))
|
||||
asks = [
|
||||
("pip", [sys.executable, "-m", "pip", "download", "--no-deps", "--no-cache-dir", "--disable-pip-version-check", "--quiet",
|
||||
"-d", tempfile.mkdtemp(), f"{dist}=={version}"], None),
|
||||
("uv", [sys.executable, "-m", "uv", "pip", "compile", "-", "--no-deps", "--no-cache", "--quiet"], f"{dist}=={version}\n"),
|
||||
]
|
||||
|
||||
|
||||
def round_says():
|
||||
"""An empty string when every installer resolves the version, else what the first that did not said."""
|
||||
for tool, command, stdin in asks:
|
||||
try:
|
||||
r = subprocess.run(command, input=stdin, capture_output=True, text=True, timeout=call_limit)
|
||||
except subprocess.TimeoutExpired:
|
||||
return f"{tool} did not answer within {call_limit:.0f} s"
|
||||
if r.returncode != 0:
|
||||
return f"{tool} said: " + ((r.stderr.strip().splitlines() or [""])[-1])
|
||||
return ""
|
||||
|
||||
|
||||
n = streak = 0
|
||||
said = ""
|
||||
while True:
|
||||
n += 1
|
||||
r = subprocess.run([sys.executable, "-m", "pip", "download", "--no-deps", "--no-cache-dir",
|
||||
"--disable-pip-version-check", "--quiet", "-d", tempfile.mkdtemp(),
|
||||
f"{dist}=={version}"], capture_output=True, text=True)
|
||||
if r.returncode == 0:
|
||||
print(f"::notice::pip downloads {dist} {version} from the index (attempt {n})")
|
||||
said = round_says()
|
||||
streak = 0 if said else streak + 1
|
||||
if streak >= need:
|
||||
print(f"::notice::pip and uv resolve {dist} {version} from the index, {need} rounds in a row (attempt {n})")
|
||||
sys.exit(0)
|
||||
said = (r.stderr.strip().splitlines() or [""])[-1]
|
||||
if time.monotonic() >= deadline:
|
||||
minutes = int(float(os.environ.get("INDEX_WAIT_SECONDS", "600")) // 60) or 1
|
||||
print(f"::error::the index does not have {dist} {version} yet, after {minutes} minutes "
|
||||
f"and {n} attempts (pip said: {said})")
|
||||
f"and {n} attempts, {streak} of {need} rounds in a row ({said})")
|
||||
sys.exit(1)
|
||||
time.sleep(poll)
|
||||
PY
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
name: webrtc-e2e
|
||||
|
||||
# Live WebRTC realness check against the shipped patched binary.
|
||||
#
|
||||
# Manual (workflow_dispatch) on purpose: it needs a firefox-N binary that
|
||||
# carries the WebRTC fixes (synthetic srflx in genuine nICEr form + the
|
||||
# default-route fallback behind a proxy). Run it after publishing such a
|
||||
# binary - it is the release gate for "WebRTC looks real behind a proxy".
|
||||
# On this Linux runner an engine older than firefox-35 never gets the synthetic
|
||||
# srflx behind a SOCKS proxy (the wildcard default-route probe, fixed in
|
||||
# firefox-35): test_not_blocked_behind_tcp_only_socks skips on it, naming that
|
||||
# defect, and the floor below turns the skip red. From firefox-35 on, a
|
||||
# missing srflx fails the test itself.
|
||||
#
|
||||
# No external proxy provider, no credentials: the "behind a proxy" condition is faked by an
|
||||
# in-process TCP-only SOCKS5 server (refuses UDP ASSOCIATE) and the egress IP
|
||||
# is injected as an RFC 5737 TEST-NET address. Fully self-contained.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Engine and GeoIP downloads go through the release API with this token.
|
||||
# Anonymous requests share a 60-an-hour limit per runner address and are the
|
||||
# ones GitHub drops first when it is degraded (2026-11-08: timeouts for
|
||||
# unauthenticated users failed the gates three times). user-install.yml stays
|
||||
# anonymous on purpose: it is the user's path.
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
# `pip install -e ".[dev]"` below resolves `invisible-core==N.M.0` from the
|
||||
# package index, and the core is published BEFORE this package. This gate
|
||||
# answers whether it is there yet; during that window the realness job is
|
||||
# SKIPPED with the reason in the run summary rather than faked green, and
|
||||
# once the core is up it runs unchanged. See
|
||||
# .github/workflows/core-on-index.yml.
|
||||
core-on-index:
|
||||
uses: ./.github/workflows/core-on-index.yml
|
||||
|
||||
webrtc-e2e:
|
||||
name: webrtc realness (ubuntu, py3.12)
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python 3.12
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: pip
|
||||
|
||||
- name: Install package + dev extras
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -e ".[dev]"
|
||||
|
||||
- name: Fetch the patched Firefox binary and expose its path
|
||||
shell: bash
|
||||
run: |
|
||||
# NOT `echo "VAR=$(cmd)" >> $GITHUB_ENV`. echo exits 0 whatever the
|
||||
# substitution did, so `set -e` never sees a failure and an EMPTY
|
||||
# value lands in the environment. Both tests below then hit
|
||||
# `pytest.skip("no patched binary")`, pytest exits 0, and the job is
|
||||
# green having verified nothing - which is exactly what run #1 did.
|
||||
set -euo pipefail
|
||||
FETCH_OUTPUT="$(python -m invisible_playwright fetch)"
|
||||
printf '%s\n' "$FETCH_OUTPUT"
|
||||
BIN="$(printf '%s\n' "$FETCH_OUTPUT" | tail -n 1)"
|
||||
if [ -z "$BIN" ] || [ ! -e "$BIN" ]; then
|
||||
echo "invisible_playwright fetch returned '$BIN', which is not a" >&2
|
||||
echo "file. Refusing to run a suite that would skip itself green." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "STEALTHFOX_E2E_BINARY=$BIN" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Run WebRTC realness e2e (xvfb for the headless Firefox)
|
||||
run: |
|
||||
set -o pipefail
|
||||
sudo apt-get update && sudo apt-get install -y xvfb
|
||||
xvfb-run -a pytest tests/test_webrtc_realness.py -m e2e -o addopts="" -v -rs | tee webrtc-report.txt
|
||||
|
||||
# Run #1 was GREEN with the headline assertion skipped: "1 passed, 1
|
||||
# skipped", and the skipped one is the test this workflow's own header
|
||||
# calls the point of the gate. pytest's exit code cannot tell that from a
|
||||
# pass, and this file was the only one of four without a floor.
|
||||
- name: Refuse a run whose main assertion did not execute
|
||||
shell: bash
|
||||
run: |
|
||||
python - <<'PY'
|
||||
import pathlib, re, sys
|
||||
text = pathlib.Path("webrtc-report.txt").read_text(encoding="utf-8", errors="ignore")
|
||||
passed = int((re.search(r"(\d+) passed", text) or [0, 0])[1] or 0)
|
||||
skipped = int((re.search(r"(\d+) skipped", text) or [0, 0])[1] or 0)
|
||||
if skipped:
|
||||
print("these tests SKIPPED, so the gate verified less than it "
|
||||
"claims:", file=sys.stderr)
|
||||
for line in text.splitlines():
|
||||
if line.startswith("SKIPPED"):
|
||||
print(" " + line, file=sys.stderr)
|
||||
if passed < 2 or skipped:
|
||||
print(f"{passed} passed / {skipped} skipped - this gate exists for "
|
||||
f"the synthetic-srflx assertion; a run that skips it is not "
|
||||
f"a pass.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
print(f"{passed} tests ran, none skipped")
|
||||
PY
|
||||
@@ -0,0 +1,75 @@
|
||||
# windows-two-tests-hunt.yml - hunt scaffolding, never merged. Runs only on a push to a `hunt/windows-two-tests**` branch.
|
||||
# The two Windows reds of PR #486 run 43383366904 judged on the time (transport late element, cross-origin count), on their fix, x20.
|
||||
name: windows two tests hunt
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['hunt/windows-two-tests**']
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: windows-two-tests-hunt-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
hunt:
|
||||
name: windows two tests x20
|
||||
runs-on: windows-2022
|
||||
timeout-minutes: 120
|
||||
strategy:
|
||||
max-parallel: 1
|
||||
matrix:
|
||||
os: [windows-2022]
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
|
||||
with: { python-version: '3.11' }
|
||||
- name: Install
|
||||
run: |
|
||||
set -e
|
||||
python -m pip install --quiet --upgrade pip
|
||||
python -m pip install --quiet ".[dev]"
|
||||
python -m pip install --quiet "playwright==$(cat scripts/playwright_pin.txt)"
|
||||
echo "FF=$(cd "$RUNNER_TEMP" && python -m invisible_playwright fetch | tail -1)" >> "$GITHUB_ENV"
|
||||
python scripts/ci_lab_geoip.py build
|
||||
- name: The two tests twenty times
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
INVPW_TEST_WATCHDOG_FILE: ${{ github.workspace }}/evidence/e2e-watchdog.log
|
||||
run: |
|
||||
set +e
|
||||
mkdir -p evidence
|
||||
export INVPW_BINARY_PATH="$FF" STEALTHFOX_E2E_BINARY="$FF"
|
||||
for n in $(seq -w 1 40); do
|
||||
export INVPW_HUNT_POPUP_TRACE="$PWD/evidence/trace_$n.jsonl"
|
||||
python -u scripts/run_e2e.py "$FF" tests/test_juggler_transport.py::test_the_public_API_WAITS_for_an_element_that_arrives_late tests/test_cross_origin_iframe.py::test_cross_origin_iframe_frame_locator_resolves_button -rA --tb=short --timeout 200 > "evidence/run_$n.log" 2>&1
|
||||
echo "run $n: $(grep -aE '^=+ .*(passed|failed|error).* =+$' evidence/run_$n.log | head -1)"
|
||||
done
|
||||
{
|
||||
echo "## the two tests x20 on Windows"
|
||||
echo '```'
|
||||
grep -ahE "^(FAILED|ERROR) " evidence/run_*.log | cut -c1-200 | sort | uniq -c | sort -rn || true
|
||||
echo '```'
|
||||
} | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
- name: Close every Firefox left
|
||||
if: always()
|
||||
shell: pwsh
|
||||
run: |
|
||||
Get-Process firefox -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||
"left: " + @(Get-Process firefox -ErrorAction SilentlyContinue).Count
|
||||
- name: Upload the evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: windows-two-tests-${{ github.run_id }}
|
||||
path: evidence
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
+29
-11
@@ -11,6 +11,35 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
### Changed
|
||||
- The project moved to the oss-invisible GitHub organization: every GitHub link, the issue templates and the package URLs point to github.com/oss-invisible/playwright. The PyPI name and the import name do not change; the old addresses redirect.
|
||||
|
||||
### Fixed
|
||||
- A popup (a `window.open` or a `target=_blank` link) could be handed to the client at `about:blank`, with the blank page's `load`, when it
|
||||
was opened with no route on the context: the commit of its address, or its `DOMContentLoaded` and `load`, arrived while the page was being
|
||||
handed from its buffer to its dispatcher and was told to nobody (`page.url` stayed `about:blank`, or `wait_for_load_state("load")` timed
|
||||
out). Measured on Windows with the library's client in the same process, `test_popups_reach_the_client_e2e.py` x20 on 4 workers: 3 runs
|
||||
red with the published firefox-62 engine and 11 with firefox-63. The page is now handed over in one step: what the client was not told is
|
||||
said once, in order, and nothing the engine sent in that period is lost.
|
||||
- The same hand-over dropped every event that is not a request: a `console` message, a `pageError`, a `dialog` (an `alert()` that opened
|
||||
while the popup was being built blocked its page for good, because no client had been told of it and none could answer it), a `crash`, a file chooser. All
|
||||
of them are given back now, in the order they arrived. The only bound left is the memory of the buffer (512 events): an event beyond it is
|
||||
lost and a `RuntimeWarning` says how many, once per page.
|
||||
- The hand-over holds when the engine's reader, the adoption and a close run at the same time: a `load` is told to the client once (not twice,
|
||||
so `page.on("load")` runs once); an event the engine sends while the held ones are being given back waits for them (a response is never handled
|
||||
before its request); a document committed at the same address as the previous one is told; a page closed while it was being adopted is not given
|
||||
frames, and is not announced, after its `__dispose__`; one frame never gets two dispatchers.
|
||||
- A popup could still be handed to the client at `about:blank` (or with its navigation pending again, and "Execution context was destroyed" in its
|
||||
first evaluate) when the destination committed while the events the page had missed were being replayed to it: the engine's reader went on
|
||||
delivering the live events to the lifecycle, and the replay then brought older ones after them. The page now subscribes its readers and is
|
||||
handed the missed events in one step, with the delivery of the sessions' events held, so a live event never overtakes the replay.
|
||||
With the three corrections together, on Windows with the library's client in the same process, under load: 680/680 and 256/256 popup cases
|
||||
green (run 43261858525).
|
||||
- `Control+A` selects all in an `<input>` and a `<textarea>` on Windows, on the published engine and the core this package pins: a new end-to-end
|
||||
test (five ways to press the shortcut, in-process and served to the stock client), run by `e2e.yml` on Windows, 20/20 green (run 43262320744).
|
||||
- Tests only: the e2e tests of the test servers take their ports from one sequence (no two servers draw the same one); the two tests that read a
|
||||
consecutive pair of host ports run alone, after the parallel tests; the sandbox e2e (the browser's seccomp filter) runs in a step of its own that
|
||||
turns unprivileged user namespaces on, and is left out of the normal run; every leg launches with a GeoIP database the repository builds (same
|
||||
bytes every run, no download); the CodeQL alerts of the test code are fixed; the install job waits for the package index through both installers;
|
||||
the raw Juggler tests wait for `Page.ready` and the main frame instead of a fixed time.
|
||||
|
||||
## [0.51.0] - 2026-11-12
|
||||
|
||||
### Changed
|
||||
@@ -62,17 +91,6 @@ comparison run is saved). The result of a `window.open` (`null` or a window) is
|
||||
`extra_prefs={"dom.disable_open_during_load": False}` for the session, knowing that a page then sees a browser that differs from a
|
||||
retail Firefox.
|
||||
|
||||
### Known issues
|
||||
- **A popup opened without a route can be announced while it is still on `about:blank`.** A popup opened with no route on the context
|
||||
(a `target=_blank` link, or `window.open` from a click) can be announced to the client while it is still on `about:blank`; its `url`
|
||||
then stays `about:blank`, or its `load` never arrives. Seen on a Windows runner with the library's client in the same process and four
|
||||
workers running the popup tests in parallel (`test_popups_reach_the_client_e2e.py`, 20 runs): with the firefox-63 engine 17 cases of 640
|
||||
in 12 of 20 runs; with the published firefox-62 engine (so also with 0.50.1) 15 cases of 640. Both causes found are in the wrapper: the hand-over of
|
||||
a new page to the client, and the replay of a new page's events while live ones are being delivered. The correction of the first alone,
|
||||
not in this release, lowers the red cases over 20 runs from 15 to 2 with engine 62 and from 17 to 13 with engine 63; the correction of the
|
||||
second is under test. On Linux no run was red (0 of 20). Not measured: a served
|
||||
launch with numbers of its own, other machines, a run without parallel workers, macOS.
|
||||
|
||||
## [0.50.1] - 2026-11-12
|
||||
|
||||
0.50.0 was tagged and never published: its end-to-end gate was red on two tests that counted processes.
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"comment": "The GeoIP database every CI leg launches with (STEALTHFOX_GEOIP_MMDB): made by scripts/ci_lab_geoip.py, the same bytes on every run, no download and no licensed data. One record answers every public address that is not one of the lab's networks and not reserved (the runner's own egress address is not known in advance). To change it (a network, a field): change the table of the script and mmdb_sha256 here in one commit; `build` refuses to go on when they differ.",
|
||||
"generator": "scripts/ci_lab_geoip.py",
|
||||
"mmdb": "geoip-aio-all.mmdb",
|
||||
"mmdb_sha256": "d02825fd0336afa72ad7b7573769f1d9efddea447133f99ae3008c56d5308929",
|
||||
"mmdb_bytes": 2706
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
[
|
||||
{"id": "wrapper.e2e.udp", "giro": "G2", "os": ["linux", "windows"], "min_tests": 43, "exact": true, "tests": ["tests/test_preload_newtab_turns_the_privileged_about_process_off_e2e.py", "tests/test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py", "tests/test_turn_over_tcp_is_tried_for_real_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_when_the_exit_of_the_lab_is_loopback", "tests/test_declared_host_network_e2e.py", "tests/test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_e2e.py", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_webrtc_realness.py::test_a_host_with_ipv6_addresses_gathers_through_an_ipv4_relay", "tests/test_webrtc_realness.py::test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_its_relay", "tests/test_webrtc_realness.py::test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far_away", "tests/test_webrtc_realness.py::test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server", "tests/test_webrtc_realness.py::test_two_contexts_with_two_proxies_each_gets_the_srflx_of_its_own", "tests/test_webrtc_realness.py::test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context", "tests/test_webrtc_realness.py::test_a_proxy_that_does_not_relay_udp_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_udp_leaves_from_another_address_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_relay_never_answers_gives_no_srflx_at_all"], "marker": "e2e", "needs_root": false, "note": "Needs the candidate binary (STEALTHFOX_E2E_BINARY) and the engine that carries the UDP line. 57 = 1+7+6+1+21 from the five files + 21 from the 10 UDP-line tests of test_webrtc_realness.py (parametrized). The chain by name is here in its variant with the lab's exit on loopback (127.0.0.2) and the pref `media.peerconnection.ice.loopback`, on Linux and Windows: the exit of the lab is loopback, and a loopback mapped address is thrown away by nICEr unless the ICE context allows it. The variant without the pref (an exit that is not loopback) is the suite wrapper.e2e.udp.exit, Linux only; the address added to the interface of the Windows runner is work of the release after firefox-63. The preload_newtab test (2) is here: seen green on Linux as root (Docker) and on Windows 10 runs of 10 (windows-2022, round 5 engine); it reads the engine's own process log."},
|
||||
{"id": "wrapper.e2e.udp.exit", "giro": "G2", "os": ["linux"], "min_tests": 7, "exact": true, "tests": ["tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick", "tests/test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux only, and not collected on Windows: the exit of the lab is a documentation address (198.51.100.9) added to lo with `ip addr add`, which needs root and iproute2; a mapped address in 127/8 would be thrown away by nICEr as bogus (stun_client_ctx.cpp nr_stun_transport_addr_check) and the pref that allows it is off in a product. The page reads a srflx equal to the gateway exit and the relay of the TURN server, the TURN name resolved by the DoH through the proxy, in the tick of 2 s. On the Windows runner of GitHub (administrator, the network of the runner) it could run too: not yet. A skipped test would turn the verdict red, hence a suite of its own. Its twin with the lab's exit on loopback and the pref stays in wrapper.e2e.udp on both systems, so that Windows keeps the walk of the chain by name."},
|
||||
{"id": "wrapper.e2e.udp.sandbox", "giro": "G2", "os": ["linux"], "min_tests": 13, "exact": true, "tests": ["tests/test_the_socket_process_is_sandboxed_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_a_gateway_without_udp_resolves_the_ice_name_then_ends_in_701"], "marker": "e2e", "needs_root": false, "note": "The browser WITH its sandbox, run by a normal user, as on any Linux that allows user namespaces. On the Ubuntu 24.04 runner AppArmor refuses them to a user, so every other non-root suite runs a browser WITHOUT the sandbox of its socket and content processes; the gate turns the restriction off for this leg (sysctl kernel.apparmor_restrict_unprivileged_userns=0) and the first test fails unless the socket and a tab process have a seccomp filter (Seccomp: 2). The three situations of the UDP line: A (a proxy that carries UDP: the srflx born through the relay), B (no proxy: the gather is real), C (a proxy with no UDP: the ICE server name goes by DoH through the proxy and the gather ends in 701). No root and no resolver trap needed."},
|
||||
{"id": "wrapper.e2e.udp.exit", "giro": "G2", "os": ["linux"], "min_tests": 7, "exact": true, "tests": ["tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick", "tests/test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux only, and not collected on Windows: the exit of the lab is a documentation address (198.51.100.9) added to lo with `ip addr add`, which needs root and iproute2; a mapped address in 127/8 would be thrown away by nICEr as bogus (stun_client_ctx.cpp nr_stun_transport_addr_check) and the pref that allows it is off in a product. The page reads a srflx equal to the gateway exit and the relay of the TURN server, the TURN name resolved by the DoH through the proxy, in the tick of 2 s. On the Windows runner of GitHub (administrator, the network of the runner) it could run too: not yet. A skipped test would turn the verdict red, hence a suite of its own. Its twin with the lab's exit on loopback and the pref stays in wrapper.e2e.udp on both systems, so that Windows keeps the walk of the chain by name.", "linux_only": "The lab's exit is a documentation address the host must hold besides its loopback (nICEr throws away a mapped address in 127/8). Linux holds it on lo as root; Windows takes no extra address on its loopback pseudo-interface, and adding it to the runner's adapter took the runner off the network (runs 43314251547 and 43334169682 died in the test step). A Windows twin waits for a way that leaves the runner's network alone."},
|
||||
{"id": "wrapper.e2e.udp.sandbox", "giro": "G2", "os": ["linux"], "min_tests": 13, "exact": true, "tests": ["tests/test_the_socket_process_is_sandboxed_e2e.py", "tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy", "tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_a_gateway_without_udp_resolves_the_ice_name_then_ends_in_701"], "marker": "e2e", "needs_root": false, "note": "The browser WITH its sandbox, run by a normal user, as on any Linux that allows user namespaces. On the Ubuntu 24.04 runner AppArmor refuses them to a user, so every other non-root suite runs a browser WITHOUT the sandbox of its socket and content processes; the gate turns the restriction off for this leg (sysctl kernel.apparmor_restrict_unprivileged_userns=0) and the first test fails unless the socket and a tab process have a seccomp filter (Seccomp: 2). The three situations of the UDP line: A (a proxy that carries UDP: the srflx born through the relay), B (no proxy: the gather is real), C (a proxy with no UDP: the ICE server name goes by DoH through the proxy and the gather ends in 701). No root and no resolver trap needed.", "linux_only": "It reads the seccomp filter of the socket and tab processes in /proc. The Windows twin reads the sandbox token of the same processes (integrity level, restrictions) and needs a measurement of the retail Firefox's tokens first; until then Linux only."},
|
||||
{"id": "wrapper.e2e.web", "giro": "G2", "os": ["linux", "windows"], "min_tests": 27, "exact": true, "tests": ["tests/test_networkidle_through_a_served_browser_with_routes_e2e.py", "tests/test_http3_through_the_proxy_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The networkidle e2e with routes and the HTTP/3 e2e, split from wrapper.e2e.udp (about 260 s of 500 on Linux; the whole suite did not fit the 15 minutes of Windows)."},
|
||||
{"id": "wrapper.e2e.doh", "giro": "G2", "os": ["linux", "windows"], "min_tests": 19, "exact": true, "tests": ["tests/test_the_hosts_file_of_the_host_is_never_read_e2e.py", "tests/test_resolver_race_e2e.py", "tests/test_doh_under_stress_e2e.py", "tests/test_context_proxy_only_resolves_by_doh_e2e.py", "tests/test_doh_through_the_proxy_e2e.py", "tests/test_ice_names_by_the_context_proxy_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "Linux needs root: the resolver trap of the file (ResolverTrap) points /etc/resolv.conf at a counting resolver on port 53. Su Windows il resolver trap non gira: l'asserzione sul resolver di sistema è l'unica omessa. Run it without xdist (port 53 is one per host). On the Linux leg the gate exports INVPW_REQUIRE_TRAP=1: a trap that cannot run or bind port 53 is a failure, not a skipped assertion."},
|
||||
{"id": "wrapper.e2e.realness", "giro": "G2", "os": ["linux", "windows"], "min_tests": 32, "exact": true, "tests": ["tests/test_realness_behind_a_declared_exit_e2e.py"], "marker": "e2e", "needs_root": ["linux"], "note": "The realness check without a real proxy: six declared exits, the values a page reads, and the roads. Linux runs as root without xdist like the DoH suite (the resolver trap); on Windows the trap does not exist and the assertion on the system resolver is the only one omitted."},
|
||||
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 221, "exact": true, "tests": ["tests/test_a_served_launch_cannot_turn_the_launch_counter_off.py", "tests/test_the_witness_picks_a_port_both_sockets_bind.py", "tests/test_preload_newtab_reaches_the_core_only_when_asked.py", "tests/test_the_resolver_trap_counts_its_own_users.py", "tests/test_the_doh_e2e_launch_on_a_virtual_display.py", "tests/test_the_realness_helpers.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_host_address_helper.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_fake_doh_answers.py", "tests/test_doh_session_prefs_unit.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py", "tests/test_the_witness_hears_a_direct_send.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added."},
|
||||
{"id": "wrapper.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 222, "exact": true, "tests": ["tests/test_a_served_launch_cannot_turn_the_launch_counter_off.py", "tests/test_the_witness_picks_a_port_both_sockets_bind.py", "tests/test_preload_newtab_reaches_the_core_only_when_asked.py", "tests/test_the_resolver_trap_counts_its_own_users.py", "tests/test_the_doh_e2e_launch_on_a_virtual_display.py", "tests/test_the_realness_helpers.py", "tests/test_the_h3_line_helpers.py", "tests/test_the_fake_doh_delays_and_refuses.py", "tests/test_the_host_address_helper.py", "tests/test_the_udp_chain_helper.py", "tests/test_the_fake_doh_answers.py", "tests/test_doh_session_prefs_unit.py", "tests/test_the_leak_watcher_sees_a_direct_connection.py", "tests/test_the_http_proxy_helper_asks_for_credentials.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_the_network_declaration_reaches_the_engine.py", "tests/test_the_resolver_trap_is_required_by_the_gate.py", "tests/test_the_exit_of_a_context_is_discovered_through_its_own_gateway.py", "tests/test_the_witness_hears_a_direct_send.py"], "marker": "unit", "needs_root": false, "note": "92 = 6+32+21+7+8+3+9+6. The leak watcher file defines exactly one of its two resolver-trap tests per host (7 everywhere), so no test is skipped. `exact`: min_tests is raised by hand when a test is added."},
|
||||
{"id": "wrapper.e2e.page", "giro": "G2", "os": ["linux", "windows"], "min_tests": 115, "exact": true, "tests": ["tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_popup_destinations_e2e.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_route_superseded_e2e.py"], "marker": "e2e", "needs_root": false, "note": "114 = 100 + the 14 of test_a_page_that_moves_on_e2e.py (a navigation the page overtook with location.replace ends; the engine fix 860ef8a6d9 is proved by it). 100 counted at the collection; was 96 = 10+32+16+34+4 before the popup tests of 6200bc2). A page is handed over when the engine says Page.ready; a popup reaches the client (link, noopener, window.open; own site and another; with and without a route; in-process and over launch_server) as Playwright's does; a superseded route. Needs the candidate binary, and the stock Playwright client of the dev extra."},
|
||||
{"id": "wrapper.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 44, "exact": true, "tests": ["tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_page_number_follows_the_call.py"], "marker": "unit", "needs_root": false, "note": "24 (counted at the collection; was 20 = 3+8+1+8 before 6200bc2). The page dispatcher's wait for Page.ready and what it hands over; the drive gate goes through the core (the engine waits for the session's road)."}
|
||||
{"id": "wrapper.unit.page", "giro": "G1", "os": ["linux", "windows"], "min_tests": 72, "exact": true, "tests": ["tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_page_number_follows_the_call.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_the_hand_over_of_a_popup_holds_under_concurrency.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py"], "marker": "unit", "needs_root": false, "note": "72 = 44 + 3+9+5+1+10 of the popup hand-over (24 counted at the collection before; was 20 = 3+8+1+8 before 6200bc2). The page dispatcher's wait for Page.ready and what it hands over; the drive gate goes through the core (the engine waits for the session's road)."}
|
||||
]
|
||||
@@ -0,0 +1,354 @@
|
||||
"""The GeoIP database of a CI leg: written by this file, the same bytes on every run, and the proof that the leg launched with it.
|
||||
|
||||
python scripts/ci_lab_geoip.py build [--pin ci/geoip.json] [--dest DIR] # writes DIR/geoip-aio-all.mmdb, exports STEALTHFOX_GEOIP_MMDB
|
||||
python scripts/ci_lab_geoip.py evidence [--out result/geoip.json] # what the environment of THIS command says
|
||||
python scripts/ci_lab_geoip.py verify [--pin ci/geoip.json] --evidence FILE [--used FILE] # exit 1: the leg did not run with the pinned database
|
||||
|
||||
Why this exists (run 43211837926, the root legs of the realness suite): without ``STEALTHFOX_GEOIP_MMDB`` the core asked GitHub which GeoIP
|
||||
database is the latest on every call, from the python of the test, and a resolver trap counted those names (github.com, api.github.com) as the
|
||||
browser's. A CI leg reaches no site for its data and uses no licensed one: the database is made here, from the table below, with nothing but the
|
||||
standard library. It holds the networks the tests look up (the six exits of tests/_realness_support.py EXITS) and the fields the core reads
|
||||
(``country.iso_code``, ``location.latitude`` / ``longitude`` / ``time_zone``); an address that is not in it (the documentation ranges the lab uses,
|
||||
loopback, any IPv6) is "not in the database", as in the real one. ``ci/geoip.json`` holds the sha256 of the file: ``build`` refuses to go on when
|
||||
what it wrote is not that, ``evidence`` says which file a launch ran with, and ``scripts/ci_verdict.py judge --geoip`` turns a leg that ran with
|
||||
anything else red. The real database is looked at only by the release (scripts/ci_real_geoip_check.py).
|
||||
|
||||
The format is MaxMind DB 2.0 (https://maxmind.github.io/MaxMind-DB/): a binary search tree of node_count nodes of two records of 24 bits, 16 zero
|
||||
bytes, the data section, the marker and the metadata map. The tree is an ip_version 6 tree with the IPv4 space under ::/96, as in the real database,
|
||||
so that a lookup of an IPv6 address answers "not found" instead of raising. The metadata integers have the types libmaxminddb checks.
|
||||
|
||||
``build`` writes ``STEALTHFOX_GEOIP_MMDB=<path>`` to ``$GITHUB_ENV`` (every later step of the job sees it, ``sudo -E`` carries it to a root leg) and to
|
||||
stdout.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ENV = "STEALTHFOX_GEOIP_MMDB"
|
||||
FILE_NAME = "geoip-aio-all.mmdb"
|
||||
MARKER = b"\xab\xcd\xefMaxMind.com"
|
||||
RECORD_BITS = 24
|
||||
BUILD_EPOCH = 1793790075 # fixed: the same bytes on every run
|
||||
|
||||
|
||||
def addr(*octets: int) -> str:
|
||||
"""A dotted address from its numbers (no address is written out as text in this repository: the tests and this table build theirs)."""
|
||||
return ".".join(str(o) for o in octets)
|
||||
|
||||
|
||||
def net(a: int, b: int, c: int) -> str:
|
||||
"""The /24 of a.b.c."""
|
||||
return addr(a, b, c, 0) + "/24"
|
||||
|
||||
|
||||
#: The six exits of tests/_realness_support.py EXITS (each test declares the .5 of its /24) and what the core reads of them: country, IANA zone,
|
||||
#: and the coordinates of the city centre (public geography). The tests ask the database for their truth at test time, so any coherent values do.
|
||||
NETWORKS = {
|
||||
net(1, 178, 10): ("DE", "Europe/Berlin", 50.1109, 8.6821), # germany
|
||||
net(1, 0, 16): ("JP", "Asia/Tokyo", 35.6895, 139.6917), # japan
|
||||
net(1, 6, 0): ("IN", "Asia/Kolkata", 12.9716, 77.5946), # india
|
||||
net(1, 0, 4): ("AU", "Australia/Melbourne", -37.8136, 144.9631), # australia
|
||||
net(1, 178, 32): ("BR", "America/Sao_Paulo", -23.5505, -46.6333), # brazil
|
||||
net(1, 32, 239): ("US", "America/Los_Angeles", 34.0522, -118.2437), # united_states
|
||||
}
|
||||
|
||||
|
||||
class Refused(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class U16(int):
|
||||
"""A uint16 of the metadata: not the smallest type that holds it, libmaxminddb checks the type of each key."""
|
||||
|
||||
|
||||
class U32(int):
|
||||
pass
|
||||
|
||||
|
||||
class U64(int):
|
||||
pass
|
||||
|
||||
|
||||
def _control(kind: int, size: int) -> bytes:
|
||||
"""The control byte(s) of a value of type `kind` (1..15) and `size`."""
|
||||
if kind <= 7:
|
||||
first, ext = kind << 5, b""
|
||||
else:
|
||||
first, ext = 0, bytes([kind - 7])
|
||||
if size < 29:
|
||||
return bytes([first | size]) + ext
|
||||
if size < 285:
|
||||
return bytes([first | 29]) + ext + bytes([size - 29])
|
||||
if size < 65821:
|
||||
return bytes([first | 30]) + ext + struct.pack(">H", size - 285)
|
||||
return bytes([first | 31]) + ext + struct.pack(">I", size - 65821)[1:]
|
||||
|
||||
|
||||
def _unsigned(kind: int, value: int, width: int) -> bytes:
|
||||
raw = value.to_bytes(width, "big").lstrip(bytes([0])) # MaxMind DB integers drop their leading zero bytes
|
||||
return _control(kind, len(raw)) + raw
|
||||
|
||||
|
||||
def encode(value) -> bytes:
|
||||
if isinstance(value, U16):
|
||||
return _unsigned(5, int(value), 2)
|
||||
if isinstance(value, U32):
|
||||
return _unsigned(6, int(value), 4)
|
||||
if isinstance(value, U64):
|
||||
return _unsigned(9, int(value), 8)
|
||||
if isinstance(value, str):
|
||||
raw = value.encode("utf-8")
|
||||
return _control(2, len(raw)) + raw
|
||||
if isinstance(value, float):
|
||||
return _control(3, 8) + struct.pack(">d", value)
|
||||
if isinstance(value, dict):
|
||||
out = _control(7, len(value))
|
||||
for key in sorted(value): # sorted: the same bytes whatever the order of the table
|
||||
out += encode(key) + encode(value[key])
|
||||
return out
|
||||
if isinstance(value, (list, tuple)):
|
||||
return _control(11, len(value)) + b"".join(encode(v) for v in value)
|
||||
raise TypeError("cannot encode %r" % (value,))
|
||||
|
||||
|
||||
#: Every address that is not reserved (RFC 6890: this network, private, shared, loopback, link-local, protocol assignments, documentation,
|
||||
#: benchmarking, multicast, the rest of class E) and is not one of the six exits above answers ONE record: the egress address of the machine that
|
||||
#: runs a test is not known in advance (a runner of any provider, any region) and a launch with no proxy asks the database for it. Without this
|
||||
#: record such a launch ends in "egress IP not present in the geoip database" (run 43351424907 of PR 486: 495 errors of one cause). The record is
|
||||
#: declared here, so it is the same on every machine, which a download of the real database is not. The reserved ranges stay "not in the
|
||||
#: database", as in the real one: the lab's own exits (the documentation addresses) must not resolve to anything.
|
||||
FALLBACK = ("US", "America/New_York", 40.7128, -74.006)
|
||||
RESERVED = tuple(ipaddress.ip_network(n) for n in (
|
||||
addr(0, 0, 0, 0) + "/8", addr(10, 0, 0, 0) + "/8", addr(100, 64, 0, 0) + "/10", addr(127, 0, 0, 0) + "/8", addr(169, 254, 0, 0) + "/16",
|
||||
addr(172, 16, 0, 0) + "/12", addr(192, 0, 0, 0) + "/24", addr(192, 0, 2, 0) + "/24", addr(192, 88, 99, 0) + "/24", addr(192, 168, 0, 0) + "/16",
|
||||
addr(198, 18, 0, 0) + "/15", addr(198, 51, 100, 0) + "/24", addr(203, 0, 113, 0) + "/24", addr(224, 0, 0, 0) + "/4", addr(240, 0, 0, 0) + "/4"))
|
||||
|
||||
|
||||
def fallback_networks() -> list:
|
||||
"""The public space minus the reserved ranges minus the networks of the table: disjoint CIDRs (the writer takes no overlap)."""
|
||||
if FALLBACK is None: # a test builds the database without it, to stand for one that has no answer for an address
|
||||
return []
|
||||
left = [ipaddress.ip_network("0.0.0.0/0")]
|
||||
for hole in list(RESERVED) + [ipaddress.ip_network(c) for c in NETWORKS]:
|
||||
nxt = []
|
||||
for net in left:
|
||||
if net.overlaps(hole):
|
||||
nxt.extend(net.address_exclude(hole) if net.supernet_of(hole) else [])
|
||||
else:
|
||||
nxt.append(net)
|
||||
left = nxt
|
||||
return sorted(left, key=lambda n: (int(n.network_address), n.prefixlen))
|
||||
|
||||
|
||||
def records() -> dict:
|
||||
def one(country, zone, lat, lon):
|
||||
return {"country": {"iso_code": country}, "location": {"latitude": lat, "longitude": lon, "time_zone": zone}}
|
||||
|
||||
table = {cidr: one(*row) for cidr, row in NETWORKS.items()}
|
||||
table.update({str(net): one(*FALLBACK) for net in fallback_networks()})
|
||||
return table
|
||||
|
||||
|
||||
def build_bytes() -> bytes:
|
||||
"""The database: the same bytes on every call."""
|
||||
data = bytearray()
|
||||
offsets: dict = {}
|
||||
leaves = []
|
||||
table = records()
|
||||
for cidr in sorted(table, key=lambda c: (int(ipaddress.ip_network(c).network_address), ipaddress.ip_network(c).prefixlen)):
|
||||
blob = encode(table[cidr])
|
||||
if blob not in offsets:
|
||||
offsets[blob] = len(data)
|
||||
data += blob
|
||||
leaves.append((ipaddress.ip_network(cidr), offsets[blob]))
|
||||
# the trie: nodes are [left, right]; a child is None (no data), ("node", index) or ("data", offset)
|
||||
nodes = [[None, None]]
|
||||
for net, offset in leaves:
|
||||
if net.version != 4:
|
||||
raise ValueError("this writer takes IPv4 networks: %s" % net)
|
||||
bits = int(net.network_address)
|
||||
prefix = 96 + net.prefixlen # the IPv4 space sits under ::/96
|
||||
index = 0
|
||||
for depth in range(prefix):
|
||||
bit = (bits >> (127 - depth)) & 1
|
||||
if depth == prefix - 1:
|
||||
nodes[index][bit] = ("data", offset)
|
||||
else:
|
||||
child = nodes[index][bit]
|
||||
if child is None:
|
||||
nodes.append([None, None])
|
||||
child = ("node", len(nodes) - 1)
|
||||
nodes[index][bit] = child
|
||||
elif child[0] != "node":
|
||||
raise ValueError("%s sits inside a network that already has data" % net)
|
||||
index = child[1]
|
||||
count = len(nodes)
|
||||
|
||||
def record(child) -> int:
|
||||
if child is None:
|
||||
return count
|
||||
return child[1] if child[0] == "node" else count + 16 + child[1]
|
||||
|
||||
tree = bytearray()
|
||||
for left, right in nodes:
|
||||
for child in (left, right):
|
||||
value = record(child)
|
||||
if value >= 1 << RECORD_BITS:
|
||||
raise ValueError("a record does not fit in %d bits" % RECORD_BITS)
|
||||
tree += value.to_bytes(RECORD_BITS // 8, "big")
|
||||
metadata = {
|
||||
"binary_format_major_version": U16(2),
|
||||
"binary_format_minor_version": U16(0),
|
||||
"build_epoch": U64(BUILD_EPOCH),
|
||||
"database_type": "GeoIP2-City",
|
||||
"description": {"en": "invisible CI lab database: the networks the tests look up, and one record for every other public address"},
|
||||
"ip_version": U16(6),
|
||||
"languages": ["en"],
|
||||
"node_count": U32(count),
|
||||
"record_size": U16(RECORD_BITS),
|
||||
}
|
||||
return bytes(tree) + bytes(16) + bytes(data) + MARKER + encode(metadata)
|
||||
|
||||
|
||||
def sha256_of_bytes(blob: bytes) -> str:
|
||||
return hashlib.sha256(blob).hexdigest()
|
||||
|
||||
|
||||
def sha256_of(path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
for block in iter(lambda: f.read(1 << 20), b""):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def load_pin(path) -> dict:
|
||||
try:
|
||||
pin = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as exc:
|
||||
raise Refused("the pin %s cannot be read: %s" % (path, exc))
|
||||
sha = pin.get("mmdb_sha256") if isinstance(pin, dict) else None
|
||||
if not isinstance(sha, str) or len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
|
||||
raise Refused("the pin %s has no mmdb_sha256 that is a sha256" % path)
|
||||
return pin
|
||||
|
||||
|
||||
def build(pin: dict, dest: Path) -> Path:
|
||||
"""Write the database to DEST and check it against the pin: a writer that no longer makes the pinned bytes is red."""
|
||||
blob = build_bytes()
|
||||
got = sha256_of_bytes(blob)
|
||||
if got != pin["mmdb_sha256"]:
|
||||
raise Refused("the lab database made by scripts/ci_lab_geoip.py has sha256 %s, the pin (ci/geoip.json) says %s: change both in one commit"
|
||||
% (got, pin["mmdb_sha256"]))
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
target = dest / FILE_NAME
|
||||
target.write_bytes(blob)
|
||||
return target
|
||||
|
||||
|
||||
def evidence(environ=None) -> dict:
|
||||
"""What the environment of this command says about the database: the value of the variable, whether it is a file, its sha256."""
|
||||
environ = os.environ if environ is None else environ
|
||||
value = environ.get(ENV, "")
|
||||
out = {"env": value, "exists": False, "sha256": None}
|
||||
if value and os.path.isfile(value):
|
||||
out["exists"] = True
|
||||
out["sha256"] = sha256_of(value)
|
||||
return out
|
||||
|
||||
|
||||
def verify(pin: dict, evidence_file, used_file=None) -> list:
|
||||
"""The reasons a leg did not run with the pinned database ([] = it did). The same reading as the judge's (scripts/ci_verdict.py), and
|
||||
independent of it: a step of the workflow runs this, so that a judge that does not know the evidence yet (the first merge to main ends that)
|
||||
is not the only thing standing between a leg with no database and a green run.
|
||||
|
||||
``evidence_file``: what the environment said BEFORE pytest was launched (the ``evidence`` command). ``used_file``: what the process of the
|
||||
tests used (tests/geoip_used.py, written when pytest ends): the variable at the end, the sha256 of that file, and how many times the core went
|
||||
to GitHub for a database, which has to be none."""
|
||||
problems = []
|
||||
|
||||
def read(path, what):
|
||||
try:
|
||||
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("not a JSON object")
|
||||
return data
|
||||
except (OSError, ValueError) as exc:
|
||||
problems.append("the %s %s cannot be read: %s" % (what, path, exc))
|
||||
return None
|
||||
|
||||
for what, path in (("evidence", evidence_file), ("record of use", used_file)):
|
||||
if path is None:
|
||||
continue
|
||||
data = read(path, what)
|
||||
if data is None:
|
||||
continue
|
||||
if not data.get("env"):
|
||||
problems.append("the %s says STEALTHFOX_GEOIP_MMDB was not set" % what)
|
||||
elif not data.get("exists") or not data.get("sha256"):
|
||||
problems.append("the %s says STEALTHFOX_GEOIP_MMDB=%s is not a file" % (what, data.get("env")))
|
||||
elif data["sha256"] != pin["mmdb_sha256"]:
|
||||
problems.append("the %s says the database has sha256 %s, the pin says %s" % (what, data["sha256"], pin["mmdb_sha256"]))
|
||||
if what == "record of use" and data.get("asked_github"):
|
||||
problems.append("the core asked GitHub for a database %s time(s) during the run: it went past STEALTHFOX_GEOIP_MMDB" % data["asked_github"])
|
||||
return problems
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
b = sub.add_parser("build")
|
||||
b.add_argument("--pin", default="ci/geoip.json")
|
||||
b.add_argument("--dest", default=None, help="default: $RUNNER_TEMP/geoip, or ./.geoip")
|
||||
e = sub.add_parser("evidence")
|
||||
e.add_argument("--out", default=None)
|
||||
v = sub.add_parser("verify")
|
||||
v.add_argument("--pin", default="ci/geoip.json")
|
||||
v.add_argument("--evidence", required=True)
|
||||
v.add_argument("--used", default=None)
|
||||
ns = ap.parse_args(argv)
|
||||
if ns.cmd == "build":
|
||||
try:
|
||||
dest = Path(ns.dest or os.path.join(os.environ.get("RUNNER_TEMP", "."), "geoip" if os.environ.get("RUNNER_TEMP") else ".geoip"))
|
||||
path = build(load_pin(ns.pin), dest.resolve())
|
||||
except Refused as exc:
|
||||
print("ci_lab_geoip: %s" % exc, file=sys.stderr)
|
||||
return 1
|
||||
# Where the process of the tests writes what the core did about the database (tests/geoip_used.py, read by `verify`).
|
||||
used = path.parent / "geoip-used.json"
|
||||
print("%s=%s" % (ENV, path))
|
||||
print("GEOIP_USED_OUT=%s" % used)
|
||||
env_file = os.environ.get("GITHUB_ENV")
|
||||
if env_file:
|
||||
with open(env_file, "a", encoding="utf-8") as fh:
|
||||
fh.write("%s=%s\n" % (ENV, path))
|
||||
fh.write("GEOIP_USED_OUT=%s\n" % used)
|
||||
return 0
|
||||
if ns.cmd == "verify":
|
||||
try:
|
||||
problems = verify(load_pin(ns.pin), ns.evidence, ns.used)
|
||||
except Refused as exc:
|
||||
print("ci_lab_geoip: %s" % exc, file=sys.stderr)
|
||||
return 1
|
||||
for problem in problems:
|
||||
print("ci_lab_geoip: FAIL: %s" % problem, file=sys.stderr)
|
||||
print("the leg ran with the pinned GeoIP database" if not problems else "%d problem(s)" % len(problems))
|
||||
return 1 if problems else 0
|
||||
data = evidence()
|
||||
text = json.dumps(data, indent=1)
|
||||
if ns.out:
|
||||
Path(ns.out).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(ns.out).write_text(text, encoding="utf-8")
|
||||
print(text)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,131 @@
|
||||
"""The three checks on the REAL GeoIP database: the only place a CI run touches it, and only in the release (publish.yml, job `real-geoip-database`).
|
||||
|
||||
The legs of the gates and of the pull requests launch with the database made by scripts/ci_lab_geoip.py (a few networks, the same bytes every run, no
|
||||
download). What it cannot prove is proved here, once per release, against the database a user gets:
|
||||
|
||||
1. THE PRODUCT'S OWN ROAD. With STEALTHFOX_GEOIP_MMDB unset and a cold cache the core downloads the latest database (``ensure_geoip_mmdb``), the file
|
||||
opens with the reader the core uses (MODE_MMAP) and answers for an address.
|
||||
2. THE LAB DATABASE AGREES. For the exit of each network of the lab database the real one gives the same country and the same IANA zone: if it does
|
||||
not, the lab table is stale (the tests ask their truth of the database at test time, so a stale table does not break them; it says the lab no longer
|
||||
looks like the world).
|
||||
3. EVERY ZONE IS KNOWN. Each distinct ``location.time_zone`` of the real database is a zone this runner's tz database knows (``ip_to_timezone``
|
||||
validates with ZoneInfo: a name the database has and the runner has not is a launch that fails for the user).
|
||||
|
||||
python scripts/ci_real_geoip_check.py # exit 0: all three hold; 1: one does not (said); 2: wrong use; 3: no database came (the network)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import ci_lab_geoip as lab # noqa: E402
|
||||
|
||||
#: The database did not come: not a finding about it (see main).
|
||||
EXIT_NO_DATABASE = 3
|
||||
|
||||
|
||||
def exit_of(cidr: str) -> str:
|
||||
"""The address each test declares in a lab network: the .5 of its /24 (tests/_realness_support.py EXITS)."""
|
||||
base = cidr.split("/")[0].rsplit(".", 1)[0]
|
||||
return "%s.5" % base
|
||||
|
||||
|
||||
def check_open_and_answer(path: Path) -> list:
|
||||
import maxminddb
|
||||
|
||||
try:
|
||||
with maxminddb.open_database(str(path), mode=maxminddb.MODE_MMAP) as reader:
|
||||
record = reader.get("8.8.8.8")
|
||||
except (OSError, ValueError, getattr(maxminddb, "InvalidDatabaseError", ValueError)) as exc:
|
||||
return ["the database %s does not open with the reader of the core: %s" % (path, exc)]
|
||||
code = ((record or {}).get("country") or {}).get("iso_code")
|
||||
return [] if code else ["the database %s has no country for 8.8.8.8: %r" % (path, record)]
|
||||
|
||||
|
||||
def check_lab_agrees(real: Path, lab_path: Path) -> list:
|
||||
from invisible_core._geo import GeoTimezoneError, ip_to_country, ip_to_timezone
|
||||
|
||||
problems = []
|
||||
for cidr in sorted(lab.NETWORKS):
|
||||
ip = exit_of(cidr)
|
||||
try:
|
||||
ours = (ip_to_country(ip, lab_path), ip_to_timezone(ip, lab_path))
|
||||
theirs = (ip_to_country(ip, real), ip_to_timezone(ip, real))
|
||||
except GeoTimezoneError as exc:
|
||||
problems.append("%s (%s): %s" % (cidr, ip, exc))
|
||||
continue
|
||||
if ours != theirs:
|
||||
problems.append("%s (%s): the lab database says %s, the real one %s" % (cidr, ip, ours, theirs))
|
||||
return problems
|
||||
|
||||
|
||||
def zones_of(path: Path) -> set:
|
||||
import maxminddb
|
||||
|
||||
zones = set()
|
||||
with maxminddb.open_database(str(path), mode=maxminddb.MODE_MMAP_EXT if hasattr(maxminddb, "MODE_MMAP_EXT") else maxminddb.MODE_MMAP) as reader:
|
||||
for _network, record in reader:
|
||||
zone = (record.get("location") or {}).get("time_zone") if isinstance(record, dict) else None
|
||||
if zone:
|
||||
zones.add(zone)
|
||||
return zones
|
||||
|
||||
|
||||
def check_zones(path: Path) -> list:
|
||||
problems = []
|
||||
zones = zones_of(path)
|
||||
if not zones:
|
||||
return ["the database %s has no time_zone at all" % path]
|
||||
for zone in sorted(zones):
|
||||
try:
|
||||
ZoneInfo(zone)
|
||||
except Exception as exc: # noqa: BLE001 - ZoneInfoNotFoundError, ValueError, OSError: all the same finding
|
||||
problems.append("the zone %r of the database is not known to the tz database of this runner: %s" % (zone, exc))
|
||||
print("%d distinct zones in %s" % (len(zones), path))
|
||||
return problems
|
||||
|
||||
|
||||
def product_download(cache: Path) -> Path:
|
||||
"""The core's own road: no variable, a cold cache."""
|
||||
os.environ.pop(lab.ENV, None)
|
||||
os.environ["INVISIBLE_PLAYWRIGHT_CACHE_DIR"] = str(cache)
|
||||
from invisible_core.download import ensure_geoip_mmdb
|
||||
|
||||
return Path(ensure_geoip_mmdb())
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
if len(argv if argv is not None else sys.argv[1:]):
|
||||
print(__doc__)
|
||||
return 2
|
||||
problems = []
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
td = Path(td)
|
||||
try:
|
||||
real = product_download(td / "cache")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# Exit 3: the database did not come (the network, GitHub, the download), which says nothing about the database. The release
|
||||
# waits for a rerun; it is not a defect of the product and not one of the three checks.
|
||||
print("1. the product's own road: NO DATABASE (%s: %s): exit 3, run it again" % (type(exc).__name__, exc))
|
||||
return EXIT_NO_DATABASE
|
||||
print("1. the product's road gave %s: tag %s, %d bytes, sha256 %s" % (real, real.parent.name, real.stat().st_size, lab.sha256_of(real)))
|
||||
results = []
|
||||
for label, found in (
|
||||
("1. it opens with the reader of the core and answers for an address", check_open_and_answer(real)),
|
||||
("2. the lab database agrees with it on the six exits (country, zone)",
|
||||
check_lab_agrees(real, lab.build(lab.load_pin(Path(__file__).resolve().parents[1] / "ci" / "geoip.json"), td / "lab"))),
|
||||
("3. every time_zone of it is known to the tz database of this runner", check_zones(real))):
|
||||
print("%s: %s" % (label, "ok" if not found else "FAILED (%d)" % len(found)))
|
||||
problems += found
|
||||
for p in problems:
|
||||
print("FAIL: %s" % p)
|
||||
print("real GeoIP database: %s" % ("all three checks hold" if not problems else "%d problem(s)" % len(problems)))
|
||||
return 1 if problems else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -307,6 +307,37 @@ def _seal_problems(path, result):
|
||||
return []
|
||||
|
||||
|
||||
def _geoip_problems(path, pin_path, result):
|
||||
"""A leg launched with the GeoIP database of the pin, or it is red.
|
||||
|
||||
``path`` is the evidence the leg wrote with ``scripts/ci_lab_geoip.py evidence``, run in the very environment pytest was started in
|
||||
(``sudo -E`` included): the value of STEALTHFOX_GEOIP_MMDB, whether it is a file, its sha256. Without the variable the core asks GitHub which
|
||||
database is the latest on every call, from the python of the test (run 43211837926: a resolver trap counted github.com and api.github.com as
|
||||
the browser's), and a leg that reaches a site for its data is not a leg of the gate.
|
||||
"""
|
||||
try:
|
||||
evidence = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
if not isinstance(evidence, dict):
|
||||
raise ValueError("not a JSON object")
|
||||
except (OSError, ValueError) as exc:
|
||||
result["geoip_sha256"] = "unreadable"
|
||||
return ["the GeoIP evidence %s cannot be read: %s: the leg did not say which database it ran with" % (path, exc)]
|
||||
result["geoip_sha256"] = evidence.get("sha256")
|
||||
if not evidence.get("env"):
|
||||
return ["the leg launched without STEALTHFOX_GEOIP_MMDB: the core would ask GitHub for its database on every call (the database of "
|
||||
"the gate is ci/geoip.json, made by scripts/ci_lab_geoip.py)"]
|
||||
if not evidence.get("exists") or not evidence.get("sha256"):
|
||||
return ["STEALTHFOX_GEOIP_MMDB=%s is not a file: the leg ran without a database" % evidence.get("env")]
|
||||
try:
|
||||
pin = json.loads(Path(pin_path).read_text(encoding="utf-8")) if pin_path else None
|
||||
expected = pin["mmdb_sha256"]
|
||||
except (OSError, ValueError, KeyError, TypeError) as exc:
|
||||
return ["the pin of the GeoIP database %s cannot be read: %s" % (pin_path, exc)]
|
||||
if evidence["sha256"] != expected:
|
||||
return ["the leg ran with a GeoIP database of sha256 %s, the pin (%s) says %s" % (evidence["sha256"], pin_path, expected)]
|
||||
return []
|
||||
|
||||
|
||||
def cmd_judge(ns):
|
||||
problems = []
|
||||
result = {"suite": ns.suite, "os": ns.os, "commit": commit_sha(ns.commit), "binary_sha256": sha256_of(ns.binary),
|
||||
@@ -329,6 +360,8 @@ def cmd_judge(ns):
|
||||
problems.append("the binary %s does not exist: a result with no hash of the engine is not a result" % ns.binary)
|
||||
if ns.seal:
|
||||
problems += _seal_problems(ns.seal, result)
|
||||
if ns.geoip:
|
||||
problems += _geoip_problems(ns.geoip, ns.geoip_pin, result)
|
||||
|
||||
counts = {"passed": 0, "failed": 0, "skipped": 0, "errors": 0}
|
||||
cases = []
|
||||
@@ -476,6 +509,8 @@ def main(argv=None):
|
||||
j.add_argument("--binary")
|
||||
j.add_argument("--commit")
|
||||
j.add_argument("--seal")
|
||||
j.add_argument("--geoip", help="the evidence of the leg (scripts/ci_lab_geoip.py evidence): a leg launched without the database is red")
|
||||
j.add_argument("--geoip-pin", help="ci/geoip.json: the sha256 of the database the leg has to have run with (main's, when main has it)")
|
||||
j.add_argument("--out")
|
||||
j.add_argument("--main-required")
|
||||
j.add_argument("--main-has-no-list", action="store_true",
|
||||
|
||||
@@ -1012,15 +1012,36 @@ class FrameDispatcher(Dispatcher):
|
||||
detached = False
|
||||
|
||||
def emit(self, method: str, params: Optional[Dict] = None) -> None:
|
||||
if method == "loadstate" and params and params.get("add") in ("domcontentloaded", "load"):
|
||||
page = self.page
|
||||
with page._announce_lock:
|
||||
if not page._announced:
|
||||
page._said_before_announcement.append((self, dict(params)))
|
||||
super().emit(method, params)
|
||||
return
|
||||
if method == "loadstate" and params:
|
||||
# ⛔ A LOAD STATE IS TOLD ONCE. The hand-over reconciles the frame with the lifecycle and the page's own listener then hears the
|
||||
# same `DOMContentLoaded`/`load`: whichever comes second finds the state already told and says nothing (a `page.on("load")`
|
||||
# that fired twice). A commit removes the states first, so the next document's are told again.
|
||||
state = params.get("add")
|
||||
told = bool(state) and not params.get("remove") and state in self.told_states
|
||||
if state in ("domcontentloaded", "load"):
|
||||
page = self.page
|
||||
with page._announce_lock:
|
||||
# ⛔ KEPT FOR THE REPLAY EVEN WHEN THE CLIENT KNOWS IT ALREADY (from the snapshot of the initializer, or from the
|
||||
# reconciliation): the replay after the announcement is what makes `page.on("load")` run for a popup that loaded
|
||||
# before the client heard of it, once per frame and state.
|
||||
if not page._announced and not any(
|
||||
f is self and p.get("add") == state for f, p in page._said_before_announcement):
|
||||
page._said_before_announcement.append((self, dict(params)))
|
||||
if not told:
|
||||
self._track_states(params)
|
||||
super().emit(method, params)
|
||||
return
|
||||
if told:
|
||||
return
|
||||
self._track_states(params)
|
||||
super().emit(method, params)
|
||||
|
||||
def _track_states(self, params: Dict) -> None:
|
||||
if params.get("add"):
|
||||
self.told_states.add(params["add"])
|
||||
if params.get("remove"):
|
||||
self.told_states.discard(params["remove"])
|
||||
|
||||
def detach(self) -> None:
|
||||
"""The frame left the page: its handles go (their frame is no more), the frame itself stays and refuses."""
|
||||
self.detached = True
|
||||
@@ -1038,15 +1059,22 @@ class FrameDispatcher(Dispatcher):
|
||||
def __init__(self, server, page: "PageDispatcher", frame_id: str,
|
||||
url: str = "about:blank", name: str = "",
|
||||
load_states: Optional[List[str]] = None,
|
||||
parent_frame: Optional["FrameDispatcher"] = None) -> None:
|
||||
parent_frame: Optional["FrameDispatcher"] = None,
|
||||
told_commit: Any = None) -> None:
|
||||
self.page = page
|
||||
self.frame_id = frame_id
|
||||
#: Which commit of the lifecycle the client was last told (its place in the engine's stream): two documents at the same address
|
||||
#: and with the same name differ only by this (`PageDispatcher._reconcile_frame`).
|
||||
self.told_commit = told_commit
|
||||
self.parent_frame = parent_frame
|
||||
#: ⛔ Kept here because the INITIALIZER is a snapshot: the client reads
|
||||
#: the url from it once, at creation, and afterwards only from
|
||||
#: `navigated` events. A frame created before it navigates keeps an
|
||||
#: empty url forever unless something updates this.
|
||||
self.url = url
|
||||
#: The load states the client has been told this frame has (the initializer's, then each `loadstate`): what the hand-over of the
|
||||
#: page from its buffer to its dispatcher compares the lifecycle's states with (`PageDispatcher._reconcile_frame`).
|
||||
self.told_states = set(load_states or ["commit"])
|
||||
#: Same reason, and both navigation events report it: a same-document
|
||||
#: navigation carries no name, so it has to repeat the one the frame
|
||||
#: already has rather than blank it.
|
||||
@@ -2785,6 +2813,9 @@ class PageDispatcher(Dispatcher):
|
||||
# replay.
|
||||
self._held: Optional[List] = []
|
||||
self._held_lock = threading.Lock()
|
||||
self._frames_lock = threading.RLock()
|
||||
#: The events that did not fit in the hold (`HELD_CAP`): counted, and said once when the hold ends (`_install_events`).
|
||||
self._held_dropped = 0
|
||||
#: ⛔ THE `domcontentloaded` AND `load` OF A POPUP THAT ARE SAID BEFORE IT IS ANNOUNCED. The page is built at once and announced when
|
||||
#: the engine says Page.ready, which is also when its document commits, so the document may have loaded before the client hears
|
||||
#: of the page: a `page.on("load")` registered in the handler of the `page` event would never fire. Playwright's own page is
|
||||
@@ -2793,9 +2824,33 @@ class PageDispatcher(Dispatcher):
|
||||
self._announce_lock = threading.RLock()
|
||||
self._announced = False
|
||||
self._said_before_announcement: List = []
|
||||
self.lifecycle = Lifecycle(conn, session)
|
||||
self.injected = InjectedScript(conn, session)
|
||||
conn.add_listener(self._route_juggler_event)
|
||||
# ⛔ SUBSCRIBE AND BE HANDED THE MISSED EVENTS IN ONE STEP, with the events of the sessions held (`events_gate`): an event the
|
||||
# engine's reader delivers between the subscription and the replay would reach the lifecycle BEFORE the older ones the replay
|
||||
# brings, and the lifecycle would end at the older state (a popup at about:blank after its destination committed). Nothing in the
|
||||
# step waits for an event or a reply: the readers are subscribed, the buffer is handed over, the gate opens.
|
||||
try:
|
||||
with context.browser.events_gate():
|
||||
self.lifecycle = Lifecycle(conn, session)
|
||||
self.injected = InjectedScript(conn, session)
|
||||
conn.add_listener(self._route_juggler_event)
|
||||
# ⛔ THE EVENTS THIS PAGE ALREADY MISSED, handed over now that the two things that need them exist. `Page.frameAttached` and
|
||||
# the `Runtime.executionContextCreated` pair are sent by the browser BEFORE the `Browser.newPage` reply that told us which
|
||||
# session to build this object for, so without the replay the lifecycle waits twenty seconds for a main frame that was
|
||||
# announced before it was born.
|
||||
#
|
||||
# ⛔ AND IT DELIBERATELY DOES NOT REACH `_on_juggler_event`, which is not wired yet and cannot be: that handler emits on
|
||||
# `self.channel`, and the channel does not exist until `super().__init__` has run, which needs the main frame this replay
|
||||
# is what delivers. The events that precede a page describe its birth, and the initializer built below carries that - the
|
||||
# main frame is in it by name. (The page's own listener holds them: `_held`.)
|
||||
self.replayed_events = context.browser.replay(session, conn.dispatch_event)
|
||||
except BaseException:
|
||||
conn.remove_listener(self._route_juggler_event)
|
||||
for part in ("lifecycle", "injected"):
|
||||
try:
|
||||
getattr(self, part).detach()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
try:
|
||||
self._build(server, context, session, conn, opener)
|
||||
except BaseException:
|
||||
@@ -2848,22 +2903,9 @@ class PageDispatcher(Dispatcher):
|
||||
context.browser.session_seed, context.browser.motion_budget_s,
|
||||
lambda: self.viewport_size,
|
||||
draws=context.browser.pointer_draws)
|
||||
# ⛔ THE EVENTS THIS PAGE ALREADY MISSED, handed over now that the two
|
||||
# things that need them exist. `Page.frameAttached` and the
|
||||
# `Runtime.executionContextCreated` pair are sent by the browser BEFORE
|
||||
# the `Browser.newPage` reply that told us which session to build this
|
||||
# object for, so without the replay the lifecycle waits twenty seconds
|
||||
# for a main frame that was announced before it was born.
|
||||
#
|
||||
# ⛔ AND IT DELIBERATELY DOES NOT REACH `_on_juggler_event`, which is
|
||||
# not wired yet and cannot be: that handler emits on `self.channel`,
|
||||
# and the channel does not exist until `super().__init__` has run,
|
||||
# which needs the main frame this replay is what delivers. The events
|
||||
# that precede a page describe its birth, and the initializer built
|
||||
# below carries that - the main frame is in it by name.
|
||||
replayed = context.browser.replay(session, conn.dispatch_event)
|
||||
self.replayed_events = replayed
|
||||
self._frames: Dict[str, Any] = {}
|
||||
#: The child frames the client was told of (`frameAttached`), to tell it of the ones born before the hook was in.
|
||||
self._told_attached: set = set()
|
||||
self._requests: Dict[str, Any] = {}
|
||||
#: navigationId -> the document RequestDispatcher of that navigation.
|
||||
#: ⛔ AN INDEX, NOT A SECOND COPY: the response itself keeps living on
|
||||
@@ -2899,7 +2941,8 @@ class PageDispatcher(Dispatcher):
|
||||
server, self, self.main_frame_id,
|
||||
url=getattr(known, "url", "") or "",
|
||||
name=getattr(known, "name", "") or "",
|
||||
load_states=sorted(getattr(known, "states", []) or []) or None)
|
||||
load_states=sorted(getattr(known, "states", []) or []) or None,
|
||||
told_commit=self._last_commit(known))
|
||||
viewport = self.viewport_size
|
||||
# `pageNumber` is ours, not Playwright's: the number the page's
|
||||
# rhythms are drawn under (`pointer.py` and the actions' nonce read it
|
||||
@@ -2961,13 +3004,21 @@ class PageDispatcher(Dispatcher):
|
||||
def announce(self, context: "BrowserContextDispatcher", replay: bool) -> None:
|
||||
"""Tell the client of the page (the context's `page` event) and, for a popup, say again the load states it reached before:
|
||||
under one lock, so a state said live in between waits for the ones that came first."""
|
||||
with self._announce_lock:
|
||||
# ⛔ NOT A PAGE THAT WAS CLOSED BEFORE ITS ANNOUNCEMENT (the context or the browser closed while it was being adopted): the close
|
||||
# has sent `close` and `__dispose__` for its guid, and a `page` event that names it makes the client throw. The close's lock first,
|
||||
# as in `_deliver`: the close is either over (nothing is announced) or waits for the announcement (and follows it).
|
||||
with self._close_lock, self._announce_lock:
|
||||
if self._announced_closed:
|
||||
self._announced = True
|
||||
self._said_before_announcement = []
|
||||
return
|
||||
context.emit("page", {"page": self.channel})
|
||||
earlier, self._said_before_announcement = self._said_before_announcement, []
|
||||
self._announced = True
|
||||
if replay:
|
||||
for frame, params in earlier:
|
||||
if not frame.detached:
|
||||
frame.told_states.discard(params["add"]) # said again on purpose: the emit would call it a duplicate
|
||||
frame.emit("loadstate", params)
|
||||
|
||||
def settle_events(self) -> None:
|
||||
@@ -2993,12 +3044,17 @@ class PageDispatcher(Dispatcher):
|
||||
their page prints nothing.
|
||||
"""
|
||||
# ⛔ Registered on the connection's list, never chained, and already
|
||||
# in `__init__`: what is left here is to stop holding. Only the NETWORK
|
||||
# events held are delivered - the rest describe the page's birth,
|
||||
# which the initializer already carries, and replaying a main frame's
|
||||
# `frameAttached` would announce it twice. Delivered under the lock, so
|
||||
# a live event waits for the held ones and keeps their order: a
|
||||
# response handled before its request is dropped as unknown.
|
||||
# in `__init__`: what is left here is to stop holding. EVERY event held
|
||||
# is delivered, of whatever kind, in the order it arrived: a `console`
|
||||
# message, a `pageError`, a `dialog` (an `alert()` blocks the page until
|
||||
# the client accepts it, and a client never told of it cannot), a
|
||||
# `crash`, a load state, a request. (Until 0.51.1 only the `Network.*`
|
||||
# ones were, and the rest were dropped.) The ones this handler does not
|
||||
# read - `Page.frameAttached` and the other events the lifecycle owns -
|
||||
# reach nothing here, and the lifecycle's own announcements are
|
||||
# reconciled below. A live event waits for the held ones and keeps
|
||||
# their order: a response handled before its request is dropped as
|
||||
# unknown.
|
||||
#
|
||||
# ⛔ AND EACH EVENT ONCE, AT ITS LAST PLACE. One that arrived after the
|
||||
# subscriber was registered but before the replay marked the session
|
||||
@@ -3006,15 +3062,52 @@ class PageDispatcher(Dispatcher):
|
||||
# hands it over a second time, behind events older than it. It is the
|
||||
# same params object both times; keeping its last occurrence restores
|
||||
# the order the engine sent them in and announces each request once.
|
||||
with self._held_lock:
|
||||
held, self._held = self._held or [], None
|
||||
#
|
||||
# ⛔ THE HOLD ENDS WHEN IT IS EMPTY, NOT WHEN IT IS TAKEN. The held events are delivered in rounds, outside the lock, and
|
||||
# `_held` is cleared only by a round that finds nothing: while a round is being delivered, a live event from the reader still
|
||||
# goes to the hold and waits for its turn. (Clearing it first, a live event went straight to its handler beside the round,
|
||||
# and a response could be handled before the request it answers.)
|
||||
delivered: Dict[int, Any] = {} # the params objects already delivered, kept alive so their ids are not reused
|
||||
|
||||
def give_back(held: List) -> None:
|
||||
last = {id(params): i for i, (_, params) in enumerate(held)}
|
||||
for i, (method, params) in enumerate(held):
|
||||
if last[id(params)] == i and method.startswith("Network."):
|
||||
if last[id(params)] == i and id(params) not in delivered:
|
||||
delivered[id(params)] = params
|
||||
try:
|
||||
self._deliver(method, params)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# A round ends when the reader is quiet. After FOUR rounds the rest is given back with the lock held (the old way): a page
|
||||
# that prints in a tight loop while it is born cannot keep the hold open for ever. The handlers do not wait for the reader, so
|
||||
# the lock is only a delay for it.
|
||||
for _ in range(4):
|
||||
with self._held_lock:
|
||||
held = self._held
|
||||
if not held:
|
||||
self._held = None
|
||||
break
|
||||
self._held = []
|
||||
give_back(held)
|
||||
else:
|
||||
with self._held_lock:
|
||||
while self._held:
|
||||
held, self._held = self._held, []
|
||||
give_back(held)
|
||||
self._held = None
|
||||
if self._held_dropped:
|
||||
warnings.warn(
|
||||
"invisible_playwright: %d event(s) of the page of target %s were lost while it was handed over to its dispatcher: more than "
|
||||
"%d were held (the cap that bounds the memory of a page that never finishes building)"
|
||||
% (self._held_dropped, self.target_id, self.HELD_CAP), RuntimeWarning, stacklevel=2)
|
||||
# ⛔ THE HAND-OVER IS ONE STEP, UNDER THE LIFECYCLE'S LOCK (`_hear_lifecycle`). What the client is told of a frame comes from two
|
||||
# places: the initializer, a snapshot of what the lifecycle knew when the frame dispatcher was made, and the lifecycle's own
|
||||
# announcements through a hook installed here. An event the lifecycle heard AFTER the snapshot and BEFORE the hook was told to
|
||||
# nobody - the commit of a popup's destination left its frame at `about:blank` for good - and the `DOMContentLoaded`/`load` held
|
||||
# at the same time were dropped with every held event that is not a `Network.*` one. Now the hook goes in and what the client was
|
||||
# not told is said in the same step, with the lock held: an event the lifecycle has heard is compared with what the client was
|
||||
# told, and the difference is said; one it has not heard yet waits for the lock and is announced by the hook.
|
||||
self._hear_lifecycle()
|
||||
|
||||
def _hear_lifecycle(self) -> None:
|
||||
@@ -3028,8 +3121,76 @@ class PageDispatcher(Dispatcher):
|
||||
`expect_navigation(wait_until="networkidle")` - which wait for exactly
|
||||
that event - timed out on a loaded, silent page. One definition, two
|
||||
consumers: `goto`'s wait and this event.
|
||||
|
||||
The hook is installed and the frames are reconciled with what the client was told in the same step, with the lifecycle's lock held
|
||||
(not while the held events are delivered: their handlers may ask the engine, and the reader thread that answers needs the lock).
|
||||
"""
|
||||
self.lifecycle.announce = self._on_lifecycle
|
||||
with self.lifecycle._cv:
|
||||
# ⛔ NOT ON A PAGE THAT CLOSED IN THE MEANTIME. The close detaches the lifecycle (no hook) and tells the client the page is gone
|
||||
# (`__dispose__`); the flag is set under the close's lock before it waits for this one. A hook put back now, and a frame
|
||||
# made under a page the client has dropped, is a `__create__` under a parent that no longer exists.
|
||||
if self._announced_closed:
|
||||
return
|
||||
self.lifecycle.announce = self._on_lifecycle
|
||||
self._reconcile_frames()
|
||||
|
||||
@staticmethod
|
||||
def _last_commit(known: Any) -> Any:
|
||||
"""The place in the engine's stream of the last document the lifecycle holds for this frame (None: none with an id)."""
|
||||
commits = getattr(known, "_commits", None)
|
||||
return commits[-1][0] if commits else None
|
||||
|
||||
CANON_STATES = ("commit", "domcontentloaded", "load", "networkidle")
|
||||
|
||||
def _forget_said_before_announcement(self, frame: "FrameDispatcher") -> None:
|
||||
"""The load states a frame said before the page was announced belong to the document it had then: a commit drops them."""
|
||||
with self._announce_lock:
|
||||
if not self._announced:
|
||||
self._said_before_announcement = [e for e in self._said_before_announcement if e[0] is not frame]
|
||||
|
||||
def _reconcile_frames(self) -> None:
|
||||
"""Say to the client what the lifecycle heard between the snapshot of the initializer and the hook: the frames born or gone, the
|
||||
document a frame committed, the load states it reached. Under the lifecycle's lock."""
|
||||
lifecycle = self.lifecycle
|
||||
if self._announced_closed:
|
||||
return
|
||||
for frame_id in list(self._frames):
|
||||
if frame_id not in lifecycle.frames:
|
||||
child = self._frames.pop(frame_id, None)
|
||||
if frame_id in self._told_attached:
|
||||
self._told_attached.discard(frame_id)
|
||||
self.emit("frameDetached", {"frame": child.channel})
|
||||
child.detach()
|
||||
for frame_id in sorted(lifecycle.frames, key=lifecycle._depth):
|
||||
if frame_id == self.frame.frame_id:
|
||||
continue
|
||||
child = self.frame_for(frame_id)
|
||||
if frame_id not in self._told_attached:
|
||||
self._told_attached.add(frame_id)
|
||||
self.emit("frameAttached", {"frame": child.channel})
|
||||
for frame_id, known in list(lifecycle.frames.items()):
|
||||
frame = self.frame if frame_id == self.frame.frame_id else self._frames.get(frame_id)
|
||||
if frame is not None:
|
||||
self._reconcile_frame(frame, known)
|
||||
|
||||
def _reconcile_frame(self, frame: "FrameDispatcher", known: Any) -> None:
|
||||
url, name = known.url or "", known.name or ""
|
||||
commit = self._last_commit(known)
|
||||
# A document the client was not told: a different address or name, or the same ones with another commit (a reload, a
|
||||
# navigation to the same address, between the snapshot and the hook).
|
||||
if url and ((url, name) != (frame.url, frame.name) or commit != frame.told_commit): # no address yet: nothing committed
|
||||
# what a commit says (`_on_lifecycle`), once
|
||||
self._forget_said_before_announcement(frame)
|
||||
for state in self.CANON_STATES:
|
||||
frame.emit("loadstate", {"remove": state})
|
||||
frame.url, frame.name, frame.told_commit = url, name, commit
|
||||
navigation = known._commits[-1][1] if known._commits else None
|
||||
frame.emit("navigated", {"url": url, "name": name, "newDocument": self.navigation_document(navigation)})
|
||||
for state in self.CANON_STATES:
|
||||
if state in known.states and state not in frame.told_states:
|
||||
frame.emit("loadstate", {"add": state})
|
||||
elif state not in known.states and state in frame.told_states and state != "commit":
|
||||
frame.emit("loadstate", {"remove": state})
|
||||
|
||||
def _on_lifecycle(self, what: str, frame_id: str,
|
||||
url: Optional[str] = None, *, name: str = "",
|
||||
@@ -3044,6 +3205,7 @@ class PageDispatcher(Dispatcher):
|
||||
# `page.frames` held eight entries for two frames (2026-10-12).
|
||||
if what == "frameDetached":
|
||||
child = self._frames.pop(frame_id, None)
|
||||
self._told_attached.discard(frame_id)
|
||||
if child is not None:
|
||||
self.emit("frameDetached", {"frame": child.channel})
|
||||
child.detach()
|
||||
@@ -3053,6 +3215,7 @@ class PageDispatcher(Dispatcher):
|
||||
# the first time, and this page is built after its main frame was
|
||||
# seen (`wait_for_main_frame`); the initializer carries it.
|
||||
child = self.frame_for(frame_id)
|
||||
self._told_attached.add(frame_id)
|
||||
self.emit("frameAttached", {"frame": child.channel})
|
||||
return
|
||||
child = self.frame_for(frame_id)
|
||||
@@ -3093,8 +3256,10 @@ class PageDispatcher(Dispatcher):
|
||||
# the page is closed: `_deliver` would not have delivered it.
|
||||
if self._announced_closed:
|
||||
return
|
||||
self._forget_said_before_announcement(child)
|
||||
for state in ("commit", "domcontentloaded", "load", "networkidle"):
|
||||
child.emit("loadstate", {"remove": state})
|
||||
child.told_commit = self._last_commit(self.lifecycle.frame(frame_id))
|
||||
child.url = url or ""
|
||||
child.name = name or ""
|
||||
child.emit("navigated", {
|
||||
@@ -3106,7 +3271,9 @@ class PageDispatcher(Dispatcher):
|
||||
|
||||
#: Events held while the page is being built. The birth of a page is a
|
||||
#: burst of a few dozen; a page that never finishes building must not
|
||||
#: grow this without bound.
|
||||
#: grow this without bound. The ones beyond the cap are lost, and not in
|
||||
#: silence: they are counted and said once, with the count, when the
|
||||
#: hold ends (`_install_events`).
|
||||
HELD_CAP = 512
|
||||
|
||||
def _route_juggler_event(self, method: str, params: Dict,
|
||||
@@ -3118,6 +3285,8 @@ class PageDispatcher(Dispatcher):
|
||||
if self._held is not None:
|
||||
if len(self._held) < self.HELD_CAP:
|
||||
self._held.append((method, params))
|
||||
else:
|
||||
self._held_dropped += 1
|
||||
return
|
||||
self._deliver(method, params)
|
||||
|
||||
@@ -3438,18 +3607,24 @@ class PageDispatcher(Dispatcher):
|
||||
"""
|
||||
if frame_id == self.frame.frame_id:
|
||||
return self.frame
|
||||
existing = self._frames.get(frame_id)
|
||||
if existing is not None and not existing.disposed:
|
||||
return existing
|
||||
frame = self.lifecycle.frame(frame_id)
|
||||
parent_id = getattr(frame, "parent", None)
|
||||
made = FrameDispatcher(
|
||||
self.server, self, frame_id,
|
||||
url=getattr(frame, "url", "") or "",
|
||||
parent_frame=self.frame_for(parent_id) if parent_id else None,
|
||||
load_states=sorted(getattr(frame, "states", []) or []) or ["commit"])
|
||||
self._frames[frame_id] = made
|
||||
return made
|
||||
# ⛔ CHECK AND CREATE IN ONE STEP. The reader thread (a held `eventFired` of a child, a frame the lifecycle announces) and the
|
||||
# adoption thread (the reconciliation of the hand-over) both come here for a frame that is new: without the lock each saw
|
||||
# no dispatcher and made one, two `__create__` for one frame, and the load states went to one of them. Recursive: the parent
|
||||
# is made by the same call.
|
||||
with self._frames_lock:
|
||||
existing = self._frames.get(frame_id)
|
||||
if existing is not None and not existing.disposed:
|
||||
return existing
|
||||
frame = self.lifecycle.frame(frame_id)
|
||||
parent_id = getattr(frame, "parent", None)
|
||||
made = FrameDispatcher(
|
||||
self.server, self, frame_id,
|
||||
url=getattr(frame, "url", "") or "",
|
||||
parent_frame=self.frame_for(parent_id) if parent_id else None,
|
||||
load_states=sorted(getattr(frame, "states", []) or []) or ["commit"],
|
||||
told_commit=self._last_commit(frame))
|
||||
self._frames[frame_id] = made
|
||||
return made
|
||||
|
||||
def op_set_interception(self, params: Dict) -> Any:
|
||||
"""`page.route()`: hold this page's requests until a handler answers.
|
||||
@@ -4607,6 +4782,11 @@ class BrowserDispatcher(Dispatcher):
|
||||
METHODS = {"newContext": "op_new_context", "close": "op_close",
|
||||
"newPage": "op_new_page"}
|
||||
|
||||
#: How long the engine's reader waits for the gate of the events before it delivers the event anyway (see `events_gate`).
|
||||
GATE_WAIT_S = 5.0
|
||||
#: How long a page that is being built waits for the gate before it is built without it.
|
||||
PAGE_GATE_WAIT_S = 30.0
|
||||
|
||||
def __init__(self, server, browser_type: "BrowserTypeDispatcher",
|
||||
conn: Any, version: str, session_seed: Any = None,
|
||||
motion_budget_s: Any = None,
|
||||
@@ -4614,6 +4794,58 @@ class BrowserDispatcher(Dispatcher):
|
||||
layout: str = "us", pointer_draws: bool = False,
|
||||
udp_stun_servers: Optional[list] = None) -> None:
|
||||
self.conn = conn
|
||||
# ⛔ THE EVENTS OF A SESSION GO THROUGH A GATE. A new page is handed the events it missed (`replay`) by the thread that builds it,
|
||||
# while the engine's reader goes on delivering the live ones to the same subscribers: a popup's destination committed (live) in the
|
||||
# middle of the replay of its first events, and the replay then went on with older ones (the initial about:blank, the
|
||||
# `navigationStarted` of the same navigation) - the lifecycle ended at about:blank, or with the navigation pending again. The
|
||||
# reader takes the gate for each event of a session; the page takes it for the whole of "subscribe, then replay" (`events_gate`).
|
||||
# The gate belongs to the CONNECTION (one wrapper, one gate, whoever builds a dispatcher over it).
|
||||
gate = getattr(conn, "_events_gate", None)
|
||||
if gate is None:
|
||||
gate = threading.RLock()
|
||||
try:
|
||||
conn._events_gate = gate
|
||||
except Exception:
|
||||
pass
|
||||
self._events_gate = gate
|
||||
self._gate_timeouts = 0
|
||||
if not getattr(conn, "_events_gate_installed", False):
|
||||
#: The delivery the reader would have made: an override on the instance if there is one, else the class's method looked up
|
||||
#: at each event (a patch of the class made after this dispatcher was built still applies).
|
||||
own = conn.__dict__.get("dispatch_event")
|
||||
stuck = {"until": 0.0}
|
||||
owner = self
|
||||
|
||||
def raw_dispatch(method, params, session):
|
||||
if own is not None:
|
||||
return own(method, params, session)
|
||||
return type(conn).dispatch_event(conn, method, params, session)
|
||||
|
||||
def gated_dispatch(method, params, session):
|
||||
if not session:
|
||||
return raw_dispatch(method, params, session)
|
||||
waiting = time.monotonic() >= stuck["until"]
|
||||
got = gate.acquire(timeout=owner.GATE_WAIT_S) if waiting else gate.acquire(blocking=False)
|
||||
if got:
|
||||
try:
|
||||
return raw_dispatch(method, params, session)
|
||||
finally:
|
||||
gate.release()
|
||||
# ⛔ WHOEVER HOLDS THE GATE DOES NOT LET GO: the event is delivered all the same (the old, unordered way), and the reader does
|
||||
# not wait again for a while (the bound is on the hold, not on each event). Said once per hold, where the connection records
|
||||
# what its handlers failed at.
|
||||
if waiting:
|
||||
stuck["until"] = time.monotonic() + 30.0
|
||||
owner._gate_timeouts += 1
|
||||
errors = getattr(conn, "handler_errors", None)
|
||||
if isinstance(errors, list) and len(errors) < 32:
|
||||
errors.append("events gate: held more than %.1fs, events delivered ungated for 30s" % owner.GATE_WAIT_S)
|
||||
return raw_dispatch(method, params, session)
|
||||
conn.dispatch_event = gated_dispatch
|
||||
try:
|
||||
conn._events_gate_installed = True
|
||||
except Exception:
|
||||
pass
|
||||
#: Where this session measures a proxy's UDP exit from (the launch's `udp_stun_servers`, "ip:port"
|
||||
#: strings; None = the two public defaults): the launch and every context proxy use the same list.
|
||||
self.udp_stun_servers = udp_stun_servers
|
||||
@@ -4869,6 +5101,22 @@ class BrowserDispatcher(Dispatcher):
|
||||
if len(held) < self.BUFFER_CAP:
|
||||
held.append((method, params))
|
||||
|
||||
@contextlib.contextmanager
|
||||
def events_gate(self):
|
||||
"""Hold the delivery of the events of every session: the engine's reader waits (at most `GATE_WAIT_S`) at its next event of a
|
||||
session. For a short step that waits for no event and no reply: a page subscribes its readers and is handed the events it missed."""
|
||||
got = self._events_gate.acquire(timeout=self.PAGE_GATE_WAIT_S)
|
||||
if not got:
|
||||
# the reader is stuck inside a handler: the page is built all the same (the old, unordered way), and it is said
|
||||
warnings.warn("invisible_playwright: the engine's events were held for more than %.0f s by a handler; a page is built without "
|
||||
"the gate of the events (its replay may be overtaken by a live event)" % self.PAGE_GATE_WAIT_S,
|
||||
RuntimeWarning, stacklevel=3)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if got:
|
||||
self._events_gate.release()
|
||||
|
||||
def replay(self, session: str, deliver) -> int:
|
||||
"""Hand a new consumer the events of its session that it missed.
|
||||
|
||||
|
||||
@@ -280,6 +280,19 @@ class FakeDoh:
|
||||
with self._lock:
|
||||
return [a for a in self.answers if a.name == name and (qtype is None or a.qtype == qtype)]
|
||||
|
||||
def certificate_refusals(self) -> List[Tuple[str, str]]:
|
||||
"""The failed handshakes in which the client REFUSED the certificate: a TLS alert (unknown CA, bad certificate...).
|
||||
|
||||
Not every failed handshake is one. A client that drops a connection before the handshake ends (a speculative or a
|
||||
duplicate DoH connection the browser abandons) fails it too, and says nothing about the certificate: on Windows as
|
||||
ConnectionAbortedError [WinError 10053], elsewhere as a reset or an end of file. Only a refusal means that a lookup
|
||||
of a context without the certificate exception reached the DoH. Windows census of 12/11 (run 43333574229): a
|
||||
ConnectionAbortedError through the gateway of a context that HAS the exception was read as such a lookup.
|
||||
"""
|
||||
with self._lock:
|
||||
return [(via, error) for via, error in self.tls_failures
|
||||
if "ALERT" in error.upper() or "CERTIFICATE" in error.upper()]
|
||||
|
||||
def seen_names(self) -> List[str]:
|
||||
with self._lock:
|
||||
return sorted({q.name for q in self.queries})
|
||||
|
||||
+27
-38
@@ -14,15 +14,17 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import datetime
|
||||
import ipaddress
|
||||
import random
|
||||
import socket
|
||||
import socketserver
|
||||
import ssl
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import List, Tuple
|
||||
|
||||
from _ports import bind_tcp_and_probe_udp
|
||||
|
||||
|
||||
def _certificate(address: str, directory: Path):
|
||||
from cryptography import x509
|
||||
@@ -48,44 +50,19 @@ 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>"
|
||||
|
||||
# How many port numbers are tried, and where the ones after the system's own pick are drawn from: the same as the witness's.
|
||||
from _witness import DRAW_FROM as _WITNESS_DRAW_FROM, TRIES as _WITNESS_TRIES # noqa: E402
|
||||
|
||||
|
||||
class _TcpServer(socketserver.ThreadingTCPServer):
|
||||
allow_reuse_address = True
|
||||
# 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"
|
||||
daemon_threads = True
|
||||
|
||||
|
||||
def _tcp_server_on_a_port_udp_binds(address: str):
|
||||
"""A TCP server on a port number that UDP can bind too, as ``(server, port)``.
|
||||
|
||||
The first try is the system's own pick (port 0); the others are drawn at random below the dynamic range. Windows hands out
|
||||
ephemeral TCP ports in sequence and keeps excluded ranges of a hundred ports for UDP inside the same zone, so asking the
|
||||
system again lands in the same refused range again and again (run 43230437094, ``wrapper.e2e.web`` on Windows: fifty
|
||||
consecutive picks refused, three tests red; the witness had the same defect and the same remedy,
|
||||
``test_the_witness_picks_a_port_both_sockets_bind.py``)."""
|
||||
draw = random.Random()
|
||||
refusals: List[str] = []
|
||||
for attempt in range(_WITNESS_TRIES):
|
||||
wanted = 0 if attempt == 0 else draw.randint(*_WITNESS_DRAW_FROM)
|
||||
try:
|
||||
tcp = _TcpServer((address, wanted), _TcpHandler)
|
||||
except OSError as exc:
|
||||
refusals.append("%s: %s" % (wanted or "system pick", exc))
|
||||
continue
|
||||
port = tcp.server_address[1]
|
||||
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
probe.bind((address, port))
|
||||
return tcp, port
|
||||
except OSError as exc:
|
||||
refusals.append("%s: %s" % (port, exc))
|
||||
tcp.server_close()
|
||||
finally:
|
||||
probe.close()
|
||||
raise RuntimeError("no port free for both TCP and UDP on %s after %d tries; the last refusals: %s"
|
||||
% (address, _WITNESS_TRIES, "; ".join(refusals[-3:])))
|
||||
"""A TCP server on a port number that UDP can bind too, as ``(server, port)``: the one picker of the harness (tests/_ports.py), which the
|
||||
witness and the resolver trap walk the same sequence of. The first try is the system's own pick (port 0); the others are drawn at random
|
||||
below the dynamic range, because Windows hands out ephemeral TCP ports in sequence and keeps excluded ranges of a hundred ports for UDP
|
||||
inside the same zone (run 43230437094, ``wrapper.e2e.web`` on Windows: fifty consecutive picks refused, three tests red). Every refusal is
|
||||
kept with its code and the last three are in the error."""
|
||||
return bind_tcp_and_probe_udp(address, lambda host, number: _TcpServer((host, number), _TcpHandler), socket_module=socket)
|
||||
|
||||
|
||||
class _TcpHandler(socketserver.BaseRequestHandler):
|
||||
@@ -235,9 +212,20 @@ class H3Server:
|
||||
self._quic = self._loop.run_until_complete(
|
||||
serve(address, port, configuration=configuration, create_protocol=Protocol))
|
||||
started.set()
|
||||
self._loop.run_forever()
|
||||
try:
|
||||
self._loop.run_forever()
|
||||
finally:
|
||||
# ⛔ THE LOOP IS CLOSED HERE, ON ITS OWN THREAD, after the QUIC server. A loop that is only stopped is closed later by
|
||||
# BaseEventLoop.__del__ on whatever thread the garbage collector runs in, and on Windows the proactor's close then
|
||||
# waits for the UDP receive still pending on it, for ever: the HTTP/3 e2e hung inside a later test's goto or
|
||||
# new_page, the test thread in base_events.__del__ -> proactor close -> _poll (Windows hunt of 13/11, run
|
||||
# 43377799126, 3 runs of 15; PR #486 part 1 twice).
|
||||
self._quic.close()
|
||||
self._loop.run_until_complete(asyncio.sleep(0.05))
|
||||
self._loop.close()
|
||||
|
||||
threading.Thread(target=run, daemon=True).start()
|
||||
self._thread = threading.Thread(target=run, daemon=True)
|
||||
self._thread.start()
|
||||
if not started.wait(10):
|
||||
raise RuntimeError("the QUIC server did not start")
|
||||
|
||||
@@ -248,8 +236,9 @@ class H3Server:
|
||||
def close(self) -> None:
|
||||
self._tcp.shutdown()
|
||||
self._tcp.server_close()
|
||||
self._quic.close()
|
||||
self._loop.call_soon_threadsafe(self._loop.stop)
|
||||
if not self._loop.is_closed():
|
||||
self._loop.call_soon_threadsafe(self._loop.stop)
|
||||
self._thread.join(10)
|
||||
self._dir.cleanup()
|
||||
|
||||
def __enter__(self) -> "H3Server":
|
||||
|
||||
+10
-20
@@ -31,6 +31,8 @@ from pathlib import Path
|
||||
from typing import Dict, Iterable, List, NamedTuple, Optional, Set, Tuple
|
||||
|
||||
from _doh_servers import RCODE_REFUSED, DohQuery, answer_for, build_response, parse_query
|
||||
from _ports import candidates
|
||||
from _ports import who_holds as _who_holds
|
||||
|
||||
RESOLV_CONF = Path("/etc/resolv.conf")
|
||||
|
||||
@@ -172,19 +174,6 @@ def _trap_capability() -> Tuple[bool, str]:
|
||||
TRAP_ADDRESSES = ("127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.5", "127.0.0.6", "127.0.0.7", "127.0.0.8")
|
||||
|
||||
|
||||
def _who_holds(port: int) -> str:
|
||||
"""What the machine says about the sockets of `port` (Linux: ss), for the message of a trap that could not bind."""
|
||||
import subprocess
|
||||
for command in (["ss", "-H", "-lntup"], ["netstat", "-lntup"]):
|
||||
try:
|
||||
done = subprocess.run(command, capture_output=True, text=True, timeout=10)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
continue
|
||||
lines = [line for line in done.stdout.splitlines() if (":%d " % port) in line]
|
||||
return "; held by: " + (" | ".join(lines) if lines else "nothing listed by %s" % command[0])
|
||||
return "; no ss or netstat to say who holds it"
|
||||
|
||||
|
||||
class Asker(NamedTuple):
|
||||
"""Who sent a question to the trap: the user, the process (None when its socket could not be traced) and its command."""
|
||||
uid: int
|
||||
@@ -435,12 +424,12 @@ class ResolverTrap:
|
||||
try:
|
||||
addresses = TRAP_ADDRESSES if self.port != 0 else TRAP_ADDRESSES[:1]
|
||||
for address in addresses:
|
||||
for attempt in range(200):
|
||||
made = self._bind_once(discarded, address)
|
||||
# A port asked for (53) is tried once per address; with 0 the numbers are the harness's sequence (tests/_ports.py): the
|
||||
# system's own pick, then numbers drawn below the ephemeral range, where Windows' excluded UDP blocks are not.
|
||||
for wanted in ([self.port] if self.port != 0 else candidates(200)):
|
||||
made = self._bind_once(discarded, address, wanted)
|
||||
if made:
|
||||
break
|
||||
if self.port != 0:
|
||||
break
|
||||
if made:
|
||||
self.address = address
|
||||
break
|
||||
@@ -458,10 +447,11 @@ class ResolverTrap:
|
||||
self._threads.append(t)
|
||||
t.start()
|
||||
|
||||
def _bind_once(self, discarded: List[socket.socket], address: str = "127.0.0.1") -> List[socket.socket]:
|
||||
"""One attempt: the sockets bound, or [] after putting what it opened in ``discarded``."""
|
||||
def _bind_once(self, discarded: List[socket.socket], address: str = "127.0.0.1", wanted: Optional[int] = None) -> List[socket.socket]:
|
||||
"""One attempt, on the number ``wanted`` (the trap's own port when None, 0 for the system's pick): the sockets bound, or [] after
|
||||
putting what it opened in ``discarded``."""
|
||||
made: List[socket.socket] = []
|
||||
port = self.port
|
||||
port = self.port if wanted is None else wanted
|
||||
for family, host, required in ((socket.AF_INET, address, True), (socket.AF_INET6, "::1", False)):
|
||||
pair: List[socket.socket] = [] # this family's TCP and UDP, kept or dropped together
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"""One port number that TCP and UDP both bind on an address, found the way the witness finds it (tests/_witness.py), and said when it is not found.
|
||||
|
||||
Windows hands out ephemeral TCP ports in sequence and keeps excluded ranges of a hundred ports for UDP in the same zone, so asking the system for
|
||||
fifty TCP ports in a row can give fifty consecutive numbers inside one range UDP may not bind: the first try is the system's own pick, the others
|
||||
are drawn at random below the ephemeral range (run 43230437094, wrapper.e2e.web on Windows: ``H3Server`` found "no port free for both TCP and UDP"
|
||||
three times, and the refusals it had swallowed were never read). Every refusal is kept, with its code, and the last ones are in the message.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
import socket
|
||||
import subprocess
|
||||
from typing import Any, Callable, List, Tuple
|
||||
|
||||
TRIES = 200
|
||||
#: Below Linux's ephemeral range (32768): a number drawn here is not the next of a sequence the system hands out.
|
||||
DRAW_FROM = (20000, 32767)
|
||||
|
||||
|
||||
def who_holds(port: int) -> str:
|
||||
"""What the machine says about the sockets of `port` (ss, or netstat), for the message of a picker or a trap that found no number."""
|
||||
for command in (["ss", "-H", "-lntup"], ["netstat", "-lntup"]):
|
||||
try:
|
||||
done = subprocess.run(command, capture_output=True, text=True, timeout=10)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
continue
|
||||
lines = [line for line in done.stdout.splitlines() if (":%d " % port) in line]
|
||||
return "; held by: " + (" | ".join(lines) if lines else "nothing listed by %s" % command[0])
|
||||
return "; no ss or netstat to say who holds it"
|
||||
|
||||
|
||||
def candidates(tries: int = TRIES, draw: Any = None):
|
||||
"""The port numbers to try, in order: 0 (the system's own pick) first, then numbers drawn at random below the ephemeral range. The ONE
|
||||
sequence of the harness for "the same number on TCP and UDP": the HTTP/3 server, the witness and the resolver trap all walk it."""
|
||||
draw = draw or random.Random()
|
||||
for attempt in range(tries):
|
||||
yield 0 if attempt == 0 else draw.randint(*DRAW_FROM)
|
||||
|
||||
|
||||
def bind_tcp_and_probe_udp(address: str, make_tcp: Callable[[str, int], Any], tries: int = TRIES, socket_module: Any = None,
|
||||
draw: Any = None) -> Tuple[Any, int]:
|
||||
"""``make_tcp(address, port)`` makes the TCP server (it binds, with port 0 for the system's pick; it has ``server_address`` and
|
||||
``server_close``). Returns ``(that server, its port)`` once UDP binds the same number too (the probe is closed again: whoever needs the UDP
|
||||
socket binds it next). Raises RuntimeError saying how many tries were made and the last refusals, codes included."""
|
||||
sock = socket_module or socket
|
||||
refusals: List[str] = []
|
||||
last = 0
|
||||
for wanted in candidates(tries, draw):
|
||||
tcp = None
|
||||
try:
|
||||
tcp = make_tcp(address, wanted)
|
||||
port = tcp.server_address[1]
|
||||
probe = sock.socket(sock.AF_INET, sock.SOCK_DGRAM)
|
||||
try:
|
||||
probe.bind((address, port))
|
||||
finally:
|
||||
probe.close()
|
||||
return tcp, port
|
||||
except OSError as exc:
|
||||
refusals.append("%s: %s" % (wanted or "system pick", exc))
|
||||
if tcp is not None:
|
||||
last = tcp.server_address[1]
|
||||
tcp.server_close()
|
||||
else:
|
||||
last = wanted
|
||||
raise RuntimeError("no port free for both TCP and UDP on %s, after %d tries (the last number tried: %s)%s; the last refusals: %s"
|
||||
% (address, tries, last or "the system's pick", who_holds(last) if last else "", "; ".join(refusals[-3:])))
|
||||
@@ -143,14 +143,14 @@ class TurnServer:
|
||||
self.sock.sendto(_message(0x0113, tid, err), src)
|
||||
continue
|
||||
user = attrs[0x0006].decode(errors="replace")
|
||||
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode()).digest()
|
||||
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode(), usedforsecurity=False).digest()
|
||||
body = (_attr(0x0016, _xor_addr(*RELAYED)) + _attr(0x0020, _xor_addr(src[0], src[1])) +
|
||||
_attr(0x000D, struct.pack("!I", 600)))
|
||||
self.allocations.append((src[0], src[1], user, time.monotonic()))
|
||||
self.sock.sendto(_message(0x0103, tid, body, key), src)
|
||||
elif mtype in (0x0004, 0x0008, 0x0009): # Refresh, CreatePermission, ChannelBind
|
||||
user = attrs.get(0x0006, b"").decode(errors="replace")
|
||||
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode()).digest()
|
||||
key = hashlib.md5(("%s:%s:%s" % (user, REALM, PASSWORD)).encode(), usedforsecurity=False).digest()
|
||||
body = _attr(0x000D, struct.pack("!I", 600)) if mtype == 0x0004 else b""
|
||||
self.sock.sendto(_message(mtype | 0x0100, tid, body, key), src)
|
||||
|
||||
|
||||
+6
-9
@@ -10,7 +10,6 @@ saw, so a road that works also gives the page a server-reflexive candidate.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
import socket
|
||||
import sys
|
||||
import struct
|
||||
@@ -19,11 +18,11 @@ from typing import Dict, Iterable, List, Tuple
|
||||
|
||||
_MAGIC = b"\x21\x12\xa4\x42"
|
||||
|
||||
#: How many port numbers the witness tries before it gives up, and where it draws them from after the system's own pick.
|
||||
TRIES = 200
|
||||
#: Below the start of Windows' dynamic range (49152), where its excluded ranges are reserved in blocks of a hundred, and
|
||||
#: below Linux's ephemeral range (32768): a number drawn here is not the next of a sequence the system hands out.
|
||||
DRAW_FROM = (20000, 32767)
|
||||
#: How many port numbers the witness tries before it gives up, and where it draws them from after the system's own pick: the sequence of
|
||||
#: tests/_ports.py, which the HTTP/3 server and the resolver trap walk too. Below the start of Windows' dynamic range (49152), where its excluded
|
||||
#: ranges are reserved in blocks of a hundred, and below Linux's ephemeral range (32768): a number drawn there is not the next of a sequence the
|
||||
#: system hands out.
|
||||
from _ports import DRAW_FROM, TRIES, candidates # noqa: E402
|
||||
|
||||
|
||||
class Witness:
|
||||
@@ -45,9 +44,7 @@ class Witness:
|
||||
@staticmethod
|
||||
def _bind_both(address: str, port: int):
|
||||
refusals: List[str] = []
|
||||
draw = random.Random()
|
||||
for attempt in range(1 if port else TRIES):
|
||||
wanted = port if port else (0 if attempt == 0 else draw.randint(*DRAW_FROM))
|
||||
for wanted in ([port] if port else candidates(TRIES)):
|
||||
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
udp = None
|
||||
try:
|
||||
|
||||
@@ -73,6 +73,12 @@ def pytest_configure(config):
|
||||
# The run stops at the first refusal of the engine (tests/engine_refusal.py).
|
||||
from engine_refusal import StopAtTheFirstRefusal
|
||||
config.pluginmanager.register(StopAtTheFirstRefusal(config), "engine-refusal-stop")
|
||||
# What the core did about the GeoIP database during the run, for scripts/ci_lab_geoip.py verify (the CI legs set GEOIP_USED_OUT).
|
||||
if os.environ.get("GEOIP_USED_OUT"):
|
||||
from geoip_used import GeoipUsedRecorder
|
||||
recorder = GeoipUsedRecorder(os.environ["GEOIP_USED_OUT"])
|
||||
recorder.start()
|
||||
config.pluginmanager.register(recorder, "geoip-used")
|
||||
|
||||
|
||||
def pytest_runtest_setup(item):
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""What the core did about the GeoIP database during a pytest run, written when the run ends.
|
||||
|
||||
Registered by tests/conftest.py when ``GEOIP_USED_OUT`` names a file (the CI legs set it; a developer's run does not). ``scripts/ci_lab_geoip.py
|
||||
verify`` reads the file: the proof of a leg is not only the environment it was LAUNCHED in (``evidence``, written before pytest) but what the
|
||||
process of the tests used: the value of ``STEALTHFOX_GEOIP_MMDB`` when the run ended, the sha256 of that file, and how many times the core went
|
||||
past the override to ask GitHub for the latest database (``_resolve_latest_geoip_tag``) or to download one (``_download_geoip_tag``): none, in a leg
|
||||
with the database of the pin. A test that removes the variable on purpose (the user-path e2e files do, in a throwaway environment of their own)
|
||||
runs in another process and is not counted here.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class GeoipUsedRecorder:
|
||||
def __init__(self, path: str) -> None:
|
||||
self.path = Path(path)
|
||||
self.asked_github = 0
|
||||
self._undo = []
|
||||
|
||||
def start(self) -> None:
|
||||
try:
|
||||
from invisible_core import _geoip_db
|
||||
except ImportError: # a run without the core installed: the file says so
|
||||
return
|
||||
for name in ("_resolve_latest_geoip_tag", "_download_geoip_tag"):
|
||||
original = getattr(_geoip_db, name, None)
|
||||
if original is None:
|
||||
continue
|
||||
|
||||
def counted(*args, __original=original, **kwargs):
|
||||
self.asked_github += 1
|
||||
return __original(*args, **kwargs)
|
||||
|
||||
setattr(_geoip_db, name, counted)
|
||||
self._undo.append((_geoip_db, name, original))
|
||||
|
||||
def stop(self) -> None:
|
||||
for module, name, original in reversed(self._undo):
|
||||
setattr(module, name, original)
|
||||
self._undo = []
|
||||
|
||||
def pytest_sessionfinish(self, session, exitstatus) -> None: # noqa: ARG002
|
||||
value = os.environ.get("STEALTHFOX_GEOIP_MMDB", "")
|
||||
digest = None
|
||||
if value and os.path.isfile(value):
|
||||
digest = hashlib.sha256(Path(value).read_bytes()).hexdigest()
|
||||
data = {"env": value, "exists": digest is not None, "sha256": digest, "asked_github": self.asked_github}
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.path.write_text(json.dumps(data, indent=1), encoding="utf-8")
|
||||
self.stop()
|
||||
@@ -57,6 +57,7 @@ def _page(handled):
|
||||
page.disposed = False
|
||||
page._held = None
|
||||
page._held_lock = threading.Lock()
|
||||
page._held_dropped = 0
|
||||
page._detach_listeners = lambda: None
|
||||
page._hear_lifecycle = lambda: None
|
||||
page.context = types.SimpleNamespace(browser=types.SimpleNamespace(
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
"""The destination's commit of a popup, whenever it comes while the page is handed from the buffer to its dispatcher, reaches the client once.
|
||||
|
||||
NO BROWSER HERE (the real dispatchers over a scripted Juggler connection, as `test_every_order_of_the_events_of_a_popup_gives_one_page_event`).
|
||||
|
||||
A popup's page is built the moment the engine attaches its target, and what the client is told of its frame comes from two places: the
|
||||
INITIALIZER (a snapshot of what the lifecycle knew when the frame dispatcher was made: url, name, load states) and the lifecycle's own
|
||||
announcements (`navigated`, `loadstate`, a new frame), which go up through a hook (`Lifecycle.announce`) that the page installs at the
|
||||
end of its construction (`_install_events` -> `_hear_lifecycle`). The page's own listener holds the events of the same period and
|
||||
`_install_events` hands over only the `Network.*` ones. So an event that the lifecycle heard AFTER the snapshot and BEFORE the hook was
|
||||
told to nobody: the commit of the destination left the client's frame at `about:blank` for good, and the `DOMContentLoaded`/`load` of
|
||||
the destination was dropped with the held events (measured on Windows, `test_popups_reach_the_client_e2e.py` with no route on the context:
|
||||
the popup "is at about:blank", or `wait_for_load_state("load")` times out).
|
||||
|
||||
The test parks the adoption thread at FOUR points of that passage - after the main frame is known (before the snapshot), as the main
|
||||
frame's dispatcher is made (after the snapshot), as the events are installed (the hold is still on) and after they are installed (the hook
|
||||
is in) - and delivers the destination's commit, `DOMContentLoaded` and `load` (in this order) at every placement of the three among the
|
||||
four points, 20 cases, none sampled. (The hand-over itself, from the release of the hold to the hook, is one step with the lifecycle's lock
|
||||
held: there is no point inside it to park at, which is the property that is wanted.) The page is then made ready and announced, and what the CLIENT was
|
||||
told of the main frame (the initializer, then each `navigated` and `loadstate`, in order) must be what the lifecycle holds: the url of the
|
||||
destination, the states commit/domcontentloaded/load, and the destination's url told exactly once.
|
||||
|
||||
Known-bad input: the code as it was -> the orders with an event between the snapshot and the hook are red.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright._juggler import dispatcher as base
|
||||
from invisible_playwright._juggler import remote
|
||||
from invisible_playwright._juggler import server as server_mod
|
||||
from invisible_playwright._juggler.server import LocalUtilsDispatcher
|
||||
|
||||
from test_every_order_of_the_events_of_a_popup_gives_one_page_event import Engine, FRAME, SESSION, TARGET, _thread, _wait
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
DEST = "http://dest.test/p"
|
||||
POINTS = ["after_main_frame", "frame_dispatcher", "events_install", "events_installed"]
|
||||
STATES = ("commit", "domcontentloaded", "load")
|
||||
|
||||
|
||||
class PopupEngine(Engine):
|
||||
def start(self):
|
||||
self.dispatch_event("Page.navigationStarted", {"frameId": FRAME, "navigationId": "n2", "url": DEST}, SESSION)
|
||||
|
||||
def commit_dest(self):
|
||||
self.dispatch_event("Page.navigationCommitted", {"frameId": FRAME, "navigationId": "n2", "url": DEST, "name": ""}, SESSION)
|
||||
|
||||
def dcl(self):
|
||||
self.dispatch_event("Page.eventFired", {"frameId": FRAME, "name": "DOMContentLoaded"}, SESSION)
|
||||
|
||||
def load(self):
|
||||
self.dispatch_event("Page.eventFired", {"frameId": FRAME, "name": "load"}, SESSION)
|
||||
|
||||
|
||||
class Parking:
|
||||
"""Stops the adoption thread of the popup at the four points of the passage, until the test lets it go on."""
|
||||
|
||||
def __init__(self):
|
||||
self.reached = [threading.Event() for _ in POINTS]
|
||||
self.release = [threading.Event() for _ in POINTS]
|
||||
|
||||
def pause(self, index):
|
||||
if threading.current_thread().name != "invpw-adopt-%s" % TARGET or self.reached[index].is_set():
|
||||
return
|
||||
self.reached[index].set()
|
||||
self.release[index].wait(10)
|
||||
|
||||
def open_all(self):
|
||||
for event in self.release:
|
||||
event.set()
|
||||
|
||||
|
||||
def _install(mp, parking, told):
|
||||
"""The parking points, and a record of what the client is told of the main frame of the popup."""
|
||||
original_wait = server_mod.Lifecycle.wait_for_main_frame
|
||||
|
||||
def after_main_frame(self, *args, **kwargs):
|
||||
result = original_wait(self, *args, **kwargs)
|
||||
parking.pause(0)
|
||||
return result
|
||||
mp.setattr(server_mod.Lifecycle, "wait_for_main_frame", after_main_frame)
|
||||
|
||||
original_init = server_mod.FrameDispatcher.__init__
|
||||
|
||||
def frame_init(self, server, page, frame_id, url="about:blank", name="", load_states=None, parent_frame=None, told_commit=None):
|
||||
if frame_id == FRAME and parent_frame is None:
|
||||
parking.pause(1)
|
||||
told["url"] = url
|
||||
told["states"] = set(load_states or ["commit"])
|
||||
told["navigated"] = []
|
||||
told["ops"] = []
|
||||
return original_init(self, server, page, frame_id, url=url, name=name, load_states=load_states, parent_frame=parent_frame, told_commit=told_commit)
|
||||
mp.setattr(server_mod.FrameDispatcher, "__init__", frame_init)
|
||||
|
||||
original_install = server_mod.PageDispatcher._install_events
|
||||
|
||||
def install(self):
|
||||
parking.pause(2)
|
||||
result = original_install(self)
|
||||
parking.pause(3)
|
||||
return result
|
||||
mp.setattr(server_mod.PageDispatcher, "_install_events", install)
|
||||
|
||||
original_emit = base.Dispatcher.emit
|
||||
|
||||
def spy(self, method, params=None):
|
||||
if getattr(self, "TYPE", "") == "Frame" and getattr(self, "frame_id", None) == FRAME and "ops" in told:
|
||||
if method == "navigated":
|
||||
told["navigated"].append(params["url"])
|
||||
told["ops"].append(("url", params["url"]))
|
||||
elif method == "loadstate":
|
||||
for key in ("add", "remove"):
|
||||
if key in params:
|
||||
told["ops"].append((key, params[key]))
|
||||
return original_emit(self, method, params)
|
||||
mp.setattr(base.Dispatcher, "emit", spy)
|
||||
|
||||
|
||||
def _client_view(told):
|
||||
url, states = told["url"], set(told["states"])
|
||||
for op, value in told["ops"]:
|
||||
if op == "url":
|
||||
url = value
|
||||
elif op == "add":
|
||||
states.add(value)
|
||||
elif op == "remove":
|
||||
states.discard(value)
|
||||
return url, states
|
||||
|
||||
|
||||
def _run(placement):
|
||||
"""One case: commit_dest, dcl and load delivered at the points in `placement` (one per event, in order)."""
|
||||
parking, told, announced = Parking(), {}, []
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
_install(mp, parking, told)
|
||||
original_emit = base.Dispatcher.emit
|
||||
|
||||
def page_spy(self, method, params=None):
|
||||
if method == "page" and getattr(self, "TYPE", "") == "BrowserContext":
|
||||
announced.append(time.monotonic())
|
||||
return original_emit(self, method, params)
|
||||
mp.setattr(base.Dispatcher, "emit", page_spy)
|
||||
server = remote._SharedServer()
|
||||
browser_type = remote.SharedBrowserType(server)
|
||||
LocalUtilsDispatcher(server)
|
||||
conn = PopupEngine()
|
||||
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
|
||||
try:
|
||||
context = server.object(server.handle({"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(t for t in conn.sessions if t != TARGET)
|
||||
del announced[:]
|
||||
conn.attach(opener_target, context.context_id)
|
||||
conn.frame()
|
||||
conn.commit() # the initial about:blank
|
||||
conn.start() # the navigation to the address starts
|
||||
todo = list(zip(["commit_dest", "dcl", "load"], placement))
|
||||
for i in range(len(POINTS)):
|
||||
assert parking.reached[i].wait(5), "the adoption thread never reached %s" % POINTS[i]
|
||||
for event, where in list(todo):
|
||||
if where == i:
|
||||
getattr(conn, event)()
|
||||
todo.remove((event, where))
|
||||
parking.release[i].set()
|
||||
conn.ready()
|
||||
assert _wait(lambda: announced), "the popup was never announced"
|
||||
assert _wait(lambda: _thread() is None), "the adoption thread never ended"
|
||||
page = browser._page_targets.get(TARGET)
|
||||
frame = page.lifecycle.frames[FRAME]
|
||||
return _client_view(told), (frame.url, {s for s in frame.states if s in STATES}), told
|
||||
finally:
|
||||
parking.open_all()
|
||||
try:
|
||||
server.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def test_the_commit_and_the_load_of_the_destination_reach_the_client_whenever_they_come_while_the_page_is_handed_over():
|
||||
failures, count = [], 0
|
||||
for combo in itertools.combinations_with_replacement(range(len(POINTS)), 3):
|
||||
count += 1
|
||||
(client_url, client_states), (url, states), told = _run(combo)
|
||||
label = "commit_dest/dcl/load at %s" % [POINTS[i] for i in combo]
|
||||
problems = []
|
||||
if client_url != url:
|
||||
problems.append("the client's frame is at %r, the lifecycle's at %r" % (client_url, url))
|
||||
if {s for s in client_states if s in STATES} != states:
|
||||
problems.append("the client has the states %s, the lifecycle %s" % (sorted(client_states & set(STATES)), sorted(states)))
|
||||
told_dest = (1 if told["url"] == DEST else 0) + told["navigated"].count(DEST)
|
||||
if told_dest != 1:
|
||||
problems.append("the destination's address was told %d times" % told_dest)
|
||||
if problems:
|
||||
failures.append("%s: %s" % (label, "; ".join(problems)))
|
||||
assert count == 20
|
||||
assert not failures, "%d of %d orders lost or doubled an event, e.g.:\n %s" % (len(failures), count, "\n ".join(failures[:12]))
|
||||
|
||||
|
||||
def _run_announcement(where):
|
||||
"""The blank page loads, the page is made ready, and the destination's commit comes at `where`: before the ready, or WHILE the page is
|
||||
announced (the adoption thread is parked inside the announcement, after the `page` event and before the replay of the states said
|
||||
before it, and the commit is delivered by another thread, as the engine's reader would)."""
|
||||
told, announced, inside = {}, [], threading.Event()
|
||||
go = threading.Event()
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
open_parking = Parking()
|
||||
open_parking.open_all()
|
||||
_install(mp, open_parking, told) # the record of what the client is told; its parking points are open
|
||||
original_emit = base.Dispatcher.emit
|
||||
|
||||
def page_spy(self, method, params=None):
|
||||
result = original_emit(self, method, params)
|
||||
if method == "page" and getattr(self, "TYPE", "") == "BrowserContext" and threading.current_thread().name == "invpw-adopt-%s" % TARGET:
|
||||
announced.append(True)
|
||||
inside.set()
|
||||
go.wait(10)
|
||||
return result
|
||||
mp.setattr(base.Dispatcher, "emit", page_spy)
|
||||
server = remote._SharedServer()
|
||||
browser_type = remote.SharedBrowserType(server)
|
||||
LocalUtilsDispatcher(server)
|
||||
conn = PopupEngine()
|
||||
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
|
||||
try:
|
||||
context = server.object(server.handle({"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(t for t in conn.sessions if t != TARGET)
|
||||
del announced[:]
|
||||
told.clear()
|
||||
conn.attach(opener_target, context.context_id)
|
||||
conn.frame()
|
||||
conn.commit()
|
||||
conn.start()
|
||||
assert _wait(lambda: (browser._adoptions.get(TARGET) is not None and browser._adoptions[TARGET].state == "waiting")), \
|
||||
"the adoption never waited for the ready"
|
||||
conn.dcl() # the blank page's load, said live and kept for the replay
|
||||
conn.load()
|
||||
deliverer = None
|
||||
if where == "before_ready":
|
||||
conn.commit_dest()
|
||||
conn.ready()
|
||||
else:
|
||||
conn.ready()
|
||||
assert inside.wait(5), "the page was never announced"
|
||||
deliverer = threading.Thread(target=conn.commit_dest, daemon=True)
|
||||
deliverer.start()
|
||||
time.sleep(0.2) # the commit is on its way while the announcement is not over
|
||||
go.set()
|
||||
if deliverer is not None:
|
||||
deliverer.join(5)
|
||||
assert _wait(lambda: _thread() is None), "the adoption thread never ended"
|
||||
page = browser._page_targets.get(TARGET)
|
||||
known = page.lifecycle.frames[FRAME]
|
||||
return _client_view(told), (known.url, {s for s in known.states if s in STATES}), told
|
||||
finally:
|
||||
go.set()
|
||||
try:
|
||||
server.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize("where", ["before_ready", "during_announcement"])
|
||||
def test_a_commit_before_or_during_the_announcement_leaves_the_client_with_the_states_of_the_destination(where):
|
||||
(client_url, client_states), (url, states), told = _run_announcement(where)
|
||||
assert client_url == url == DEST
|
||||
assert {s for s in client_states if s in STATES} == states == {"commit"}, (
|
||||
"the client has the states %s of a destination that has only committed: the load of the blank page, said again after the "
|
||||
"commit, is still on its frame" % sorted(client_states & set(STATES)))
|
||||
assert (1 if told["url"] == DEST else 0) + told["navigated"].count(DEST) == 1
|
||||
@@ -34,6 +34,8 @@ def page():
|
||||
page.injected = Mock()
|
||||
page.actions = Mock()
|
||||
page._frames = {}
|
||||
page._told_attached = set()
|
||||
page._frames_lock = __import__("threading").RLock()
|
||||
page._navigation_requests = {}
|
||||
page._announced_closed = False
|
||||
Dispatcher.__init__(page, server, context)
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
"""An event the engine sends LIVE while the events a new page missed are being replayed to it does not reach it before them.
|
||||
|
||||
NO BROWSER HERE (the real dispatchers over a scripted Juggler connection, as `test_the_hand_over_of_a_popup_holds_under_concurrency`).
|
||||
|
||||
The browser buffers the events of a session nobody reads yet, and `PageDispatcher` is handed them (`BrowserDispatcher.replay`) once its
|
||||
lifecycle and its injected script are subscribed. The replay ran on the adoption thread while the engine's reader went on delivering the
|
||||
live events to the same subscribers: a popup's destination committed (live) in the middle of the replay of its first events, and the
|
||||
replay then went on with the OLDER ones - the initial `about:blank` (no navigation of ours) and the `navigationStarted` of the same
|
||||
navigation. The lifecycle ended at `about:blank` for good (a popup "at about:blank": the client was never told of the destination), or
|
||||
had the navigation pending again after its own commit ("Execution context was destroyed" in the first evaluate). Measured on Windows with
|
||||
the engine's events traced (`POPUP-63-SECONDA-CAUSA.md`): the second `Page.frameAttached` of every popup in the traces IS the replay, and
|
||||
the engine sends each event once - 13 reds in 20 runs of the popup file on engine 63 after the hand-over fix, none of them with a second
|
||||
`frameAttached` from the engine (`PageHandler._onFrameAttached` answers nothing for a frame it holds live).
|
||||
|
||||
Sequence of the test: the first events of a popup are buffered (frame, blank commit, the destination's navigation started) -> the page is
|
||||
built and the replay starts, stopped after its first event -> the engine's reader delivers the destination's commit -> the replay goes on.
|
||||
Whatever the interleaving, the lifecycle must end at the destination, with the navigation committed and not pending, and the client's
|
||||
frame must be told the destination.
|
||||
|
||||
Known-bad input: the replay as it was -> the lifecycle ends at `about:blank` and the navigation of the destination is pending again.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright._juggler import server as server_mod
|
||||
|
||||
from test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once import DEST
|
||||
from test_the_hand_over_of_a_popup_holds_under_concurrency import World, _finish
|
||||
from test_every_order_of_the_events_of_a_popup_gives_one_page_event import FRAME, SESSION, TARGET, _thread, _wait
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
def _case(stop_after, scenario="commit"):
|
||||
"""The replay is stopped after `stop_after` of its events; the live event of the scenario is delivered by another thread (the reader):
|
||||
the destination's commit, or (`context`) the creation of a new utility context after the old one was destroyed."""
|
||||
parked, go, delivered = threading.Event(), threading.Event(), []
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
original = server_mod.BrowserDispatcher.replay
|
||||
|
||||
def replay(self, session, deliver):
|
||||
if session != SESSION:
|
||||
return original(self, session, deliver)
|
||||
count = [0]
|
||||
|
||||
def slow(method, params, s):
|
||||
deliver(method, params, s)
|
||||
delivered.append(method)
|
||||
count[0] += 1
|
||||
if count[0] == stop_after:
|
||||
parked.set()
|
||||
go.wait(10)
|
||||
return original(self, session, slow)
|
||||
mp.setattr(server_mod.BrowserDispatcher, "replay", replay)
|
||||
# the adoption thread is held before the page is built, so that the first events of the popup are buffered when it is
|
||||
entered, begin = threading.Event(), threading.Event()
|
||||
original_build = server_mod.BrowserDispatcher._enter_building
|
||||
|
||||
def enter_building(self, *args, **kwargs):
|
||||
if threading.current_thread().name == "invpw-adopt-%s" % TARGET:
|
||||
entered.set()
|
||||
begin.wait(10)
|
||||
return original_build(self, *args, **kwargs)
|
||||
mp.setattr(server_mod.BrowserDispatcher, "_enter_building", enter_building)
|
||||
world = World()
|
||||
reader = None
|
||||
try:
|
||||
conn = world.conn
|
||||
conn.attach(world.opener_target, world.context.context_id)
|
||||
assert entered.wait(5), "the adoption never started"
|
||||
conn.frame()
|
||||
conn.commit() # the initial about:blank (navigation n1)
|
||||
conn.start() # the navigation to the destination starts (n2)
|
||||
if scenario == "context":
|
||||
conn.dispatch_event("Runtime.executionContextDestroyed", {"executionContextId": "eutility"}, SESSION)
|
||||
begin.set() # the page is built now, and the replay hands it those events
|
||||
assert parked.wait(5), "the replay never delivered %d event(s): %s" % (stop_after, delivered)
|
||||
live = conn.commit_dest if scenario == "commit" else (lambda: conn.dispatch_event("Runtime.executionContextCreated", {
|
||||
"executionContextId": "eutility2", "auxData": {"frameId": FRAME, "name": "utility"}}, SESSION))
|
||||
reader = threading.Thread(target=live, daemon=True, name="engine-reader")
|
||||
reader.start()
|
||||
reader.join(0.3) # with the replay ordered, the reader waits behind it; unordered, it is through
|
||||
go.set()
|
||||
reader.join(5)
|
||||
assert not reader.is_alive(), "the reader never got through"
|
||||
conn.ready()
|
||||
assert _wait(lambda: _thread() is None), "the adoption thread never ended"
|
||||
page = world.browser._page_targets.get(TARGET)
|
||||
known = page.lifecycle.frames[FRAME]
|
||||
if scenario == "context":
|
||||
return page.injected.contexts.get((FRAME, "utility"))
|
||||
return known.url, known.navigation, sorted(known.states), page.frame.url
|
||||
finally:
|
||||
begin.set()
|
||||
go.set()
|
||||
world.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stop_after", [1, 2, 3, 4, 5])
|
||||
def test_the_destination_commit_delivered_while_the_replay_goes_on_is_the_last_word(stop_after):
|
||||
url, navigation, states, told = _case(stop_after)
|
||||
assert url == DEST, "the lifecycle ended at %r: an older event of the replay came after the live commit" % url
|
||||
assert navigation == "n2", "the frame's navigation is %r" % navigation
|
||||
assert "commit" in states
|
||||
assert told == DEST, "the client's frame is at %r" % told
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stop_after", [1, 2])
|
||||
def test_a_context_created_while_the_replay_goes_on_is_not_undone_by_an_older_event(stop_after):
|
||||
"""The same race for the injected script: the replay brings the creation of the utility context and its destruction, the engine creates a
|
||||
new one meanwhile. The new one is the context the injected script must end with."""
|
||||
context = _case(stop_after, "context")
|
||||
assert context == "eutility2", "the injected script ended with the utility context %r" % (context,)
|
||||
|
||||
|
||||
def test_a_patch_of_the_class_made_after_the_browser_was_built_still_sees_the_events():
|
||||
"""The reader looked the delivery up on the class at each event; the gate keeps doing so (the e2e fixtures that record the events patch
|
||||
`EventListeners.dispatch_event` after the browser exists)."""
|
||||
from invisible_core.juggler.connection import EventListeners
|
||||
|
||||
world = World()
|
||||
try:
|
||||
seen = []
|
||||
original = EventListeners.dispatch_event
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setattr(EventListeners, "dispatch_event", lambda self, method, params, session: seen.append((method, session)))
|
||||
world.conn.dispatch_event("Page.x", {}, "S-patched")
|
||||
assert seen == [("Page.x", "S-patched")]
|
||||
assert EventListeners.dispatch_event is original
|
||||
finally:
|
||||
world.close()
|
||||
|
||||
|
||||
def test_a_gate_that_is_never_let_go_costs_the_reader_one_wait_and_is_said():
|
||||
"""The bound is on the hold, not on each event: the first event waits GATE_WAIT_S, the next ones are delivered at once, and the
|
||||
connection records it."""
|
||||
import time
|
||||
|
||||
world = World()
|
||||
held, release, got = threading.Event(), threading.Event(), []
|
||||
try:
|
||||
world.browser.GATE_WAIT_S = 0.2
|
||||
|
||||
def holder():
|
||||
with world.browser.events_gate():
|
||||
held.set()
|
||||
release.wait(10)
|
||||
t = threading.Thread(target=holder, daemon=True)
|
||||
t.start()
|
||||
assert held.wait(5)
|
||||
world.conn.add_listener(lambda m, p, s: got.append(m) if s == "S-stuck" else None)
|
||||
began = time.monotonic()
|
||||
for n in range(3):
|
||||
world.conn.dispatch_event("Page.e%d" % n, {}, "S-stuck")
|
||||
took = time.monotonic() - began
|
||||
assert got == ["Page.e0", "Page.e1", "Page.e2"], got
|
||||
assert took < 1.0, "the reader waited %.2fs for three events: the bound is per event" % took
|
||||
assert world.browser._gate_timeouts == 1
|
||||
assert any("events gate" in str(e) for e in world.conn.handler_errors), world.conn.handler_errors
|
||||
finally:
|
||||
release.set()
|
||||
world.close()
|
||||
|
||||
|
||||
def test_a_page_built_while_the_reader_is_stuck_in_a_handler_is_built_all_the_same_and_it_is_said():
|
||||
import warnings
|
||||
|
||||
world = World()
|
||||
held, release = threading.Event(), threading.Event()
|
||||
try:
|
||||
world.browser.PAGE_GATE_WAIT_S = 0.2
|
||||
|
||||
def stuck_reader():
|
||||
with world.browser.events_gate():
|
||||
held.set()
|
||||
release.wait(10)
|
||||
t = threading.Thread(target=stuck_reader, daemon=True)
|
||||
t.start()
|
||||
assert held.wait(5)
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
with world.browser.events_gate():
|
||||
pass
|
||||
assert any("held for more than" in str(w.message) for w in caught), [str(w.message) for w in caught]
|
||||
finally:
|
||||
release.set()
|
||||
world.close()
|
||||
@@ -0,0 +1,60 @@
|
||||
"""A popup's page that is closed (the caller closes the context or the browser) while it is being adopted is not announced to the client afterwards.
|
||||
|
||||
NO BROWSER HERE (the real dispatchers over a scripted Juggler connection, as `test_the_hand_over_of_a_popup_holds_under_concurrency`).
|
||||
|
||||
The page's guid exists for the client from the moment the page is built (its `__create__`), and the context's `page` event is what tells the client
|
||||
to treat it as a page. A close that comes in between sends `close` and `__dispose__` for that guid; the adoption then said `page` for it, and the
|
||||
client threw (an event naming an object it had dropped, the family of `'dict' object has no attribute '_object'`).
|
||||
|
||||
Sequence: the adoption thread is parked before the hook goes in -> the page is closed (`announce_closed`) -> the adoption thread goes on to
|
||||
announce the page. Nothing may be sent for the page, or about it, after its `__dispose__`.
|
||||
|
||||
Known-bad input: 436f815 + the fixes of the concurrency review, without the guard in `announce` -> a `page` event after the `__dispose__`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from test_the_hand_over_of_a_popup_holds_under_concurrency import World, _adopter, _wait, _thread, POINTS, Parking, _install
|
||||
from invisible_playwright._juggler import server as server_mod
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
def test_a_page_closed_before_its_announcement_is_never_announced():
|
||||
parking, told = Parking(), {}
|
||||
sent, caught, at_hook, go = [], [], threading.Event(), threading.Event()
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
_install(mp, parking, told)
|
||||
original = server_mod.PageDispatcher._hear_lifecycle
|
||||
|
||||
def hear(self):
|
||||
if _adopter() and not caught:
|
||||
caught.append(self)
|
||||
at_hook.set()
|
||||
go.wait(10)
|
||||
return original(self)
|
||||
mp.setattr(server_mod.PageDispatcher, "_hear_lifecycle", hear)
|
||||
world = World()
|
||||
mp.setattr(world.server, "send_up", lambda message: sent.append(message))
|
||||
try:
|
||||
world.born()
|
||||
for i in range(3):
|
||||
assert parking.reached[i].wait(5), "the adoption thread never reached %s" % POINTS[i]
|
||||
parking.release[i].set()
|
||||
assert at_hook.wait(5), "the adoption thread never reached the hook"
|
||||
page = caught[0]
|
||||
page.announce_closed()
|
||||
disposed_at = next(i for i, m in enumerate(sent) if m.get("method") == "__dispose__" and m.get("guid") == page.guid)
|
||||
go.set()
|
||||
parking.open_all()
|
||||
assert _wait(lambda: _thread() is None), "the adoption thread never ended"
|
||||
after = [m for m in sent[disposed_at + 1:] if m.get("method") in ("page", "__create__")
|
||||
or m.get("params", {}).get("page", {}).get("guid") == page.guid]
|
||||
assert not after, "told after the page's __dispose__: %s" % [(m.get("method"), m.get("guid")) for m in after]
|
||||
finally:
|
||||
go.set()
|
||||
parking.open_all()
|
||||
world.close()
|
||||
@@ -28,8 +28,10 @@ def _serve():
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
kind = self.path.strip("/").split("/")[0].split("?")[0]
|
||||
if kind in BODIES:
|
||||
asked = self.path.strip("/").split("/")[0].split("?")[0]
|
||||
# the name that goes into the header is the dict's own key, found by comparison: nothing of the request is written back
|
||||
kind = next((name for name in BODIES if name == asked), None)
|
||||
if kind is not None:
|
||||
body = BODIES[kind]
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "application/octet-stream")
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""scripts/ci_lab_geoip.py: the GeoIP database of a CI leg is made by the repository, the same bytes on every run, and a leg says what it ran with."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _load():
|
||||
spec = importlib.util.spec_from_file_location("ci_lab_geoip_under_test", ROOT / "scripts" / "ci_lab_geoip.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
lab = _load()
|
||||
EXITS = {"germany": lab.addr(1, 178, 10, 5), "japan": lab.addr(1, 0, 16, 5), "india": lab.addr(1, 6, 0, 5), "australia": lab.addr(1, 0, 4, 5),
|
||||
"brazil": lab.addr(1, 178, 32, 5), "united_states": lab.addr(1, 32, 239, 5)}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def database(tmp_path):
|
||||
path = tmp_path / lab.FILE_NAME
|
||||
path.write_bytes(lab.build_bytes())
|
||||
return path
|
||||
|
||||
|
||||
def test_the_same_bytes_on_every_run_and_the_pin_is_their_hash():
|
||||
first, second = lab.build_bytes(), lab.build_bytes()
|
||||
assert first == second
|
||||
pin = lab.load_pin(ROOT / "ci" / "geoip.json")
|
||||
assert lab.sha256_of_bytes(first) == pin["mmdb_sha256"], "the table of scripts/ci_lab_geoip.py and ci/geoip.json changed apart"
|
||||
assert len(first) == pin["mmdb_bytes"]
|
||||
|
||||
|
||||
def test_the_exits_of_the_realness_suite_are_the_networks_of_the_database():
|
||||
support = (ROOT / "tests" / "_realness_support.py").read_text(encoding="utf-8")
|
||||
for label, address in EXITS.items():
|
||||
assert '"%s": _address(%s)' % (label, ", ".join(address.split("."))) in support, "%s moved in tests/_realness_support.py" % label
|
||||
net = ".".join(address.split(".")[:3]) + ".0/24"
|
||||
assert net in lab.NETWORKS, "%s (%s) is not a network of the lab database" % (label, address)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["MODE_MMAP_EXT", "MODE_MMAP", "MODE_FILE", "MODE_MEMORY"])
|
||||
def test_every_reader_of_maxminddb_opens_it(database, mode):
|
||||
maxminddb = pytest.importorskip("maxminddb")
|
||||
if not hasattr(maxminddb, mode):
|
||||
pytest.skip("no %s in this maxminddb" % mode)
|
||||
with maxminddb.open_database(str(database), mode=getattr(maxminddb, mode)) as reader:
|
||||
record = reader.get(EXITS["germany"])
|
||||
assert record["country"]["iso_code"] == "DE" and record["location"]["time_zone"] == "Europe/Berlin"
|
||||
|
||||
|
||||
def test_the_core_reads_what_it_reads_from_it(database):
|
||||
from invisible_core._geo import ip_to_coordinates, ip_to_country, ip_to_timezone
|
||||
|
||||
for cidr, (country, zone, lat, lon) in lab.NETWORKS.items():
|
||||
ip = cidr.split("/")[0].rsplit(".", 1)[0] + ".5"
|
||||
assert ip_to_country(ip, database) == country
|
||||
assert ip_to_timezone(ip, database) == zone
|
||||
assert ip_to_coordinates(ip, database) == (lat, lon)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("address", ["198.51.100.4", "198.51.100.5", "198.51.100.6", "198.51.100.9", "203.0.113.7", "127.0.0.1",
|
||||
"2001:db8::1", "::1"])
|
||||
def test_an_address_that_is_not_in_it_is_not_in_the_database_and_never_an_error(database, address):
|
||||
from invisible_core._geo import GeoTimezoneError, ip_to_country, ip_to_timezone
|
||||
|
||||
assert ip_to_country(address, database) is None
|
||||
with pytest.raises(GeoTimezoneError) as caught:
|
||||
ip_to_timezone(address, database)
|
||||
assert caught.value.kind == "ip_not_in_db"
|
||||
|
||||
|
||||
def test_a_writer_that_no_longer_makes_the_pinned_bytes_is_refused_and_exports_nothing(tmp_path, monkeypatch, capsys):
|
||||
pin = tmp_path / "geoip.json"
|
||||
pin.write_text(json.dumps({"mmdb_sha256": "0" * 64}), encoding="utf-8")
|
||||
env_file = tmp_path / "github_env"
|
||||
monkeypatch.setenv("GITHUB_ENV", str(env_file))
|
||||
code = lab.main(["build", "--pin", str(pin), "--dest", str(tmp_path / "dest")])
|
||||
assert code == 1 and not env_file.exists() and not (tmp_path / "dest" / lab.FILE_NAME).exists()
|
||||
assert "change both in one commit" in capsys.readouterr().err
|
||||
|
||||
|
||||
def test_a_pin_that_is_not_a_pin_is_refused(tmp_path):
|
||||
bad = tmp_path / "geoip.json"
|
||||
for text in ("not json", "{}", json.dumps({"mmdb_sha256": "xyz"})):
|
||||
bad.write_text(text, encoding="utf-8")
|
||||
with pytest.raises(lab.Refused):
|
||||
lab.load_pin(bad)
|
||||
|
||||
|
||||
def test_the_evidence_is_what_the_environment_says(tmp_path):
|
||||
db = tmp_path / "db.mmdb"
|
||||
db.write_bytes(b"x")
|
||||
assert lab.evidence({lab.ENV: str(db)})["exists"] is True
|
||||
assert lab.evidence({}) == {"env": "", "exists": False, "sha256": None}
|
||||
assert lab.evidence({lab.ENV: str(tmp_path / "no")}) == {"env": str(tmp_path / "no"), "exists": False, "sha256": None}
|
||||
|
||||
|
||||
def test_the_evidence_command_writes_the_file_the_judge_reads(tmp_path, monkeypatch):
|
||||
out = tmp_path / "result" / "geoip.json"
|
||||
monkeypatch.delenv(lab.ENV, raising=False)
|
||||
assert lab.main(["evidence", "--out", str(out)]) == 0
|
||||
assert json.loads(out.read_text(encoding="utf-8")) == {"env": "", "exists": False, "sha256": None}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("address", [lab.addr(20, 118, 230, 145), lab.addr(8, 8, 8, 8), lab.addr(1, 178, 11, 5), lab.addr(52, 0, 0, 1), lab.addr(223, 255, 255, 1)])
|
||||
def test_a_public_address_that_is_not_a_lab_network_answers_the_declared_record(database, address):
|
||||
"""A launch with no proxy asks the database for the egress address of the runner, which is not known in advance (run 43351424907 of PR 486: 495
|
||||
errors "egress IP ... not present in the geoip database", every one from a test that launches without a proxy). One declared record answers it."""
|
||||
from invisible_core._geo import ip_to_country, ip_to_timezone
|
||||
|
||||
country, zone, _lat, _lon = lab.FALLBACK
|
||||
assert ip_to_country(address, database) == country and ip_to_timezone(address, database) == zone
|
||||
|
||||
|
||||
def test_the_fallback_cuts_out_every_network_of_the_table_and_every_reserved_range():
|
||||
import ipaddress
|
||||
|
||||
cut = lab.fallback_networks()
|
||||
for net in [ipaddress.ip_network(c) for c in lab.NETWORKS] + list(lab.RESERVED):
|
||||
assert not any(n.overlaps(net) for n in cut), "%s is covered by the fallback" % net
|
||||
assert sum(n.num_addresses for n in cut) + sum(ipaddress.ip_network(c).num_addresses for c in lab.NETWORKS) + sum(n.num_addresses for n in lab.RESERVED) == 1 << 32
|
||||
@@ -0,0 +1,71 @@
|
||||
"""scripts/ci_lab_geoip.py verify: the leg ran with the pinned database and the core never went past it to GitHub; and `build` says where the record goes."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _load():
|
||||
spec = importlib.util.spec_from_file_location("ci_lab_geoip_verify_under_test", ROOT / "scripts" / "ci_lab_geoip.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
lab = _load()
|
||||
PIN = ROOT / "ci" / "geoip.json"
|
||||
|
||||
|
||||
def _proof(tmp_path, name, **fields):
|
||||
data = {"env": "/db/geoip-aio-all.mmdb", "exists": True, "sha256": lab.load_pin(PIN)["mmdb_sha256"]}
|
||||
data.update(fields)
|
||||
path = tmp_path / name
|
||||
path.write_text(json.dumps(data), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def test_build_exports_the_variable_and_the_place_of_the_record_of_use(tmp_path, monkeypatch, capsys):
|
||||
env_file = tmp_path / "github_env"
|
||||
monkeypatch.setenv("GITHUB_ENV", str(env_file))
|
||||
assert lab.main(["build", "--pin", str(PIN), "--dest", str(tmp_path / "dest")]) == 0
|
||||
path = (tmp_path / "dest" / lab.FILE_NAME).resolve()
|
||||
used = path.parent / "geoip-used.json"
|
||||
assert env_file.read_text(encoding="utf-8") == "STEALTHFOX_GEOIP_MMDB=%s\nGEOIP_USED_OUT=%s\n" % (path, used)
|
||||
assert "GEOIP_USED_OUT=%s" % used in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_leg_with_the_pinned_database_and_no_question_to_github_verifies(tmp_path):
|
||||
evidence = _proof(tmp_path, "evidence.json")
|
||||
used = _proof(tmp_path, "used.json", asked_github=0)
|
||||
assert lab.verify(lab.load_pin(PIN), evidence, used) == []
|
||||
assert lab.main(["verify", "--pin", str(PIN), "--evidence", str(evidence), "--used", str(used)]) == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fields, said", [({"env": "", "exists": False, "sha256": None}, "was not set"),
|
||||
({"exists": False, "sha256": None}, "is not a file"),
|
||||
({"sha256": "d" * 64}, "the pin says")])
|
||||
def test_evidence_of_a_leg_without_the_database_does_not_verify(tmp_path, fields, said):
|
||||
problems = lab.verify(lab.load_pin(PIN), _proof(tmp_path, "evidence.json", **fields))
|
||||
assert len(problems) == 1 and said in problems[0], problems
|
||||
|
||||
|
||||
def test_a_core_that_went_past_the_variable_to_github_does_not_verify(tmp_path):
|
||||
problems = lab.verify(lab.load_pin(PIN), _proof(tmp_path, "evidence.json"), _proof(tmp_path, "used.json", asked_github=3))
|
||||
assert len(problems) == 1 and "asked GitHub" in problems[0] and "3 time" in problems[0]
|
||||
|
||||
|
||||
def test_a_variable_gone_by_the_end_of_the_run_does_not_verify(tmp_path):
|
||||
used = _proof(tmp_path, "used.json", env="", exists=False, sha256=None, asked_github=0)
|
||||
problems = lab.verify(lab.load_pin(PIN), _proof(tmp_path, "evidence.json"), used)
|
||||
assert len(problems) == 1 and "record of use" in problems[0]
|
||||
|
||||
|
||||
def test_a_record_that_is_not_there_does_not_verify(tmp_path):
|
||||
problems = lab.verify(lab.load_pin(PIN), _proof(tmp_path, "evidence.json"), tmp_path / "none.json")
|
||||
assert len(problems) == 1 and "cannot be read" in problems[0]
|
||||
assert lab.main(["verify", "--pin", str(PIN), "--evidence", str(tmp_path / "none.json")]) == 1
|
||||
@@ -0,0 +1,109 @@
|
||||
"""scripts/ci_real_geoip_check.py, the three checks on the REAL database that only the release runs: here against databases made on the spot."""
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _load(name):
|
||||
spec = importlib.util.spec_from_file_location(name + "_under_test", ROOT / "scripts" / (name + ".py"))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
check = _load("ci_real_geoip_check")
|
||||
lab = check.lab
|
||||
|
||||
|
||||
def _database(tmp_path, name, networks=None):
|
||||
"""A database made like the lab one, from `networks` (the table of the script when None)."""
|
||||
old = dict(lab.NETWORKS)
|
||||
try:
|
||||
if networks is not None:
|
||||
lab.NETWORKS.clear()
|
||||
lab.NETWORKS.update(networks)
|
||||
path = tmp_path / name
|
||||
path.write_bytes(lab.build_bytes())
|
||||
return path
|
||||
finally:
|
||||
lab.NETWORKS.clear()
|
||||
lab.NETWORKS.update(old)
|
||||
|
||||
|
||||
def _database_without_fallback(tmp_path, name):
|
||||
"""The lab table alone, with no record for the other public addresses: a database that has no answer for 8.8.8.8."""
|
||||
old = lab.FALLBACK
|
||||
lab.FALLBACK = None
|
||||
try:
|
||||
return _database(tmp_path, name)
|
||||
finally:
|
||||
lab.FALLBACK = old
|
||||
|
||||
|
||||
def test_the_exit_of_a_network_is_the_dot_five_of_its_slash_24():
|
||||
assert check.exit_of(lab.net(1, 178, 10)) == lab.addr(1, 178, 10, 5)
|
||||
|
||||
|
||||
def test_a_database_that_agrees_passes_the_comparison_and_the_zones(tmp_path, capsys):
|
||||
real = _database(tmp_path, "real.mmdb")
|
||||
ours = _database(tmp_path, "lab.mmdb")
|
||||
assert check.check_lab_agrees(real, ours) == []
|
||||
assert check.check_zones(real) == []
|
||||
assert "distinct zones" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_zone_that_differs_is_said_with_the_network(tmp_path):
|
||||
changed = dict(lab.NETWORKS)
|
||||
changed[lab.net(1, 0, 16)] = ("JP", "Asia/Seoul", 35.0, 139.0)
|
||||
real = _database(tmp_path, "real.mmdb", changed)
|
||||
ours = _database(tmp_path, "lab.mmdb")
|
||||
problems = check.check_lab_agrees(real, ours)
|
||||
assert len(problems) == 1 and lab.net(1, 0, 16) in problems[0] and "Asia/Seoul" in problems[0]
|
||||
|
||||
|
||||
def test_a_network_the_real_database_does_not_have_is_said(tmp_path):
|
||||
real = _database(tmp_path, "real.mmdb", {lab.net(1, 178, 10): lab.NETWORKS[lab.net(1, 178, 10)]})
|
||||
ours = _database(tmp_path, "lab.mmdb")
|
||||
problems = check.check_lab_agrees(real, ours)
|
||||
assert len(problems) == len(lab.NETWORKS) - 1
|
||||
|
||||
|
||||
def test_a_zone_the_runner_does_not_know_is_a_finding(tmp_path):
|
||||
odd = dict(lab.NETWORKS)
|
||||
odd[lab.net(1, 6, 0)] = ("IN", "Mars/Olympus_Mons", 1.0, 1.0)
|
||||
real = _database(tmp_path, "real.mmdb", odd)
|
||||
problems = check.check_zones(real)
|
||||
assert len(problems) == 1 and "Mars/Olympus_Mons" in problems[0]
|
||||
|
||||
|
||||
def test_a_database_that_does_not_open_or_has_no_country_is_a_finding(tmp_path):
|
||||
broken = tmp_path / "broken.mmdb"
|
||||
broken.write_bytes(b"not a database")
|
||||
assert check.check_open_and_answer(broken)
|
||||
assert check.check_open_and_answer(_database_without_fallback(tmp_path, "lab.mmdb")) # no 8.8.8.8 in it: no country
|
||||
|
||||
|
||||
def test_the_command_takes_no_argument():
|
||||
assert check.main(["--something"]) == 2
|
||||
|
||||
|
||||
def test_the_product_road_is_the_one_without_the_variable_and_with_a_cold_cache(tmp_path, monkeypatch):
|
||||
seen = {}
|
||||
|
||||
def fake():
|
||||
seen["variable"] = os.environ.get("STEALTHFOX_GEOIP_MMDB")
|
||||
seen["cache"] = os.environ.get("INVISIBLE_PLAYWRIGHT_CACHE_DIR")
|
||||
return tmp_path / "x.mmdb"
|
||||
|
||||
monkeypatch.setenv("STEALTHFOX_GEOIP_MMDB", "/somewhere")
|
||||
monkeypatch.setenv("INVISIBLE_PLAYWRIGHT_CACHE_DIR", "/before")
|
||||
import invisible_core.download as download
|
||||
monkeypatch.setattr(download, "ensure_geoip_mmdb", fake)
|
||||
assert check.product_download(tmp_path / "cold") == tmp_path / "x.mmdb"
|
||||
assert seen == {"variable": None, "cache": str(tmp_path / "cold")}
|
||||
@@ -0,0 +1,41 @@
|
||||
"""scripts/ci_real_geoip_check.py exits 3 when no database came (the network): that says nothing about the database, and the release is run again."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _load():
|
||||
spec = importlib.util.spec_from_file_location("ci_real_geoip_exit_under_test", ROOT / "scripts" / "ci_real_geoip_check.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
check = _load()
|
||||
|
||||
|
||||
def test_a_database_that_did_not_come_is_exit_3_and_not_a_finding(monkeypatch, capsys):
|
||||
def no_network(cache):
|
||||
raise OSError("name resolution failed")
|
||||
|
||||
monkeypatch.setattr(check, "product_download", no_network)
|
||||
assert check.main([]) == check.EXIT_NO_DATABASE == 3
|
||||
assert "NO DATABASE" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_database_that_came_and_fails_a_check_is_exit_1_and_names_the_check(tmp_path, monkeypatch, capsys):
|
||||
lab = check.lab
|
||||
broken = tmp_path / "geoip-aio-all.mmdb"
|
||||
with monkeypatch.context() as m:
|
||||
m.setattr(lab, "FALLBACK", None) # no record for 8.8.8.8 in the lab database: the first check fails
|
||||
broken.write_bytes(lab.build_bytes())
|
||||
monkeypatch.setattr(check, "product_download", lambda cache: broken)
|
||||
assert check.main([]) == 1
|
||||
out = capsys.readouterr().out
|
||||
assert "sha256 %s" % lab.sha256_of(broken) in out and "1. it opens with the reader of the core and answers for an address: FAILED" in out
|
||||
assert "2. the lab database agrees" in out and "3. every time_zone" in out
|
||||
@@ -316,6 +316,53 @@ def test_a_seal_that_cannot_be_read_is_red(tmp_path, capsys):
|
||||
assert code == 1 and "cannot be read" in capsys.readouterr().out
|
||||
|
||||
|
||||
# --- the GeoIP database of the leg ---------------------------------------------------------------------------------
|
||||
MMDB_SHA = "c" * 64
|
||||
|
||||
|
||||
def _geoip(tmp_path, **evidence):
|
||||
pin = tmp_path / "geoip.json"
|
||||
pin.write_text(json.dumps({"mmdb_sha256": MMDB_SHA}), encoding="utf-8")
|
||||
proof = tmp_path / "geoip-evidence.json"
|
||||
base = {"env": "/db/geoip-aio-all.mmdb", "exists": True, "sha256": MMDB_SHA}
|
||||
base.update(evidence)
|
||||
proof.write_text(json.dumps(base), encoding="utf-8")
|
||||
return ["--geoip", str(proof), "--geoip-pin", str(pin)]
|
||||
|
||||
|
||||
def test_a_leg_that_ran_with_the_database_of_the_pin_is_green(tmp_path):
|
||||
code, result = _judge(tmp_path, GREEN, extra=_geoip(tmp_path))
|
||||
assert code == 0 and result["geoip_sha256"] == MMDB_SHA
|
||||
|
||||
|
||||
def test_a_leg_launched_without_the_variable_is_red(tmp_path, capsys):
|
||||
code, result = _judge(tmp_path, GREEN, extra=_geoip(tmp_path, env="", exists=False, sha256=None))
|
||||
out = capsys.readouterr().out
|
||||
assert code == 1 and result["verdict"] == "red" and "without STEALTHFOX_GEOIP_MMDB" in out
|
||||
|
||||
|
||||
def test_a_variable_that_names_no_file_is_red(tmp_path, capsys):
|
||||
code, _r = _judge(tmp_path, GREEN, extra=_geoip(tmp_path, exists=False, sha256=None))
|
||||
assert code == 1 and "is not a file" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_database_that_is_not_the_one_of_the_pin_is_red(tmp_path, capsys):
|
||||
code, _r = _judge(tmp_path, GREEN, extra=_geoip(tmp_path, sha256="d" * 64))
|
||||
assert code == 1 and "the pin" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_evidence_that_is_missing_or_unreadable_is_red(tmp_path, capsys):
|
||||
code, _r = _judge(tmp_path, GREEN, extra=["--geoip", str(tmp_path / "none.json"), "--geoip-pin", str(tmp_path / "geoip.json")])
|
||||
assert code == 1 and "did not say which database" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_a_pin_that_cannot_be_read_is_red(tmp_path, capsys):
|
||||
extra = _geoip(tmp_path)
|
||||
(tmp_path / "geoip.json").write_text("not json", encoding="utf-8")
|
||||
code, _r = _judge(tmp_path, GREEN, extra=extra)
|
||||
assert code == 1 and "pin of the GeoIP database" in capsys.readouterr().out
|
||||
|
||||
|
||||
# --- exact, every test of a file, xunit2 ---------------------------------------------------------------------------
|
||||
def test_an_exact_suite_with_more_tests_than_min_tests_is_red(tmp_path, capsys):
|
||||
cases = GREEN + [_case(FILE_B, "test_new")]
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"""The workflows that run the wrapper's tests launch with the GeoIP database of ci/geoip.json; the release alone looks at the real one.
|
||||
|
||||
Without STEALTHFOX_GEOIP_MMDB the core asks GitHub which database is the latest on every call (run 43211837926). tests.yml and e2e.yml (its Linux run and its Windows parts) make
|
||||
the database (scripts/ci_lab_geoip.py: the same bytes every run, no download) BEFORE the step that runs pytest. user-install.yml proves the installation a user
|
||||
gets and is left as it is. publish.yml is the release: it runs the three checks on the REAL database (scripts/ci_real_geoip_check.py) before it uploads, and
|
||||
nothing else touches it.
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
WORKFLOWS = Path(__file__).resolve().parents[1] / ".github" / "workflows"
|
||||
BUILD = "scripts/ci_lab_geoip.py build"
|
||||
REAL = "scripts/ci_real_geoip_check.py"
|
||||
RUNS_PYTEST = {
|
||||
"tests.yml": " - name: Run pytest\n",
|
||||
"e2e.yml": " - name: Run the full e2e suite under a virtual display, without the root ones\n",
|
||||
"e2e.yml#windows": " - name: Run this part of the e2e\n",
|
||||
}
|
||||
|
||||
|
||||
def _scope(name):
|
||||
"""The text of one workflow, or of one leg of it: `e2e.yml` is its Linux job, `e2e.yml#windows` its Windows parts."""
|
||||
file, _, leg = name.partition("#")
|
||||
text = (WORKFLOWS / file).read_text(encoding="utf-8")
|
||||
if file != "e2e.yml":
|
||||
return text
|
||||
windows = text.index("\n e2e-windows:\n")
|
||||
if leg == "windows":
|
||||
return text[windows:]
|
||||
ends = [i for i in (text.find("\n e2e-windows-control-a:\n"), windows) if i >= 0]
|
||||
return text[:min(ends)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name, pytest_step", sorted(RUNS_PYTEST.items()))
|
||||
def test_the_database_is_made_before_the_step_that_runs_the_tests(name, pytest_step):
|
||||
text = _scope(name)
|
||||
assert text.count(BUILD) == 1, "%s makes the GeoIP database %d times" % (name, text.count(BUILD))
|
||||
assert pytest_step in text, "the step that runs the tests of %s moved: update this test with it" % name
|
||||
assert text.index(BUILD) < text.index(pytest_step), "%s makes the database after the tests started" % name
|
||||
assert REAL not in text, "the real database is the release's alone"
|
||||
|
||||
|
||||
def test_the_workflow_that_proves_the_installation_is_left_alone():
|
||||
text = (WORKFLOWS / "user-install.yml").read_text(encoding="utf-8")
|
||||
assert BUILD not in text and REAL not in text
|
||||
|
||||
|
||||
def test_the_release_checks_the_real_database_before_it_uploads_and_makes_no_lab_one():
|
||||
text = (WORKFLOWS / "publish.yml").read_text(encoding="utf-8")
|
||||
assert text.count("python " + REAL) == 1 and BUILD not in text
|
||||
assert " real-geoip-database:\n" in text
|
||||
assert "needs: [already-published, gate, real-geoip-database]" in text, "the upload does not wait for the real database"
|
||||
# and no other workflow runs the real checks
|
||||
for other in sorted(WORKFLOWS.glob("*.yml")):
|
||||
if other.name != "publish.yml":
|
||||
assert REAL not in other.read_text(encoding="utf-8"), "%s runs the checks of the release" % other.name
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name, pytest_step", sorted(RUNS_PYTEST.items()))
|
||||
def test_the_leg_verifies_after_the_tests_that_it_ran_with_the_pinned_database(name, pytest_step):
|
||||
text = _scope(name)
|
||||
step = " - name: The leg ran with the pinned GeoIP database\n if: always()\n"
|
||||
assert text.count(step) == 1 and "ci_lab_geoip.py verify" in text, name
|
||||
assert text.index(pytest_step) < text.index(step), "%s verifies before the tests ran" % name
|
||||
@@ -89,11 +89,11 @@ def test_a_context_that_is_the_only_proxy_resolves_its_names_by_doh_through_it(f
|
||||
assert _asked_outside(doh, "page-a.test") == [], (
|
||||
"the DoH was asked for a name that is not the proxied context's: the default context, which has no proxy, must "
|
||||
"resolve natively and never use the DoH: %s" % _asked_outside(doh, "page-a.test") + why)
|
||||
# A lookup of a context without `ignore_https_errors` (the default one) can only fail the handshake with the FakeDoh:
|
||||
# a failed handshake is a lookup of the wrong context that reached the DoH through this gateway.
|
||||
assert doh.tls_failures == [], (
|
||||
"a DoH handshake failed: a context that does not accept the FakeDoh certificate (the default context, which has no "
|
||||
"proxy) used the DoH: %s" % doh.tls_failures + why)
|
||||
# A lookup of a context without `ignore_https_errors` (the default one) can only REFUSE the FakeDoh's certificate: a refusal
|
||||
# is a lookup of the wrong context that reached the DoH through this gateway (a dropped connection is not one).
|
||||
assert doh.certificate_refusals() == [], (
|
||||
"a DoH handshake was refused: a context that does not accept the FakeDoh certificate (the default context, which has no "
|
||||
"proxy) used the DoH: %s (every failed handshake: %s)" % (doh.certificate_refusals(), doh.tls_failures) + why)
|
||||
|
||||
assert watcher.watched_pids, ("the watcher never saw a browser process (it saw: %s): a watcher that cannot see proves "
|
||||
"nothing" % watcher.process_names)
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""``Control+A`` selects all in an <input> and a <textarea>, in-process and served to the stock Playwright client, as it does on the stock Firefox.
|
||||
|
||||
Measured on the published wrapper 0.50.1 and on the engine of the giro 7 (Docker Linux, a field with 11 characters, focus, the selection collapsed
|
||||
before each press): ``press("Control+A")``, ``press("ControlOrMeta+A")``, ``down("Control")`` + ``press("A")`` + ``up("Control")`` and
|
||||
``locator.press("Control+A")`` left ``selectionStart == selectionEnd == 0``; ``press("Control+a")`` selected all (0, 11); the stock Firefox of
|
||||
Playwright selected all with every one of them. Cause: the keyboard of invisible_core held Shift for the capital ``A`` (a character that only
|
||||
exists with Shift), so the browser got Control+Shift+A, which is not the select-all command (juggler/keyboard.py, ``_shortcut_letter``).
|
||||
|
||||
What a page reads here is only ``selectionStart`` and ``selectionEnd`` after the shortcut: the same on every machine.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
_HTML = '<html><body><input id="i" value="hello world"><br><textarea id="t">hello world</textarea></body></html>'
|
||||
_LENGTH = len("hello world")
|
||||
|
||||
_VARIANTS = ["Control+A", "Control+a", "ControlOrMeta+A", "separate", "locator.press"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("variant", _VARIANTS)
|
||||
@pytest.mark.parametrize("field", ["i", "t"])
|
||||
def test_control_a_selects_all_in_the_field(browser, field, variant):
|
||||
page = browser.new_page()
|
||||
try:
|
||||
page.set_content(_HTML)
|
||||
page.evaluate("(id) => { const e = document.getElementById(id); e.focus(); e.setSelectionRange(0, 0); }", field)
|
||||
if variant == "separate":
|
||||
page.keyboard.down("Control")
|
||||
page.keyboard.press("A")
|
||||
page.keyboard.up("Control")
|
||||
elif variant == "locator.press":
|
||||
page.locator("#" + field).press("Control+A")
|
||||
else:
|
||||
page.keyboard.press(variant)
|
||||
got = page.evaluate(
|
||||
"(id) => { const e = document.getElementById(id); return [e.selectionStart, e.selectionEnd, document.activeElement.id]; }",
|
||||
field)
|
||||
finally:
|
||||
page.close()
|
||||
assert got == [0, _LENGTH, field], (
|
||||
"%s in #%s: selection %r, expected (0, %d) in the same field" % (variant, field, got, _LENGTH))
|
||||
@@ -314,6 +314,10 @@ def test_cross_origin_iframe_frame_locator_resolves_button(firefox_binary, cross
|
||||
page.goto(cross_origin_harness["parent_url"], wait_until="domcontentloaded", timeout=30_000)
|
||||
page.wait_for_selector("iframe#ifr_plain", timeout=10_000)
|
||||
|
||||
# count() does not wait (Playwright's own semantics): the iframe ELEMENT is in the parent, but its cross-origin document,
|
||||
# in a process of its own, can load later on a loaded runner (Windows CI of 13/11, run 43383366904: 0 elements). Wait for
|
||||
# the button first, as a script that counts it would.
|
||||
page.frame_locator("iframe#ifr_plain").locator("button#ok").wait_for(timeout=10_000)
|
||||
for selector in ("button#ok", "button.btn-primary"):
|
||||
cnt = page.frame_locator("iframe#ifr_plain").locator(selector).count()
|
||||
assert cnt == 1, f"locator({selector!r}) found {cnt} elements (expected 1)"
|
||||
|
||||
@@ -32,6 +32,8 @@ import pytest
|
||||
from test_webrtc_realness import _e2e_binary, _launch, candidates, decode_priority, host_candidates, is_mdns # noqa: F401
|
||||
|
||||
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
|
||||
# The two tests that read a consecutive pair of ports (N, N+1) carry `wall_clock`: the e2e run gives them the machine alone, after the parallel tests,
|
||||
# so that another worker's browser or test server cannot take port N+1 between the engine's draw and the bind (tests/test_the_consecutive_port_tests_run_serially.py).
|
||||
|
||||
NETWORK_ENV = "STEALTHFOX_WEBRTC_NETWORK"
|
||||
# retail 159 on Windows. The interface rank is the position in the prioritizer's sort, starting at 127
|
||||
@@ -158,6 +160,7 @@ def test_ipv6_without_the_exit_prefix_is_no_ipv6(local_https_page, socks5_tcp_on
|
||||
assert _by_protocol(hosts) == {"UDP": [UDP_127], "TCP": [TCP_127]}, hosts
|
||||
|
||||
|
||||
@pytest.mark.wall_clock
|
||||
def test_the_host_ports_are_those_of_a_windows_machine(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""Retail on Windows (6 of 6 runs, ``captures/retail/firefox-159.0-win/direct-dualstack-srflx-ports``): the UDP host
|
||||
ports are in the dynamic range 49152-65535 and, on one connection, the IPv4 port and the IPv6 port are consecutive
|
||||
@@ -188,6 +191,7 @@ def _ports_of_two_connections(declaration, socks, page_url, monkeypatch, seed):
|
||||
sorted(c["port"] for c in second if c["proto"] == "UDP"))
|
||||
|
||||
|
||||
@pytest.mark.wall_clock
|
||||
def test_two_connections_on_one_page_get_their_own_port_pair(local_https_page, socks5_tcp_only, monkeypatch):
|
||||
"""Retail (``captures/retail/firefox-159.0-win/two-pc-port-sequence``, 6 of 6): each connection gets its own pair,
|
||||
consecutive (N, N+1) in the range, and the second pair is unrelated to the first (not increasing)."""
|
||||
|
||||
@@ -96,9 +96,11 @@ def _only_the_doh_road_was_used(doh, gw, watcher):
|
||||
"a CONNECT carried a name: the browser must resolve with the DoH and connect by address" + why)
|
||||
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy of the context" + why
|
||||
_assert_every_connection_went_through_the_gateway(doh, gw)
|
||||
# Context-only layout: the default context resolves natively and never uses the DoH, so a failed handshake (the lookup
|
||||
# Context-only layout: the default context resolves natively and never uses the DoH, so a refused certificate (the lookup
|
||||
# of a context that does not accept the FakeDoh certificate) is a lookup of the wrong context sent to the DoH.
|
||||
assert doh.tls_failures == [], "a DoH handshake failed: the default context used the DoH: %s" % doh.tls_failures + why
|
||||
assert doh.certificate_refusals() == [], (
|
||||
"a DoH handshake was refused: the default context used the DoH: %s (every failed handshake: %s)"
|
||||
% (doh.certificate_refusals(), doh.tls_failures) + why)
|
||||
assert watcher.watched_pids, ("the watcher never saw a browser process (it saw: %s): a watcher that cannot see proves "
|
||||
"nothing" % watcher.process_names)
|
||||
assert _direct_to_the_doh(watcher) == [], (
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Every test of the product runs on Linux AND on Windows (no browser here).
|
||||
|
||||
Federico, 12/11: a test seen only on Linux proves nothing about the system the product imitates. On that day 562 of the 808
|
||||
e2e of this package had never run on Windows in any round (the e2e of a pull request ran on Linux only, and the candidate's
|
||||
gate carried 246 of them), and two suites of the gate (`wrapper.e2e.udp.exit`, `wrapper.e2e.udp.sandbox`) were Linux only.
|
||||
Where Windows behaves differently the test adapts to the system; it does not stay on one.
|
||||
|
||||
What this holds, reading the files as text (PyYAML is not a dependency of this package):
|
||||
|
||||
* every row of ci/required-suites.json names both systems, or names its Windows twin (`windows_twin`: the id of a row
|
||||
that runs on Windows), or says why it can only be Linux (`linux_only`: a test of Linux converging on Windows, which has
|
||||
no Windows counterpart because Windows IS the reference);
|
||||
* the jobs of e2e.yml that run scripts/run_e2e.py run on a Linux and on a Windows runner between them;
|
||||
* the unit job of tests.yml runs on both.
|
||||
|
||||
Known-bad inputs: the files as they were on 12/11 (two Linux-only rows with no twin; e2e.yml on ubuntu-24.04 only) ->
|
||||
`problems` names each of them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SUITES = ROOT / "ci" / "required-suites.json"
|
||||
WORKFLOWS = ROOT / ".github" / "workflows"
|
||||
|
||||
|
||||
def suite_problems(rows: list) -> list:
|
||||
out = []
|
||||
windows_ids = {r["id"] for r in rows if "windows" in r.get("os", [])}
|
||||
for r in rows:
|
||||
systems = set(r.get("os", []))
|
||||
if {"linux", "windows"} <= systems:
|
||||
continue
|
||||
twin = r.get("windows_twin")
|
||||
reason = (r.get("linux_only") or "").strip()
|
||||
if "windows" not in systems and twin:
|
||||
if twin not in windows_ids:
|
||||
out.append("%s: its windows_twin %r is not a row that runs on Windows" % (r["id"], twin))
|
||||
continue
|
||||
if "windows" not in systems and reason:
|
||||
continue
|
||||
missing = sorted({"linux", "windows"} - systems)
|
||||
out.append("%s runs on %s only: it needs %s, a windows_twin, or a linux_only reason"
|
||||
% (r["id"], "/".join(sorted(systems)) or "nothing", " and ".join(missing)))
|
||||
return out
|
||||
|
||||
|
||||
def _jobs(text: str) -> list:
|
||||
"""(name, body) of each job under `jobs:` (two-space indentation, as every workflow here is written)."""
|
||||
body = text.split("\njobs:\n", 1)[1] if "\njobs:\n" in text else ""
|
||||
marks = list(re.finditer(r"^ ([A-Za-z0-9_-]+):\s*$", body, re.M))
|
||||
return [(m.group(1), body[m.start():(marks[i + 1].start() if i + 1 < len(marks) else len(body))]) for i, m in enumerate(marks)]
|
||||
|
||||
|
||||
def _runs_on_both(job: str) -> bool:
|
||||
runners = re.findall(r"\b(ubuntu-[0-9a-z.]+|windows-[0-9a-z.]+)\b", job)
|
||||
return any(r.startswith("ubuntu") for r in runners) and any(r.startswith("windows") for r in runners)
|
||||
|
||||
|
||||
def workflow_problems(e2e_text: str, tests_text: str) -> list:
|
||||
out = []
|
||||
e2e = [(n, b) for n, b in _jobs(e2e_text) if "scripts/run_e2e.py" in b]
|
||||
if not e2e:
|
||||
out.append("e2e.yml has no job that runs scripts/run_e2e.py")
|
||||
elif not _runs_on_both(" ".join(b for _n, b in e2e)):
|
||||
out.append("the jobs of e2e.yml that run scripts/run_e2e.py (%s) do not run on both a Linux and a Windows runner"
|
||||
% ", ".join(n for n, _b in e2e))
|
||||
unit = [(n, b) for n, b in _jobs(tests_text) if re.search(r"python -m pytest|pytest ", b) and "matrix" in b]
|
||||
if not unit:
|
||||
out.append("tests.yml has no unit job with a matrix")
|
||||
for name, body in unit:
|
||||
if not _runs_on_both(body):
|
||||
out.append("tests.yml job %r does not run on both a Linux and a Windows runner" % name)
|
||||
return out
|
||||
|
||||
|
||||
def test_every_suite_of_the_gate_runs_on_both_systems_or_names_its_twin():
|
||||
assert suite_problems(json.loads(SUITES.read_text(encoding="utf-8"))) == []
|
||||
|
||||
|
||||
def test_the_e2e_and_the_unit_tests_of_a_pull_request_run_on_both_systems():
|
||||
assert workflow_problems((WORKFLOWS / "e2e.yml").read_text(encoding="utf-8"),
|
||||
(WORKFLOWS / "tests.yml").read_text(encoding="utf-8")) == []
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------- the checkers can fail
|
||||
ROWS_OF_12_11 = [
|
||||
{"id": "wrapper.e2e.udp", "os": ["linux", "windows"]},
|
||||
{"id": "wrapper.e2e.udp.exit", "os": ["linux"]},
|
||||
{"id": "wrapper.e2e.udp.sandbox", "os": ["linux"]},
|
||||
]
|
||||
|
||||
E2E_OF_12_11 = """
|
||||
jobs:
|
||||
core-on-index:
|
||||
uses: ./.github/workflows/core-on-index.yml
|
||||
e2e:
|
||||
name: e2e (linux, xvfb)
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- run: xvfb-run -a python -u scripts/run_e2e.py "$FF"
|
||||
"""
|
||||
|
||||
TESTS_OF_12_11 = """
|
||||
jobs:
|
||||
unit:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- { os: ubuntu-latest, python: '3.11' }
|
||||
- { os: windows-latest, python: '3.12' }
|
||||
steps:
|
||||
- run: python -m pytest -m unit
|
||||
"""
|
||||
|
||||
|
||||
def test_the_rows_of_12_11_are_refused():
|
||||
found = suite_problems(ROWS_OF_12_11)
|
||||
assert len(found) == 2 and all("linux only" in p for p in found), found
|
||||
|
||||
|
||||
def test_a_twin_that_does_not_run_on_windows_is_refused():
|
||||
rows = [{"id": "a", "os": ["linux"], "windows_twin": "b"}, {"id": "b", "os": ["linux"]}]
|
||||
assert any("windows_twin 'b' is not a row that runs on Windows" in p for p in suite_problems(rows))
|
||||
|
||||
|
||||
def test_a_twin_or_a_reason_is_accepted():
|
||||
rows = [{"id": "a", "os": ["linux"], "windows_twin": "b"}, {"id": "b", "os": ["windows"], "windows_twin": None},
|
||||
{"id": "c", "os": ["linux"], "linux_only": "Linux converging on Windows: Windows is the reference"}]
|
||||
assert [p for p in suite_problems(rows) if not p.startswith("b ")] == []
|
||||
|
||||
|
||||
def test_the_e2e_of_12_11_is_refused_and_the_unit_job_passes():
|
||||
found = workflow_problems(E2E_OF_12_11, TESTS_OF_12_11)
|
||||
assert found == ["the jobs of e2e.yml that run scripts/run_e2e.py (e2e) do not run on both a Linux and a Windows runner"], found
|
||||
@@ -33,6 +33,11 @@ def page():
|
||||
page.injected = Mock()
|
||||
page.actions = Mock()
|
||||
page._frames = {}
|
||||
page._told_attached = set()
|
||||
page._frames_lock = __import__("threading").RLock()
|
||||
page._announce_lock = threading.RLock()
|
||||
page._announced = True
|
||||
page._said_before_announcement = []
|
||||
page._navigation_requests = {}
|
||||
page._announced_closed = False
|
||||
Dispatcher.__init__(page, server, context)
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""tests/geoip_used.py: what the core did about the GeoIP database during a run, for `scripts/ci_lab_geoip.py verify`."""
|
||||
import json
|
||||
import sys
|
||||
import types
|
||||
|
||||
import pytest
|
||||
|
||||
import geoip_used
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
def _fake_core(monkeypatch):
|
||||
module = types.ModuleType("invisible_core._geoip_db")
|
||||
module.calls = []
|
||||
module._resolve_latest_geoip_tag = lambda: module.calls.append("tag") or "2026.11.04"
|
||||
module._download_geoip_tag = lambda tag, attempts=1: module.calls.append("download") or "x"
|
||||
package = types.ModuleType("invisible_core")
|
||||
package._geoip_db = module
|
||||
monkeypatch.setitem(sys.modules, "invisible_core", package)
|
||||
monkeypatch.setitem(sys.modules, "invisible_core._geoip_db", module)
|
||||
return module
|
||||
|
||||
|
||||
def test_the_recorder_counts_the_questions_to_github_and_gives_the_functions_back(tmp_path, monkeypatch):
|
||||
core = _fake_core(monkeypatch)
|
||||
original = (core._resolve_latest_geoip_tag, core._download_geoip_tag)
|
||||
db = tmp_path / "db.mmdb"
|
||||
db.write_bytes(b"x")
|
||||
monkeypatch.setenv("STEALTHFOX_GEOIP_MMDB", str(db))
|
||||
out = tmp_path / "used" / "geoip-used.json"
|
||||
recorder = geoip_used.GeoipUsedRecorder(str(out))
|
||||
recorder.start()
|
||||
core._resolve_latest_geoip_tag()
|
||||
core._download_geoip_tag("2026.11.04")
|
||||
recorder.pytest_sessionfinish(None, 0)
|
||||
data = json.loads(out.read_text(encoding="utf-8"))
|
||||
assert data["asked_github"] == 2 and data["env"] == str(db) and data["exists"] is True and len(data["sha256"]) == 64
|
||||
assert core.calls == ["tag", "download"], "the real functions were called through"
|
||||
assert (core._resolve_latest_geoip_tag, core._download_geoip_tag) == original, "the functions were given back"
|
||||
|
||||
|
||||
def test_a_run_with_no_variable_is_recorded_as_such(tmp_path, monkeypatch):
|
||||
_fake_core(monkeypatch)
|
||||
monkeypatch.delenv("STEALTHFOX_GEOIP_MMDB", raising=False)
|
||||
out = tmp_path / "geoip-used.json"
|
||||
recorder = geoip_used.GeoipUsedRecorder(str(out))
|
||||
recorder.start()
|
||||
recorder.pytest_sessionfinish(None, 0)
|
||||
assert json.loads(out.read_text(encoding="utf-8")) == {"env": "", "exists": False, "sha256": None, "asked_github": 0}
|
||||
|
||||
|
||||
def test_the_conftest_registers_it_only_when_a_file_is_named():
|
||||
from pathlib import Path
|
||||
|
||||
text = (Path(__file__).parent / "conftest.py").read_text(encoding="utf-8")
|
||||
assert 'os.environ.get("GEOIP_USED_OUT")' in text and "GeoipUsedRecorder" in text
|
||||
@@ -111,9 +111,14 @@ def _open(binary, body):
|
||||
srv = LocalServer(("127.0.0.1", 0), _serve(body))
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
c = conn.launch(binary, profile_dir, headless=True, env=plan.env)
|
||||
# ⛔ THE PAGE'S LISTENERS ARE BORN ON THE ATTACH, on the reader thread, before the next event of the session is delivered:
|
||||
# the connection hands each event to the listeners of that moment (dispatch_event copies the list), so a Lifecycle built
|
||||
# later from this thread missed the page's first frameAttached and Page.ready when they came in between, and waited for
|
||||
# ever (Windows CI of 13/11, run 43373058301 part 2: "the engine never said Page.ready (frames seen: [])").
|
||||
sessions: dict = {}
|
||||
c.add_listener(lambda m, p, s: (
|
||||
sessions.__setitem__(p["targetInfo"]["targetId"], p["sessionId"])
|
||||
sessions.__setitem__(p["targetInfo"]["targetId"], (p["sessionId"], Lifecycle(c, p["sessionId"]),
|
||||
InjectedScript(c, p["sessionId"])))
|
||||
if m == "Browser.attachedToTarget" else None))
|
||||
c.send("Browser.enable", {"attachToDefaultContext": True})
|
||||
ctx = c.send("Browser.createBrowserContext", {"removeOnDetach": True})
|
||||
@@ -122,11 +127,12 @@ def _open(binary, body):
|
||||
deadline = time.time() + 20
|
||||
while page["targetId"] not in sessions and time.time() < deadline:
|
||||
time.sleep(0.02)
|
||||
sess = sessions[page["targetId"]]
|
||||
lifecycle = Lifecycle(c, sess)
|
||||
inj = InjectedScript(c, sess)
|
||||
sess, lifecycle, inj = sessions[page["targetId"]]
|
||||
inj.install()
|
||||
time.sleep(0.4)
|
||||
# The page is the caller's when the engine says it is ready, as Playwright hands it over (Page.ready); a fixed 0.4 s was a race
|
||||
# that the Windows census lost (run 43307193708: "no frame: the page has not announced its main frame yet", 6 tests).
|
||||
lifecycle.wait_for_page_ready(30)
|
||||
lifecycle.wait_for_main_frame(30)
|
||||
lifecycle.goto("http://127.0.0.1:%d/" % srv.server_address[1],
|
||||
until="load", timeout=30)
|
||||
actions = Actions(c, sess, lifecycle, inj, acts=PageActs(1),
|
||||
|
||||
@@ -56,9 +56,14 @@ def _open(binary, body):
|
||||
srv = LocalServer(("127.0.0.1", 0), _serve(body))
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
c = conn.launch(binary, profile_dir, headless=True, env=plan.env)
|
||||
# ⛔ THE PAGE'S LISTENERS ARE BORN ON THE ATTACH, on the reader thread, before the next event of the session is delivered:
|
||||
# the connection hands each event to the listeners of that moment (dispatch_event copies the list), so a Lifecycle built
|
||||
# later from this thread missed the page's first frameAttached and Page.ready when they came in between, and waited for
|
||||
# ever (Windows CI of 13/11, run 43373058301 part 2: "the engine never said Page.ready (frames seen: [])").
|
||||
sessions: dict = {}
|
||||
c.add_listener(lambda m, p, s: (
|
||||
sessions.__setitem__(p["targetInfo"]["targetId"], p["sessionId"])
|
||||
sessions.__setitem__(p["targetInfo"]["targetId"], (p["sessionId"], Lifecycle(c, p["sessionId"]),
|
||||
ini.InjectedScript(c, p["sessionId"])))
|
||||
if m == "Browser.attachedToTarget" else None))
|
||||
c.send("Browser.enable", {"attachToDefaultContext": True})
|
||||
ctx = c.send("Browser.createBrowserContext", {"removeOnDetach": True})
|
||||
@@ -67,11 +72,11 @@ def _open(binary, body):
|
||||
deadline = time.time() + 20
|
||||
while page["targetId"] not in sessions and time.time() < deadline:
|
||||
time.sleep(0.02)
|
||||
sess = sessions[page["targetId"]]
|
||||
lifecycle = Lifecycle(c, sess)
|
||||
inj = ini.InjectedScript(c, sess)
|
||||
sess, lifecycle, inj = sessions[page["targetId"]]
|
||||
inj.install()
|
||||
time.sleep(0.4)
|
||||
# Page.ready, not a fixed 0.4 s: the Windows census lost that race (run 43307193708).
|
||||
lifecycle.wait_for_page_ready(30)
|
||||
lifecycle.wait_for_main_frame(30)
|
||||
lifecycle.goto("http://127.0.0.1:%d/" % srv.server_address[1],
|
||||
until="load", timeout=30)
|
||||
|
||||
|
||||
@@ -51,10 +51,14 @@ def test_the_four_states_are_reached_on_a_real_page(firefox_binary):
|
||||
c = conn.launch(firefox_binary, profile_dir, headless=True,
|
||||
env=plan.env)
|
||||
try:
|
||||
# ⛔ THE PAGE'S LISTENERS ARE BORN ON THE ATTACH, on the reader thread, before the next event of the session is delivered:
|
||||
# the connection hands each event to the listeners of that moment (dispatch_event copies the list), so a Lifecycle built
|
||||
# later from this thread missed the page's first frameAttached and Page.ready when they came in between, and waited for
|
||||
# ever (Windows CI of 13/11, run 43373058301 part 2: "the engine never said Page.ready (frames seen: [])").
|
||||
sessions: dict = {}
|
||||
c.add_listener(lambda m, p, s: (
|
||||
sessions.__setitem__(
|
||||
p["targetInfo"]["targetId"], p["sessionId"])
|
||||
p["targetInfo"]["targetId"], Lifecycle(c, p["sessionId"]))
|
||||
if m == "Browser.attachedToTarget" else None))
|
||||
c.send("Browser.enable", {"attachToDefaultContext": True})
|
||||
ctx = c.send("Browser.createBrowserContext",
|
||||
@@ -64,8 +68,10 @@ def test_the_four_states_are_reached_on_a_real_page(firefox_binary):
|
||||
deadline = time.time() + 15
|
||||
while page["targetId"] not in sessions and time.time() < deadline:
|
||||
time.sleep(0.02)
|
||||
v = Lifecycle(c, sessions[page["targetId"]])
|
||||
time.sleep(0.5)
|
||||
v = sessions[page["targetId"]]
|
||||
# Page.ready, not a fixed 0.5 s: the Windows census lost that race (run 43307193708).
|
||||
v.wait_for_page_ready(30)
|
||||
v.wait_for_main_frame(30)
|
||||
|
||||
result = v.goto("http://127.0.0.1:%d/" % port,
|
||||
until="load", timeout=30)
|
||||
|
||||
@@ -275,9 +275,27 @@ def test_the_public_API_WAITS_for_an_element_that_arrives_late(firefox_binary):
|
||||
headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(url)
|
||||
assert page.query_selector("#slow") is None, (
|
||||
# The late element is the test's own, scheduled HERE, 800 ms from now. The page's #slow comes from a timer started at its
|
||||
# load, and on a Windows runner more than 800 ms can pass between the load and the first read (CI of 13/11, run
|
||||
# 43383366904, and 5 runs of 20 in run 43386328818 even after emptying it: the page's timer fired after the emptying).
|
||||
# Nothing of the page adds #later, so only this timer can.
|
||||
import time as _ht
|
||||
_t0 = _ht.monotonic()
|
||||
page.evaluate("""() => {
|
||||
const box = document.createElement('div');
|
||||
document.body.appendChild(box);
|
||||
window.__h = {set: performance.now()};
|
||||
setTimeout(() => { window.__h.fired = performance.now(); box.innerHTML = '<span id=later>arrived</span>'; }, 800);
|
||||
}""")
|
||||
_t1 = _ht.monotonic()
|
||||
_q = page.query_selector("#later")
|
||||
_t2 = _ht.monotonic()
|
||||
_h = page.evaluate("() => ({...window.__h, now: performance.now()})")
|
||||
print("HUNT-TIMING evaluate=%.0fms query=%.0fms page=%r found=%s" % (
|
||||
(_t1 - _t0) * 1000, (_t2 - _t1) * 1000, _h, _q is not None), flush=True)
|
||||
assert _q is None, (
|
||||
"the element was already there: the test proves nothing")
|
||||
handle = page.wait_for_selector("#slow", timeout=8000)
|
||||
handle = page.wait_for_selector("#later", timeout=8000)
|
||||
assert handle is not None
|
||||
assert handle.text_content() == "arrived"
|
||||
finally:
|
||||
|
||||
@@ -71,9 +71,15 @@ def _bare_page():
|
||||
page._request_log = []
|
||||
page._navigation_requests = {}
|
||||
page._announced_closed = False
|
||||
page._frames = {}
|
||||
page._told_attached = set()
|
||||
page._frames_lock = __import__("threading").RLock()
|
||||
page._announce_lock = threading.RLock()
|
||||
page._announced = True
|
||||
page._said_before_announcement = []
|
||||
# The network branches ask the session's lifecycle which requests are the
|
||||
# favicon; an empty memory answers "none", as for a page without one.
|
||||
page.lifecycle = SimpleNamespace(favicons=FaviconRequests())
|
||||
page.lifecycle = SimpleNamespace(favicons=FaviconRequests(), frame=lambda fid: None)
|
||||
page.messages = up
|
||||
page.context = SimpleNamespace(emit=lambda *a, **k: None, intercepting=False,
|
||||
options={})
|
||||
@@ -96,6 +102,8 @@ def test_new_document_request_is_a_channel_or_omitted(has_request, source):
|
||||
frame.disposed = False
|
||||
frame.page = page
|
||||
frame.frame_id = "F1"
|
||||
frame.told_states = {"commit"}
|
||||
frame.told_commit = None
|
||||
page.frame_for = lambda fid: frame
|
||||
|
||||
def committed():
|
||||
@@ -107,7 +115,7 @@ def test_new_document_request_is_a_channel_or_omitted(has_request, source):
|
||||
committed()
|
||||
return {"navigationId": "NAV1", "url": "about:blank"}
|
||||
|
||||
page.lifecycle = SimpleNamespace(goto=goto)
|
||||
page.lifecycle = SimpleNamespace(goto=goto, frame=lambda fid: None)
|
||||
frame.op_goto({"url": "about:blank"})
|
||||
else:
|
||||
committed()
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
"""An event of ANY family that the engine sends while a popup's page is handed from its buffer to its dispatcher reaches the client once, in order.
|
||||
|
||||
NO BROWSER HERE (the real dispatchers over a scripted Juggler connection; the parking points and the record of the previous test).
|
||||
|
||||
The page's own listener holds the events of the period between its construction and the end of `_install_events`, and the hand-over gave
|
||||
back only the `Network.*` ones: a `console` message, a `pageError`, a `dialog`, a `crash` or any other event that came in that period was
|
||||
dropped. A dialog is the worst of them: `alert()` blocks the page until the client accepts it, and a client that was never told of the dialog
|
||||
cannot. The hand-over now gives back every held event, whatever its kind, in the order it arrived and once (the events the lifecycle owns - a
|
||||
frame, a navigation, a load state - are also said again by the reconciliation, which is idempotent).
|
||||
|
||||
One event of each family (console, pageError, dialog, crash), in this order, at every placement among FOUR points of the passage (before the
|
||||
snapshot of the initializer, as the main frame's dispatcher is made, as the events are installed, after): 35 cases, none sampled. Each must
|
||||
be told once, in the order of arrival, a dialog must be known to the page (`_dialogs_open`) so that the client can accept it, and the
|
||||
console message must be in the page's log.
|
||||
|
||||
Known-bad input: the hand-over as it was (only `Network.*` given back) -> every order with an event before the end of `_install_events`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright._juggler import dispatcher as base
|
||||
from invisible_playwright._juggler import remote
|
||||
from invisible_playwright._juggler.server import LocalUtilsDispatcher
|
||||
|
||||
from test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once import POINTS, Parking, PopupEngine, _install
|
||||
from test_every_order_of_the_events_of_a_popup_gives_one_page_event import FRAME, SESSION, TARGET, _thread, _wait
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
FAMILIES = ["console", "pageError", "dialog", "crash"]
|
||||
|
||||
|
||||
def _send(conn, family):
|
||||
if family == "console":
|
||||
conn.dispatch_event("Runtime.console", {"type": "log", "args": [], "location": {"url": "", "lineNumber": 0, "columnNumber": 0}}, SESSION)
|
||||
elif family == "pageError":
|
||||
conn.dispatch_event("Page.uncaughtError", {"message": "boom", "stack": "", "location": {"url": "", "lineNumber": 0, "columnNumber": 0}}, SESSION)
|
||||
elif family == "dialog":
|
||||
conn.dispatch_event("Page.dialogOpened", {"dialogId": "d1", "type": "alert", "message": "m", "defaultValue": ""}, SESSION)
|
||||
elif family == "crash":
|
||||
conn.dispatch_event("Page.crashed", {}, SESSION)
|
||||
|
||||
|
||||
def _run(placement, accept=False):
|
||||
parking, told, trace, dialog_guids, sent = Parking(), {}, [], [], []
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
_install(mp, parking, told)
|
||||
original_emit = base.Dispatcher.emit
|
||||
|
||||
def spy(self, method, params=None):
|
||||
kind = getattr(self, "TYPE", "")
|
||||
if (kind == "BrowserContext" and method in ("console", "pageError", "dialog")) or (
|
||||
kind == "Page" and method == "crash" and getattr(self, "target_id", None) == TARGET):
|
||||
trace.append(method)
|
||||
if method == "dialog":
|
||||
dialog_guids.append(params["dialog"]["guid"])
|
||||
elif kind == "BrowserContext" and method == "page":
|
||||
trace.append("page")
|
||||
return original_emit(self, method, params)
|
||||
mp.setattr(base.Dispatcher, "emit", spy)
|
||||
server = remote._SharedServer()
|
||||
browser_type = remote.SharedBrowserType(server)
|
||||
LocalUtilsDispatcher(server)
|
||||
conn = PopupEngine()
|
||||
original_send = conn.send
|
||||
|
||||
def recording_send(method, params=None, session=None, timeout=30):
|
||||
sent.append((method, dict(params or {})))
|
||||
return original_send(method, params, session, timeout)
|
||||
conn.send = recording_send
|
||||
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
|
||||
try:
|
||||
context = server.object(server.handle({"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(t for t in conn.sessions if t != TARGET)
|
||||
del trace[:]
|
||||
conn.attach(opener_target, context.context_id)
|
||||
conn.frame()
|
||||
conn.commit()
|
||||
todo = list(zip(FAMILIES, placement))
|
||||
for i in range(len(POINTS)):
|
||||
assert parking.reached[i].wait(5), "the adoption thread never reached %s" % POINTS[i]
|
||||
for family, where in list(todo):
|
||||
if where == i:
|
||||
_send(conn, family)
|
||||
todo.remove((family, where))
|
||||
parking.release[i].set()
|
||||
conn.ready()
|
||||
assert _wait(lambda: "page" in trace), "the popup was never announced"
|
||||
assert _wait(lambda: _thread() is None), "the adoption thread never ended"
|
||||
page = browser._page_targets.get(TARGET)
|
||||
result = [t for t in trace if t != "page"], sorted(page._dialogs_open), len(page._console_log)
|
||||
if accept:
|
||||
# the client accepts the dialog, as a handler of `page.on("dialog")` does: the answer reaches the engine
|
||||
server.object(dialog_guids[0]).call("accept", {})
|
||||
return result + ([m for m in sent if m[0] == "Page.handleDialog"],)
|
||||
return result
|
||||
finally:
|
||||
parking.open_all()
|
||||
try:
|
||||
server.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def test_one_event_of_each_family_reaches_the_client_once_and_in_order_at_every_point_of_the_hand_over():
|
||||
failures, count = [], 0
|
||||
for combo in itertools.combinations_with_replacement(range(len(POINTS)), len(FAMILIES)):
|
||||
count += 1
|
||||
told, dialogs, console_entries = _run(combo)[:3]
|
||||
problems = []
|
||||
if told != FAMILIES:
|
||||
problems.append("the client was told %s" % told)
|
||||
if dialogs != ["d1"]:
|
||||
problems.append("the dialog is %s for the page: the client cannot accept it" % (dialogs,))
|
||||
if console_entries != 1:
|
||||
problems.append("%d console messages in the page's log" % console_entries)
|
||||
if problems:
|
||||
failures.append("%s: %s" % ([POINTS[i] for i in combo], "; ".join(problems)))
|
||||
assert count == 35
|
||||
assert not failures, "%d of %d orders lost or doubled an event, e.g.:\n %s" % (len(failures), count, "\n ".join(failures[:12]))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("point", [0, 1, 2])
|
||||
def test_a_dialog_opened_during_the_hand_over_can_be_accepted_by_the_client(point):
|
||||
"""The dialog that opened before the page was handed over is announced, and accepting it sends the engine the answer that unblocks the page."""
|
||||
told, dialogs, _, answers = _run((point, point, point, point), accept=True)
|
||||
assert "dialog" in told
|
||||
assert [a[1].get("dialogId") for a in answers] == ["d1"], "the engine was not answered: %s" % answers
|
||||
assert answers[0][1].get("accept") is True
|
||||
|
||||
|
||||
def test_an_event_that_does_not_fit_in_the_hold_is_not_lost_in_silence(monkeypatch):
|
||||
"""The hold has a cap (it bounds the memory of a page that never finishes building). The events beyond it are lost, and the loss is said once,
|
||||
with its count, when the hold ends."""
|
||||
import warnings
|
||||
|
||||
from invisible_playwright._juggler import server as server_mod
|
||||
monkeypatch.setattr(server_mod.PageDispatcher, "HELD_CAP", 8) # the birth of the page already holds a few events
|
||||
parking, told, trace = Parking(), {}, []
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
_install(mp, parking, told)
|
||||
original_emit = base.Dispatcher.emit
|
||||
|
||||
def spy(self, method, params=None):
|
||||
if getattr(self, "TYPE", "") == "BrowserContext" and method in ("console", "page"):
|
||||
trace.append(method)
|
||||
return original_emit(self, method, params)
|
||||
mp.setattr(base.Dispatcher, "emit", spy)
|
||||
server = remote._SharedServer()
|
||||
browser_type = remote.SharedBrowserType(server)
|
||||
LocalUtilsDispatcher(server)
|
||||
conn = PopupEngine()
|
||||
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
|
||||
try:
|
||||
context = server.object(server.handle({"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(t for t in conn.sessions if t != TARGET)
|
||||
del trace[:]
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
conn.attach(opener_target, context.context_id)
|
||||
conn.frame()
|
||||
conn.commit()
|
||||
for i in range(len(POINTS)):
|
||||
assert parking.reached[i].wait(5)
|
||||
if i == 0:
|
||||
for _ in range(20):
|
||||
_send(conn, "console") # the hold takes what is left of its 8, loses the rest
|
||||
parking.release[i].set()
|
||||
conn.ready()
|
||||
assert _wait(lambda: "page" in trace)
|
||||
assert _wait(lambda: _thread() is None)
|
||||
lost = [str(w.message) for w in caught if "were lost while it was handed over" in str(w.message)]
|
||||
kept = trace.count("console")
|
||||
assert 0 < kept < 20, "the hold keeps %d of 20" % kept
|
||||
assert len(lost) == 1, "the loss was said %d times: %s" % (len(lost), lost)
|
||||
assert "%d event(s)" % (20 - kept) in lost[0] and "more than 8" in lost[0], lost[0]
|
||||
finally:
|
||||
parking.open_all()
|
||||
try:
|
||||
server.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class ChooserEngine(PopupEngine):
|
||||
"""The engine as far as a file chooser needs it: the injected script is built, the node is adopted into the utility world, it is asked
|
||||
whether it takes several files."""
|
||||
|
||||
def frame(self):
|
||||
self.dispatch_event("Page.frameAttached", {"frameId": FRAME, "parentFrameId": None}, SESSION)
|
||||
for world in ("", "__ctx_aux__"): # the page's own world and the utility one, under the names the client looks for
|
||||
self.dispatch_event("Runtime.executionContextCreated", {
|
||||
"executionContextId": "e%s" % world, "auxData": {"frameId": FRAME, "name": world}}, SESSION)
|
||||
|
||||
def send(self, method, params=None, session=None, timeout=30):
|
||||
if method == "Runtime.evaluate":
|
||||
return {"result": {"objectId": "injected-1"}}
|
||||
if method == "Page.adoptNode":
|
||||
return {"remoteObject": {"objectId": "adopted-1"}}
|
||||
if method == "Runtime.callFunction":
|
||||
return {"result": {"value": True}}
|
||||
return super().send(method, params, session, timeout)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("point", range(len(POINTS)), ids=POINTS)
|
||||
def test_a_file_chooser_opened_during_the_hand_over_reaches_the_client_and_can_be_answered(point):
|
||||
"""The chooser is told once, with the handle of its input element (the client answers a chooser through that handle) and its `isMultiple`."""
|
||||
parking, told, chooser = Parking(), {}, []
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
_install(mp, parking, told)
|
||||
original_emit = base.Dispatcher.emit
|
||||
|
||||
def spy(self, method, params=None):
|
||||
if getattr(self, "TYPE", "") == "Page" and method == "fileChooser" and getattr(self, "target_id", None) == TARGET:
|
||||
chooser.append(params)
|
||||
return original_emit(self, method, params)
|
||||
mp.setattr(base.Dispatcher, "emit", spy)
|
||||
server = remote._SharedServer()
|
||||
browser_type = remote.SharedBrowserType(server)
|
||||
LocalUtilsDispatcher(server)
|
||||
conn = ChooserEngine()
|
||||
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
|
||||
try:
|
||||
context = server.object(server.handle({"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
|
||||
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
opener_target = next(t for t in conn.sessions if t != TARGET)
|
||||
conn.attach(opener_target, context.context_id)
|
||||
conn.frame()
|
||||
conn.commit()
|
||||
for i in range(len(POINTS)):
|
||||
assert parking.reached[i].wait(5), "the adoption thread never reached %s" % POINTS[i]
|
||||
if i == point:
|
||||
conn.dispatch_event("Page.fileChooserOpened", {"element": {"objectId": "input-1"}, "executionContextId": "e"}, SESSION)
|
||||
parking.release[i].set()
|
||||
conn.ready()
|
||||
assert _wait(lambda: chooser), "the file chooser opened during the hand-over never reached the client (%s)" % (conn.handler_errors,)
|
||||
assert _wait(lambda: _thread() is None)
|
||||
assert len(chooser) == 1 and chooser[0]["isMultiple"] is True
|
||||
assert server.object(chooser[0]["element"]["guid"]) is not None, "the client has no handle to answer the chooser through"
|
||||
finally:
|
||||
parking.open_all()
|
||||
try:
|
||||
server.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -146,7 +146,9 @@ def _back_to_back_contexts(mode, firefox_binary, doh, pages, gateway, trap, watc
|
||||
assert _asked_outside(doh, *names) == [], (
|
||||
"the DoH was asked for a name that is not one of the proxied contexts' (the default context has no proxy and "
|
||||
"must resolve natively): %s" % _asked_outside(doh, *names) + why)
|
||||
assert doh.tls_failures == [], "a context without the FakeDoh certificate exception used the DoH: %s" % doh.tls_failures + why
|
||||
assert doh.certificate_refusals() == [], (
|
||||
"a context without the FakeDoh certificate exception used the DoH (it refused the certificate): %s (every failed "
|
||||
"handshake: %s)" % (doh.certificate_refusals(), doh.tls_failures) + why)
|
||||
else:
|
||||
# The launch proxy is the proxy of the default context too: its background names go to the DoH through the launch
|
||||
# proxy (their handshakes fail BY DESIGN and are counted by the accounting above), so here nothing may go direct or
|
||||
@@ -188,7 +190,9 @@ def _beside_a_proxied_context(firefox_binary, doh, pages, gateway, trap, watcher
|
||||
"the FakeDoh was asked for a name that is not A's (B and the default context have no proxy and must not use the "
|
||||
"DoH): %s" % _asked_outside(doh, name_a) + why)
|
||||
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without A's proxy" + why
|
||||
assert doh.tls_failures == [], "a context without the FakeDoh certificate exception used the DoH: %s" % doh.tls_failures + why
|
||||
assert doh.certificate_refusals() == [], (
|
||||
"a context without the FakeDoh certificate exception used the DoH (it refused the certificate): %s (every failed "
|
||||
"handshake: %s)" % (doh.certificate_refusals(), doh.tls_failures) + why)
|
||||
_assert_every_connection_went_through_the_gateway(doh, gw_a)
|
||||
|
||||
assert watcher.watched_pids, ("the watcher never saw a browser process (it saw: %s): a watcher that cannot see "
|
||||
|
||||
@@ -55,7 +55,7 @@ def _page_with_one_frame():
|
||||
up: list = []
|
||||
server.attach(type("R", (), {"emit_message": lambda self, m: up.append(m)})())
|
||||
|
||||
frame = SimpleNamespace(url="http://127.0.0.1/", name="", emitted=[])
|
||||
frame = SimpleNamespace(url="http://127.0.0.1/", name="", emitted=[], frame_id="F1", told_states={"commit"}, told_commit=None)
|
||||
frame.emit = lambda method, params=None: frame.emitted.append((method, params))
|
||||
|
||||
page = object.__new__(PageDispatcher)
|
||||
@@ -68,6 +68,12 @@ def _page_with_one_frame():
|
||||
page._request_log = []
|
||||
page._navigation_requests = {}
|
||||
page._announced_closed = False
|
||||
page._frames = {}
|
||||
page._told_attached = set()
|
||||
page._frames_lock = __import__("threading").RLock()
|
||||
page._announce_lock = threading.RLock()
|
||||
page._announced = True
|
||||
page._said_before_announcement = []
|
||||
page.context = SimpleNamespace(emit=lambda *a, **k: None, intercepting=False)
|
||||
page.frame = frame
|
||||
page.frame_for = lambda fid: frame
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""A test that asserts the host ports of a connection are consecutive (N, N+1) runs alone, in the serial pass of the e2e run.
|
||||
|
||||
``tests/test_declared_host_network_e2e.py`` reads the ports the browser chose for one connection: the engine draws a pair N, N+1 at random in
|
||||
49152-65535. With four workers in parallel, another worker's browser or test server can take N+1 between the draw and the bind (the same port space,
|
||||
the same machine), and the test reads a pair that is not consecutive. The e2e run already has a place for a test that needs the machine alone: the
|
||||
``wall_clock`` group (``invisible_core.testing.e2e.passes``: everything else first at the width asked, then these on the serial path, after the last
|
||||
parallel test has ended). The tests that assert consecutive ports carry that marker. Found by reading the file's AST: any test function with an
|
||||
assertion that something equals another plus one.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
FILE = Path(__file__).resolve().parent / "test_declared_host_network_e2e.py"
|
||||
|
||||
|
||||
def _marks(fn: ast.FunctionDef) -> set:
|
||||
return {d.attr for d in fn.decorator_list if isinstance(d, ast.Attribute) and isinstance(d.value, ast.Attribute) and d.value.attr == "mark"}
|
||||
|
||||
|
||||
def _asserts_a_consecutive_pair(fn: ast.FunctionDef) -> bool:
|
||||
for node in ast.walk(fn):
|
||||
if isinstance(node, ast.Assert):
|
||||
for sub in ast.walk(node.test):
|
||||
if isinstance(sub, ast.BinOp) and isinstance(sub.op, ast.Add) and isinstance(sub.right, ast.Constant) and sub.right.value == 1:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def unserial(source: str) -> list:
|
||||
tree = ast.parse(source)
|
||||
return [n.name for n in tree.body
|
||||
if isinstance(n, ast.FunctionDef) and n.name.startswith("test_") and _asserts_a_consecutive_pair(n) and "wall_clock" not in _marks(n)]
|
||||
|
||||
|
||||
def test_every_test_that_asserts_consecutive_ports_runs_in_the_serial_group():
|
||||
assert unserial(FILE.read_text(encoding="utf-8")) == []
|
||||
|
||||
|
||||
def test_the_two_known_tests_are_found():
|
||||
tree = ast.parse(FILE.read_text(encoding="utf-8"))
|
||||
found = sorted(n.name for n in tree.body if isinstance(n, ast.FunctionDef) and _asserts_a_consecutive_pair(n))
|
||||
assert found == ["test_the_host_ports_are_those_of_a_windows_machine", "test_two_connections_on_one_page_get_their_own_port_pair"], found
|
||||
|
||||
|
||||
def test_a_consecutive_port_test_without_the_marker_is_refused():
|
||||
body = ["def test_x():", " assert b == a + 1"]
|
||||
assert unserial("\n".join(body)) == ["test_x"]
|
||||
assert unserial("\n".join(["@pytest.mark.wall_clock"] + body)) == []
|
||||
@@ -47,6 +47,7 @@ def read_response(message: bytes):
|
||||
|
||||
def _tls(host_port, *, alpn):
|
||||
context = ssl.create_default_context()
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(alpn)
|
||||
@@ -192,10 +193,12 @@ def test_the_certificate_covers_the_doh_host_and_loopback(doh):
|
||||
"""A client that VERIFIES (trusting the certificate file) accepts both names the DoH may be reached by."""
|
||||
for server_name in (DOH_HOST, "127.0.0.1"):
|
||||
context = ssl.create_default_context(cafile=str(doh.certificate_path))
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
raw = socket.create_connection(("127.0.0.1", doh.port), timeout=10)
|
||||
tls = context.wrap_socket(raw, server_hostname=server_name)
|
||||
tls.close()
|
||||
context = ssl.create_default_context(cafile=str(doh.certificate_path))
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
raw = socket.create_connection(("127.0.0.1", doh.port), timeout=10)
|
||||
with pytest.raises(ssl.SSLCertVerificationError):
|
||||
context.wrap_socket(raw, server_hostname="some-other-host.test")
|
||||
@@ -204,6 +207,7 @@ def test_the_certificate_covers_the_doh_host_and_loopback(doh):
|
||||
|
||||
def test_a_client_that_refuses_the_certificate_is_listed_as_a_tls_failure(doh):
|
||||
context = ssl.create_default_context() # verifies, and does not trust the self-signed certificate
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
raw = socket.create_connection(("127.0.0.1", doh.port), timeout=10)
|
||||
with pytest.raises(ssl.SSLError):
|
||||
context.wrap_socket(raw, server_hostname=DOH_HOST)
|
||||
@@ -221,6 +225,7 @@ def _h2_query(doh, method, message, raw=None):
|
||||
tls = _tls(("127.0.0.1", doh.port), alpn=["h2", "http/1.1"])
|
||||
else:
|
||||
context = ssl.create_default_context()
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(["h2", "http/1.1"])
|
||||
@@ -308,6 +313,7 @@ def _socks_connect(gateway_port, host, port, *, credentials=None, by_name=False)
|
||||
|
||||
def _query_through(sock, name, qtype=QTYPE_A):
|
||||
context = ssl.create_default_context()
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(["http/1.1"])
|
||||
@@ -421,6 +427,7 @@ def test_a_killed_gateway_refuses_and_drops_its_open_tunnels(doh):
|
||||
s, code = _socks_connect(port, DOH_BOOTSTRAP, 443)
|
||||
assert code == 0
|
||||
context = ssl.create_default_context()
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(["http/1.1"])
|
||||
|
||||
@@ -220,6 +220,7 @@ def test_a_gateway_hands_the_knobs_over_with_the_connection():
|
||||
s, code = _socks_connect(gw.port, ds.DOH_BOOTSTRAP, 443)
|
||||
assert code == 0
|
||||
context = ssl.create_default_context()
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(["http/1.1"])
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""The FakeDoh tells a certificate the client refused from a connection the client dropped (no browser).
|
||||
|
||||
Windows census of 12/11 (run 43333574229): test_resolver_race_e2e read a ConnectionAbortedError [WinError 10053], through the
|
||||
gateway of a context that HAS the certificate exception, as "a context without the FakeDoh certificate exception used the DoH".
|
||||
A dropped connection (a speculative or duplicate DoH connection the browser abandons) says nothing about the certificate; only
|
||||
a TLS alert from the client does. Known-bad: FakeDoh before this change has no certificate_refusals, and the e2e asserted
|
||||
`tls_failures == []`, which a dropped connection alone fails.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from _doh_servers import FakeDoh
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ABORTED_ON_WINDOWS = ("gw-a", "ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine")
|
||||
RESET = ("gw-1", "ConnectionResetError: [Errno 104] Connection reset by peer")
|
||||
EOF = ("gw-1", "SSLEOFError: EOF occurred in violation of protocol (_ssl.c:1006)")
|
||||
UNKNOWN_CA = ("gw-1", "SSLError: [SSL: TLSV1_ALERT_UNKNOWN_CA] tlsv1 alert unknown ca (_ssl.c:1006)")
|
||||
BAD_CERTIFICATE = ("direct", "SSLError: [SSL: SSLV3_ALERT_BAD_CERTIFICATE] sslv3 alert bad certificate (_ssl.c:1006)")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def doh():
|
||||
server = FakeDoh({})
|
||||
yield server
|
||||
server.close()
|
||||
|
||||
|
||||
def test_a_dropped_connection_is_not_a_refused_certificate(doh):
|
||||
doh.tls_failures.extend([ABORTED_ON_WINDOWS, RESET, EOF])
|
||||
assert doh.certificate_refusals() == []
|
||||
assert len(doh.tls_failures) == 3, "the failures stay listed for the message of a failed assertion"
|
||||
|
||||
|
||||
def test_a_tls_alert_from_the_client_is_a_refused_certificate(doh):
|
||||
doh.tls_failures.extend([ABORTED_ON_WINDOWS, UNKNOWN_CA, BAD_CERTIFICATE])
|
||||
assert doh.certificate_refusals() == [UNKNOWN_CA, BAD_CERTIFICATE]
|
||||
@@ -25,6 +25,7 @@ pytestmark = pytest.mark.unit
|
||||
# -- the server ---------------------------------------------------------------------------------------------------------
|
||||
def _tls_client(server, alpn):
|
||||
context = ssl.create_default_context()
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(alpn)
|
||||
@@ -431,4 +432,17 @@ def test_a_server_that_can_bind_nothing_says_so_after_a_bounded_number_of_tries(
|
||||
with pytest.raises(RuntimeError) as raised:
|
||||
module._tcp_server_on_a_port_udp_binds("127.0.0.1")
|
||||
assert "both TCP and UDP" in str(raised.value) and "127.0.0.1" in str(raised.value), str(raised.value)
|
||||
assert len(_FakeUdpSocket.tried) == module._WITNESS_TRIES, len(_FakeUdpSocket.tried)
|
||||
import _ports
|
||||
|
||||
assert len(_FakeUdpSocket.tried) == _ports.TRIES, len(_FakeUdpSocket.tried)
|
||||
|
||||
|
||||
def test_the_server_closes_its_event_loop_on_its_own_thread_when_it_closes():
|
||||
"""A loop that is only stopped is closed later by BaseEventLoop.__del__ on whatever thread the garbage collector runs in, and on
|
||||
Windows the proactor's close then waits for the UDP receive still pending on it, for ever (Windows hunt of 13/11, run
|
||||
43377799126: the HTTP/3 e2e hung inside a later goto, the test thread in base_events.__del__ -> proactor close -> _poll).
|
||||
Known-bad: the server before this change stops the loop and never closes it."""
|
||||
with H3Server("127.0.0.1") as server:
|
||||
loop, thread = server._loop, server._thread
|
||||
assert not thread.is_alive(), "the server's thread is still running after close()"
|
||||
assert loop.is_closed(), "the server's event loop was left for the garbage collector to close"
|
||||
@@ -0,0 +1,317 @@
|
||||
"""The hand-over of a popup's page, from the buffer to its dispatcher, holds when the engine's reader, the adoption thread and a close run AT THE SAME TIME.
|
||||
|
||||
NO BROWSER HERE (the real dispatchers over a scripted Juggler connection; the parking points and the record of
|
||||
`test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once`). The earlier tests deliver the events while the adoption thread is
|
||||
parked, one thread at a time. These put the TWO threads in the window that the parking cannot reach: the engine's reader between the lifecycle's
|
||||
listener and the page's own (the lifecycle hears an event first, the page second, and the hand-over can fall between them), the reader
|
||||
against the loop that gives the held events back, a close against the hook. Each is one sequence of events, written out, no sampling.
|
||||
|
||||
A the reader is stopped between the lifecycle's listener and the page's for a `load`; the hand-over runs; the reader goes on.
|
||||
The client must be told the `load` of the frame ONCE after the page is announced (twice, `page.on("load")` fires twice).
|
||||
B the adoption thread is delivering the held events (a, b); the engine sends c. The client must be told a, b, c.
|
||||
C the page is closed (`close`, `__dispose__`) after the held events are given back and before the lifecycle's hook goes in, while the
|
||||
lifecycle knows a frame the client was not told of. Nothing may be sent for the page's frames after its `__dispose__`.
|
||||
D the reader and the hand-over both need the dispatcher of a frame that does not have one yet. It is made once.
|
||||
E a document is committed at the SAME address as the one in the initializer, after the snapshot and before the hook. The client must be told it.
|
||||
|
||||
Known-bad input: 7d934a6 -> all five are red, each for the reason named in its assertion.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright._juggler import dispatcher as base
|
||||
from invisible_playwright._juggler import remote
|
||||
from invisible_playwright._juggler import server as server_mod
|
||||
from invisible_playwright._juggler.server import LocalUtilsDispatcher
|
||||
|
||||
from test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once import POINTS, Parking, PopupEngine, _install
|
||||
from test_every_order_of_the_events_of_a_popup_gives_one_page_event import FRAME, SESSION, TARGET, _thread, _wait
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
CHILD = "fx2"
|
||||
BLANK = "about:blank"
|
||||
STATES = ("commit", "domcontentloaded", "load", "networkidle")
|
||||
|
||||
|
||||
def _adopter():
|
||||
return threading.current_thread().name == "invpw-adopt-%s" % TARGET
|
||||
|
||||
|
||||
class World:
|
||||
"""A served browser over the scripted engine, the opener built, the context known."""
|
||||
|
||||
def __init__(self):
|
||||
self.server = remote._SharedServer()
|
||||
browser_type = remote.SharedBrowserType(self.server)
|
||||
LocalUtilsDispatcher(self.server)
|
||||
self.conn = PopupEngine()
|
||||
self.browser = remote.SharedBrowserDispatcher(self.server, browser_type, self.conn, "firefox/1")
|
||||
self.context = self.server.object(
|
||||
self.server.handle({"guid": self.browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
|
||||
self.server.handle({"guid": self.context.guid, "method": "newPage", "params": {"pageNumber": 1}})
|
||||
self.opener_target = next(t for t in self.conn.sessions if t != TARGET)
|
||||
|
||||
def born(self):
|
||||
self.conn.attach(self.opener_target, self.context.context_id)
|
||||
self.conn.frame()
|
||||
self.conn.commit()
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
self.server.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _mark_announcement(mp, told, announced):
|
||||
"""`told['announced_at']`: how many things the client had been told of the main frame when the context said `page`."""
|
||||
original = base.Dispatcher.emit
|
||||
|
||||
def spy(self, method, params=None):
|
||||
if method == "page" and getattr(self, "TYPE", "") == "BrowserContext" and _adopter():
|
||||
told["announced_at"] = len(told.get("ops", []))
|
||||
announced.append(True)
|
||||
return original(self, method, params)
|
||||
mp.setattr(base.Dispatcher, "emit", spy)
|
||||
|
||||
|
||||
def _gate_page_listener(mp, gate, entered, match):
|
||||
"""The page's own listener of the popup stops at `gate` for the events `match` picks: the lifecycle's listener, registered first, has
|
||||
heard them already - which is the window between the two."""
|
||||
original = server_mod.PageDispatcher._route_juggler_event
|
||||
|
||||
def wrapper(self, method, params, session):
|
||||
if getattr(self, "target_id", None) == TARGET and match(method, params):
|
||||
entered.set()
|
||||
gate.wait(10)
|
||||
return original(self, method, params, session)
|
||||
mp.setattr(server_mod.PageDispatcher, "_route_juggler_event", wrapper)
|
||||
|
||||
|
||||
def _finish(world, announced):
|
||||
world.conn.ready()
|
||||
assert _wait(lambda: announced), "the popup was never announced"
|
||||
assert _wait(lambda: _thread() is None), "the adoption thread never ended"
|
||||
|
||||
|
||||
# --- A ----------------------------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def test_a_load_heard_by_the_lifecycle_between_its_listener_and_the_pages_is_told_once():
|
||||
"""Sequence: [reader] lifecycle hears Page.eventFired(load) -> [reader] page listener stops -> [adoption] _install_events: the held events are
|
||||
given back, the hook goes in, the frames are reconciled: `load` is in the lifecycle's states and not in the client's, so it is told ->
|
||||
[reader] page listener goes on: the same event, now delivered live, tells it again. The replay after the announcement says what was said
|
||||
before it, so the client hears the load twice and `page.on("load")` runs twice."""
|
||||
parking, told, announced, gate, entered = Parking(), {}, [], threading.Event(), threading.Event()
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
_install(mp, parking, told)
|
||||
_mark_announcement(mp, told, announced)
|
||||
_gate_page_listener(mp, gate, entered, lambda m, p: m == "Page.eventFired" and p.get("name") == "load")
|
||||
world = World()
|
||||
reader = None
|
||||
try:
|
||||
world.born()
|
||||
for i in range(len(POINTS)):
|
||||
assert parking.reached[i].wait(5), "the adoption thread never reached %s" % POINTS[i]
|
||||
if i == 2:
|
||||
reader = threading.Thread(target=world.conn.load, daemon=True)
|
||||
reader.start()
|
||||
assert entered.wait(5), "the reader never reached the page's listener"
|
||||
if i == 3:
|
||||
gate.set() # the hand-over is over: the reader goes on with the same event
|
||||
reader.join(5)
|
||||
parking.release[i].set()
|
||||
_finish(world, announced)
|
||||
after = told["ops"][told["announced_at"]:]
|
||||
loads = [op for op in after if op == ("add", "load")]
|
||||
assert len(loads) == 1, "after the page was announced the client was told `load` %d times: %s" % (len(loads), after)
|
||||
finally:
|
||||
gate.set()
|
||||
parking.open_all()
|
||||
world.close()
|
||||
|
||||
|
||||
# --- B ----------------------------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def _console(conn, number):
|
||||
conn.dispatch_event("Runtime.console", {"type": "log", "args": [], "location": {"url": "", "lineNumber": number, "columnNumber": 0}}, SESSION)
|
||||
|
||||
|
||||
def test_an_event_sent_while_the_held_ones_are_given_back_does_not_overtake_them():
|
||||
"""Sequence: held = [console 1, console 2] -> [adoption] gives back console 1, stops inside the loop -> [reader] the engine sends console 3 ->
|
||||
[adoption] goes on, gives back console 2. The hold is released as the FIRST thing the hand-over does, and the reader's check of it takes
|
||||
no lock, so 3 goes straight to the handler: the client hears 1, 3, 2. (A response before its request is dropped as unknown.)"""
|
||||
parking, told, announced = Parking(), {}, []
|
||||
heard, inside, go = [], threading.Event(), threading.Event()
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
_install(mp, parking, told)
|
||||
_mark_announcement(mp, told, announced)
|
||||
original = server_mod.PageDispatcher._deliver
|
||||
|
||||
def deliver(self, method, params):
|
||||
result = original(self, method, params) # the close's lock is let go when this returns: the pause is outside it
|
||||
if getattr(self, "target_id", None) == TARGET and method == "Runtime.console":
|
||||
heard.append(params["location"]["lineNumber"])
|
||||
if _adopter() and len(heard) == 1:
|
||||
inside.set()
|
||||
go.wait(10)
|
||||
return result
|
||||
mp.setattr(server_mod.PageDispatcher, "_deliver", deliver)
|
||||
world = World()
|
||||
try:
|
||||
world.born()
|
||||
for i in range(len(POINTS)):
|
||||
assert parking.reached[i].wait(5), "the adoption thread never reached %s" % POINTS[i]
|
||||
if i == 2:
|
||||
_console(world.conn, 1)
|
||||
_console(world.conn, 2)
|
||||
parking.release[i].set()
|
||||
assert inside.wait(5), "the adoption thread never gave back the first held event"
|
||||
_console(world.conn, 3) # the engine's reader, while the adoption thread is inside the loop
|
||||
go.set()
|
||||
continue
|
||||
parking.release[i].set()
|
||||
_finish(world, announced)
|
||||
assert heard == [1, 2, 3], "the page heard the messages in the order %s: a message the engine sent later overtook one it held" % heard
|
||||
finally:
|
||||
go.set()
|
||||
parking.open_all()
|
||||
world.close()
|
||||
|
||||
|
||||
# --- C ----------------------------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def test_a_page_closed_before_the_hook_goes_in_is_not_given_a_frame_after_its_dispose():
|
||||
"""Sequence: [adoption] the held events are given back, stops before the hook -> the engine attaches a child frame (the lifecycle knows it,
|
||||
the client does not) -> [caller] the page is closed: `close`, `__dispose__` -> [adoption] goes on: the hook is installed on a closed page and
|
||||
the frames reconciled, the child's dispatcher is made under the disposed page and its `__create__` is sent."""
|
||||
parking, told, announced = Parking(), {}, []
|
||||
sent, caught, at_hook, go = [], [], threading.Event(), threading.Event()
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
_install(mp, parking, told)
|
||||
_mark_announcement(mp, told, announced)
|
||||
original = server_mod.PageDispatcher._hear_lifecycle
|
||||
|
||||
def hear(self):
|
||||
if _adopter() and not caught:
|
||||
caught.append(self)
|
||||
at_hook.set()
|
||||
go.wait(10)
|
||||
return original(self)
|
||||
mp.setattr(server_mod.PageDispatcher, "_hear_lifecycle", hear)
|
||||
world = World()
|
||||
mp.setattr(world.server, "send_up", lambda message: sent.append(message))
|
||||
try:
|
||||
world.born()
|
||||
for i in range(3):
|
||||
assert parking.reached[i].wait(5), "the adoption thread never reached %s" % POINTS[i]
|
||||
parking.release[i].set()
|
||||
assert at_hook.wait(5), "the adoption thread never reached the hook"
|
||||
world.conn.dispatch_event("Page.frameAttached", {"frameId": CHILD, "parentFrameId": FRAME}, SESSION)
|
||||
page = caught[0]
|
||||
page.announce_closed()
|
||||
disposed_at = next(i for i, m in enumerate(sent) if m.get("method") == "__dispose__" and m.get("guid") == page.guid)
|
||||
go.set()
|
||||
parking.open_all()
|
||||
assert _wait(lambda: _thread() is None), "the adoption thread never ended"
|
||||
after = [m for m in sent[disposed_at + 1:] if m.get("method") == "__create__"]
|
||||
assert not after, "created after the page's __dispose__: %s" % [(m["params"]["type"], m["params"]["guid"], "under", m["guid"]) for m in after]
|
||||
finally:
|
||||
go.set()
|
||||
parking.open_all()
|
||||
world.close()
|
||||
|
||||
|
||||
# --- D ----------------------------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def test_a_frame_the_reader_and_the_hand_over_both_need_is_made_once():
|
||||
"""Sequence: the lifecycle knows a child frame the client was not told of; its `load` is heard by the lifecycle and the reader stops before the
|
||||
page's listener -> [adoption] stops before the hook -> both go on at once: the reader's handler (`Page.eventFired`) and the reconciliation each
|
||||
ask for the dispatcher of the child, each finds none, each makes one. The client gets two `__create__` of a Frame for one frame id."""
|
||||
parking, told, announced = Parking(), {}, []
|
||||
gate, entered, at_hook, go = threading.Event(), threading.Event(), threading.Event(), threading.Event()
|
||||
made = []
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
_install(mp, parking, told)
|
||||
_mark_announcement(mp, told, announced)
|
||||
_gate_page_listener(mp, gate, entered, lambda m, p: m == "Page.eventFired" and p.get("frameId") == CHILD)
|
||||
meeting = threading.Barrier(2, timeout=0.6)
|
||||
before = server_mod.FrameDispatcher.__init__
|
||||
|
||||
def frame_init(self, server, page, frame_id, *args, **kwargs):
|
||||
if frame_id == CHILD:
|
||||
made.append(threading.current_thread().name)
|
||||
try:
|
||||
meeting.wait() # a second maker is the case: where there is a lock, the second one waits outside and this times out
|
||||
except threading.BrokenBarrierError:
|
||||
pass
|
||||
return before(self, server, page, frame_id, *args, **kwargs)
|
||||
mp.setattr(server_mod.FrameDispatcher, "__init__", frame_init)
|
||||
original = server_mod.PageDispatcher._hear_lifecycle
|
||||
|
||||
def hear(self):
|
||||
if _adopter() and not at_hook.is_set():
|
||||
at_hook.set()
|
||||
go.wait(10)
|
||||
return original(self)
|
||||
mp.setattr(server_mod.PageDispatcher, "_hear_lifecycle", hear)
|
||||
world = World()
|
||||
reader = None
|
||||
try:
|
||||
world.born()
|
||||
for i in range(3):
|
||||
assert parking.reached[i].wait(5), "the adoption thread never reached %s" % POINTS[i]
|
||||
parking.release[i].set()
|
||||
world.conn.dispatch_event("Page.frameAttached", {"frameId": CHILD, "parentFrameId": FRAME}, SESSION)
|
||||
reader = threading.Thread(target=world.conn.dispatch_event, args=("Page.eventFired", {"frameId": CHILD, "name": "load"}, SESSION), daemon=True)
|
||||
reader.start()
|
||||
assert entered.wait(5), "the reader never reached the page's listener"
|
||||
assert at_hook.wait(5), "the adoption thread never reached the hook"
|
||||
gate.set()
|
||||
go.set()
|
||||
reader.join(10)
|
||||
parking.open_all()
|
||||
_finish(world, announced)
|
||||
assert len(made) == 1, "the dispatcher of one frame was made %d times (by %s): the client was told of it %d times" % (len(made), made, len(made))
|
||||
finally:
|
||||
gate.set()
|
||||
go.set()
|
||||
parking.open_all()
|
||||
world.close()
|
||||
|
||||
|
||||
# --- E ----------------------------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
def test_a_document_committed_at_the_same_address_between_the_snapshot_and_the_hook_is_told_to_the_client():
|
||||
"""Sequence: the blank page has loaded (the initializer says about:blank, domcontentloaded, load) -> [reader] the page commits ANOTHER document at
|
||||
about:blank, after the snapshot -> the hook goes in. The reconciliation compares the address and the name: they are the same, so no
|
||||
`navigated` is sent, and the client's frame keeps the old document's identity (a reload that waits for its navigation is never told it)."""
|
||||
parking, told, announced = Parking(), {}, []
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
_install(mp, parking, told)
|
||||
_mark_announcement(mp, told, announced)
|
||||
world = World()
|
||||
try:
|
||||
world.born()
|
||||
world.conn.dcl()
|
||||
world.conn.load()
|
||||
for i in range(len(POINTS)):
|
||||
assert parking.reached[i].wait(5), "the adoption thread never reached %s" % POINTS[i]
|
||||
if i == 1: # parked as the frame's dispatcher is made: the initializer is the snapshot already taken
|
||||
world.conn.dispatch_event("Page.navigationStarted", {"frameId": FRAME, "navigationId": "n2", "url": BLANK}, SESSION)
|
||||
world.conn.dispatch_event("Page.navigationCommitted", {"frameId": FRAME, "navigationId": "n2", "url": BLANK, "name": ""}, SESSION)
|
||||
parking.release[i].set()
|
||||
_finish(world, announced)
|
||||
assert {"domcontentloaded", "load"} <= set(told["states"]), "the snapshot should carry the blank page's states: %s" % told["states"]
|
||||
page = world.browser._page_targets.get(TARGET)
|
||||
known = page.lifecycle.frames[FRAME]
|
||||
navigated = [value for op, value in told["ops"] if op == "url"]
|
||||
assert navigated == [BLANK], (
|
||||
"the client was told of %d document(s) committed after the snapshot, the lifecycle heard one (states now %s)"
|
||||
% (len(navigated), sorted(s for s in known.states if s in STATES)))
|
||||
finally:
|
||||
parking.open_all()
|
||||
world.close()
|
||||
@@ -104,6 +104,7 @@ def test_a_connect_with_the_right_credentials_is_accepted_and_the_header_is_reco
|
||||
s, status, _h = _connect_raw(proxy, "%s:443" % DOH_BOOTSTRAP, basic(USER, PASSWORD))
|
||||
assert status.split()[1] == "200"
|
||||
context = ssl.create_default_context()
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
context.check_hostname = False
|
||||
context.verify_mode = ssl.CERT_NONE
|
||||
context.set_alpn_protocols(["http/1.1"])
|
||||
|
||||
@@ -4,8 +4,10 @@ Ledger #476 of 0.50.1: the Linux job of `user-install` failed in ``test_upgrade_
|
||||
move the wrapper" ('0.49.1' != '0.49.1') three minutes after the upload: the step that waited for the index had asked the
|
||||
JSON endpoint of the version, which answered, while the ``pip install --upgrade`` that followed was served an older page.
|
||||
The wait now asks pip itself and ends in an error that says what is missing; the upgrade installs the version the same
|
||||
listing named. The script of the step is run here as it stands in the workflow, with a ``pip`` that answers as a lagging
|
||||
index does.
|
||||
listing named. The installers are two - the upgrade test installs with pip, the release test with uv (the README's way in) - so
|
||||
each round asks both, and the job goes on after three rounds in a row in which both said yes (one yes proves that one request saw the
|
||||
version, not that the next is served by the same node). The script of the step is run here as it stands in the workflow, with a
|
||||
``pip`` and a ``uv`` that answer as a lagging index does.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -33,47 +35,97 @@ def _wait_script() -> str:
|
||||
return textwrap.dedent(m.group(1)) + "\n"
|
||||
|
||||
|
||||
def _run_the_wait(tmp_path, *, succeeds_on_call, seconds=2.0, poll=0.05):
|
||||
"""Run the script of the step in a project named ``invisible-playwright`` 9.9.9, with a ``pip`` that fails until its
|
||||
``succeeds_on_call``-th call (0: never)."""
|
||||
(tmp_path / "pyproject.toml").write_text('[project]\nname = "invisible-playwright"\nversion = "9.9.9"\n', encoding="utf-8")
|
||||
shim = tmp_path / "shim" / "pip"
|
||||
def _tool(tmp_path, name, plan):
|
||||
"""A regular package `name` on the shim path whose `__main__` answers call number i as plan[i] says (the last letter repeats):
|
||||
y = resolves it, n = no such version, h = does not answer (sleeps 30 s). It counts its calls in `<name>-calls`."""
|
||||
shim = tmp_path / "shim" / name
|
||||
shim.mkdir(parents=True)
|
||||
(shim / "__init__.py").write_text("", encoding="utf-8") # a REGULAR package: a namespace one loses to the pip of the environment
|
||||
counter = tmp_path / "calls"
|
||||
(shim / "__init__.py").write_text("", encoding="utf-8") # a REGULAR package: a namespace one loses to the real one of the environment
|
||||
(shim / "__main__.py").write_text(textwrap.dedent("""
|
||||
import pathlib, sys
|
||||
import pathlib, sys, time
|
||||
p = pathlib.Path(%r)
|
||||
n = (int(p.read_text()) if p.exists() else 0) + 1
|
||||
p.write_text(str(n))
|
||||
if %d and n >= %d:
|
||||
n = int(p.read_text()) if p.exists() else 0
|
||||
p.write_text(str(n + 1))
|
||||
sys.stdin.read() if %r == "uv" else None
|
||||
plan = %r
|
||||
what = plan[min(n, len(plan) - 1)]
|
||||
if what == "h":
|
||||
time.sleep(30)
|
||||
if what == "y":
|
||||
sys.exit(0)
|
||||
sys.stderr.write("ERROR: No matching distribution found for invisible-playwright==9.9.9\\n")
|
||||
sys.stderr.write("ERROR: No matching distribution found for invisible-playwright==9.9.9" + chr(10))
|
||||
sys.exit(1)
|
||||
""") % (str(counter), succeeds_on_call, succeeds_on_call), encoding="utf-8")
|
||||
""") % (str(tmp_path / (name + "-calls")), name, plan), encoding="utf-8")
|
||||
|
||||
|
||||
def _run_the_wait(tmp_path, pip="y", uv="y", *, seconds=3.0, poll=0.05, call_seconds=None):
|
||||
"""Run the script of the step in a project named ``invisible-playwright`` 9.9.9, with a ``pip`` and a ``uv`` that answer as their plans say.
|
||||
Returns (completed process, pip calls, uv calls)."""
|
||||
(tmp_path / "pyproject.toml").write_text('[project]\nname = "invisible-playwright"\nversion = "9.9.9"\n', encoding="utf-8")
|
||||
_tool(tmp_path, "pip", pip)
|
||||
_tool(tmp_path, "uv", uv)
|
||||
env = dict(os.environ, PYTHONPATH=str(tmp_path / "shim"), INDEX_WAIT_SECONDS=str(seconds), INDEX_WAIT_POLL=str(poll))
|
||||
if call_seconds is not None:
|
||||
env["INDEX_WAIT_CALL_SECONDS"] = str(call_seconds)
|
||||
try:
|
||||
r = subprocess.run([sys.executable, "-c", _wait_script()], cwd=tmp_path, env=env, capture_output=True, text=True,
|
||||
timeout=30)
|
||||
r = subprocess.run([sys.executable, "-c", _wait_script()], cwd=tmp_path, env=env, capture_output=True, text=True, timeout=60)
|
||||
except subprocess.TimeoutExpired:
|
||||
pytest.fail("the wait did not end within 30 s with INDEX_WAIT_SECONDS=%s: it does not read its deadline" % seconds)
|
||||
calls = int(counter.read_text()) if counter.exists() else 0
|
||||
return r, calls
|
||||
pytest.fail("the wait did not end within 60 s with INDEX_WAIT_SECONDS=%s: it does not read its deadline" % seconds)
|
||||
|
||||
def calls(name):
|
||||
f = tmp_path / (name + "-calls")
|
||||
return int(f.read_text()) if f.exists() else 0
|
||||
return r, calls("pip"), calls("uv")
|
||||
|
||||
|
||||
def test_the_wait_asks_pip_and_goes_on_when_pip_gets_the_version(tmp_path):
|
||||
r, calls = _run_the_wait(tmp_path, succeeds_on_call=3)
|
||||
def test_the_wait_asks_both_installers_three_rounds_in_a_row(tmp_path):
|
||||
r, pip_calls, uv_calls = _run_the_wait(tmp_path)
|
||||
assert r.returncode == 0, r.stdout + r.stderr
|
||||
assert calls == 3, "it polled %d times, pip answered on the 3rd" % calls
|
||||
assert "pip downloads invisible-playwright 9.9.9" in r.stdout
|
||||
assert (pip_calls, uv_calls) == (3, 3), "one yes is not enough: pip %d, uv %d" % (pip_calls, uv_calls)
|
||||
assert "pip and uv resolve invisible-playwright 9.9.9 from the index, 3 rounds in a row" in r.stdout
|
||||
|
||||
|
||||
def test_uv_alone_saying_no_keeps_the_wait_going(tmp_path):
|
||||
"""The release test installs with uv: pip seeing the version is not enough."""
|
||||
r, pip_calls, uv_calls = _run_the_wait(tmp_path, pip="y", uv="nyyy")
|
||||
assert r.returncode == 0, r.stdout + r.stderr
|
||||
assert uv_calls == 4 and pip_calls == 4, "the round with uv's no counted: pip %d, uv %d" % (pip_calls, uv_calls)
|
||||
|
||||
|
||||
def test_a_no_between_the_yes_starts_the_count_again(tmp_path):
|
||||
r, pip_calls, _ = _run_the_wait(tmp_path, pip="yynyyy")
|
||||
assert r.returncode == 0 and pip_calls == 6, r.stdout + r.stderr
|
||||
|
||||
|
||||
def test_the_wait_ends_in_an_error_that_names_the_missing_version_when_the_index_never_has_it(tmp_path):
|
||||
r, calls = _run_the_wait(tmp_path, succeeds_on_call=0, seconds=1.0)
|
||||
r, pip_calls, _ = _run_the_wait(tmp_path, pip="n", uv="n", seconds=1.0)
|
||||
assert r.returncode == 1, "a forgotten publish must fail the job here: " + r.stdout + r.stderr
|
||||
assert "::error::the index does not have invisible-playwright 9.9.9 yet" in r.stdout
|
||||
assert "minutes" in r.stdout and "No matching distribution" in r.stdout
|
||||
assert calls >= 2
|
||||
assert "minutes" in r.stdout and "pip said: ERROR: No matching distribution" in r.stdout and "0 of 3 rounds" in r.stdout
|
||||
assert pip_calls >= 2
|
||||
|
||||
|
||||
def test_pip_yes_and_uv_never_is_an_error_naming_uv(tmp_path):
|
||||
r, _, uv_calls = _run_the_wait(tmp_path, pip="y", uv="n", seconds=1.0)
|
||||
assert r.returncode == 1 and "uv said:" in r.stdout, r.stdout + r.stderr
|
||||
assert uv_calls >= 2
|
||||
|
||||
|
||||
def test_a_call_that_does_not_answer_is_a_no_and_does_not_stop_the_wait(tmp_path):
|
||||
r, pip_calls, _ = _run_the_wait(tmp_path, pip="hyyy", seconds=20.0, call_seconds=0.5)
|
||||
assert r.returncode == 0 and pip_calls == 4, r.stdout + r.stderr
|
||||
|
||||
|
||||
def test_a_call_that_never_answers_ends_in_the_error_with_what_happened(tmp_path):
|
||||
r, _, _ = _run_the_wait(tmp_path, pip="h", seconds=1.5, call_seconds=0.3)
|
||||
assert r.returncode == 1 and "pip did not answer within" in r.stdout, r.stdout + r.stderr
|
||||
|
||||
|
||||
def test_the_harness_has_uv_for_the_wait_to_ask():
|
||||
"""Read as text: PyYAML is not a dependency of this package (nor of [dev]), as tests/test_ci_runs_once_per_commit.py says."""
|
||||
found = re.search(r"^[ \t]*-[ \t]*name:[ \t]*Test harness only[ \t]*\n[ \t]*run:[ \t]*(?P<run>.+)$", WORKFLOW.read_text(encoding="utf-8"), re.M)
|
||||
assert found, "the harness step is gone"
|
||||
assert "pip" in found.group("run") and found.group("run").split()[-1] == "uv", found.group("run")
|
||||
|
||||
|
||||
def test_the_wait_step_still_passes_the_gate_of_the_core():
|
||||
|
||||
@@ -163,23 +163,35 @@ def test_the_trap_goes_to_the_next_loopback_address_when_the_first_has_its_port_
|
||||
of TRAP_ADDRESSES it can bind, says which, and that is the address a resolv.conf is written with (run 43146661635: the
|
||||
trap could not bind and eight tests ended in error at setup)."""
|
||||
import _leaks
|
||||
from _ports import bind_tcp_and_probe_udp
|
||||
|
||||
holder_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
class _Listener:
|
||||
"""A TCP listener the picker can open and close, and the number it holds."""
|
||||
|
||||
def __init__(self, address, number):
|
||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
try:
|
||||
self.sock.bind((address, number))
|
||||
except OSError:
|
||||
self.sock.close()
|
||||
raise
|
||||
self.sock.listen(1)
|
||||
self.server_address = self.sock.getsockname()
|
||||
|
||||
def server_close(self):
|
||||
self.sock.close()
|
||||
|
||||
# The number is one that TCP and UDP both bind (the system's own pick can fall in a block of ports UDP may not bind on Windows: the shared picker).
|
||||
holder_tcp, port = bind_tcp_and_probe_udp("127.0.0.1", _Listener)
|
||||
holder_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
holder_tcp.bind(("127.0.0.1", 0))
|
||||
port = holder_tcp.getsockname()[1]
|
||||
try:
|
||||
holder_udp.bind(("127.0.0.1", port))
|
||||
except OSError:
|
||||
raise
|
||||
holder_tcp.listen(1)
|
||||
holder_udp.bind(("127.0.0.1", port))
|
||||
# port != 0 is the case of port 53: the addresses are tried in order
|
||||
with ResolverTrap(port=port, rewrite_resolv_conf=False) as trap:
|
||||
assert trap.address != "127.0.0.1" and trap.address in _leaks.TRAP_ADDRESSES, trap.address
|
||||
assert _udp_ask_at(trap.address, port, "leak.test")[3] & 0xF == ds.RCODE_REFUSED
|
||||
finally:
|
||||
holder_tcp.close()
|
||||
holder_tcp.server_close()
|
||||
holder_udp.close()
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
"""The harness has ONE way to find a port number where TCP and UDP both bind (tests/_ports.py): the HTTP/3 server, the witness and the resolver trap walk it, and it says why when it finds none.
|
||||
|
||||
The known-bad case (run 43230437094, wrapper.e2e.web on Windows, three tests of tests/test_http3_through_the_proxy_e2e.py): ``H3Server`` asked the system for a TCP
|
||||
port fifty times, took the same number for a UDP probe, swallowed every refusal and raised "no port free for both TCP and UDP". Windows hands out ephemeral TCP
|
||||
ports in sequence and keeps excluded ranges of a hundred ports for UDP in the same zone (tests/test_the_witness_picks_a_port_both_sockets_bind.py has the same case
|
||||
for the witness): fifty consecutive numbers can all be refused. A fake socket layer does that here, without the machine. The old server is red on it (it has no
|
||||
picker to call and, as it was written, raised after fifty refusals); this one finds a number outside the range, and when it finds none it lists the codes.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import types
|
||||
|
||||
import pytest
|
||||
|
||||
import _h3_server
|
||||
import _ports
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
REFUSED = range(50000, 50200)
|
||||
|
||||
|
||||
class _Udp:
|
||||
def __init__(self, layer):
|
||||
self.layer = layer
|
||||
|
||||
def bind(self, pair):
|
||||
self.layer.udp_tries.append(pair[1])
|
||||
if self.layer.refuse_all or pair[1] in REFUSED:
|
||||
raise OSError(10013, "An attempt was made to access a socket in a way forbidden by its access permissions")
|
||||
|
||||
def close(self):
|
||||
self.layer.udp_closed += 1
|
||||
|
||||
|
||||
class _Layer:
|
||||
AF_INET, SOCK_DGRAM = 2, 2
|
||||
|
||||
def __init__(self, refuse_all=False):
|
||||
self.refuse_all = refuse_all
|
||||
self.udp_tries = []
|
||||
self.udp_closed = 0
|
||||
self.next_pick = 50000
|
||||
self.tcp_open = []
|
||||
|
||||
def socket(self, family, kind):
|
||||
return _Udp(self)
|
||||
|
||||
def make_tcp(self, address, port):
|
||||
if port == 0:
|
||||
port = self.next_pick
|
||||
self.next_pick += 1
|
||||
layer = self
|
||||
|
||||
class Tcp:
|
||||
server_address = (address, port)
|
||||
|
||||
def server_close(self):
|
||||
layer.tcp_open.remove(self)
|
||||
|
||||
tcp = Tcp()
|
||||
self.tcp_open.append(tcp)
|
||||
return tcp
|
||||
|
||||
|
||||
def test_the_picker_leaves_the_range_that_the_systems_sequential_picks_fall_in():
|
||||
layer = _Layer()
|
||||
tcp, port = _ports.bind_tcp_and_probe_udp("10.1.0.111", layer.make_tcp, socket_module=layer)
|
||||
assert port not in REFUSED and 20000 <= port <= 32767, port
|
||||
assert tcp.server_address == ("10.1.0.111", port)
|
||||
assert layer.tcp_open == [tcp], "the refused TCP servers were closed and the chosen one is kept"
|
||||
assert layer.udp_tries[0] in REFUSED, "the first try is the system's own pick"
|
||||
assert layer.udp_closed == len(layer.udp_tries), "every probe was closed again"
|
||||
|
||||
|
||||
def test_the_picker_that_finds_none_says_how_many_tries_and_the_codes_of_the_last_refusals(monkeypatch):
|
||||
layer = _Layer(refuse_all=True)
|
||||
asked = []
|
||||
monkeypatch.setattr(_ports, "who_holds", lambda port: asked.append(port) or "; held by: a process")
|
||||
with pytest.raises(RuntimeError) as caught:
|
||||
_ports.bind_tcp_and_probe_udp("10.1.0.111", layer.make_tcp, tries=7, socket_module=layer)
|
||||
message = str(caught.value)
|
||||
assert "10.1.0.111" in message and "7 tries" in message and message.count("10013") == 3, message
|
||||
# The last number tried is named and the machine is asked who holds it (ss or netstat: Linux says, the message carries it).
|
||||
assert len(asked) == 1 and ("the last number tried: %d" % asked[0]) in message and "held by: a process" in message, message
|
||||
assert layer.tcp_open == [], "nothing is left open"
|
||||
|
||||
|
||||
def test_a_tcp_bind_that_is_refused_is_a_refusal_too_and_the_next_number_is_tried():
|
||||
layer = _Layer()
|
||||
real = layer.make_tcp
|
||||
calls = []
|
||||
|
||||
def flaky(address, port):
|
||||
calls.append(port)
|
||||
if len(calls) == 1:
|
||||
raise OSError(10048, "address in use")
|
||||
return real(address, port)
|
||||
|
||||
tcp, port = _ports.bind_tcp_and_probe_udp("10.1.0.111", flaky, socket_module=layer)
|
||||
assert len(calls) >= 2 and tcp.server_address[1] == port
|
||||
|
||||
|
||||
def test_the_h3_server_takes_its_port_from_the_shared_picker(monkeypatch):
|
||||
layer = _Layer()
|
||||
monkeypatch.setattr(_h3_server, "socket", layer)
|
||||
monkeypatch.setattr(_h3_server, "_TcpServer", lambda pair, handler: layer.make_tcp(pair[0], pair[1]))
|
||||
monkeypatch.setattr(_h3_server, "bind_tcp_and_probe_udp", _ports.bind_tcp_and_probe_udp)
|
||||
tcp, port = _h3_server._tcp_server_on_a_port_udp_binds("10.1.0.111")
|
||||
assert port not in REFUSED and tcp.server_address == ("10.1.0.111", port)
|
||||
import inspect
|
||||
assert "_ports" in inspect.getsource(_h3_server) and "randint" not in inspect.getsource(_h3_server), "a copy of the picker is back in the server"
|
||||
|
||||
|
||||
def test_the_tcp_server_of_the_h3_server_does_not_share_a_port_on_windows():
|
||||
import sys
|
||||
|
||||
assert _h3_server._TcpServer.allow_reuse_address is (sys.platform != "win32")
|
||||
|
||||
|
||||
# --- the same sequence for the witness and the resolver trap -----------------------------------------------------------------------------------
|
||||
|
||||
def test_the_sequence_is_the_system_pick_then_numbers_below_the_ephemeral_range():
|
||||
numbers = list(_ports.candidates(30))
|
||||
assert numbers[0] == 0 and len(numbers) == 30
|
||||
assert all(_ports.DRAW_FROM[0] <= n <= _ports.DRAW_FROM[1] for n in numbers[1:]) and _ports.DRAW_FROM[1] < 32768
|
||||
assert len(set(numbers[1:])) > 1, "the numbers are drawn, not repeated"
|
||||
|
||||
|
||||
def test_the_witness_and_the_trap_walk_the_same_sequence_and_the_same_limits():
|
||||
import _leaks
|
||||
import _witness
|
||||
|
||||
assert _witness.candidates is _ports.candidates and _leaks.candidates is _ports.candidates
|
||||
assert (_witness.TRIES, _witness.DRAW_FROM) == (_ports.TRIES, _ports.DRAW_FROM)
|
||||
|
||||
|
||||
class _TrapLayer(_Layer):
|
||||
"""The socket module of the trap: IPv6 is not there (::1 is optional), TCP picks are sequential, UDP refuses REFUSED."""
|
||||
|
||||
AF_INET6, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR = 10, 1, 1, 2
|
||||
|
||||
def __init__(self, refuse_all=False):
|
||||
super().__init__(refuse_all)
|
||||
self.tcp_ports = []
|
||||
|
||||
def socket(self, family, kind):
|
||||
return _TrapSocket(self, family, kind)
|
||||
|
||||
|
||||
class _TrapSocket:
|
||||
def __init__(self, layer, family, kind):
|
||||
self.layer, self.family, self.type, self.port = layer, family, kind, None
|
||||
|
||||
def setsockopt(self, *args):
|
||||
pass
|
||||
|
||||
def settimeout(self, seconds):
|
||||
pass
|
||||
|
||||
def bind(self, where):
|
||||
address, port = where
|
||||
if self.family == self.layer.AF_INET6:
|
||||
raise OSError(99, "no ::1 here")
|
||||
if self.type == self.layer.SOCK_STREAM:
|
||||
if port == 0:
|
||||
port = self.layer.next_pick
|
||||
self.layer.next_pick += 1
|
||||
self.port = port
|
||||
self.layer.tcp_ports.append(port)
|
||||
return
|
||||
self.layer.udp_tries.append(port)
|
||||
if self.layer.refuse_all or port in REFUSED:
|
||||
raise OSError(10013, "An attempt was made to access a socket in a way forbidden by its access permissions")
|
||||
self.port = port
|
||||
|
||||
def getsockname(self):
|
||||
return ("127.0.0.1", self.port)
|
||||
|
||||
def listen(self, backlog):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
class _NoThread:
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def start(self):
|
||||
pass
|
||||
|
||||
|
||||
def _trap_with(monkeypatch, layer, port):
|
||||
import threading
|
||||
|
||||
import _leaks
|
||||
|
||||
monkeypatch.setattr(_leaks, "socket", layer)
|
||||
monkeypatch.setattr(_leaks, "threading", types.SimpleNamespace(Thread=_NoThread, Lock=threading.Lock, Event=threading.Event))
|
||||
return _leaks.ResolverTrap(port=port, rewrite_resolv_conf=False)
|
||||
|
||||
|
||||
def test_the_resolver_trap_with_port_0_leaves_the_block_that_the_systems_sequential_picks_fall_in(monkeypatch):
|
||||
layer = _TrapLayer()
|
||||
trap = _trap_with(monkeypatch, layer, 0)
|
||||
trap._bind()
|
||||
assert trap.port not in REFUSED and trap.address == "127.0.0.1", (trap.port, trap.address)
|
||||
assert layer.udp_tries[0] in REFUSED, "the first try is the system's own pick"
|
||||
assert len(trap._sockets) == 2, "TCP and UDP of 127.0.0.1 (::1 is not there)"
|
||||
|
||||
|
||||
def test_the_resolver_trap_with_a_port_asked_for_tries_it_once_per_address_and_says_the_last_error(monkeypatch):
|
||||
import _leaks
|
||||
|
||||
layer = _TrapLayer(refuse_all=True)
|
||||
trap = _trap_with(monkeypatch, layer, 5300)
|
||||
with pytest.raises(OSError) as caught:
|
||||
trap._bind()
|
||||
assert layer.udp_tries == [5300] * len(_leaks.TRAP_ADDRESSES), "a port asked for (53 on the root leg) is not replaced by another"
|
||||
assert "10013" in str(caught.value) and "port 5300" in str(caught.value), str(caught.value)
|
||||
@@ -71,7 +71,7 @@ def test_a_question_of_another_user_is_answered_and_listed_not_counted():
|
||||
assert _ask(trap, "github.com"), "a question of another user is still answered"
|
||||
assert trap.names() == [] and trap.queries == []
|
||||
assert [(q.name, a.uid) for q, a in trap.foreign] == [("github.com", 1001)]
|
||||
assert "github.com" in trap.describe() and "not counted" in trap.describe()
|
||||
assert trap.describe() == "nothing [and 1 question(s) of other processes, not counted: github.com from pid ? (uid 1001) ]"
|
||||
|
||||
|
||||
def test_a_question_whose_socket_is_gone_counts_as_the_browsers():
|
||||
|
||||
@@ -44,7 +44,8 @@ def problems(text: str, suite: dict) -> list:
|
||||
nodes = [t for t in suite["tests"] if "::" in t]
|
||||
steps = _steps(text)
|
||||
root = [body for name, body in steps if "root e2e" in name]
|
||||
runner = [body for name, body in steps if "scripts/run_e2e.py" in body]
|
||||
# the Linux run (xvfb): the Windows parts of e2e.yml leave the linux_only suites out by reading ci/required-suites.json
|
||||
runner = [body for name, body in steps if "scripts/run_e2e.py" in body and "xvfb-run" in body]
|
||||
if len(root) != 1:
|
||||
return ["there is no (or more than one) step for the root e2e: %d" % len(root)]
|
||||
if len(runner) != 1:
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""The e2e that needs the browser's sandbox runs in a step that turns user namespaces on, and is left out of the normal run.
|
||||
|
||||
``tests/test_the_socket_process_is_sandboxed_e2e.py`` (suite ``wrapper.e2e.udp.sandbox``) FAILS by design when the socket and a tab process have no
|
||||
seccomp filter. On the Ubuntu 24.04 runner AppArmor refuses user namespaces to a normal user (``kernel.apparmor_restrict_unprivileged_userns=1``), so
|
||||
collected in the normal run of e2e.yml it is red on a runner without the sysctl, and no test of the repository can make it green there. The engine's
|
||||
gate runs it in a leg that turns the restriction off first; e2e.yml now does the same, the way it already handles the root files: the normal run
|
||||
ignores the file by name (``SANDBOX_FILES``) and a step of its own, after the run, runs exactly that file as the runner user after
|
||||
``sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0``, reads its own junit and refuses anything but exactly that many tests, all passed.
|
||||
|
||||
This test reads the workflow as text (PyYAML is not a dependency of this package). Known-bad input: e2e.yml as it was, with no sandbox step and no
|
||||
exclusion -> ``problems`` names both.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from test_the_root_e2e_run_in_the_root_step_and_nowhere_else import _steps
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WORKFLOW = ROOT / ".github" / "workflows" / "e2e.yml"
|
||||
FILE = "tests/test_the_socket_process_is_sandboxed_e2e.py"
|
||||
SYSCTL = "kernel.apparmor_restrict_unprivileged_userns=0"
|
||||
|
||||
|
||||
def _env(body: str, key: str) -> list:
|
||||
found = re.search(r"^\s*%s: \"?([^\"\n]*)\"?\s*$" % key, body, re.M)
|
||||
return found.group(1).split() if found else []
|
||||
|
||||
|
||||
def problems(text: str) -> list:
|
||||
out = []
|
||||
steps = _steps(text)
|
||||
sandbox = [body for name, body in steps if "sandbox e2e" in name]
|
||||
# the Linux run (xvfb): the Windows parts of e2e.yml leave the linux_only suites out by reading ci/required-suites.json
|
||||
runner = [body for name, body in steps if "scripts/run_e2e.py" in body and "xvfb-run" in body]
|
||||
if len(sandbox) != 1:
|
||||
return ["there is no (or more than one) step for the sandbox e2e: %d" % len(sandbox)]
|
||||
if len(runner) != 1:
|
||||
return ["the normal run is not one step: %d" % len(runner)]
|
||||
sandbox, runner = sandbox[0], runner[0]
|
||||
bodies = [body for _name, body in steps]
|
||||
head, _, script = sandbox.partition("run: |")
|
||||
if bodies.index(sandbox) < bodies.index(runner):
|
||||
out.append("the sandbox step comes BEFORE the normal run")
|
||||
if "if: success() || failure()" not in head:
|
||||
out.append("the sandbox step does not run after a red normal run (`if: success() || failure()`)")
|
||||
if FILE not in _env(runner, "SANDBOX_FILES") or "$SANDBOX_FILES" not in runner or "--ignore=$f" not in runner:
|
||||
out.append("the normal run does not ignore %s (SANDBOX_FILES -> --ignore)" % FILE)
|
||||
if FILE not in _env(sandbox, "SANDBOX_FILES"):
|
||||
out.append("the sandbox step does not run %s (SANDBOX_FILES)" % FILE)
|
||||
expected = len(re.findall(r"^def test_", (ROOT / FILE).read_text(encoding="utf-8"), re.M))
|
||||
if _env(sandbox, "SANDBOX_TESTS") != [str(expected)]:
|
||||
out.append("the sandbox step does not demand exactly %d test(s)" % expected)
|
||||
if SYSCTL not in script or script.find(SYSCTL) > script.find("pytest"):
|
||||
out.append("the sandbox step does not turn user namespaces on (%s) before pytest" % SYSCTL)
|
||||
if "sudo -H" in script or "sudo python" in script or "sudo -E env" in script:
|
||||
out.append("the sandbox step runs the test as root: the sandbox leg is the runner user")
|
||||
if "-p no:rerunfailures" not in script or "--junitxml" not in script:
|
||||
out.append("the sandbox step has no junit or allows a rerun")
|
||||
if not all('counts["%s"]' % k in script for k in ("failures", "errors", "skipped")):
|
||||
out.append("the sandbox step does not refuse failures, errors and skips")
|
||||
for name, body in steps:
|
||||
if body is sandbox or body is runner:
|
||||
continue
|
||||
# The comment block above a step belongs, by the slicing of `_steps`, to the step before it: only the lines that are not comments count.
|
||||
if FILE in " ".join(l for l in body.splitlines() if not l.lstrip().startswith("#")):
|
||||
out.append("step %r names %s outside the sandbox step" % (name, FILE))
|
||||
return out
|
||||
|
||||
|
||||
def test_the_workflow_runs_the_sandbox_e2e_in_its_own_step_and_leaves_it_out_of_the_normal_run():
|
||||
assert problems(WORKFLOW.read_text(encoding="utf-8")) == []
|
||||
|
||||
|
||||
def test_the_file_is_one_of_the_tests_of_the_sandbox_suite_of_the_gate():
|
||||
suite = next(s for s in json.loads((ROOT / "ci" / "required-suites.json").read_text(encoding="utf-8")) if s["id"] == "wrapper.e2e.udp.sandbox")
|
||||
assert FILE in suite["tests"] and suite["os"] == ["linux"] and suite["needs_root"] is False
|
||||
|
||||
|
||||
BAD_BEFORE = """
|
||||
steps:
|
||||
- name: Run the full e2e suite under a virtual display, without the root ones
|
||||
run: xvfb-run -a python -u scripts/run_e2e.py "$FF"
|
||||
"""
|
||||
|
||||
|
||||
def test_the_workflow_as_it_was_is_refused():
|
||||
found = problems(BAD_BEFORE)
|
||||
assert found and "no (or more than one) step for the sandbox e2e" in found[0]
|
||||
|
||||
|
||||
def test_the_current_workflow_without_the_exclusion_is_refused():
|
||||
text = WORKFLOW.read_text(encoding="utf-8").replace("for f in $ROOT_FILES $SANDBOX_FILES;", "for f in $ROOT_FILES;")
|
||||
assert any("does not ignore" in p for p in problems(text))
|
||||
|
||||
|
||||
def test_a_sandbox_step_without_the_sysctl_is_refused():
|
||||
text = WORKFLOW.read_text(encoding="utf-8").replace(SYSCTL, "kernel.apparmor_restrict_unprivileged_userns=1")
|
||||
assert any("does not turn user namespaces on" in p for p in problems(text))
|
||||
|
||||
|
||||
def test_a_sandbox_step_that_may_skip_is_refused():
|
||||
text = WORKFLOW.read_text(encoding="utf-8")
|
||||
sandbox = next(body for name, body in _steps(text) if "sandbox e2e" in name)
|
||||
assert any("refuse failures" in p for p in problems(text.replace(sandbox, sandbox.replace('counts["skipped"]', 'counts["nothing"]'))))
|
||||
|
||||
|
||||
def test_the_file_named_in_another_step_is_refused():
|
||||
text = WORKFLOW.read_text(encoding="utf-8") + " - name: Also\n run: python -m pytest %s\n" % FILE
|
||||
assert any("outside the sandbox step" in p for p in problems(text))
|
||||
@@ -0,0 +1,52 @@
|
||||
"""A test that compares two measured durations (a gather next to a gateway and the same gather behind one 250 ms away) runs alone, in the serial pass.
|
||||
|
||||
Run 43353896238 of PR 486 (Linux e2e, four workers): 765 passed and one failed, ``test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server``:
|
||||
``assert (350 - 84) <= 100``, the host candidate of the far gather came 266 ms after the one of the near gather. Nothing in the engine waited; two browsers
|
||||
launched one after the other on a runner that was also running three other workers took different times. A verdict on the difference of two wall-clock
|
||||
measures belongs to the group the e2e run already has for it, ``wall_clock`` (``invisible_core.testing.e2e.passes``: everything else first at the width asked,
|
||||
then these alone on the serial path). Found by reading the file's AST: a test whose assertions name both ``near`` and ``far`` timings.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from test_the_consecutive_port_tests_run_serially import _marks
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
FILE = Path(__file__).resolve().parent / "test_webrtc_realness.py"
|
||||
|
||||
|
||||
def _compares_near_and_far(fn: ast.FunctionDef) -> bool:
|
||||
for node in ast.walk(fn):
|
||||
if isinstance(node, ast.Assert):
|
||||
names = {n.id for n in ast.walk(node.test) if isinstance(n, ast.Name)}
|
||||
if {"near", "far"} <= names:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def unserial(source: str) -> list:
|
||||
tree = ast.parse(source)
|
||||
return [n.name for n in tree.body
|
||||
if isinstance(n, ast.FunctionDef) and n.name.startswith("test_") and _compares_near_and_far(n) and "wall_clock" not in _marks(n)]
|
||||
|
||||
|
||||
def test_every_test_that_compares_a_near_and_a_far_duration_runs_in_the_serial_group():
|
||||
assert unserial(FILE.read_text(encoding="utf-8")) == []
|
||||
|
||||
|
||||
def test_the_two_known_tests_are_found():
|
||||
tree = ast.parse(FILE.read_text(encoding="utf-8"))
|
||||
found = sorted(n.name for n in tree.body if isinstance(n, ast.FunctionDef) and _compares_near_and_far(n))
|
||||
assert found == ["test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server",
|
||||
"test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far_away"], found
|
||||
|
||||
|
||||
def test_a_comparison_without_the_marker_is_refused():
|
||||
body = ["def test_x():", " assert far['host'] - near['host'] <= 100"]
|
||||
assert unserial("\n".join(body)) == ["test_x"]
|
||||
assert unserial("\n".join(["@pytest.mark.wall_clock"] + body)) == []
|
||||
@@ -57,6 +57,7 @@ def _via(relay_sock, relay, host_ip, port, payload):
|
||||
def _http_over_tls(sock, chain, method, target, body=b"", content_type=None, host=DOH_HOST):
|
||||
"""One HTTP/1.1 request over TLS on a tunnel, trusting the certificate of the chain's DoH."""
|
||||
context = ssl.create_default_context(cafile=str(chain.doh.certificate_path))
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
context.set_alpn_protocols(["http/1.1"])
|
||||
tls = context.wrap_socket(sock, server_hostname=host)
|
||||
head = "%s %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\nContent-Length: %d\r\n" % (method, target, host, len(body))
|
||||
@@ -105,7 +106,7 @@ def test_a_client_walks_the_whole_road_and_the_turn_server_sees_the_gateways_exi
|
||||
assert attrs[0x0014] == c.REALM.encode() and attrs[0x0015] == c.NONCE.encode()
|
||||
# with the credentials: a success signed with the long-term key
|
||||
user = b"challenge-1"
|
||||
key = hashlib.md5(b"challenge-1:" + c.REALM.encode() + b":" + c.PASSWORD.encode()).digest()
|
||||
key = hashlib.md5(b"challenge-1:" + c.REALM.encode() + b":" + c.PASSWORD.encode(), usedforsecurity=False).digest()
|
||||
body = (c._attr(0x0019, b"\x11\x00\x00\x00") + c._attr(0x0006, user) + c._attr(0x0014, c.REALM.encode()) +
|
||||
c._attr(0x0015, c.NONCE.encode()))
|
||||
req = c._message(0x0003, b"\x02" * 12, body, key)
|
||||
|
||||
@@ -52,13 +52,14 @@ def _host_ip():
|
||||
|
||||
|
||||
class _TurnTcp:
|
||||
"""Accepts TCP connections, reads what comes, closes N ms after the accept."""
|
||||
"""Accepts TCP connections, reads what comes, closes N ms after the accept. Listens on the one address the browser is told to
|
||||
connect to (`host`), not on every interface of the machine."""
|
||||
|
||||
def __init__(self, n_ms):
|
||||
def __init__(self, n_ms, host):
|
||||
self.n_ms, self.accepts, self.bytes_in = n_ms, [], 0
|
||||
self._s = socket.socket()
|
||||
self._s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
self._s.bind(("0.0.0.0", 0))
|
||||
self._s.bind((host, 0))
|
||||
self._s.listen(16)
|
||||
self.port = self._s.getsockname()[1]
|
||||
threading.Thread(target=self._serve, daemon=True).start()
|
||||
@@ -134,7 +135,7 @@ def test_a_turn_server_over_tcp_is_connected_to_and_waited_for(local_page, monke
|
||||
if not binary:
|
||||
pytest.fail("no patched binary: set STEALTHFOX_E2E_BINARY", pytrace=False)
|
||||
monkeypatch.setenv("STEALTHFOX_WEBRTC_NETWORK", DECLARED)
|
||||
turn = _TurnTcp(N_MS)
|
||||
turn = _TurnTcp(N_MS, _host_ip())
|
||||
socks = Socks5TcpOnly() if through_socks5 else None
|
||||
kw = {}
|
||||
if socks:
|
||||
|
||||
@@ -494,6 +494,7 @@ def test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_it
|
||||
assert took_the_relay, "the page's STUN request did not take the relay. " + verdict
|
||||
|
||||
|
||||
@pytest.mark.wall_clock # its verdict compares two durations (near and far): the e2e run gives it the machine alone
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.parametrize("ice_prefs", _ICE_PREFS, ids=_ICE_IDS)
|
||||
@pytest.mark.usefixtures("the_udp_line")
|
||||
@@ -517,6 +518,7 @@ def test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far
|
||||
f"the srflx came {far['srflx'] - far['host']} ms after the host candidate. {far_verdict}")
|
||||
|
||||
|
||||
@pytest.mark.wall_clock # its verdict compares two durations (near and far): the e2e run gives it the machine alone
|
||||
@pytest.mark.e2e
|
||||
@pytest.mark.usefixtures("the_udp_line")
|
||||
def test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server(monkeypatch):
|
||||
|
||||
Reference in new issue
Block a user