Compare commits
25
Commits
No files matched your search
@@ -34,18 +34,35 @@ 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
|
||||
|
||||
# One run of this workflow per branch at a time. A newer push cancels the older
|
||||
# in-flight run as a whole, cleanly, instead of leaving its queued jobs to be
|
||||
# cancelled one by one - which left the run marked failed even though nothing
|
||||
# had actually failed. Keyed by workflow + ref so tests and e2e never cancel
|
||||
# each other; only an older run of THIS workflow on the same branch is replaced.
|
||||
# A newer push to a pull request cancels the older in-flight run of THIS
|
||||
# workflow on that pull request as a whole, cleanly, instead of leaving its
|
||||
# queued jobs to be cancelled one by one - which left the run marked failed even
|
||||
# though nothing had actually failed. Keyed by workflow + pull request number,
|
||||
# so tests and e2e never cancel each other.
|
||||
#
|
||||
# NEVER on main. The release gate (scripts/e2e_is_green.py) asks for the e2e
|
||||
# check-run of the commit being tagged, and a cancelled one refuses the release:
|
||||
# with the group keyed by ref, the next push to main cancelled the run of the
|
||||
# commit before it. Outside a pull request the group is unique to the run
|
||||
# (`github.run_id`), so every commit of main keeps its own finished run, and a
|
||||
# pending run is not replaced by a newer one either (a group with a fixed name
|
||||
# drops the older pending run, cancel or not).
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
# 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
|
||||
@@ -67,7 +84,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:
|
||||
@@ -163,3 +180,34 @@ 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
|
||||
@@ -51,9 +51,12 @@ on:
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
# A publishing workflow is never cancelled half-way: the second run waits for
|
||||
# the first (a newer pending run replaces an older pending one, which is
|
||||
# harmless: the wiki is rebuilt in full from the repository each time).
|
||||
concurrency:
|
||||
group: publish-wiki
|
||||
cancel-in-progress: true
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish-wiki:
|
||||
|
||||
@@ -15,9 +15,12 @@ permissions:
|
||||
# cancelled one by one - which left the run marked failed even though nothing
|
||||
# had actually failed. Keyed by workflow + ref so tests and e2e never cancel
|
||||
# each other; only an older run of THIS workflow on the same branch is replaced.
|
||||
# A newer push to a pull request cancels the run it supersedes. Never on main:
|
||||
# outside a pull request the group is unique to the run (`github.run_id`), so
|
||||
# every commit of main keeps its own finished run (see e2e.yml for why).
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
# 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
|
||||
|
||||
@@ -72,9 +72,11 @@ on:
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Only a new push to a ledger pull request cancels the run it supersedes. The
|
||||
# weekly schedule and a manual run (both on main) never cancel each other.
|
||||
concurrency:
|
||||
group: user-install-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
install:
|
||||
@@ -107,43 +109,48 @@ jobs:
|
||||
# 0.2.5. The job reported a forgotten publish that had happened two minutes
|
||||
# earlier, which is the most expensive kind of red: it looks exactly like the
|
||||
# real defect this workflow exists to catch.
|
||||
# MEASURED AGAIN 2026-11-12 (0.50.1, ledger #476): the per-version JSON endpoint
|
||||
# of PyPI answered at once, `pip index versions` listed 0.50.1, and the
|
||||
# `pip install --upgrade` of the Linux job still resolved 0.49.1 (the Windows job,
|
||||
# started later, was green). Those are three different pages of the index, and
|
||||
# the job only needs the one pip installs from.
|
||||
#
|
||||
# Bounded at five minutes, so a genuinely forgotten publish still fails. The
|
||||
# PER-VERSION endpoint is the authority; the aggregate `info.version` lags it
|
||||
# by minutes and has its own trap, so this asks for the exact URL.
|
||||
# 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
|
||||
# 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
|
||||
# racing anything, and a wait there would hide a real absence behind five
|
||||
# racing anything, and a wait there would hide a real absence behind ten
|
||||
# minutes of polling.
|
||||
- name: wait for the index to serve this version
|
||||
if: github.event_name == 'pull_request'
|
||||
shell: bash
|
||||
run: |
|
||||
python - <<'PY'
|
||||
import json, os, sys, time, tomllib, urllib.error, urllib.request
|
||||
import os, subprocess, sys, tempfile, time, tomllib
|
||||
dist = tomllib.load(open("pyproject.toml", "rb"))["project"]["name"]
|
||||
version = tomllib.load(open("pyproject.toml", "rb"))["project"]["version"]
|
||||
url = f"https://pypi.org/pypi/{dist}/{version}/json"
|
||||
deadline = time.monotonic() + 300
|
||||
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
|
||||
said = ""
|
||||
while True:
|
||||
n += 1
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=30) as r:
|
||||
if json.load(r).get("urls"):
|
||||
print(f"::notice::{dist} {version} is on the index (attempt {n})")
|
||||
sys.exit(0)
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code != 404:
|
||||
print(f"::warning::index returned HTTP {e.code}; not waiting further")
|
||||
sys.exit(0)
|
||||
except OSError as e:
|
||||
print(f"index unreachable ({e}); retrying")
|
||||
if time.monotonic() >= deadline:
|
||||
print(f"::warning::{dist} {version} still not on the index after 300s; "
|
||||
f"running the checks anyway so a real absence is reported")
|
||||
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})")
|
||||
sys.exit(0)
|
||||
time.sleep(10)
|
||||
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})")
|
||||
sys.exit(1)
|
||||
time.sleep(poll)
|
||||
PY
|
||||
|
||||
- name: Linux runtime libraries for the browser
|
||||
|
||||
+61
-1
@@ -6,6 +6,65 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.51.0] - 2026-11-12
|
||||
|
||||
### Changed
|
||||
- Engine firefox-63 through invisible-core 63.66.0, which this version pins. Behind a proxy: names are resolved by the browser's own
|
||||
DNS-over-HTTPS through the proxy (not by the machine's resolver; checked with a resolver trap on Linux), WebRTC and HTTP/3 send
|
||||
their UDP through the proxy's relay when its UDP was measured to leave from the same address as its TCP, and a proxy whose UDP
|
||||
does not hold (including one whose UDP leaves from another address) is treated as a router that drops it (HTTP/3 falls back to
|
||||
HTTP/2, ICE gathers no server-reflexive candidate). A proxy given to a context declares its own measured UDP exit. The interface
|
||||
list WebRTC gathers is the network the session declares.
|
||||
- A STUN server list can be given at launch (`udp_stun_servers`) for the measurement of the proxy's UDP.
|
||||
- Every context carries the position the core declares for the session (the geolocation override of the context).
|
||||
- The package's launcher and server refuse the two prefs that govern the launch counter, `invisible_firefox.usage_ping.enabled` and
|
||||
`invisible_firefox.usage_ping.url`, in `extra_prefs` (and in the `firefoxUserPrefs` of a served launch). The engine counts launches with
|
||||
an anonymous GET to the `usage-counter` release of the engine's repository (`feder-cr/firefox_antidetect_patch`).
|
||||
|
||||
### Added
|
||||
- `preload_newtab=False` turns off the preloaded New Tab page, on request only (`InvisiblePlaywright`,
|
||||
`invisible_playwright.async_api.InvisiblePlaywright` and `launch_server`): by default the browser keeps it, as a retail Firefox does.
|
||||
A retail Firefox keeps the New Tab page ready in a content process of its own; with the option it is not started. `None` writes
|
||||
nothing, `True` says the retail value aloud, and a `browser.newtab.preload` in `extra_prefs` wins over it. Needs invisible-core
|
||||
63.66.0. Measured on Windows (run 43211271731), on an engine build of the firefox-63 candidate line (not the published engine), one
|
||||
page of a site, five alternating runs: the browser's processes together take 448-454 MB as shipped and 231-239 MB with the option
|
||||
(private memory 301-307 against 158-171 MB).
|
||||
|
||||
### Fixed
|
||||
- A request the browser resumed and whose channel is replaced and cancelled before the replacement starts (a `fetch` with
|
||||
`keepalive`, a beacon) is reported as failed, so it no longer keeps `networkidle` from arriving (engine firefox-63).
|
||||
- A navigation the page overtakes (`location.replace`) ends, and the document that overtook it is told (engine firefox-63).
|
||||
- A click in a frame under a CSS transform is mapped back to the point the frame shows, and a click in a frame scrolls the
|
||||
element in even when its point is inside the main viewport (invisible-core 63.66.0).
|
||||
- `request.resource_type` agrees with the pinned driver: a beacon is `beacon` and a CSP report is `cspreport` (it said `other`).
|
||||
- A download whose finish is seen before its announcement is marked finished: `save_as`, `path` and `failure` used to wait for ever on it.
|
||||
The early finishes the browser keeps are bounded (64) and forgotten with their context. (That the engine sends a finish before the
|
||||
announcement is not proven; the path is defensive.)
|
||||
- The opener kept for the downloads of a target whose adoption failed lives until the engine detaches the target, and none is
|
||||
made for a target already detached.
|
||||
- Tests only: the end-to-end tests that look at content processes ask for the processes of a site by its name and no longer compare two counts.
|
||||
|
||||
### Known differences from stock Playwright
|
||||
What a script that drives the browser can observe, from the configuration of Playwright's own Firefox and of a retail Firefox (no
|
||||
comparison run is saved). The result of a `window.open` (`null` or a window) is read by the page; the others are what the script sees.
|
||||
|
||||
- **A `window.open` from a script with no user gesture is blocked, as in a retail Firefox.** Playwright's own Firefox turns the popup
|
||||
blocker off (`dom.disable_open_during_load` false in its `playwright.cfg`); a retail Firefox keeps it on, and so does this browser. So
|
||||
`page.evaluate("window.open(url)")` returns `null` to the page and no `page` event comes; the same `window.open` from a click opens
|
||||
the popup on both. To get stock's behaviour: open the popup from a click; or pass
|
||||
`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. On Linux (the firefox-63 engine) 0 red in
|
||||
20 runs. In the last two runs with Playwright's own client over a served browser none was red. The defect is in the hand-over of the popup's page in this
|
||||
package, not in the engine; the correction is in 0.51.1. 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.
|
||||
@@ -2171,7 +2230,8 @@ browser reads that decision.
|
||||
repository that builds and ships the engine. The engine's compiled default
|
||||
says the same from the next build. Engines older than firefox-21 do not read
|
||||
the pref and are not counted. To opt out of the ping, set
|
||||
`invisible_firefox.usage_ping.enabled` to `False` in `extra_prefs`.
|
||||
`invisible_firefox.usage_ping.enabled` to `False` in `extra_prefs`. (Since 0.51.0 this is no longer possible: the
|
||||
counter cannot be turned off or redirected.)
|
||||
- **The `browser launches` badge is back.** It was removed in 0.7.2 because the
|
||||
counter behind it lived on a repository that had been deleted, so the badge
|
||||
would have redrawn a frozen number every morning. The counter has lived on
|
||||
|
||||
@@ -214,6 +214,11 @@ not carry raises, and the error lists the ones it does.
|
||||
|
||||
Full list of pinnable keys, how pinning interacts with the Bayesian sampler, and common patterns are in **[docs/pinning.md](docs/pinning.md)**.
|
||||
|
||||
|
||||
### Launch counter
|
||||
|
||||
The engine counts launches with an anonymous GET to the `usage-counter` release of the engine's repository (`feder-cr/firefox_antidetect_patch`) on GitHub. This package's launcher and server refuse the two prefs that govern it, `invisible_firefox.usage_ping.enabled` and `invisible_firefox.usage_ping.url`, in `extra_prefs`.
|
||||
|
||||
---
|
||||
|
||||
## CLI
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
[
|
||||
{"id": "wrapper.e2e.udp", "giro": "G2", "os": ["linux", "windows"], "min_tests": 41, "exact": true, "tests": ["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."},
|
||||
{"id": "wrapper.e2e.udp.exit", "giro": "G2", "os": ["linux"], "min_tests": 9, "exact": true, "tests": ["tests/test_preload_newtab_turns_the_privileged_about_process_off_e2e.py", "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. The preload_newtab test (2) is here because it was seen green as root on Linux (Docker, the engine of round 3); it reads the engine's own process log, which holds on every system, and is moved to wrapper.e2e.udp once it has been seen on Windows."},
|
||||
{"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.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": 195, "exact": true, "tests": ["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": 114, "exact": true, "tests": ["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": 34, "exact": true, "tests": ["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.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.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)."}
|
||||
]
|
||||
+2
-2
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "invisible_playwright"
|
||||
version = "0.50.1"
|
||||
version = "0.51.0"
|
||||
description = "Playwright wrapper for a patched Firefox with deterministic stealth profile."
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
@@ -69,7 +69,7 @@ dependencies = [
|
||||
# metadata; nothing in src/ hardcodes a second copy (tests/test_core_pin.py
|
||||
# fails if one appears). What stays invisible to install-time machinery is the
|
||||
# --no-deps / lockfile residue, and _pin.py is the only layer that sees it.
|
||||
"invisible_core==62.65.0",
|
||||
"invisible_core==63.66.0",
|
||||
# ⛔ playwright is NO LONGER a dependency: since the full fork, the Python
|
||||
# client lives in src/invisible_playwright/_pw/ and its server in
|
||||
# src/invisible_playwright/_juggler/ (no Node driver). Reintroducing it would not visibly
|
||||
|
||||
@@ -180,6 +180,15 @@ class APIRequestContextDispatcher(RefusingDispatcher):
|
||||
#: what the alternative reads like.
|
||||
_HANDLE = "<element handle>"
|
||||
|
||||
#: ⛔ ABSENT, NOT "FINISHED WITH NO ERROR". `BrowserDispatcher._finished_early` keeps the error of a download the
|
||||
#: engine finished before it announced it, and a download that SUCCEEDED has `None` for an error: popping with a
|
||||
#: `None` default and testing `is not None` read a success as "nothing was recorded", so the artifact was never
|
||||
#: marked finished and `save_as`, `path` and `failure` waited forever on a download that was complete. This
|
||||
#: marker is what a pop returns when nothing was recorded, so the two are told apart.
|
||||
_NOT_FINISHED_EARLY = object()
|
||||
#: How many finishes of downloads not announced yet a browser keeps (see `BrowserDispatcher._on_download_finished`).
|
||||
_EARLY_FINISHES_KEPT = 64
|
||||
|
||||
|
||||
def _key_delay(params: Dict) -> Optional[float]:
|
||||
"""The caller's `delay` for a key operation, in milliseconds, or None.
|
||||
@@ -287,6 +296,23 @@ def session_udp_stun_servers(prefs: Dict) -> Optional[list]:
|
||||
return ["%s:%d" % server for server in stun_servers(str(value).split(","))]
|
||||
|
||||
|
||||
def refuse_the_launch_counter(prefs: Dict) -> None:
|
||||
"""The launch counter is part of the package and a client of this server cannot turn it off or point it elsewhere.
|
||||
|
||||
⛔ The core refuses `invisible_firefox.usage_ping.enabled` and `.url` in `extra_prefs` (invisible_core.prefs), but a client of
|
||||
this server sends `firefoxUserPrefs` straight into `session_for_launch`: a stock Playwright `launch(firefox_user_prefs=...)`
|
||||
is put on TOP of the session the server composes, and a launch marked as composed is taken as it comes. Either road would
|
||||
have carried the two prefs past the core. The only thing allowed is the address the core itself wrote, in a composed launch."""
|
||||
from invisible_core.prefs import USAGE_PING_PREFS, USAGE_PING_REFUSAL, USAGE_PING_URL
|
||||
composed = COMPOSED_PREF in prefs
|
||||
for key in USAGE_PING_PREFS:
|
||||
if key not in prefs:
|
||||
continue
|
||||
if composed and key.endswith(".url") and prefs[key] == USAGE_PING_URL:
|
||||
continue
|
||||
raise ValueError("%s: %s" % (key, USAGE_PING_REFUSAL))
|
||||
|
||||
|
||||
def session_for_launch(prefs: Dict, executable: str, proxy: Optional[Dict] = None) -> tuple:
|
||||
"""What a launch writes into its profile and adds to its environment: always a
|
||||
composed session. Returns (prefs, session_env).
|
||||
@@ -316,6 +342,7 @@ def session_for_launch(prefs: Dict, executable: str, proxy: Optional[Dict] = Non
|
||||
measures there (timezone, locale) and the network it declares are the proxy's,
|
||||
not this machine's. The engine is told the proxy by `op_launch`, as before.
|
||||
"""
|
||||
refuse_the_launch_counter(prefs)
|
||||
if COMPOSED_PREF in prefs:
|
||||
return dict(prefs), {}
|
||||
from invisible_playwright._session import default_session
|
||||
@@ -4304,6 +4331,9 @@ class BrowserContextDispatcher(Dispatcher):
|
||||
self.browser.contexts.remove(self)
|
||||
except ValueError:
|
||||
pass
|
||||
forget = getattr(self.browser, "_forget_downloads_of", None)
|
||||
if forget is not None:
|
||||
forget(self.context_id)
|
||||
|
||||
def op_context_init_script(self, params: Dict) -> Any:
|
||||
"""The same, for every page of this context - present and future.
|
||||
@@ -4714,6 +4744,12 @@ class BrowserDispatcher(Dispatcher):
|
||||
self.contexts: List[BrowserContextDispatcher] = []
|
||||
self._artifacts: Dict[str, "ArtifactDispatcher"] = {}
|
||||
self._finished_early: Dict[str, Optional[str]] = {}
|
||||
# ⛔ EVERY DOWNLOAD THE ENGINE ANNOUNCED, WITH ITS CONTEXT, UNTIL IT FINISHES OR ITS CONTEXT ENDS. A finish whose
|
||||
# artifact is gone (its context was already closed when it was announced, or the client released the artifact)
|
||||
# is told apart from a finish that came before its announcement by this, and writes nothing: the early entry is
|
||||
# only for a download not announced yet. Emptied by the finish and by the end of the context, so it holds at
|
||||
# most the downloads in flight.
|
||||
self._download_contexts: Dict[str, Optional[str]] = {}
|
||||
self._downloads_root: Optional[str] = None
|
||||
# ⛔ Adoptions start HERE, not at `add_listener` above. Anything the
|
||||
# engine attached in between predates every context (see the note on
|
||||
@@ -5456,13 +5492,17 @@ class BrowserDispatcher(Dispatcher):
|
||||
# "if it's a new window download, report it on the pop-up's opener"); looking only among the announced pages, as this did,
|
||||
# lost the download altogether.
|
||||
origin = announced or (adoption.opener if adoption is not None else self._gone_openers.get(target))
|
||||
# Popped BEFORE the context check: a download of a context that is gone leaves no artifact to finish, and its
|
||||
# early entry would stay in the dict for the life of the browser.
|
||||
early = self._finished_early.pop(params["uuid"], _NOT_FINISHED_EARLY)
|
||||
if early is _NOT_FINISHED_EARLY:
|
||||
self._download_contexts[params["uuid"]] = params.get("browserContextId")
|
||||
if context is None:
|
||||
return
|
||||
directory = self._downloads_dir(params.get("browserContextId"))
|
||||
artifact = ArtifactDispatcher(self.server, context, params["uuid"],
|
||||
os.path.join(directory, params["uuid"]))
|
||||
self._artifacts[params["uuid"]] = artifact
|
||||
early = self._finished_early.pop(params["uuid"], None)
|
||||
if page is not None or origin is not None:
|
||||
# ⛔ THE ENGINE ENDS A NAVIGATION THAT BECAME A DOWNLOAD WITH NO
|
||||
# EVENT AT ALL (no navigationCommitted, no navigationAborted), so
|
||||
@@ -5496,16 +5536,32 @@ class BrowserDispatcher(Dispatcher):
|
||||
deferred = True
|
||||
if not deferred:
|
||||
origin.emit("download", payload)
|
||||
if early is not None:
|
||||
if early is not _NOT_FINISHED_EARLY:
|
||||
artifact.report_finished(early)
|
||||
|
||||
def _on_download_finished(self, params: Dict) -> None:
|
||||
uuid = params.get("uuid")
|
||||
error = params.get("error") or ("canceled" if params.get("canceled") else None)
|
||||
artifact = self._artifacts.get(params.get("uuid"))
|
||||
if artifact is None:
|
||||
self._finished_early[params.get("uuid")] = error
|
||||
else:
|
||||
announced = uuid in self._download_contexts
|
||||
self._download_contexts.pop(uuid, None)
|
||||
artifact = self._artifacts.get(uuid)
|
||||
if artifact is not None:
|
||||
artifact.report_finished(error)
|
||||
elif not announced:
|
||||
# Not announced yet: kept for its announcement. ⛔ BOUNDED: the engine says a download's creation before its
|
||||
# end on one connection, so an entry can only wait for the handling of the event before it; one whose
|
||||
# announcement never comes (a uuid the engine never announced) is dropped once newer ones push it out,
|
||||
# instead of staying for the life of the browser.
|
||||
self._finished_early[uuid] = error
|
||||
while len(self._finished_early) > _EARLY_FINISHES_KEPT:
|
||||
self._finished_early.pop(next(iter(self._finished_early)))
|
||||
# else: announced, and its artifact is gone (its context was already closed, or the client released it):
|
||||
# nobody can read this finish, so nothing is kept.
|
||||
|
||||
def _forget_downloads_of(self, context_id: Optional[str]) -> None:
|
||||
"""The end of a context: the downloads it announced and that never finished are forgotten with it."""
|
||||
for uuid in [u for u, c in self._download_contexts.items() if c == context_id]:
|
||||
self._download_contexts.pop(uuid, None)
|
||||
|
||||
def _context_send(self, command: str, params: Dict) -> Any:
|
||||
"""A `Browser.*` command about one context. The literal dicts above
|
||||
|
||||
+36
-13
@@ -14,6 +14,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import datetime
|
||||
import ipaddress
|
||||
import random
|
||||
import socket
|
||||
import socketserver
|
||||
import ssl
|
||||
@@ -47,12 +48,46 @@ 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
|
||||
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:])))
|
||||
|
||||
|
||||
class _TcpHandler(socketserver.BaseRequestHandler):
|
||||
"""One TCP connection: the TLS handshake here (not in the accept loop), then HTTP/2 or HTTP/1.1 by the ALPN."""
|
||||
|
||||
@@ -157,19 +192,7 @@ class H3Server:
|
||||
server = self
|
||||
|
||||
# One port for both: the TCP port first, then the same number for UDP.
|
||||
for _ in range(50):
|
||||
tcp = _TcpServer((address, 0), _TcpHandler)
|
||||
port = tcp.server_address[1]
|
||||
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
probe.bind((address, port))
|
||||
probe.close()
|
||||
break
|
||||
except OSError:
|
||||
probe.close()
|
||||
tcp.server_close()
|
||||
else:
|
||||
raise RuntimeError("no port free for both TCP and UDP")
|
||||
tcp, port = _tcp_server_on_a_port_udp_binds(address)
|
||||
self.port = port
|
||||
#: What the TCP answer says about HTTP/3: the same port, for an hour.
|
||||
self.alt_svc = 'h3=":%d"; ma=3600' % port
|
||||
|
||||
+145
-24
@@ -185,27 +185,123 @@ def _who_holds(port: int) -> str:
|
||||
return "; no ss or netstat to say who holds it"
|
||||
|
||||
|
||||
def uid_from_proc_net(text: str, port: int) -> Optional[int]:
|
||||
"""The uid of the socket bound to local port ``port`` in the text of one of /proc/net/{udp,udp6,tcp,tcp6}, or None.
|
||||
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
|
||||
pid: Optional[int]
|
||||
command: str
|
||||
|
||||
|
||||
def row_from_proc_net(text: str, port: int) -> Optional[Tuple[int, int]]:
|
||||
"""``(uid, inode)`` of the socket bound to local port ``port`` in the text of one of /proc/net/{udp,udp6,tcp,tcp6}, or None.
|
||||
|
||||
A row is ``sl local_address rem_address st tx:rx tr:tm retrnsmt uid timeout inode ...``; the local address is
|
||||
``HEX_ADDRESS:HEX_PORT``. The client of a DNS question is a socket still open (it waits for the answer), on an
|
||||
ephemeral port of its own."""
|
||||
for line in text.splitlines()[1:]:
|
||||
fields = line.split()
|
||||
if len(fields) < 8 or ":" not in fields[1]:
|
||||
if len(fields) < 10 or ":" not in fields[1]:
|
||||
continue
|
||||
try:
|
||||
if int(fields[1].rsplit(":", 1)[1], 16) == port:
|
||||
return int(fields[7])
|
||||
return int(fields[7]), int(fields[9])
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def owner_of_the_peer(protocol: str, peer) -> Optional[int]:
|
||||
"""The uid of the process that sent a question to the trap, read where the kernel says it (Linux), or None when
|
||||
the socket cannot be found any more or the machine is not Linux. ``peer`` is the (address, port...) of the client."""
|
||||
def uid_from_proc_net(text: str, port: int) -> Optional[int]:
|
||||
"""The uid of that socket (see :func:`row_from_proc_net`)."""
|
||||
row = row_from_proc_net(text, port)
|
||||
return None if row is None else row[0]
|
||||
|
||||
|
||||
def pid_of_socket_inode(inode: int, proc: str = "/proc") -> Optional[int]:
|
||||
"""The pid of a process that holds the socket with this inode open (root sees every process), or None."""
|
||||
needle = "socket:[%d]" % inode
|
||||
try:
|
||||
entries = os.listdir(proc)
|
||||
except OSError:
|
||||
return None
|
||||
for name in entries:
|
||||
if not name.isdigit():
|
||||
continue
|
||||
fd_dir = os.path.join(proc, name, "fd")
|
||||
try:
|
||||
for fd in os.listdir(fd_dir):
|
||||
try:
|
||||
if os.readlink(os.path.join(fd_dir, fd)) == needle:
|
||||
return int(name)
|
||||
except OSError:
|
||||
continue
|
||||
except OSError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def parent_of(pid: int, proc: str = "/proc") -> Optional[int]:
|
||||
"""The parent of a process, from /proc/<pid>/stat (the name between parentheses may hold spaces), or None."""
|
||||
try:
|
||||
with open(os.path.join(proc, str(pid), "stat"), encoding="utf-8", errors="replace") as handle:
|
||||
return int(handle.read().rsplit(")", 1)[1].split()[1])
|
||||
except (OSError, ValueError, IndexError):
|
||||
return None
|
||||
|
||||
|
||||
def command_of(pid: int, proc: str = "/proc") -> str:
|
||||
"""What a process is, for a message: its name and the start of its command line."""
|
||||
try:
|
||||
with open(os.path.join(proc, str(pid), "comm"), encoding="utf-8", errors="replace") as handle:
|
||||
name = handle.read().strip()
|
||||
with open(os.path.join(proc, str(pid), "cmdline"), "rb") as handle:
|
||||
line = b" ".join(handle.read().split(b"\0")).decode("utf-8", "replace").strip()
|
||||
return ("%s: %s" % (name, line))[:120]
|
||||
except OSError:
|
||||
return "(gone)"
|
||||
|
||||
|
||||
def descends_from(pid: int, root: int, parent=parent_of) -> bool:
|
||||
"""Whether ``pid`` is ``root`` or one of its descendants, going up the parents (at most 64 steps)."""
|
||||
for _ in range(64):
|
||||
if pid == root:
|
||||
return True
|
||||
up = parent(pid)
|
||||
if up is None or up <= 1 or up == pid:
|
||||
return False
|
||||
pid = up
|
||||
return False
|
||||
|
||||
|
||||
def is_a_browser_process(pid: int, proc: str = "/proc") -> bool:
|
||||
"""Whether a process is the browser's own (the main process, ``firefox``, or ``firefox-bin``), by its name in /proc/<pid>/comm.
|
||||
Its children (content, socket, forkserver) are found by their parents."""
|
||||
try:
|
||||
with open(os.path.join(proc, str(pid), "comm"), encoding="utf-8", errors="replace") as handle:
|
||||
return handle.read().strip() in ("firefox", "firefox-bin", "firefox.exe")
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def under_a_browser(pid: int, root: int, parent=parent_of, is_browser=is_a_browser_process) -> bool:
|
||||
"""Whether ``pid`` is a browser process or one of its descendants, going up the parents and stopping at ``root`` (the test
|
||||
process: it is NOT the browser, and neither is anything it runs that is not a browser, like the core's own download of a
|
||||
database) or at a process with no parent known (at most 64 steps)."""
|
||||
for _ in range(64):
|
||||
if is_browser(pid):
|
||||
return True
|
||||
if pid == root:
|
||||
return False
|
||||
up = parent(pid)
|
||||
if up is None or up <= 1 or up == pid:
|
||||
return False
|
||||
pid = up
|
||||
return False
|
||||
|
||||
|
||||
def who_asked(protocol: str, peer) -> Optional[Asker]:
|
||||
"""Who sent a question to the trap, read where the kernel says it (Linux): the row of the client's socket in /proc/net
|
||||
gives the user and the inode, and the inode gives the process that holds it. None off Linux or when the socket is
|
||||
gone. ``peer`` is the (address, port...) of the client."""
|
||||
if not sys.platform.startswith("linux"):
|
||||
return None
|
||||
six = ":" in str(peer[0])
|
||||
@@ -213,27 +309,40 @@ def owner_of_the_peer(protocol: str, peer) -> Optional[int]:
|
||||
for name in names:
|
||||
try:
|
||||
with open("/proc/net/" + name, encoding="utf-8") as table:
|
||||
uid = uid_from_proc_net(table.read(), int(peer[1]))
|
||||
row = row_from_proc_net(table.read(), int(peer[1]))
|
||||
except OSError:
|
||||
continue
|
||||
if uid is not None:
|
||||
return uid
|
||||
if row is not None:
|
||||
uid, inode = row
|
||||
pid = pid_of_socket_inode(inode) if inode else None
|
||||
return Asker(uid, pid, command_of(pid) if pid is not None else "")
|
||||
return None
|
||||
|
||||
|
||||
def owner_of_the_peer(protocol: str, peer) -> Optional[int]:
|
||||
"""The uid of the process that sent a question to the trap (see :func:`who_asked`), or None."""
|
||||
asker = who_asked(protocol, peer)
|
||||
return None if asker is None else asker.uid
|
||||
|
||||
|
||||
class ResolverTrap:
|
||||
"""A resolver on loopback that counts what it is asked. See the module docstring.
|
||||
|
||||
It counts what the processes of the USER THAT RUNS THE TEST ask (``only_uid``, by default the effective uid: under
|
||||
``sudo`` the browser and the test are root). A question from a socket of another user is answered and listed in
|
||||
:attr:`foreign`, not counted: /etc/resolv.conf is the machine's, and on a CI runner the agent of the runner asks for
|
||||
github.com through it (run 43188313516: the browser was blamed for names it never asked). There is no list of names.
|
||||
A question whose socket cannot be found any more counts as the browser's."""
|
||||
It counts what the BROWSER asks, and the test says "the browser asked the resolver of the machine". The browser is found from
|
||||
the socket the question came from (its inode, the process that holds it, its parents up to ``root_pid``, by default the
|
||||
test process): a question counts if that process is the browser or descends from it. A question from any other process is
|
||||
answered and listed in :attr:`foreign` with its pid and command, not counted: /etc/resolv.conf is the machine's, and on a
|
||||
CI runner the agent of the runner, even as root, asks for github.com through it; and the test process's own python (the
|
||||
core, which asks github.com for the latest GeoIP tag when no database is given) is not the browser either (runs
|
||||
43188313516, 43211837926: the browser was blamed for names it never asked, and a user filter cannot tell them apart). There
|
||||
is no list of names. A question whose process cannot be traced is judged by its user (``only_uid``, by default the
|
||||
effective uid), and one whose socket cannot be found any more counts as the browser's."""
|
||||
|
||||
available, reason = _trap_capability()
|
||||
|
||||
def __init__(self, answers: Optional[Dict[str, str]] = None, *, port: int = 53,
|
||||
rewrite_resolv_conf: bool = True, only_uid: Optional[int] = None, owner_of=None):
|
||||
rewrite_resolv_conf: bool = True, only_uid: Optional[int] = None, owner_of=None,
|
||||
root_pid: Optional[int] = None, parent_of_pid=None, is_browser=None):
|
||||
self.answers = {k.lower(): v for k, v in (answers or {}).items()}
|
||||
self.port = port
|
||||
#: The loopback address the trap listens on once it is bound (see TRAP_ADDRESSES).
|
||||
@@ -242,9 +351,12 @@ class ResolverTrap:
|
||||
#: Every question: (name, qtype, "udp"|"tcp").
|
||||
self.queries: List[DohQuery] = []
|
||||
#: The questions of other users' processes: (query, uid). Answered, not counted.
|
||||
self.foreign: List[Tuple[DohQuery, int]] = []
|
||||
self.foreign: List[Tuple[DohQuery, Asker]] = []
|
||||
self.root_pid = root_pid if root_pid is not None else os.getpid()
|
||||
self._parent_of = parent_of_pid or parent_of
|
||||
self._is_browser = is_browser or is_a_browser_process
|
||||
self.only_uid = only_uid if only_uid is not None else (os.geteuid() if hasattr(os, "geteuid") else None)
|
||||
self._owner_of = owner_of or owner_of_the_peer
|
||||
self._owner_of = owner_of or who_asked
|
||||
self._lock = threading.Lock()
|
||||
self._sockets: List[socket.socket] = []
|
||||
#: The threads that answer on `_sockets`, and the flag that ends them: see `_restore`.
|
||||
@@ -269,8 +381,9 @@ class ResolverTrap:
|
||||
with self._lock:
|
||||
seen = ", ".join("%s/%d (%s)" % q for q in self.queries) or "nothing"
|
||||
if self.foreign:
|
||||
seen += " [and %d question(s) of other users' processes, not counted: %s]" % (
|
||||
len(self.foreign), ", ".join(sorted({q.name for q, _ in self.foreign})))
|
||||
seen += " [and %d question(s) of other processes, not counted: %s]" % (
|
||||
len(self.foreign), "; ".join(sorted({"%s from pid %s (uid %d) %s" % (
|
||||
q.name, a.pid if a.pid is not None else "?", a.uid, a.command or "") for q, a in self.foreign})))
|
||||
return seen
|
||||
|
||||
# --- control -------------------------------------------------------------------------------------------------
|
||||
@@ -382,12 +495,20 @@ class ResolverTrap:
|
||||
query = parse_query(message)
|
||||
except ValueError:
|
||||
return None
|
||||
owner = self._owner_of(protocol, peer) if peer is not None and self.only_uid is not None else None
|
||||
asker = self._owner_of(protocol, peer) if peer is not None else None
|
||||
if isinstance(asker, int): # an owner given as a bare uid
|
||||
asker = Asker(asker, None, "")
|
||||
ours = True
|
||||
if asker is not None:
|
||||
if asker.pid is not None:
|
||||
ours = under_a_browser(asker.pid, self.root_pid, self._parent_of, self._is_browser)
|
||||
elif self.only_uid is not None:
|
||||
ours = asker.uid == self.only_uid
|
||||
with self._lock:
|
||||
if owner is not None and owner != self.only_uid:
|
||||
self.foreign.append((DohQuery(query.name, query.qtype, protocol), owner))
|
||||
else:
|
||||
if ours:
|
||||
self.queries.append(DohQuery(query.name, query.qtype, protocol))
|
||||
else:
|
||||
self.foreign.append((DohQuery(query.name, query.qtype, protocol), asker))
|
||||
if query.name in self.answers:
|
||||
return answer_for(self.answers, query)
|
||||
return build_response(query, RCODE_REFUSED)
|
||||
|
||||
+54
-21
@@ -1,16 +1,26 @@
|
||||
"""Which of the engine's processes host a site: what the e2e tests that count processes read.
|
||||
"""Which of the engine's processes host a site, told by the name of the site: what the e2e tests that look at processes read.
|
||||
|
||||
A content process is not a site's by being new. The engine keeps preallocated content processes
|
||||
(`dom.ipc.processPrelaunch.fission.number`, 3), hands one to a site when a site needs a process, and starts
|
||||
another to refill the pool whenever it gets to it, so a pid that appears between two reads is often that refill.
|
||||
On Linux the process says which it is: `ContentChild::SetProcessName` names it by its remote type with
|
||||
`prctl(PR_SET_NAME)` (ipc/glue/ProcessUtils_linux.cpp), "Isolated Web Co" once it hosts a site of strategy 1
|
||||
(`webIsolated=<site>`), "Web Content" while it is preallocated. Windows names no process
|
||||
(ProcessUtils_none.cpp): a test that counts sites skips there and says so.
|
||||
Counting processes between two reads does not tell a site's process from the browser's own. The browser starts
|
||||
content processes for itself: it refills the pool of preallocated ones (`dom.ipc.processPrelaunch.fission.number`)
|
||||
whenever it gets to it, and the New Tab page starts a process for a Mozilla site of its own (remote type
|
||||
`webIsolated=https://mozgcp.net`, born about a second after the process of the New Tab page, with any page, even
|
||||
about:blank). Under load that process arrives after the first read of a test, and "the set of processes changed"
|
||||
read it as the effect of the frame under test: the same-site control was red in 14 of 30 runs of the whole e2e suite
|
||||
(`[P] -> [P, P2]`), and "at least one new process" for a cross-site frame was satisfied by that process alone.
|
||||
|
||||
Measured on firefox-62 (Linux): a cross-site frame renames one preallocated process and a new "Web Content"
|
||||
refills the pool; a same-site frame changes neither; a closed context leaves no "Isolated Web Co", while the
|
||||
pool of "Web Content" fills up behind it in about half the runs.
|
||||
So a test asks for the processes of ONE site, by name. With the pref `fission.processSiteNames` on (`NAMED_BY_SITE`,
|
||||
test-only: the product never sets it) a content process that hosts a site is named by that site
|
||||
(`ContentChild::SetProcessName`, dom/ipc/ContentChild.cpp: a leading `https://` is dropped), and on Linux
|
||||
`prctl(PR_SET_NAME)` keeps 15 characters (ipc/glue/ProcessUtils_linux.cpp). Measured on firefox-62 (Linux):
|
||||
|
||||
- the process of `http://a.test` in a Playwright context is named `http://a.test^u`: the site, then the start of
|
||||
`^userContextId=N`, cut at 15 characters;
|
||||
- the process the New Tab page starts is named `mozgcp.net`;
|
||||
- a process with no site keeps its type: `Web Content`, `Privileged Cont`, `WebExtensions`.
|
||||
|
||||
The process gets its name before any document loads in it, so when a page of the site has run, its process already
|
||||
answers to the site. Windows names no process (ProcessUtils_none.cpp): a test that looks at sites skips there and
|
||||
says so.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -19,14 +29,37 @@ import sys
|
||||
|
||||
import pytest
|
||||
|
||||
#: The name a content process of strategy 1 takes once it hosts a site (PR_SET_NAME keeps 15 characters of
|
||||
#: "Isolated Web Content"). A preallocated one is "Web Content" until a site is given to it.
|
||||
SITE_PROCESS_NAME = "Isolated Web Co"
|
||||
#: The pref overlay that names a content process by the site it hosts. Test-only.
|
||||
NAMED_BY_SITE = {"fission.processSiteNames": True}
|
||||
|
||||
#: What PR_SET_NAME keeps of a process name on Linux.
|
||||
NAME_LENGTH = 15
|
||||
|
||||
|
||||
def site_pids(processes, engine_dir=None):
|
||||
"""The pids, among `processes` (psutil-like), of the content processes that host a site; with `engine_dir`,
|
||||
only those of the engine in that directory."""
|
||||
def name_of_site(site):
|
||||
"""What the process name of `site` starts with: the site without a leading `https://`, cut at 15 characters."""
|
||||
if site.startswith("https://"):
|
||||
site = site[len("https://"):]
|
||||
return site[:NAME_LENGTH]
|
||||
|
||||
|
||||
def hosts_site(name, site):
|
||||
"""True when a process called `name` is a process of `site`.
|
||||
|
||||
The name is the prefix itself, or the prefix followed by `^` (the start of `^userContextId=N`). When the prefix is
|
||||
shorter than 15 characters the next character has to be `^`, so `http://a.test` does not match a process of
|
||||
`http://a.testing.example`."""
|
||||
prefix = name_of_site(site)
|
||||
if name == prefix:
|
||||
return True
|
||||
if not name.startswith(prefix):
|
||||
return False
|
||||
return len(prefix) >= NAME_LENGTH or name[len(prefix)] == "^"
|
||||
|
||||
|
||||
def site_pids(processes, site, engine_dir=None):
|
||||
"""The pids, among `processes` (psutil-like), of the content processes (`-contentproc ... tab`) that host `site`;
|
||||
with `engine_dir`, only those of the engine in that directory."""
|
||||
import psutil
|
||||
|
||||
pids = set()
|
||||
@@ -37,13 +70,13 @@ def site_pids(processes, engine_dir=None):
|
||||
name, cmd = proc.name(), proc.cmdline()
|
||||
except psutil.Error:
|
||||
continue
|
||||
if "-contentproc" in cmd and cmd and cmd[-1] == "tab" and name == SITE_PROCESS_NAME:
|
||||
if "-contentproc" in cmd and cmd and cmd[-1] == "tab" and hosts_site(name, site):
|
||||
pids.add(proc.pid)
|
||||
return pids
|
||||
|
||||
|
||||
def site_processes_below(root_pid, engine_dir=None):
|
||||
"""The pids of the processes below `root_pid` that host a site. Off Linux the test skips: no name says it."""
|
||||
def site_processes_below(root_pid, site, engine_dir=None):
|
||||
"""The pids of the processes below `root_pid` that host `site`. Off Linux the test skips: no name says it."""
|
||||
import psutil
|
||||
|
||||
if not sys.platform.startswith("linux"):
|
||||
@@ -52,4 +85,4 @@ def site_processes_below(root_pid, engine_dir=None):
|
||||
children = psutil.Process(root_pid).children(recursive=True)
|
||||
except psutil.Error:
|
||||
return set()
|
||||
return site_pids(children, engine_dir)
|
||||
return site_pids(children, site, engine_dir)
|
||||
+36
-21
@@ -10,6 +10,7 @@ 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
|
||||
@@ -18,6 +19,12 @@ 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)
|
||||
|
||||
|
||||
class Witness:
|
||||
def __init__(self, address: str, port: int = 0) -> None:
|
||||
@@ -26,36 +33,44 @@ class Witness:
|
||||
self.tcp: List[Tuple[str, int]] = []
|
||||
self._lock = threading.Lock()
|
||||
self._closed = False
|
||||
# One port number for both: the TCP listener takes one, the UDP socket the same (retry with another if it is busy).
|
||||
# TCP FIRST: Windows keeps big excluded ranges for TCP and hands out ephemeral ports in sequence, so a UDP-first pick
|
||||
# can land in a range TCP may not bind (WinError 10013), again and again (the resolver trap does the same).
|
||||
last: Exception = OSError("no port")
|
||||
for _ in range(20):
|
||||
# One port number for both, TCP and UDP. Each try binds TCP and then UDP on the same number; if either is refused, both
|
||||
# are released and another number is tried. The first try is the system's own pick (TCP, port 0). The others are drawn
|
||||
# at random: Windows hands out ephemeral TCP ports in sequence and keeps excluded ranges of a hundred ports for UDP
|
||||
# inside the same zone, so "the next pick" lands in the same refused range again and again (WinError 10013, twenty
|
||||
# tries in a row on a work machine). A given ``port`` is tried once and its refusal is raised as it is.
|
||||
self._udp, self._tcp, self.port = self._bind_both(address, port)
|
||||
threading.Thread(target=self._serve_udp, daemon=True).start()
|
||||
threading.Thread(target=self._serve_tcp, daemon=True).start()
|
||||
|
||||
@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))
|
||||
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
udp = None
|
||||
try:
|
||||
if sys.platform != "win32": # on Windows SO_REUSEADDR is "share the port": it breaks bind
|
||||
tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
tcp.bind((address, port))
|
||||
tcp.bind((address, wanted))
|
||||
chosen = tcp.getsockname()[1]
|
||||
tcp.listen(16)
|
||||
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
udp.bind((address, chosen))
|
||||
except OSError:
|
||||
udp.close()
|
||||
raise
|
||||
udp.bind((address, chosen))
|
||||
tcp.listen(16)
|
||||
return udp, tcp, chosen
|
||||
except OSError as exc:
|
||||
tcp.close()
|
||||
last = exc
|
||||
if port:
|
||||
tcp.close()
|
||||
if udp is not None:
|
||||
udp.close()
|
||||
raise
|
||||
continue
|
||||
self._udp, self._tcp, self.port = udp, tcp, chosen
|
||||
break
|
||||
else:
|
||||
raise last
|
||||
threading.Thread(target=self._serve_udp, daemon=True).start()
|
||||
threading.Thread(target=self._serve_tcp, daemon=True).start()
|
||||
refusals.append("%s: %s" % (wanted or "system pick", exc))
|
||||
tcp.close()
|
||||
if udp is not None:
|
||||
udp.close()
|
||||
raise OSError("the witness found no port number on %s where both TCP and UDP bind, after %d tries; the last refusals: %s"
|
||||
% (address, TRIES, "; ".join(refusals[-3:])))
|
||||
|
||||
# --- what a test reads ------------------------------------------------------------------------------------------
|
||||
def heard(self) -> Dict[str, list]:
|
||||
|
||||
@@ -10,10 +10,13 @@ ones that stay.
|
||||
The test closes five such contexts in a row. While each page is open it counts the processes that host a site
|
||||
(at least one: the page's, or the count would prove nothing), and once `close` has answered it waits a few
|
||||
seconds for them to be gone: none may be left (on the old engine every context leaves its own, one more each
|
||||
time). Only the processes that host a site are counted (tests/_processes.py): the engine refills its pool of
|
||||
preallocated content processes behind a closed context, in about half the runs, and counting every content
|
||||
process read that refill as a leak ([2, 2, 2, 5, 5] on the e2e of the 0.50.0 commit, three "Web Content" and no
|
||||
site left). Off Linux the test skips: no other system names the process.
|
||||
time). Only the processes of the page's site are counted, asked for by name (tests/_processes.py): the browser is
|
||||
launched with `fission.processSiteNames`, which names a content process by the site it hosts (the page is served
|
||||
from `http://127.0.0.1:<port>`; a site never includes the port). The browser starts processes of its own, and
|
||||
counting every content process, or every one that hosts any site, read them as a leak ([2, 2, 2, 5, 5] on the e2e
|
||||
of the 0.50.0 commit, three "Web Content" and no site left; a process for a Mozilla site started by the New Tab
|
||||
page). If the name were not what the test expects, the count while the page is open would be 0 and the first assert
|
||||
says so. Off Linux the test skips: no other system names the process.
|
||||
|
||||
The engine that does it is not published when this file is written: `engine_at_least` makes the test wait for
|
||||
it, and on an older engine it is skipped, never passed.
|
||||
@@ -30,12 +33,13 @@ import pytest
|
||||
import websockets # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
|
||||
from websockets.asyncio.client import connect # noqa: E402
|
||||
|
||||
from _processes import site_processes_below # noqa: E402
|
||||
from _processes import NAMED_BY_SITE, site_processes_below # noqa: E402
|
||||
from _servers import LocalServer # noqa: E402
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
ENGINE_WITH_THE_FIX = "firefox-61"
|
||||
SITE = "http://127.0.0.1" # the site of the served page; a site never includes the port
|
||||
|
||||
PAGE = (b"<!doctype html><title>sw</title><script>"
|
||||
b"navigator.serviceWorker.register('/sw.js').catch(e => { document.title = 'ERR ' + e; });</script>")
|
||||
@@ -98,10 +102,11 @@ def test_closed_contexts_with_a_never_stopping_service_worker_leave_no_process(f
|
||||
|
||||
server, base = _serve()
|
||||
launched = launch_server(host="127.0.0.1", port=0, headless=True, virtual_display=False, humanize=False,
|
||||
seed=4266, binary_path=firefox_binary, launch_timeout_ms=180_000)
|
||||
seed=4266, binary_path=firefox_binary, launch_timeout_ms=180_000,
|
||||
extra_prefs=NAMED_BY_SITE)
|
||||
|
||||
def sites():
|
||||
return site_processes_below(launched.process.pid)
|
||||
return site_processes_below(launched.process.pid, SITE)
|
||||
|
||||
async def drive():
|
||||
opened, left = [], []
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
"""A download the engine finished BEFORE it announced it is finished once it is announced.
|
||||
|
||||
`BrowserDispatcher._on_download_finished` keeps the error of a download whose artifact does not exist yet, and
|
||||
`_on_download_created` hands it to the artifact later. A download that succeeded has no error (`None`), and the old
|
||||
code read that as "nothing was kept": the artifact was never marked finished, so `save_as`, `path` and `failure`
|
||||
waited forever on a complete file (seen on tiny downloads, where the transfer ends before the announcement is handled).
|
||||
|
||||
No browser and no socket: the two real methods run on a stand-in that carries the attributes they read, and the
|
||||
artifact is a fake that records what it was told.
|
||||
|
||||
Known-bad input: the code before 6a50ad1 -> (a) and (d) are red; the code of 6a50ad1 -> (e), (f) and (g) are red.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import types
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright._juggler import server as juggler_server
|
||||
from invisible_playwright._juggler.server import BrowserDispatcher
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
CONTEXT = "ctx-1"
|
||||
|
||||
|
||||
class FakeArtifact:
|
||||
"""What `ArtifactDispatcher` is to the two methods: built with (server, context, uuid, path), told once."""
|
||||
|
||||
def __init__(self, server, context, uuid, path):
|
||||
self.uuid = uuid
|
||||
self.path = path
|
||||
self.channel = {"guid": "artifact@" + uuid}
|
||||
self.finished = threading.Event()
|
||||
self.reports = []
|
||||
|
||||
def report_finished(self, error):
|
||||
self.reports.append(error)
|
||||
self.finished.set()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def browser(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(juggler_server, "ArtifactDispatcher", FakeArtifact)
|
||||
return types.SimpleNamespace(
|
||||
contexts=[types.SimpleNamespace(context_id=CONTEXT)],
|
||||
_targets_lock=threading.Lock(),
|
||||
_page_targets={},
|
||||
_adoptions={},
|
||||
_gone_openers={},
|
||||
_artifacts={},
|
||||
_finished_early={},
|
||||
_download_contexts={},
|
||||
server=object(),
|
||||
_downloads_dir=lambda context_id: str(tmp_path),
|
||||
)
|
||||
|
||||
|
||||
def _created(browser, uuid, context=CONTEXT):
|
||||
BrowserDispatcher._on_download_created(
|
||||
browser, {"uuid": uuid, "browserContextId": context, "pageTargetId": "t1",
|
||||
"url": "http://x/f", "suggestedFileName": "f.bin"})
|
||||
|
||||
|
||||
def _finished(browser, uuid, **extra):
|
||||
BrowserDispatcher._on_download_finished(browser, dict({"uuid": uuid}, **extra))
|
||||
|
||||
|
||||
def test_a_download_that_succeeded_before_it_was_announced_is_finished(browser):
|
||||
_finished(browser, "u1")
|
||||
_created(browser, "u1")
|
||||
artifact = browser._artifacts["u1"]
|
||||
assert artifact.finished.wait(2), "the artifact was never marked finished: save_as would wait forever"
|
||||
assert artifact.reports == [None]
|
||||
assert browser._finished_early == {}
|
||||
|
||||
|
||||
def test_a_download_canceled_before_it_was_announced_is_finished_with_the_reason(browser):
|
||||
_finished(browser, "u2", canceled=True)
|
||||
_created(browser, "u2")
|
||||
artifact = browser._artifacts["u2"]
|
||||
assert artifact.finished.wait(2)
|
||||
assert artifact.reports == ["canceled"]
|
||||
assert browser._finished_early == {}
|
||||
|
||||
|
||||
def test_a_download_that_failed_before_it_was_announced_keeps_its_error(browser):
|
||||
_finished(browser, "u3", error="NS_ERROR_NET_RESET")
|
||||
_created(browser, "u3")
|
||||
assert browser._artifacts["u3"].reports == ["NS_ERROR_NET_RESET"]
|
||||
|
||||
|
||||
def test_a_download_announced_and_then_finished_is_finished(browser):
|
||||
_created(browser, "u4")
|
||||
artifact = browser._artifacts["u4"]
|
||||
assert not artifact.finished.is_set()
|
||||
_finished(browser, "u4")
|
||||
assert artifact.finished.wait(2)
|
||||
assert artifact.reports == [None]
|
||||
assert browser._finished_early == {}
|
||||
|
||||
|
||||
def test_a_download_announced_and_not_finished_stays_open(browser):
|
||||
_created(browser, "u5")
|
||||
assert not browser._artifacts["u5"].finished.is_set()
|
||||
assert browser._finished_early == {}
|
||||
|
||||
|
||||
def test_an_early_finish_of_a_context_that_does_not_exist_is_not_kept(browser):
|
||||
_finished(browser, "u6")
|
||||
assert "u6" in browser._finished_early
|
||||
_created(browser, "u6", context="gone")
|
||||
assert "u6" not in browser._artifacts
|
||||
assert browser._finished_early == {}
|
||||
|
||||
|
||||
def test_e_a_finish_after_the_announcement_of_a_gone_context_keeps_nothing(browser):
|
||||
"""(e) The context was already closed when the download was announced: no artifact, and the finish that follows has no
|
||||
reader. It used to be kept as an early finish for the life of the browser."""
|
||||
_created(browser, "u7", context="ctx-gone")
|
||||
_finished(browser, "u7")
|
||||
assert browser._finished_early == {} and browser._download_contexts == {}
|
||||
|
||||
|
||||
def test_f_a_finish_after_the_artifact_was_released_keeps_nothing(browser):
|
||||
"""(f) The client released the artifact (its index entry is gone) before the engine said the download ended."""
|
||||
_created(browser, "u8")
|
||||
browser._artifacts.pop("u8") # what ArtifactDispatcher.released() does
|
||||
_finished(browser, "u8")
|
||||
assert browser._finished_early == {} and browser._download_contexts == {}
|
||||
|
||||
|
||||
def test_g_finishes_never_announced_are_bounded(browser):
|
||||
"""(g) uuids the engine never announced: their early finishes are dropped once newer ones push them out."""
|
||||
for n in range(juggler_server._EARLY_FINISHES_KEPT + 10):
|
||||
_finished(browser, "never-%d" % n)
|
||||
assert len(browser._finished_early) == juggler_server._EARLY_FINISHES_KEPT
|
||||
assert "never-0" not in browser._finished_early and "never-%d" % (juggler_server._EARLY_FINISHES_KEPT + 9) in browser._finished_early
|
||||
|
||||
|
||||
def test_h_the_end_of_a_context_forgets_its_unfinished_downloads(browser):
|
||||
"""(h) A download announced and never finished: the end of its context forgets it (no growth across contexts)."""
|
||||
browser._forget_downloads_of = lambda context_id: BrowserDispatcher._forget_downloads_of(browser, context_id)
|
||||
_created(browser, "u9")
|
||||
_created(browser, "u10", context="ctx-gone")
|
||||
BrowserDispatcher._forget_downloads_of(browser, CONTEXT)
|
||||
assert list(browser._download_contexts) == ["u10"]
|
||||
@@ -0,0 +1,50 @@
|
||||
"""A client of the server cannot turn the launch counter off or point it elsewhere (no browser).
|
||||
|
||||
The core refuses the two prefs of the counter in ``extra_prefs``; the server takes ``firefoxUserPrefs`` from a client and, for a launch
|
||||
that names no session, puts them on top of the session it composes, and for a marked launch takes them as they come. Both roads are
|
||||
closed here, at ``session_for_launch``, with the core's own refusal.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_core.prefs import USAGE_PING_PREFS, USAGE_PING_REFUSAL, USAGE_PING_URL
|
||||
from invisible_playwright._juggler import server
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ENABLED, URL = USAGE_PING_PREFS
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def composed_session(monkeypatch):
|
||||
"""The session the server composes for an unmarked launch, without composing one (that needs an engine)."""
|
||||
import invisible_playwright._session as session
|
||||
monkeypatch.setattr(session, "default_session", lambda executable, proxy=None: ({URL: USAGE_PING_URL, "x": 1}, {}))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pref,value", [(ENABLED, False), (ENABLED, True), (ENABLED, None), (URL, "https://example.invalid/x"), (URL, None)])
|
||||
@pytest.mark.parametrize("marked", [False, True], ids=["bare launch", "marked launch"])
|
||||
def test_a_client_cannot_send_the_counter_prefs(pref, value, marked):
|
||||
prefs = {pref: value}
|
||||
if marked:
|
||||
prefs[server.COMPOSED_PREF] = True
|
||||
with pytest.raises(ValueError) as refused:
|
||||
server.session_for_launch(prefs, "firefox")
|
||||
assert pref in str(refused.value) and USAGE_PING_REFUSAL in str(refused.value)
|
||||
|
||||
|
||||
def test_the_address_the_core_wrote_travels_in_a_marked_launch():
|
||||
prefs, _env = server.session_for_launch({server.COMPOSED_PREF: True, URL: USAGE_PING_URL, "y": 2}, "firefox")
|
||||
assert prefs[URL] == USAGE_PING_URL and prefs["y"] == 2 and ENABLED not in prefs
|
||||
|
||||
|
||||
def test_a_bare_launch_gets_the_core_address_and_the_clients_other_prefs():
|
||||
prefs, _env = server.session_for_launch({"z": 3}, "firefox")
|
||||
assert prefs[URL] == USAGE_PING_URL and prefs["z"] == 3 and ENABLED not in prefs
|
||||
|
||||
|
||||
def test_the_same_address_in_a_bare_launch_is_still_refused():
|
||||
"""Only the address the CORE wrote, inside a composed launch, is let through: a bare client that names it is refused too."""
|
||||
with pytest.raises(ValueError):
|
||||
server.session_for_launch({URL: USAGE_PING_URL}, "firefox")
|
||||
@@ -0,0 +1,92 @@
|
||||
"""A proof of use, not of the order: on one connection the engine says a download's creation before its end, so this test does not force a finish before the announcement (the unit test test_a_download_finished_before_it_was_announced_is_finished.py does). It shows that tiny downloads, the case where the end comes soonest, are saved whole through a served browser.
|
||||
|
||||
Tiny downloads through a served browser are saved by a stock client, every one.
|
||||
|
||||
One served browser, a stock Playwright client, a page that links to a 300-byte attachment and to a 1-byte one:
|
||||
ten downloads of each, each saved and compared byte for byte.
|
||||
|
||||
Not a known-bad input for the order: it is not expected to be red on the server before the fix (the unit test is the proof of
|
||||
the fix); it guards the use.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import importlib
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
BODIES = {"big": bytes(range(256)) + b"\x01" * 44, "one": b"Z"}
|
||||
COUNT = 10
|
||||
|
||||
|
||||
def _serve():
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
kind = self.path.strip("/").split("/")[0].split("?")[0]
|
||||
if kind in BODIES:
|
||||
body = BODIES[kind]
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "application/octet-stream")
|
||||
self.send_header("content-disposition", 'attachment; filename="%s.bin"' % kind)
|
||||
self.send_header("content-length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
links = "".join('<a id="%s%d" href="/%s?n=%d">%s</a> ' % (k, i, k, i, k)
|
||||
for k in BODIES for i in range(COUNT))
|
||||
page = ("<!doctype html><title>d</title>" + links).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "text/html")
|
||||
self.send_header("content-length", str(len(page)))
|
||||
self.end_headers()
|
||||
self.wfile.write(page)
|
||||
|
||||
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
srv.daemon_threads = True
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
return srv, "http://127.0.0.1:%d/" % srv.server_address[1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def served():
|
||||
srv, url = _serve()
|
||||
try:
|
||||
yield url
|
||||
finally:
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
def test_ten_tiny_downloads_of_each_size_are_saved_through_a_served_browser(firefox_binary, served, tmp_path):
|
||||
try: # the stock client (a pinned dev dependency), imported by name: the fork's guard forbids a static import
|
||||
sync_playwright = importlib.import_module("playwright.sync_api").sync_playwright
|
||||
except ImportError as exc:
|
||||
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc,
|
||||
pytrace=False)
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome")
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.firefox.connect(server.ws_endpoint)
|
||||
try:
|
||||
page = browser.new_context(accept_downloads=True).new_page()
|
||||
page.goto(served, timeout=30_000)
|
||||
for kind, body in BODIES.items():
|
||||
for i in range(COUNT):
|
||||
with page.expect_download(timeout=20_000) as info:
|
||||
page.click("#%s%d" % (kind, i))
|
||||
target = tmp_path / ("%s%d.bin" % (kind, i))
|
||||
info.value.save_as(target)
|
||||
assert target.read_bytes() == body, (kind, i)
|
||||
assert info.value.failure() is None
|
||||
finally:
|
||||
browser.close()
|
||||
finally:
|
||||
server.close()
|
||||
@@ -0,0 +1,329 @@
|
||||
"""One CI run per commit, and a new push replaces the run it supersedes.
|
||||
|
||||
A pull request is covered by `pull_request`; `push` stays only for main and for
|
||||
the tags `publish.yml` starts on. What the workflows promise, checked here on
|
||||
the files themselves:
|
||||
|
||||
1. A workflow with a `pull_request` trigger has no `push` trigger that also
|
||||
matches feature branches (an unfiltered push, `**`, or a wildcard).
|
||||
2. The push triggers the release reads are still there. `publish.yml` asks the
|
||||
checks API for the `e2e` check-run of the commit being tagged
|
||||
(scripts/e2e_is_green.py), so `e2e.yml` must run on every push to main with
|
||||
the job name `e2e (linux, xvfb)`, and the required `gate` context of
|
||||
`tests.yml` keeps its name.
|
||||
3. A workflow that runs on pull requests has a concurrency group that cancels
|
||||
on pull requests and on nothing else. The group used to be keyed on the
|
||||
ref, which is `refs/heads/main` for every push to main: the next push
|
||||
cancelled the run of the commit before it, and a cancelled e2e refuses a
|
||||
release (`cancelled` is not in e2e_is_green.FINE). Publishing and scheduled
|
||||
workflows never cancel.
|
||||
4. A hunt workflow has its own group and caps every matrix at 8 parallel
|
||||
jobs.
|
||||
|
||||
The checkers are tested on known-bad inputs first, because a check that has
|
||||
only ever said "fine" is not known to be able to say anything else.
|
||||
|
||||
PyYAML is not a dependency of this package, so the workflows are read with a
|
||||
small parser for the subset these files use (mappings, block and flow lists,
|
||||
block scalars skipped, steps skipped).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
WORKFLOWS = Path(__file__).resolve().parents[1] / ".github" / "workflows"
|
||||
|
||||
#: The one expression a cancelling group may use, whitespace aside.
|
||||
CANCEL_ONLY_PULL_REQUESTS = "${{github.event_name=='pull_request'}}"
|
||||
#: Publishing and scheduled workflows: an upload or a snapshot that has started
|
||||
#: is allowed to finish.
|
||||
NEVER_CANCEL = {"publish.yml", "publish-wiki.yml", "counters.yml"}
|
||||
MAX_HUNT_PARALLEL = 8
|
||||
|
||||
|
||||
# --------------------------------------------------------------- the reader
|
||||
|
||||
_KEY = re.compile(r"""^(?P<k>"[^"]*"|'[^']*'|[^\s:#'"\[{-][^:]*?)\s*:(?:\s+(?P<v>.*))?$""")
|
||||
_BLOCK_SCALAR = re.compile(r"^[|>][+-]?\d*$")
|
||||
|
||||
|
||||
def _significant(text: str) -> list[tuple[int, str]]:
|
||||
out = []
|
||||
for raw in text.splitlines():
|
||||
stripped = raw.strip()
|
||||
if not stripped or stripped.startswith("#"):
|
||||
continue
|
||||
out.append((len(raw) - len(raw.lstrip(" ")), stripped))
|
||||
return out
|
||||
|
||||
|
||||
def _scalar(v: str):
|
||||
v = v.strip()
|
||||
if " #" in v and not (v[:1] in "'\"" or "${{" in v):
|
||||
v = v.split(" #", 1)[0].strip()
|
||||
if v.startswith("[") and v.endswith("]"):
|
||||
return [_scalar(x) for x in v[1:-1].split(",") if x.strip()]
|
||||
if v in ("{}", ""):
|
||||
return {} if v == "{}" else None
|
||||
if len(v) >= 2 and v[0] == v[-1] and v[0] in "'\"":
|
||||
return v[1:-1]
|
||||
if v in ("true", "false"):
|
||||
return v == "true"
|
||||
if re.fullmatch(r"-?\d+", v):
|
||||
return int(v)
|
||||
return v
|
||||
|
||||
|
||||
def _parse(lines, i, indent):
|
||||
"""A mapping or a list starting at lines[i], all at `indent`."""
|
||||
if lines[i][1].startswith("- ") or lines[i][1] == "-":
|
||||
items = []
|
||||
while i < len(lines) and lines[i][0] == indent and lines[i][1].startswith("-"):
|
||||
body = lines[i][1][1:].strip()
|
||||
if body and _KEY.match(body) and not body.startswith(("'", '"')):
|
||||
# "- key: value": the item is a mapping whose first line sits at indent + 2
|
||||
lines[i] = (indent + 2, body)
|
||||
item, i = _parse(lines, i, indent + 2)
|
||||
items.append(item)
|
||||
else:
|
||||
items.append(_scalar(body))
|
||||
i += 1
|
||||
return items, i
|
||||
out = {}
|
||||
while i < len(lines) and lines[i][0] == indent:
|
||||
m = _KEY.match(lines[i][1])
|
||||
if not m:
|
||||
i += 1
|
||||
continue
|
||||
key, value = m.group("k").strip("'\""), m.group("v")
|
||||
i += 1
|
||||
if value is not None and (_BLOCK_SCALAR.match(value.split(" #")[0].strip())):
|
||||
while i < len(lines) and lines[i][0] > indent:
|
||||
i += 1
|
||||
out[key] = "<block>"
|
||||
elif value:
|
||||
out[key] = _scalar(value)
|
||||
elif i < len(lines) and (lines[i][0] > indent or
|
||||
(lines[i][0] == indent and lines[i][1].startswith("-"))):
|
||||
if key == "steps":
|
||||
while i < len(lines) and (lines[i][0] > indent or lines[i][1].startswith("-")):
|
||||
if lines[i][0] < indent:
|
||||
break
|
||||
i += 1
|
||||
out[key] = "<steps>"
|
||||
else:
|
||||
out[key], i = _parse(lines, i, lines[i][0])
|
||||
else:
|
||||
out[key] = None
|
||||
return out, i
|
||||
|
||||
|
||||
def load(text: str) -> dict:
|
||||
lines = _significant(text)
|
||||
spec, _ = _parse(lines, 0, lines[0][0])
|
||||
return spec
|
||||
|
||||
|
||||
def triggers(spec: dict) -> dict:
|
||||
on = spec.get("on")
|
||||
if isinstance(on, str):
|
||||
return {on: {}}
|
||||
if isinstance(on, list):
|
||||
return {e: {} for e in on}
|
||||
return {e: (c if isinstance(c, dict) else {}) for e, c in (on or {}).items()}
|
||||
|
||||
|
||||
def _flat(expr) -> str:
|
||||
return re.sub(r"\s+", "", str(expr))
|
||||
|
||||
|
||||
# ------------------------------------------------------------- the checkers
|
||||
|
||||
def problems_double_run(name: str, spec: dict) -> list[str]:
|
||||
ev = triggers(spec)
|
||||
if "pull_request" not in ev or "push" not in ev:
|
||||
return []
|
||||
push = ev["push"]
|
||||
branches = push.get("branches")
|
||||
if not branches:
|
||||
if push.get("tags") and not push.get("branches-ignore"):
|
||||
return [] # tags only
|
||||
return [f"{name}: `push` without a branch list also runs on feature branches"]
|
||||
bad = [b for b in branches if b != "main"]
|
||||
if bad:
|
||||
return [f"{name}: `push` matches {bad}, which a pull request already covers"]
|
||||
return []
|
||||
|
||||
|
||||
def problems_concurrency(name: str, spec: dict) -> list[str]:
|
||||
ev = triggers(spec)
|
||||
conc = spec.get("concurrency")
|
||||
cancel = conc.get("cancel-in-progress") if isinstance(conc, dict) else None
|
||||
out = []
|
||||
if name in NEVER_CANCEL:
|
||||
if conc is not None and cancel is not False:
|
||||
out.append(f"{name}: publishing/scheduled workflow may cancel ({cancel!r})")
|
||||
return out
|
||||
if "hunt" in name:
|
||||
return out # judged by problems_hunt
|
||||
if "pull_request" not in ev:
|
||||
if cancel not in (None, False) and _flat(cancel) != CANCEL_ONLY_PULL_REQUESTS:
|
||||
out.append(f"{name}: cancels without a pull request ({cancel!r})")
|
||||
return out
|
||||
if not isinstance(conc, dict):
|
||||
return [f"{name}: runs on pull requests and has no concurrency group"]
|
||||
group = str(conc.get("group", ""))
|
||||
if _flat(cancel) != CANCEL_ONLY_PULL_REQUESTS:
|
||||
out.append(f"{name}: cancel-in-progress is {cancel!r}, not "
|
||||
f"`github.event_name == 'pull_request'`")
|
||||
if "github.event.pull_request.number" not in group:
|
||||
out.append(f"{name}: the group is not keyed on the pull request number")
|
||||
if "github.run_id" not in group:
|
||||
out.append(f"{name}: outside a pull request the group is not unique to the run, "
|
||||
f"so a newer pending run of main replaces an older one")
|
||||
if "github.ref" in group or "head_ref" in group:
|
||||
out.append(f"{name}: the group is keyed on the ref, which is main for every push to main")
|
||||
return out
|
||||
|
||||
|
||||
def problems_hunt(name: str, spec: dict) -> list[str]:
|
||||
if "hunt" not in name:
|
||||
return []
|
||||
out = []
|
||||
conc = spec.get("concurrency")
|
||||
if not isinstance(conc, dict) or "hunt" not in (
|
||||
str(conc.get("group", "")) + str(spec.get("name", ""))).lower():
|
||||
out.append(f"{name}: a hunt needs a concurrency group of its own")
|
||||
for job, body in (spec.get("jobs") or {}).items():
|
||||
strategy = (body or {}).get("strategy") if isinstance(body, dict) else None
|
||||
if not isinstance(strategy, dict) or "matrix" not in strategy:
|
||||
continue
|
||||
cap = strategy.get("max-parallel")
|
||||
if not isinstance(cap, int) or cap > MAX_HUNT_PARALLEL:
|
||||
out.append(f"{name}: matrix job `{job}` has max-parallel {cap!r} "
|
||||
f"(needs an integer <= {MAX_HUNT_PARALLEL})")
|
||||
return out
|
||||
|
||||
|
||||
def all_workflows():
|
||||
return sorted(WORKFLOWS.glob("*.yml"))
|
||||
|
||||
|
||||
def _load(path: Path) -> dict:
|
||||
return load(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
# ----------------------------------------------------- the checkers can fail
|
||||
|
||||
OLD_CI = """
|
||||
name: ci
|
||||
on:
|
||||
push:
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
"""
|
||||
BAD_CONCURRENCY = """
|
||||
name: x
|
||||
on:
|
||||
pull_request:
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
"""
|
||||
GOOD_CONCURRENCY = """
|
||||
name: x
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
"""
|
||||
HUNT_WITHOUT_CAP = """
|
||||
name: e2e hunt
|
||||
on:
|
||||
workflow_dispatch:
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
jobs:
|
||||
suite:
|
||||
strategy:
|
||||
matrix:
|
||||
include: ${{ fromJSON(needs.plan.outputs.m) }}
|
||||
"""
|
||||
|
||||
|
||||
def test_the_reader_reads_what_the_checkers_need():
|
||||
spec = load(GOOD_CONCURRENCY)
|
||||
assert triggers(spec)["push"]["branches"] == ["main"]
|
||||
assert "pull_request" in triggers(spec)
|
||||
assert spec["concurrency"]["cancel-in-progress"] == "${{ github.event_name == 'pull_request' }}"
|
||||
assert load(HUNT_WITHOUT_CAP)["jobs"]["suite"]["strategy"]["matrix"]["include"].startswith("${{")
|
||||
|
||||
|
||||
def test_the_old_trigger_is_caught():
|
||||
assert problems_double_run("ci.yml", load(OLD_CI))
|
||||
assert problems_double_run("ci.yml", load(GOOD_CONCURRENCY)) == []
|
||||
|
||||
|
||||
def test_a_group_keyed_on_the_ref_that_cancels_everywhere_is_caught():
|
||||
assert len(problems_concurrency("e2e.yml", load(BAD_CONCURRENCY))) >= 3
|
||||
assert problems_concurrency("e2e.yml", load(GOOD_CONCURRENCY)) == []
|
||||
|
||||
|
||||
def test_a_hunt_matrix_without_a_cap_is_caught():
|
||||
assert problems_hunt("e2e-hunt.yml", load(HUNT_WITHOUT_CAP))
|
||||
capped = HUNT_WITHOUT_CAP.replace(" strategy:\n", " strategy:\n max-parallel: 8\n")
|
||||
assert problems_hunt("e2e-hunt.yml", load(capped)) == []
|
||||
assert problems_hunt("e2e-hunt.yml", load(capped.replace("max-parallel: 8", "max-parallel: 9")))
|
||||
|
||||
|
||||
# ------------------------------------------------------ the workflows here
|
||||
|
||||
def test_no_workflow_runs_twice_for_a_commit_of_a_pull_request():
|
||||
problems = []
|
||||
for path in all_workflows():
|
||||
problems += problems_double_run(path.name, _load(path))
|
||||
assert not problems, "\n".join(problems)
|
||||
|
||||
|
||||
def test_the_push_triggers_the_release_reads_are_still_there():
|
||||
e2e = triggers(_load(WORKFLOWS / "e2e.yml"))
|
||||
assert e2e["push"]["branches"] == ["main"], \
|
||||
"scripts/e2e_is_green.py needs the e2e of the push to main on the tagged commit"
|
||||
assert "pull_request" in e2e
|
||||
tests = triggers(_load(WORKFLOWS / "tests.yml"))
|
||||
assert tests["push"]["branches"] == ["main"] and "pull_request" in tests
|
||||
publish = triggers(_load(WORKFLOWS / "publish.yml"))
|
||||
assert publish["push"]["tags"] == ["v*"], "publish must start on a release tag"
|
||||
|
||||
|
||||
def test_the_names_the_release_and_the_branch_protection_read_are_unchanged():
|
||||
e2e = _load(WORKFLOWS / "e2e.yml")
|
||||
assert e2e["name"] == "e2e" and e2e["jobs"]["e2e"]["name"] == "e2e (linux, xvfb)"
|
||||
tests = _load(WORKFLOWS / "tests.yml")
|
||||
assert tests["name"] == "tests" and "gate" in tests["jobs"]
|
||||
assert "name" not in tests["jobs"]["gate"]
|
||||
|
||||
|
||||
def test_every_workflow_cancels_on_pull_requests_and_nowhere_else():
|
||||
problems = []
|
||||
for path in all_workflows():
|
||||
problems += problems_concurrency(path.name, _load(path))
|
||||
assert not problems, "\n".join(problems)
|
||||
|
||||
|
||||
def test_a_hunt_has_its_own_group_and_caps_its_matrices():
|
||||
hunts = [p for p in all_workflows() if "hunt" in p.name]
|
||||
assert hunts, "e2e-hunt.yml is gone: this check would pass on nothing"
|
||||
problems = []
|
||||
for path in hunts:
|
||||
problems += problems_hunt(path.name, _load(path))
|
||||
assert not problems, "\n".join(problems)
|
||||
@@ -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))
|
||||
@@ -21,10 +21,14 @@ test says what the product does not do yet and the step that makes it green:
|
||||
9 named world after the OOP frame step 1a + 2b
|
||||
10 console of the OOP frame step 1a
|
||||
|
||||
The oracle for "another process" is the set of the engine's processes that host a site, below the test
|
||||
(tests/_processes.py says how a site's process is told from a preallocated one): a cross-site frame adds at
|
||||
least one, a same-site one changes nothing. The set is read once it is quiet. Off Linux the two tests that
|
||||
count processes skip: no other system names the process.
|
||||
The oracle for "another process" is the name of the site (tests/_processes.py): with `fission.processSiteNames`
|
||||
on, the engine's process that hosts `http://a.test` is named after it, and the two tests that look at processes
|
||||
ask for the processes of one site and never compare two counts. Counting was wrong because the browser starts
|
||||
processes of its own: in every run, a second isolated process (remote type `webIsolated=https://mozgcp.net`) is
|
||||
born about a second after the process of the New Tab page, with any page, and under load it arrived between the
|
||||
two reads (red in 14 of 30 runs of the whole e2e suite, `[P] -> [P, P2]`). A cross-site frame gives a process
|
||||
for the frame's site; a same-site one leaves the page's site in its single process. Off Linux the two tests
|
||||
skip: no other system names the process.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -38,14 +42,18 @@ from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
import pytest
|
||||
|
||||
from _processes import site_processes_below
|
||||
from _processes import NAMED_BY_SITE, site_processes_below
|
||||
from _servers import LocalServer
|
||||
|
||||
SITE_A = "http://a.test"
|
||||
SITE_B = "http://b.test"
|
||||
|
||||
FISSION_ON = {
|
||||
"fission.autostart": True,
|
||||
"fission.webContentIsolationStrategy": 1, # IsolateEverything: site-origin
|
||||
"dom.ipc.processCount.webIsolated": 4, # the desktop default
|
||||
"network.dns.localDomains": "a.test,b.test,c.test",
|
||||
**NAMED_BY_SITE, # test-only: a process is named by its site (tests/_processes.py)
|
||||
}
|
||||
|
||||
|
||||
@@ -127,23 +135,9 @@ def engine_dir(firefox_binary):
|
||||
return str(Path(firefox_binary).resolve().parent)
|
||||
|
||||
|
||||
def site_processes(engine_dir):
|
||||
"""The pids of the engine's processes below this test that host a site (tests/_processes.py)."""
|
||||
return site_processes_below(os.getpid(), engine_dir)
|
||||
|
||||
|
||||
def quiet(engine_dir, seconds=3.0, limit=30.0):
|
||||
"""The set of the processes that host a site, once it has not changed for `seconds`."""
|
||||
end = time.time() + limit
|
||||
last, since = site_processes(engine_dir), time.time()
|
||||
while time.time() < end:
|
||||
time.sleep(0.25)
|
||||
now = site_processes(engine_dir)
|
||||
if now != last:
|
||||
last, since = now, time.time()
|
||||
elif time.time() - since >= seconds:
|
||||
break
|
||||
return last
|
||||
def processes_of(site, engine_dir):
|
||||
"""The pids of the engine's processes below this test that host `site` (named by it, tests/_processes.py)."""
|
||||
return site_processes_below(os.getpid(), site, engine_dir)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -163,21 +157,6 @@ def page(browser):
|
||||
return page
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def page_without_a_pool(firefox_binary):
|
||||
"""A page of a browser that keeps NO preallocated content processes (`dom.ipc.processPrelaunch.fission.number` 0): a process of a
|
||||
site then appears only because a site needed one. The default pool hands a preallocated process to a site whenever it gets to it, so
|
||||
a test that counts the processes of the sites between two reads sees the hand-out of the pool as if the frame had asked for it."""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False, headless=True,
|
||||
extra_prefs=dict(FISSION_ON, **{"dom.ipc.processPrelaunch.fission.number": 0})) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.set_default_timeout(3000)
|
||||
page.set_default_navigation_timeout(20000)
|
||||
yield page
|
||||
|
||||
|
||||
def wait_for(page, predicate, seconds=8.0):
|
||||
"""Until `predicate()`, with the client's events being read: the sync client takes the engine's events
|
||||
only inside its own calls, so a plain sleep would never see a frame arrive."""
|
||||
@@ -216,41 +195,52 @@ def frame_with_origin(page, origin):
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_cross_site_iframe_gets_its_own_process(page, cross_site_loop, engine_dir):
|
||||
"""Green today: it says the bench separates sites. Two sites in the frame tree add at least one process."""
|
||||
"""Green today: it says the bench separates sites. A frame of b.test in a page of a.test has a process of its own.
|
||||
|
||||
The processes are asked for by the name of their site, never counted between two reads (tests/_processes.py): the
|
||||
page of a.test has exactly one, nobody has b.test; once the top has loaded, b.test has one, and a.test still has
|
||||
one (the a.test leaf inside the b.test frame is in the top's process). The pid of a.test is not compared across
|
||||
the navigation: a top-level navigation may land in another process of the same site (`mReplaceBrowsingContext`,
|
||||
dom/ipc/ProcessIsolation.cpp, see the control below)."""
|
||||
page.goto(cross_site_loop["plain"])
|
||||
before = quiet(engine_dir)
|
||||
here = processes_of(SITE_A, engine_dir)
|
||||
assert len(here) == 1, "the page of a.test must have one process of its site: %s" % sorted(here)
|
||||
assert not processes_of(SITE_B, engine_dir), "a process for b.test before any page of it"
|
||||
page.goto(cross_site_loop["top"], wait_until="load")
|
||||
assert wait_for(page, lambda: any(r["path"] == "/report/loaded" and r["host"] == "a.test" and
|
||||
r["query"]["path"] == ["/leaf"] for r in cross_site_loop["reports"]))
|
||||
after = quiet(engine_dir)
|
||||
assert len(after - before) >= 1, "no new process for a site: before %s, after %s" % (sorted(before), sorted(after))
|
||||
framed = processes_of(SITE_B, engine_dir)
|
||||
assert len(framed) >= 1, "no process for the site of the frame (b.test)"
|
||||
tops = processes_of(SITE_A, engine_dir)
|
||||
assert len(tops) == 1, "the processes of a.test must still be one: %s" % sorted(tops)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_same_site_other_port_stays_in_process(page_without_a_pool, cross_site_loop, engine_dir):
|
||||
"""Green today, the control: a frame of the page's own site adds no process for a site.
|
||||
def test_same_site_other_port_stays_in_process(page, cross_site_loop, engine_dir):
|
||||
"""Green today, the control: a frame of the page's own site gets no process, and none for another site.
|
||||
|
||||
The browser here keeps NO preallocated processes (`page_without_a_pool`): with the default pool of three the count of the processes of
|
||||
the sites moved between two reads without the frame having asked for anything - a preallocated process handed to a site later than
|
||||
the first read ([63248] -> [63248, 63386] on a four-worker runner, the third time in a row that this control was red there for the
|
||||
pool and not for the frame: 5402da4, ff2123e, fef0bc5). The frame is in the page's own origin (`a.test/leaf` in `a.test/plain`).
|
||||
The processes of a.test are asked for by name before and after the frame is added: one pid, the same pid. Nothing
|
||||
else is looked at: the browser starts processes of its own (the pool refill, a process for a Mozilla site started
|
||||
by the New Tab page, `webIsolated=https://mozgcp.net`, there in every run and under load born after the first
|
||||
read), and counting every process between two reads took them for the frame's (red in 14 of 30 runs). The frame
|
||||
has run in its process when it reports, and that process got its name before any document loaded in it, so no
|
||||
waiting for quiet is needed. The frame is in the page's own origin (`a.test/leaf` in `a.test/plain`).
|
||||
|
||||
The frame is put in the page that is already shown, not reached by a navigation of the top. A top-level
|
||||
navigation whose old document may enter the back-forward cache replaces the browsing context
|
||||
(`mReplaceBrowsingContext`, dom/ipc/ProcessIsolation.cpp), and the new one may land in another process of
|
||||
the same site (`dom.ipc.processCount.webIsolated` is 4): seen once on the e2e of #451, [10878] -> [10878,
|
||||
11208] after a.test/plain -> a.test/same-site, never in 87 local runs. That is the top's process, not the
|
||||
frame's; a frame of the page's site stays in the page's process."""
|
||||
page = page_without_a_pool
|
||||
the same site (`dom.ipc.processCount.webIsolated` is 4). That is the top's process, not the frame's; a frame of
|
||||
the page's site stays in the page's process."""
|
||||
page.goto(cross_site_loop["plain"])
|
||||
before = quiet(engine_dir)
|
||||
assert len(before) >= 1, "the page of a site has no process of its own to compare with: %s" % sorted(before)
|
||||
before = processes_of(SITE_A, engine_dir)
|
||||
assert len(before) == 1, "the page of a.test must have one process of its site: %s" % sorted(before)
|
||||
page.evaluate("(u) => { const f = document.createElement('iframe'); f.id = 's'; f.src = u;"
|
||||
" document.body.appendChild(f); }", cross_site_loop["leaf"])
|
||||
assert wait_for(page, lambda: any(r["path"] == "/report/loaded" and r["query"]["path"] == ["/leaf"]
|
||||
for r in cross_site_loop["reports"]))
|
||||
after = quiet(engine_dir)
|
||||
assert after == before, "a same-site frame changed the processes of the sites: %s -> %s" % (sorted(before), sorted(after))
|
||||
after = processes_of(SITE_A, engine_dir)
|
||||
assert after == before, "a same-site frame changed the processes of a.test: %s -> %s" % (sorted(before), sorted(after))
|
||||
assert not processes_of(SITE_B, engine_dir), "a process for b.test, which no page here belongs to"
|
||||
|
||||
|
||||
# ── 3 .. 10: what the product does not do yet ──────────────────────────────────
|
||||
|
||||
@@ -1,158 +1,239 @@
|
||||
"""A popup reaches the client: the `page` event arrives, the new page is at its address and answers.
|
||||
|
||||
Why this file exists: the page dispatcher once waited for the engine's ready signal (`Page.ready`) before it handed a new
|
||||
page over. A popup whose first request goes through a context route (the shape of every production client: abort the
|
||||
images, continue the rest) was held behind a page that did not exist yet, the engine never said ready for it, the wait gave
|
||||
up after 20 s and the popup vanished: the client never got the `page` event. That was found by a user journey (a
|
||||
`target=_blank` link) and it is the same for a link and for `window.open`, to the page's own site and to another one.
|
||||
|
||||
The matrix: four ways to open a popup (a `target=_blank` link, the same link with `rel=noopener`, `window.open(url)` from a
|
||||
click, `window.open(url, '_blank', 'noopener')`) x the target on the opener's site (`127.0.0.1`) or on another site
|
||||
(`localhost`: another site for the engine, no pref needed) x with and without a context route x two transports: the client
|
||||
of this wheel in the same process, and the stock Playwright client over `launch_server` (the way the fake web does it).
|
||||
Each case: the `page` event arrives within 10 s, the page ends at the target address, answers an `evaluate`, and has an
|
||||
opener (`page.opener()`). Stock Firefox (Playwright 1.62) gives an opener in all four kinds, `noopener` included, so this is
|
||||
asserted for all four; if the engine ever returns None for a noopener kind the test says so.
|
||||
|
||||
One extra case proves that the other-site target is really in another process, so that the matrix cannot quietly become a
|
||||
same-site test: opening it adds a content process below the test; the same-site target does not.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
OWN, OTHER = "127.0.0.1", "localhost"
|
||||
KINDS = {
|
||||
"a-blank": "a1",
|
||||
"a-noopener": "a2",
|
||||
"open": "w1",
|
||||
"open-noopener": "w2",
|
||||
}
|
||||
|
||||
|
||||
class _Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
port = self.server.server_address[1]
|
||||
if self.path.startswith("/main"):
|
||||
body = ""
|
||||
for tag, host in (("s", OWN), ("o", OTHER)):
|
||||
url = "http://%s:%d/p" % (host, port)
|
||||
body += (
|
||||
"<a id=a1%s target=_blank href='%s'>a</a> "
|
||||
"<a id=a2%s target=_blank rel=noopener href='%s'>a</a> "
|
||||
"<button id=w1%s onclick=\"window.open('%s')\">w</button> "
|
||||
"<button id=w2%s onclick=\"window.open('%s','_blank','noopener')\">w</button><br>"
|
||||
) % (tag, url, tag, url, tag, url, tag, url)
|
||||
else:
|
||||
body = "<p>popup</p>"
|
||||
data = ("<!doctype html><title>t</title>" + body).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def site():
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
yield srv.server_address[1]
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
def _route(context):
|
||||
context.route("**/*", lambda route: route.abort() if route.request.resource_type in ("image", "media")
|
||||
else route.continue_())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("routed", [False, True], ids=["no-route", "route"])
|
||||
@pytest.mark.parametrize("target", ["same-site", "other-site"])
|
||||
@pytest.mark.parametrize("kind", sorted(KINDS))
|
||||
def test_a_popup_reaches_the_client(browser, site, kind, target, routed):
|
||||
host, tag = (OWN, "s") if target == "same-site" else (OTHER, "o")
|
||||
context = browser.new_context()
|
||||
try:
|
||||
if routed:
|
||||
_route(context)
|
||||
page = context.new_page()
|
||||
page.goto("http://%s:%d/main" % (OWN, site))
|
||||
t0 = time.time()
|
||||
with context.expect_page(timeout=10000) as info:
|
||||
page.click("#%s%s" % (KINDS[kind], tag))
|
||||
popup = info.value
|
||||
arrived = time.time() - t0
|
||||
popup.wait_for_load_state("load", timeout=10000)
|
||||
assert popup.url == "http://%s:%d/p" % (host, site), "the popup is at %s" % popup.url
|
||||
assert popup.evaluate("document.title") == "t"
|
||||
assert popup.opener() is not None, "no opener (stock Firefox gives one for every kind)"
|
||||
assert arrived < 10
|
||||
finally:
|
||||
context.close()
|
||||
|
||||
|
||||
def _content_processes(engine_dir):
|
||||
"""The pids of the engine's web content processes (`-contentproc ... tab`) below this test."""
|
||||
import psutil
|
||||
|
||||
pids = set()
|
||||
for child in psutil.Process(os.getpid()).children(recursive=True):
|
||||
try:
|
||||
if not os.path.normcase(child.exe()).startswith(os.path.normcase(engine_dir)):
|
||||
continue
|
||||
cmd = child.cmdline()
|
||||
except psutil.Error:
|
||||
continue
|
||||
if "-contentproc" in cmd and cmd[-1] == "tab":
|
||||
pids.add(child.pid)
|
||||
return pids
|
||||
|
||||
|
||||
def _quiet(engine_dir, seconds=3.0, limit=30.0):
|
||||
"""The set of content processes once it has not changed for `seconds` (the engine keeps a spare one)."""
|
||||
end = time.time() + limit
|
||||
last, since = _content_processes(engine_dir), time.time()
|
||||
while time.time() < end:
|
||||
time.sleep(0.25)
|
||||
now = _content_processes(engine_dir)
|
||||
if now != last:
|
||||
last, since = now, time.time()
|
||||
elif time.time() - since >= seconds:
|
||||
break
|
||||
return last
|
||||
|
||||
|
||||
def test_the_other_site_popup_runs_in_another_process(browser, firefox_binary, site):
|
||||
"""The control of the matrix above: the popup to `localhost` adds a content process, the one to `127.0.0.1` does not."""
|
||||
engine_dir = str(Path(firefox_binary).resolve().parent)
|
||||
context = browser.new_context()
|
||||
page = context.new_page()
|
||||
page.goto("http://%s:%d/main" % (OWN, site))
|
||||
before = _quiet(engine_dir)
|
||||
with context.expect_page(timeout=10000) as info:
|
||||
page.click("#a1s")
|
||||
info.value.wait_for_load_state("load")
|
||||
same = _quiet(engine_dir)
|
||||
info.value.close()
|
||||
page.goto("http://%s:%d/main" % (OWN, site))
|
||||
base = _quiet(engine_dir)
|
||||
with context.expect_page(timeout=10000) as info:
|
||||
page.click("#a1o")
|
||||
info.value.wait_for_load_state("load")
|
||||
other = _quiet(engine_dir)
|
||||
assert not (same - before), "a popup to the opener's own site started a process: %s" % sorted(same - before)
|
||||
assert len(other - base) >= 1, "the other-site popup added no content process: %s -> %s" % (
|
||||
sorted(base), sorted(other))
|
||||
"""A popup reaches the client: the `page` event arrives, the new page is at its address and answers.
|
||||
|
||||
Why this file exists: the page dispatcher once waited for the engine's ready signal (`Page.ready`) before it handed a new
|
||||
page over. A popup whose first request goes through a context route (the shape of every production client: abort the
|
||||
images, continue the rest) was held behind a page that did not exist yet, the engine never said ready for it, the wait gave
|
||||
up after 20 s and the popup vanished: the client never got the `page` event. That was found by a user journey (a
|
||||
`target=_blank` link) and it is the same for a link and for `window.open`, to the page's own site and to another one.
|
||||
|
||||
The matrix: four ways to open a popup (a `target=_blank` link, the same link with `rel=noopener`, `window.open(url)` from a
|
||||
click, `window.open(url, '_blank', 'noopener')`) x the target on the opener's site (`127.0.0.1`) or on another site
|
||||
(`localhost`: another site for the engine, no pref needed) x with and without a context route x two transports: the client
|
||||
of this wheel in the same process, and the stock Playwright client over `launch_server` (the way the fake web does it).
|
||||
Each case: the `page` event arrives within 10 s, the page ends at the target address, answers an `evaluate`, and has an
|
||||
opener (`page.opener()`). Stock Firefox (Playwright 1.62) gives an opener in all four kinds, `noopener` included, so this is
|
||||
asserted for all four; if the engine ever returns None for a noopener kind the test says so.
|
||||
|
||||
One extra case proves that the other-site target is really in another process, so that the matrix cannot quietly become a
|
||||
same-site test: opening it adds a content process below the test; the same-site target does not. That case has a browser
|
||||
of its own that starts no content process by itself (`QUIET_PREFS`, test-only): a browser as shipped preallocates content
|
||||
processes and refills its pool whenever it gets to it, and its preloaded New Tab page starts a process of its own and, in
|
||||
some countries, one more for a Mozilla site, about a second later and with any page. Counted between two reads, any of
|
||||
those was taken for the popup's doing. Where the system names a process by its site (Linux, `NAMED_BY_SITE`), the case
|
||||
also asks by name: the other-site popup's process is the process of `http://localhost`. It runs on Windows too: there is
|
||||
no skip, so the count stays the same on every system.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import importlib
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from _processes import NAMED_BY_SITE, site_pids
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
OWN, OTHER = "127.0.0.1", "localhost"
|
||||
|
||||
#: The browser of the process case starts no content process by itself: no pool of preallocated processes, and no
|
||||
#: preloaded New Tab page (which starts a process of its own and, in some countries, one for a Mozilla site). Test-only.
|
||||
QUIET_PREFS = dict(NAMED_BY_SITE, **{"dom.ipc.processPrelaunch.fission.number": 0, "browser.newtab.preload": False})
|
||||
KINDS = {
|
||||
"a-blank": "a1",
|
||||
"a-noopener": "a2",
|
||||
"open": "w1",
|
||||
"open-noopener": "w2",
|
||||
}
|
||||
|
||||
|
||||
class _Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
port = self.server.server_address[1]
|
||||
if self.path.startswith("/main"):
|
||||
body = ""
|
||||
for tag, host in (("s", OWN), ("o", OTHER)):
|
||||
url = "http://%s:%d/p" % (host, port)
|
||||
body += (
|
||||
"<a id=a1%s target=_blank href='%s'>a</a> "
|
||||
"<a id=a2%s target=_blank rel=noopener href='%s'>a</a> "
|
||||
"<button id=w1%s onclick=\"window.open('%s')\">w</button> "
|
||||
"<button id=w2%s onclick=\"window.open('%s','_blank','noopener')\">w</button><br>"
|
||||
) % (tag, url, tag, url, tag, url, tag, url)
|
||||
else:
|
||||
body = "<p>popup</p>"
|
||||
data = ("<!doctype html><title>t</title>" + body).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def site():
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
yield srv.server_address[1]
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _quiet_browser(transport, firefox_binary):
|
||||
"""A browser of its own for the process case, that starts no content process by itself."""
|
||||
if transport == "in-process":
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(binary_path=firefox_binary, headless=True, extra_prefs=QUIET_PREFS) as b:
|
||||
yield b
|
||||
return
|
||||
try:
|
||||
sync_playwright = importlib.import_module("playwright.sync_api").sync_playwright
|
||||
except ImportError as exc:
|
||||
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc,
|
||||
pytrace=False)
|
||||
from invisible_playwright._juggler.remote import launch_server
|
||||
|
||||
server = launch_server(headless=True, binary_path=firefox_binary, locale="en-US", timezone="Europe/Rome",
|
||||
extra_prefs=QUIET_PREFS)
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
b = p.firefox.connect(server.ws_endpoint)
|
||||
try:
|
||||
yield b
|
||||
finally:
|
||||
b.close()
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
def _in_a_thread_of_its_own(fn, timeout=300):
|
||||
"""Runs `fn` in a thread of its own and gives back its result or raises its error. The module's browser of the matrix
|
||||
keeps a sync client open in this thread, and a sync client refuses to start inside another one's loop: a second
|
||||
browser needs a thread with no loop."""
|
||||
box = {}
|
||||
|
||||
def run():
|
||||
try:
|
||||
box["value"] = fn()
|
||||
except BaseException as exc: # handed back to the test's thread below
|
||||
box["error"] = exc
|
||||
|
||||
worker = threading.Thread(target=run, name="quiet-browser", daemon=True)
|
||||
worker.start()
|
||||
worker.join(timeout)
|
||||
if worker.is_alive():
|
||||
pytest.fail("the process case did not end within %d s" % timeout)
|
||||
if "error" in box:
|
||||
raise box["error"]
|
||||
return box.get("value")
|
||||
|
||||
|
||||
def _route(context):
|
||||
context.route("**/*", lambda route: route.abort() if route.request.resource_type in ("image", "media")
|
||||
else route.continue_())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("routed", [False, True], ids=["no-route", "route"])
|
||||
@pytest.mark.parametrize("target", ["same-site", "other-site"])
|
||||
@pytest.mark.parametrize("kind", sorted(KINDS))
|
||||
def test_a_popup_reaches_the_client(browser, site, kind, target, routed):
|
||||
host, tag = (OWN, "s") if target == "same-site" else (OTHER, "o")
|
||||
context = browser.new_context()
|
||||
try:
|
||||
if routed:
|
||||
_route(context)
|
||||
page = context.new_page()
|
||||
page.goto("http://%s:%d/main" % (OWN, site))
|
||||
t0 = time.time()
|
||||
with context.expect_page(timeout=10000) as info:
|
||||
page.click("#%s%s" % (KINDS[kind], tag))
|
||||
popup = info.value
|
||||
arrived = time.time() - t0
|
||||
popup.wait_for_load_state("load", timeout=10000)
|
||||
assert popup.url == "http://%s:%d/p" % (host, site), "the popup is at %s" % popup.url
|
||||
assert popup.evaluate("document.title") == "t"
|
||||
assert popup.opener() is not None, "no opener (stock Firefox gives one for every kind)"
|
||||
assert arrived < 10
|
||||
finally:
|
||||
context.close()
|
||||
|
||||
|
||||
def _content_processes(engine_dir):
|
||||
"""The pids of the engine's web content processes (`-contentproc ... tab`) below this test."""
|
||||
import psutil
|
||||
|
||||
pids = set()
|
||||
for child in psutil.Process(os.getpid()).children(recursive=True):
|
||||
try:
|
||||
if not os.path.normcase(child.exe()).startswith(os.path.normcase(engine_dir)):
|
||||
continue
|
||||
cmd = child.cmdline()
|
||||
except psutil.Error:
|
||||
continue
|
||||
if "-contentproc" in cmd and cmd[-1] == "tab":
|
||||
pids.add(child.pid)
|
||||
return pids
|
||||
|
||||
|
||||
def _quiet(engine_dir, seconds=3.0, limit=30.0):
|
||||
"""The set of content processes once it has not changed for `seconds` (the engine keeps a spare one)."""
|
||||
end = time.time() + limit
|
||||
last, since = _content_processes(engine_dir), time.time()
|
||||
while time.time() < end:
|
||||
time.sleep(0.25)
|
||||
now = _content_processes(engine_dir)
|
||||
if now != last:
|
||||
last, since = now, time.time()
|
||||
elif time.time() - since >= seconds:
|
||||
break
|
||||
return last
|
||||
|
||||
|
||||
@pytest.mark.parametrize("transport", ["in-process", "stock-client"])
|
||||
def test_the_other_site_popup_runs_in_another_process(transport, firefox_binary, site):
|
||||
"""The control of the matrix above: the popup to `localhost` adds a content process, the one to `127.0.0.1` does not."""
|
||||
_in_a_thread_of_its_own(lambda: _the_process_case(transport, firefox_binary, site))
|
||||
|
||||
|
||||
def _the_process_case(transport, firefox_binary, site):
|
||||
import psutil
|
||||
|
||||
engine_dir = str(Path(firefox_binary).resolve().parent)
|
||||
with _quiet_browser(transport, firefox_binary) as quiet_browser:
|
||||
_the_process_case_in(quiet_browser, engine_dir, site, psutil)
|
||||
|
||||
|
||||
def _the_process_case_in(quiet_browser, engine_dir, site, psutil):
|
||||
context = quiet_browser.new_context()
|
||||
page = context.new_page()
|
||||
page.goto("http://%s:%d/main" % (OWN, site))
|
||||
before = _quiet(engine_dir)
|
||||
with context.expect_page(timeout=10000) as info:
|
||||
page.click("#a1s")
|
||||
info.value.wait_for_load_state("load")
|
||||
same = _quiet(engine_dir)
|
||||
info.value.close()
|
||||
page.goto("http://%s:%d/main" % (OWN, site))
|
||||
base = _quiet(engine_dir)
|
||||
with context.expect_page(timeout=10000) as info:
|
||||
page.click("#a1o")
|
||||
info.value.wait_for_load_state("load")
|
||||
other = _quiet(engine_dir)
|
||||
assert not (same - before), "a popup to the opener's own site started a process: %s" % sorted(same - before)
|
||||
assert len(other - base) >= 1, "the other-site popup added no content process: %s -> %s" % (
|
||||
sorted(base), sorted(other))
|
||||
if sys.platform.startswith("linux"): # only Linux names a process by its site; elsewhere the count above is the proof
|
||||
children = psutil.Process(os.getpid()).children(recursive=True)
|
||||
assert site_pids(children, "http://" + OTHER, engine_dir) & (other - base), (
|
||||
"none of the new processes is the process of %s: %s" % (OTHER, sorted(other - base)))
|
||||
@@ -358,3 +358,77 @@ def test_the_fake_stun_of_a_relay_that_leaves_from_the_address_of_the_host_answe
|
||||
finally:
|
||||
control.close()
|
||||
client.close()
|
||||
|
||||
|
||||
# -- the port the server takes -------------------------------------------------------------------------------------------
|
||||
# The known-bad case, seen on the Windows runner (run 43230437094, wrapper.e2e.web: three tests red with "no port free for both TCP
|
||||
# and UDP", and on a work machine twice): Windows hands out ephemeral TCP ports in sequence and keeps excluded ranges of a hundred
|
||||
# ports for UDP in the same zone, so the old loop (fifty times "the system's pick") got fifty consecutive numbers inside one
|
||||
# refused range and gave up. A fake socket layer does the same here, without the machine.
|
||||
_REFUSED_UDP = range(50000, 50200)
|
||||
|
||||
|
||||
class _FakeTcpServer:
|
||||
"""A TCP server whose port 0 is the next number of a sequence (50000, 50001, ...), as Windows picks."""
|
||||
|
||||
next_pick = 50000
|
||||
opened: list = []
|
||||
|
||||
def __init__(self, where, handler):
|
||||
address, port = where
|
||||
if port == 0:
|
||||
port = _FakeTcpServer.next_pick
|
||||
_FakeTcpServer.next_pick += 1
|
||||
self.server_address = (address, port)
|
||||
self.closed = False
|
||||
_FakeTcpServer.opened.append(self)
|
||||
|
||||
def server_close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
class _FakeUdpSocket:
|
||||
tried: list = []
|
||||
|
||||
def __init__(self, family, kind):
|
||||
pass
|
||||
|
||||
def bind(self, where):
|
||||
_FakeUdpSocket.tried.append(where[1])
|
||||
if where[1] in _REFUSED_UDP or _FakeUdpSocket.refuse_all:
|
||||
raise PermissionError(10013, "An attempt was made to access a socket in a way forbidden by its access permissions")
|
||||
|
||||
refuse_all = False
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
def _fake_layer(monkeypatch, refuse_all=False):
|
||||
import types
|
||||
|
||||
import _h3_server
|
||||
|
||||
_FakeTcpServer.next_pick, _FakeTcpServer.opened = 50000, []
|
||||
_FakeUdpSocket.tried, _FakeUdpSocket.refuse_all = [], refuse_all
|
||||
monkeypatch.setattr(_h3_server, "_TcpServer", _FakeTcpServer)
|
||||
monkeypatch.setattr(_h3_server, "socket", types.SimpleNamespace(
|
||||
AF_INET=socket.AF_INET, SOCK_DGRAM=socket.SOCK_DGRAM, socket=_FakeUdpSocket))
|
||||
return _h3_server
|
||||
|
||||
|
||||
def test_the_server_takes_a_number_both_tcp_and_udp_bind_outside_a_refused_udp_range(monkeypatch):
|
||||
module = _fake_layer(monkeypatch)
|
||||
server, port = module._tcp_server_on_a_port_udp_binds("127.0.0.1")
|
||||
assert port not in _REFUSED_UDP, "the server took a number UDP refuses: %d" % port
|
||||
assert server.server_address[1] == port
|
||||
assert _FakeUdpSocket.tried[0] in _REFUSED_UDP, "the fake did not make the system's first pick a refused one"
|
||||
assert all(s.closed for s in _FakeTcpServer.opened if s is not server), "a TCP server of a refused number was left open"
|
||||
|
||||
|
||||
def test_a_server_that_can_bind_nothing_says_so_after_a_bounded_number_of_tries(monkeypatch):
|
||||
module = _fake_layer(monkeypatch, refuse_all=True)
|
||||
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)
|
||||
@@ -0,0 +1,86 @@
|
||||
"""The wait of the install job for the index, and the upgrade test's two versions (no network, no browser).
|
||||
|
||||
Ledger #476 of 0.50.1: the Linux job of `user-install` failed in ``test_upgrade_e2e.py`` with "the upgrade did not
|
||||
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.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||
WORKFLOW = ROOT / ".github" / "workflows" / "user-install.yml"
|
||||
|
||||
|
||||
def _wait_script() -> str:
|
||||
text = WORKFLOW.read_text(encoding="utf-8")
|
||||
start = text.index("- name: wait for the index to serve this version")
|
||||
block = text[start:]
|
||||
m = re.search(r"python - <<'PY'\n(.*?)\n\s*PY\n", block, re.S)
|
||||
assert m, "the wait step has no python script"
|
||||
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"
|
||||
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 / "__main__.py").write_text(textwrap.dedent("""
|
||||
import pathlib, sys
|
||||
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:
|
||||
sys.exit(0)
|
||||
sys.stderr.write("ERROR: No matching distribution found for invisible-playwright==9.9.9\\n")
|
||||
sys.exit(1)
|
||||
""") % (str(counter), succeeds_on_call, succeeds_on_call), encoding="utf-8")
|
||||
env = dict(os.environ, PYTHONPATH=str(tmp_path / "shim"), INDEX_WAIT_SECONDS=str(seconds), INDEX_WAIT_POLL=str(poll))
|
||||
try:
|
||||
r = subprocess.run([sys.executable, "-c", _wait_script()], cwd=tmp_path, env=env, capture_output=True, text=True,
|
||||
timeout=30)
|
||||
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
|
||||
|
||||
|
||||
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)
|
||||
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
|
||||
|
||||
|
||||
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)
|
||||
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
|
||||
|
||||
|
||||
def test_the_wait_step_still_passes_the_gate_of_the_core():
|
||||
from invisible_core import install_job
|
||||
assert install_job.problems(WORKFLOW.read_text(encoding="utf-8")) == []
|
||||
|
||||
|
||||
def test_the_upgrade_goes_from_the_second_newest_to_the_newest_of_one_listing():
|
||||
import test_upgrade_e2e as upgrade
|
||||
assert upgrade._previous_and_latest(["0.48.0", "0.49.1", "0.50.1"]) == ("0.49.1", "0.50.1")
|
||||
@@ -145,7 +145,9 @@ def _udp_ask_at(address: str, port: int, name: str) -> bytes:
|
||||
|
||||
|
||||
def test_the_trap_counts_a_query_it_is_sent_and_refuses_what_it_cannot_answer():
|
||||
with ResolverTrap(port=0, rewrite_resolv_conf=False) as trap:
|
||||
# The test itself is the asker here, so it stands for the browser (the trap counts only a browser's questions, found by
|
||||
# the process that holds the socket: on Linux the test's own python is not one).
|
||||
with ResolverTrap(port=0, rewrite_resolv_conf=False, is_browser=lambda pid: True) as trap:
|
||||
assert trap.port > 0
|
||||
refused = _udp_ask(trap.port, "leak.test")
|
||||
assert refused[0:2] == b"\x00\x4d" and refused[3] & 0xF == ds.RCODE_REFUSED
|
||||
@@ -196,7 +198,7 @@ if ResolverTrap.available:
|
||||
def test_the_trap_points_resolv_conf_at_itself_and_restores_it_byte_for_byte():
|
||||
from pathlib import Path
|
||||
original = Path("/etc/resolv.conf").read_bytes()
|
||||
with ResolverTrap({"page-d.test": "127.0.0.1"}) as trap:
|
||||
with ResolverTrap({"page-d.test": "127.0.0.1"}, is_browser=lambda pid: True) as trap:
|
||||
assert b"nameserver 127.0.0.1" in Path("/etc/resolv.conf").read_bytes()
|
||||
assert socket.gethostbyname("page-d.test") == "127.0.0.1"
|
||||
assert trap.asked("page-d.test")
|
||||
|
||||
@@ -12,7 +12,8 @@ import socket
|
||||
import pytest
|
||||
|
||||
from _doh_servers import QTYPE_A, encode_query
|
||||
from _leaks import ResolverTrap, owner_of_the_peer, uid_from_proc_net
|
||||
from _leaks import (Asker, ResolverTrap, descends_from, owner_of_the_peer, row_from_proc_net, uid_from_proc_net,
|
||||
under_a_browser, who_asked)
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
@@ -69,7 +70,7 @@ def test_a_question_of_another_user_is_answered_and_listed_not_counted():
|
||||
owner_of=lambda protocol, peer: 1001) as trap:
|
||||
assert _ask(trap, "github.com"), "a question of another user is still answered"
|
||||
assert trap.names() == [] and trap.queries == []
|
||||
assert [(q.name, uid) for q, uid in trap.foreign] == [("github.com", 1001)]
|
||||
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()
|
||||
|
||||
|
||||
@@ -110,3 +111,82 @@ def test_the_owner_of_a_question_that_waits_for_its_answer_is_always_found():
|
||||
answered = sum(1 for _ in range(200) if _ask(trap, "page-w.test"))
|
||||
assert answered == 200 and len(trap.queries) == 200 and trap.foreign == []
|
||||
assert len(unreadable) == (200 if not sys.platform.startswith("linux") else 0), unreadable[:3]
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------- by the tree of processes
|
||||
#: A machine: the test is pid 100 (its core makes its own requests); the browser is 400, started by the test, with a content
|
||||
#: process 777 under it; the agent of the runner is 555 under the provisioner 90 - as ROOT too, the user a filter cannot tell
|
||||
#: from the root browser.
|
||||
PARENT = {400: 100, 777: 400, 555: 90, 90: 1, 650: 100}
|
||||
BROWSERS = {400}
|
||||
|
||||
|
||||
def _trap(owner, answers, **kwargs):
|
||||
return ResolverTrap(answers, port=0, rewrite_resolv_conf=False, only_uid=0, root_pid=100, parent_of_pid=PARENT.get,
|
||||
is_browser=lambda pid: pid in BROWSERS, owner_of=owner, **kwargs)
|
||||
|
||||
|
||||
def test_a_process_is_the_root_or_one_of_its_descendants():
|
||||
assert descends_from(100, 100, PARENT.get) and descends_from(777, 100, PARENT.get) and descends_from(400, 100, PARENT.get)
|
||||
assert not descends_from(555, 100, PARENT.get)
|
||||
assert not descends_from(300, 100, PARENT.get), "a process with no known parent is not a descendant"
|
||||
|
||||
|
||||
def test_the_browser_and_what_it_starts_are_under_a_browser_and_the_test_and_the_rest_are_not():
|
||||
def under(pid):
|
||||
return under_a_browser(pid, 100, PARENT.get, lambda p: p in BROWSERS)
|
||||
assert under(400) and under(777)
|
||||
assert not under(100), "the test process is not the browser"
|
||||
assert not under(650), "a process the test started that is not a browser (a download) is not the browser"
|
||||
assert not under(555) and not under(300)
|
||||
|
||||
|
||||
def test_a_row_of_proc_net_gives_the_user_and_the_inode():
|
||||
assert row_from_proc_net(UDP_TABLE, 0xC350) == (1001, 67890)
|
||||
assert row_from_proc_net(UDP_TABLE, 4242) is None
|
||||
|
||||
|
||||
def test_a_root_process_that_is_not_the_browsers_is_foreign_even_with_the_same_user():
|
||||
"""The agent of the runner runs as root, like the browser under sudo: the user cannot separate them, the tree does."""
|
||||
with _trap(lambda protocol, peer: Asker(0, 555, "Runner.Provisioner: /opt/agent/provisioner"), {"github.com": "127.0.0.1"}) as trap:
|
||||
assert _ask(trap, "github.com")
|
||||
assert trap.names() == [] and [q.name for q, _ in trap.foreign] == ["github.com"]
|
||||
say = trap.describe()
|
||||
assert "github.com from pid 555" in say and "Runner.Provisioner" in say and "not counted" in say
|
||||
|
||||
|
||||
def test_the_test_process_itself_and_its_own_python_are_not_the_browser():
|
||||
"""The core of the test process asks github.com for the latest GeoIP tag: a question of the test, not of the browser."""
|
||||
for pid in (100, 650):
|
||||
with _trap(lambda protocol, peer, pid=pid: Asker(0, pid, "python"), {"github.com": "127.0.0.1"}) as trap:
|
||||
_ask(trap, "github.com")
|
||||
assert trap.names() == [] and len(trap.foreign) == 1, pid
|
||||
|
||||
|
||||
def test_the_browser_and_what_it_starts_are_counted():
|
||||
for pid in (400, 777):
|
||||
with _trap(lambda protocol, peer, pid=pid: Asker(0, pid, "firefox"), {"page-d.test": "127.0.0.1"}) as trap:
|
||||
assert _ask(trap, "page-d.test")
|
||||
assert trap.names() == ["page-d.test"] and trap.foreign == [], pid
|
||||
|
||||
|
||||
def test_a_process_that_cannot_be_traced_is_judged_by_its_user():
|
||||
with _trap(lambda protocol, peer: Asker(1001, None, ""), {"a.test": "127.0.0.1"}) as trap:
|
||||
_ask(trap, "a.test")
|
||||
assert trap.names() == [] and len(trap.foreign) == 1
|
||||
with _trap(lambda protocol, peer: Asker(0, None, ""), {"b.test": "127.0.0.1"}) as trap:
|
||||
_ask(trap, "b.test")
|
||||
assert trap.names() == ["b.test"] and trap.foreign == []
|
||||
|
||||
|
||||
def test_the_kernel_names_this_process_as_the_asker_of_its_own_socket():
|
||||
"""On Linux the socket of this process leads, by its inode, to this process and its command; elsewhere nobody is found."""
|
||||
import os
|
||||
import sys
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as mine:
|
||||
mine.bind(("127.0.0.1", 0))
|
||||
asker = who_asked("udp", mine.getsockname())
|
||||
if sys.platform.startswith("linux"):
|
||||
assert asker is not None and asker.pid == os.getpid() and asker.uid == os.geteuid() and asker.command != ""
|
||||
else:
|
||||
assert asker is None
|
||||
@@ -0,0 +1,105 @@
|
||||
"""The browser of the suite ``wrapper.e2e.udp.sandbox`` runs with its sandbox ON, as it does for a user whose system allows user namespaces.
|
||||
|
||||
Why this file exists (run 43188313516, diagnosis of the root legs): on the Ubuntu 24.04 runner a normal user is refused user namespaces by
|
||||
AppArmor (``kernel.apparmor_restrict_unprivileged_userns``), so the browser starts WITHOUT the sandbox of its socket and content processes and
|
||||
every non-root suite passed on a browser that no user with a sandbox runs; as root the namespace is allowed, the sandbox is on, and the gather
|
||||
of a PeerConnection came back empty. The suite of this file is the non-root leg that turns the restriction off (``sysctl``, in the gate), so
|
||||
the browser has its sandbox like on any Linux that allows it, and this test is what makes the leg mean something: it FAILS when the sandbox
|
||||
is not on, because a green run of WebRTC on an unsandboxed browser proves nothing about the sandboxed one.
|
||||
|
||||
It reads the kernel's word: ``Seccomp: 2`` (a filter is installed) in ``/proc/<pid>/status`` of the socket process and of a tab process.
|
||||
Linux only (the suite is listed for Linux only).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
|
||||
def _seccomp(pid: int) -> str:
|
||||
try:
|
||||
for line in pathlib.Path("/proc/%d/status" % pid).read_text(encoding="utf-8", errors="replace").splitlines():
|
||||
if line.startswith("Seccomp:"):
|
||||
return line.split(":", 1)[1].strip()
|
||||
except OSError:
|
||||
return "gone"
|
||||
return "?"
|
||||
|
||||
|
||||
# The name the kernel keeps for a process (``Name:`` in /proc/<pid>/status, set by the browser itself) -> its kind.
|
||||
_KIND_BY_NAME = {"Socket Process": "socket", "Web Content": "tab"}
|
||||
|
||||
|
||||
def _children_of(binary: str):
|
||||
"""(pid, kind) of every child process of ``binary``; the kind is ``socket`` or ``tab`` (other kinds are named by their last word).
|
||||
|
||||
A process that the fork server makes (every tab) has NO ``tab`` at the end of its command line: it is forked, not exec'ed, so its argv is the
|
||||
one of the fork server, and the browser then overwrites it with a single string (``<binary> -contentproc``) that has no NUL in it. Only the
|
||||
socket process, which is exec'ed, keeps the full argument list. So the kind of a process comes from its last argument when that is one of the
|
||||
known words, and from the name the browser gave it (``Web Content``, ``Socket Process``) otherwise.
|
||||
"""
|
||||
target = os.path.realpath(binary)
|
||||
found = []
|
||||
for entry in pathlib.Path("/proc").iterdir():
|
||||
if not entry.name.isdigit():
|
||||
continue
|
||||
try:
|
||||
exe = os.path.realpath(os.readlink(entry / "exe"))
|
||||
raw = (entry / "cmdline").read_bytes()
|
||||
status = (entry / "status").read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
continue
|
||||
words = [w.decode("utf-8", "replace") for w in raw.split(b"\0") if w]
|
||||
if exe != target or "-contentproc" not in raw.decode("utf-8", "replace"):
|
||||
continue
|
||||
name = next((l.split(":", 1)[1].strip() for l in status.splitlines() if l.startswith("Name:")), "")
|
||||
kind = words[-1] if words and words[-1] in ("socket", "tab") else _KIND_BY_NAME.get(name, words[-1] if words else name)
|
||||
found.append((int(entry.name), kind))
|
||||
return found
|
||||
|
||||
|
||||
def _kernel_says() -> str:
|
||||
out = []
|
||||
for name in ("kernel.apparmor_restrict_unprivileged_userns", "kernel.unprivileged_userns_clone", "user.max_user_namespaces"):
|
||||
path = pathlib.Path("/proc/sys") / name.replace(".", "/")
|
||||
try:
|
||||
out.append("%s=%s" % (name, path.read_text(encoding="utf-8").strip()))
|
||||
except OSError:
|
||||
out.append("%s=(absent)" % name)
|
||||
return ", ".join(out) + ", uid=%d" % os.getuid()
|
||||
|
||||
|
||||
def test_the_socket_process_and_a_tab_process_have_a_seccomp_filter(firefox_binary):
|
||||
with InvisiblePlaywright(headless=True, binary_path=firefox_binary) as browser:
|
||||
page = browser.new_page()
|
||||
# A PeerConnection makes the socket process do what the UDP line is about.
|
||||
page.evaluate("""async () => {
|
||||
const pc = new RTCPeerConnection();
|
||||
pc.createDataChannel('x');
|
||||
await pc.setLocalDescription(await pc.createOffer());
|
||||
await new Promise(r => setTimeout(r, 1500));
|
||||
}""")
|
||||
sockets, tabs = [], []
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
kids = _children_of(firefox_binary)
|
||||
sockets = [pid for pid, kind in kids if kind == "socket"]
|
||||
tabs = [pid for pid, kind in kids if kind == "tab"]
|
||||
if sockets and tabs:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
say = {pid: _seccomp(pid) for pid in sockets + tabs}
|
||||
known = "socket %s, tab %s; %s" % (sockets, tabs, _kernel_says())
|
||||
assert sockets, "the browser has no socket process after a PeerConnection (%s)" % known
|
||||
assert tabs, "the browser has no tab process (%s)" % known
|
||||
unsandboxed = {pid: s for pid, s in say.items() if s != "2"}
|
||||
assert unsandboxed == {}, (
|
||||
"these processes run without a seccomp filter (Seccomp in /proc/<pid>/status is not 2): %s. The browser is not "
|
||||
"sandboxed on this machine, so this leg proves nothing about WebRTC with the sandbox on (%s)" % (unsandboxed, known))
|
||||
@@ -0,0 +1,102 @@
|
||||
"""The witness binds TCP and UDP on one port number even where the system's picks fall, one after the other, in a range UDP may not bind.
|
||||
|
||||
The known-bad case, seen on a Windows work machine: ``Witness("127.0.0.1")`` failed with WinError 10013 in three unit tests, while the
|
||||
push before had passed them. Windows hands out ephemeral TCP ports in sequence and keeps excluded ranges of a hundred ports for UDP in
|
||||
the same zone; the old witness asked the system for a TCP port twenty times, got twenty consecutive numbers inside one UDP range, and
|
||||
gave up. Here a fake socket layer does the same, without the machine: the system's TCP picks are 50000, 50001, ... and UDP refuses
|
||||
50000-50199. The old witness is red on it (20 refusals), this one finds a number outside the range. No browser, no real socket.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import types
|
||||
|
||||
import pytest
|
||||
|
||||
import _witness
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
REFUSED = range(50000, 50200)
|
||||
|
||||
|
||||
class _Layer:
|
||||
"""A socket module whose TCP picks are sequential and whose UDP refuses REFUSED (or everything, with ``refuse_all``)."""
|
||||
|
||||
AF_INET, SOCK_STREAM, SOCK_DGRAM, SOL_SOCKET, SO_REUSEADDR = 2, 1, 2, 1, 2
|
||||
|
||||
def __init__(self, refuse_all=False):
|
||||
self.next_pick = 50000
|
||||
self.refuse_all = refuse_all
|
||||
self.udp_tries = []
|
||||
self.inet_aton = _witness.socket.inet_aton
|
||||
|
||||
def socket(self, family, kind):
|
||||
return _Socket(self, kind)
|
||||
|
||||
|
||||
class _Socket:
|
||||
def __init__(self, layer, kind):
|
||||
self.layer, self.kind, self.port = layer, kind, None
|
||||
|
||||
def setsockopt(self, *args):
|
||||
pass
|
||||
|
||||
def bind(self, where):
|
||||
address, port = where
|
||||
if self.kind == _Layer.SOCK_STREAM:
|
||||
if port == 0:
|
||||
port = self.layer.next_pick
|
||||
self.layer.next_pick += 1
|
||||
self.port = port
|
||||
return
|
||||
self.layer.udp_tries.append(port)
|
||||
if self.layer.refuse_all or port in REFUSED:
|
||||
raise PermissionError(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 recvfrom(self, size):
|
||||
raise OSError("closed")
|
||||
|
||||
def accept(self):
|
||||
raise OSError("closed")
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
def test_the_witness_binds_both_on_one_number_outside_a_refused_udp_range(monkeypatch):
|
||||
layer = _Layer()
|
||||
monkeypatch.setattr(_witness, "socket", types.SimpleNamespace(**{k: getattr(layer, k) for k in (
|
||||
"AF_INET", "SOCK_STREAM", "SOCK_DGRAM", "SOL_SOCKET", "SO_REUSEADDR", "inet_aton", "socket")}))
|
||||
w = _witness.Witness("127.0.0.1")
|
||||
try:
|
||||
assert w.port not in REFUSED, "the witness took a number UDP refuses: %d" % w.port
|
||||
assert w._tcp.port == w._udp.port == w.port, "TCP and UDP are not on one number"
|
||||
assert layer.udp_tries[0] in REFUSED, "the fake did not make the system's first pick a refused one: %r" % layer.udp_tries[:3]
|
||||
finally:
|
||||
w.close()
|
||||
|
||||
|
||||
def test_a_witness_that_can_bind_nothing_says_so_after_a_bounded_number_of_tries(monkeypatch):
|
||||
layer = _Layer(refuse_all=True)
|
||||
monkeypatch.setattr(_witness, "socket", types.SimpleNamespace(**{k: getattr(layer, k) for k in (
|
||||
"AF_INET", "SOCK_STREAM", "SOCK_DGRAM", "SOL_SOCKET", "SO_REUSEADDR", "inet_aton", "socket")}))
|
||||
with pytest.raises(OSError) as raised:
|
||||
_witness.Witness("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(layer.udp_tries) == _witness.TRIES, "the witness tried %d times, not %d" % (len(layer.udp_tries), _witness.TRIES)
|
||||
|
||||
|
||||
def test_a_port_that_is_asked_for_is_tried_once_and_its_refusal_raised(monkeypatch):
|
||||
layer = _Layer()
|
||||
monkeypatch.setattr(_witness, "socket", types.SimpleNamespace(**{k: getattr(layer, k) for k in (
|
||||
"AF_INET", "SOCK_STREAM", "SOCK_DGRAM", "SOL_SOCKET", "SO_REUSEADDR", "inet_aton", "socket")}))
|
||||
with pytest.raises(PermissionError):
|
||||
_witness.Witness("127.0.0.1", 50050)
|
||||
assert layer.udp_tries == [50050]
|
||||
@@ -195,6 +195,13 @@ def _pinned_core(py: Path) -> str:
|
||||
return m.group(1)
|
||||
|
||||
|
||||
def _previous_and_latest(released: list[str]) -> tuple[str, str]:
|
||||
"""The release to upgrade FROM and the one to upgrade TO, both from the one listing the install then uses: the two
|
||||
newest of ``released`` (newest last). A bare ``--upgrade`` asks the index again for "the latest", and an index page
|
||||
that lags (run of the ledger of 0.50.1: the listing had 0.50.1, the upgrade resolved 0.49.1) answers with the old one."""
|
||||
return released[-2], released[-1]
|
||||
|
||||
|
||||
def _released_versions(py: Path, dist: str) -> list[str]:
|
||||
"""Versions the index will serve, newest last. Read from pip itself so the
|
||||
test does not carry a hardcoded list that goes stale on the next release."""
|
||||
@@ -230,7 +237,7 @@ def test_upgrading_from_the_previous_release_moves_the_core_too(workspace: Path)
|
||||
released = _released_versions(py, WRAPPER)
|
||||
if len(released) < 2:
|
||||
pytest.skip("only one release on the index; nothing to upgrade FROM")
|
||||
previous = released[-2]
|
||||
previous, latest = _previous_and_latest(released)
|
||||
|
||||
_run([str(py), "-m", "pip", "install", "--no-cache-dir",
|
||||
f"{WRAPPER}=={previous}"], timeout=900)
|
||||
@@ -238,10 +245,10 @@ def test_upgrading_from_the_previous_release_moves_the_core_too(workspace: Path)
|
||||
assert before["wrapper"] == previous
|
||||
|
||||
_run([str(py), "-m", "pip", "install", "--no-cache-dir", "--upgrade",
|
||||
WRAPPER], timeout=900)
|
||||
f"{WRAPPER}=={latest}"], timeout=900)
|
||||
after = _versions(py)
|
||||
|
||||
assert after["wrapper"] != previous, "the upgrade did not move the wrapper"
|
||||
assert after["wrapper"] == latest, "the upgrade did not move the wrapper to %s: %s" % (latest, after["wrapper"])
|
||||
_run([str(py), "-m", "pip", "check"], timeout=180)
|
||||
|
||||
declared = _run([str(py), "-c",
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""The e2e tests that count processes count the ones that host a site, not every new content process. No browser.
|
||||
"""The e2e tests that look at processes ask for the processes of a site by its name. No browser.
|
||||
|
||||
The engine keeps preallocated content processes and starts one to refill the pool after it hands one to a site,
|
||||
whenever it gets to it. The bench counted every `-contentproc ... tab` pid, so a refill that landed between its
|
||||
two reads was "a process the same-site frame started" (test_same_site_other_port_stays_in_process, red on the
|
||||
e2e of the commit of 0.50.0: `[13443]`). The processes below are the ones measured on firefox-62 (Linux):
|
||||
names and command lines as /proc gives them.
|
||||
With `fission.processSiteNames` on, a content process that hosts a site is named by that site, and on Linux the name
|
||||
is cut at 15 characters. The browser starts processes of its own (the pool refill, a process for a Mozilla site
|
||||
started by the New Tab page), so a test that compared two counts of processes read them as the effect of the frame
|
||||
under test (test_same_site_other_port_stays_in_process, red in 14 of 30 runs of the e2e suite). The names below are
|
||||
the ones measured on firefox-62 (Linux), with command lines as /proc gives them.
|
||||
"""
|
||||
import _processes
|
||||
import pytest
|
||||
@@ -13,10 +13,11 @@ pytestmark = pytest.mark.unit
|
||||
|
||||
ENGINE = "/cache/firefox-62/firefox"
|
||||
DIR = "/cache/firefox-62"
|
||||
A, B = "http://a.test", "http://b.test"
|
||||
|
||||
|
||||
class _Proc:
|
||||
def __init__(self, pid, name, kind, exe=ENGINE):
|
||||
def __init__(self, pid, name, kind="tab", exe=ENGINE):
|
||||
self.pid, self._name, self._exe = pid, name, exe
|
||||
self._cmd = [exe, "-contentproc", "-isForBrowser", "-prefsLen", "1", "-parentBuildID", "20261111073531",
|
||||
"-appDir", DIR + "/browser", str(pid), kind]
|
||||
@@ -31,35 +32,57 @@ class _Proc:
|
||||
return self._cmd
|
||||
|
||||
|
||||
def _engine_at_plain():
|
||||
"""a.test/plain shown: one process for the site, three preallocated, and the engine's other children."""
|
||||
return [_Proc(184, "Socket Process", "socket"), _Proc(200, "WebExtensions", "tab"),
|
||||
_Proc(334, "Isolated Web Co", "tab"), _Proc(377, "Privileged Cont", "tab"),
|
||||
_Proc(433, "Web Content", "tab"), _Proc(438, "Web Content", "tab"), _Proc(460, "Web Content", "tab")]
|
||||
def _engine_at_a():
|
||||
"""a.test shown: its process, the one the New Tab page started, and the engine's other children."""
|
||||
return [_Proc(184, "Socket Process", "socket"), _Proc(200, "WebExtensions"), _Proc(334, "http://a.test^u"),
|
||||
_Proc(377, "Privileged Cont"), _Proc(410, "mozgcp.net"), _Proc(433, "Web Content"),
|
||||
_Proc(438, "Web Content")]
|
||||
|
||||
|
||||
def test_a_preallocated_process_that_arrives_is_not_a_site():
|
||||
before = _processes.site_pids(_engine_at_plain(), DIR)
|
||||
after = _processes.site_pids(_engine_at_plain() + [_Proc(549, "Web Content", "tab")], DIR)
|
||||
def test_a_process_named_by_the_site_is_the_sites():
|
||||
assert _processes.site_pids(_engine_at_a(), A, DIR) == {334}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["mozgcp.net", "Web Content", "Privileged Cont", "WebExtensions", "Isolated Web Co"])
|
||||
def test_a_process_with_another_name_is_not_the_sites(name):
|
||||
assert _processes.site_pids([_Proc(1, name)], A) == set()
|
||||
|
||||
|
||||
def test_the_process_of_another_site_is_not_the_sites():
|
||||
assert _processes.site_pids([_Proc(1, "http://b.test^u")], A) == set()
|
||||
assert _processes.site_pids([_Proc(1, "http://b.test^u")], B) == {1}
|
||||
|
||||
|
||||
def test_the_process_the_browser_starts_for_itself_does_not_move_the_sites():
|
||||
"""The measured flaw: a second isolated process (mozgcp.net) arriving between two reads changed the old count."""
|
||||
before = _processes.site_pids(_engine_at_a(), A, DIR)
|
||||
after = _processes.site_pids(_engine_at_a() + [_Proc(549, "mozgcp.net"), _Proc(550, "Web Content")], A, DIR)
|
||||
assert before == after == {334}
|
||||
|
||||
|
||||
def test_a_preallocated_process_given_to_a_site_is_a_new_site_process():
|
||||
"""A cross-site frame: 433 leaves the pool for b.test (and is renamed), 549 refills the pool."""
|
||||
procs = [p for p in _engine_at_plain() if p.pid != 433]
|
||||
procs += [_Proc(433, "Isolated Web Co", "tab"), _Proc(549, "Web Content", "tab")]
|
||||
assert _processes.site_pids(procs, DIR) - _processes.site_pids(_engine_at_plain(), DIR) == {433}
|
||||
def test_https_is_dropped_from_the_site():
|
||||
assert _processes.name_of_site("https://example.com") == "example.com"
|
||||
assert _processes.hosts_site("example.com", "https://example.com")
|
||||
assert _processes.hosts_site("example.com^use", "https://example.com")
|
||||
|
||||
|
||||
def test_a_site_longer_than_the_name_matches_on_its_first_15_characters():
|
||||
site = "http://a-very-long-site.example"
|
||||
assert _processes.name_of_site(site) == "http://a-very-l"
|
||||
assert _processes.hosts_site("http://a-very-l", site)
|
||||
assert not _processes.hosts_site("http://a-very-x", site)
|
||||
|
||||
|
||||
def test_a_site_that_starts_like_another_is_not_the_other():
|
||||
assert not _processes.hosts_site("http://a.testin", A)
|
||||
assert not _processes.hosts_site("http://a.testing.example", A)
|
||||
assert _processes.hosts_site("http://a.test^u", A)
|
||||
|
||||
|
||||
def test_a_process_of_another_firefox_is_not_counted():
|
||||
other = _Proc(900, "Isolated Web Co", "tab", exe="/usr/lib/firefox/firefox")
|
||||
assert _processes.site_pids(_engine_at_plain() + [other], DIR) == {334}
|
||||
other = _Proc(900, "http://a.test^u", exe="/usr/lib/firefox/firefox")
|
||||
assert _processes.site_pids(_engine_at_a() + [other], A, DIR) == {334}
|
||||
|
||||
|
||||
def test_the_pool_refilled_behind_a_closed_context_is_not_a_process_left():
|
||||
"""After the fourth closed context of test_a_context_that_ends_leaves_no_process_e2e, as measured: three
|
||||
preallocated processes and no site. Counting every content process said 5 ([2, 2, 2, 5, 5])."""
|
||||
left = [_Proc(1219, "WebExtensions", "tab"), _Proc(1382, "Privileged Cont", "tab"),
|
||||
_Proc(1739, "Web Content", "tab"), _Proc(1744, "Web Content", "tab"), _Proc(1821, "Web Content", "tab")]
|
||||
assert _processes.site_pids(left) == set()
|
||||
assert _processes.site_pids(left + [_Proc(1900, "Isolated Web Co", "tab")]) == {1900}
|
||||
def test_a_process_that_is_not_a_tab_is_not_counted():
|
||||
assert _processes.site_pids([_Proc(1, "http://a.test^u", kind="gpu")], A) == set()
|
||||
Reference in new issue
Block a user