Compare commits

...
Author SHA1 Message Date
feder-crandClaude Sonnet 5.5 4ea36371f5 ci: e2e.yml runs the Control+A e2e on Windows, on the published engine, as a job of its own (dispatchable alone with only=windows-control-a)
tests/test_control_a_selects_all_in_a_field_e2e.py (5 ways to press the shortcut x an <input> and a <textarea>, in-process and served to the stock
client) is red on the keyboard that held Shift for the capital A and was measured on Linux; the keyboard of a user is Windows. The new job
installs the wrapper (which pins the core of the release), fetches the published engine and runs that file on windows-latest with bash as the
shell, behind the same core-on-index gate as the Linux job: skipped with the reason in the summary until the core is on the index. The
workflow_dispatch input `only` lets it run alone (`windows-control-a`) without the 40 minutes of the Linux job.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 17:41:31 +01:00
feder-crandClaude Sonnet 5.5 9b0f474bc8 tests: Control+A selects all in an input and a textarea, in-process and served to the stock client (e2e, red on the keyboard that held Shift for the capital A)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 17:41:30 +01:00
feder-crandClaude Sonnet 5.5 97ba055d77 Release 0.51.0: the CHANGELOG line of the process tests says only what is proven
Markdown only. The line that came with the end-to-end process tests carried a count of red runs and a cause of the extra
process that nothing saved; it now says that these are tests only and what they ask for.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:22:27 +01:00
feder-crandClaude Opus 5.5 54b2f26c69 tests: the popup process case runs its own browser in a thread of its own
The e2e of the previous commit failed at setup: the module's browser of the
matrix keeps a sync client open in the test's thread, and a second sync client
refuses to start inside its loop ("Sync API inside the asyncio loop"). The case
now opens its quiet browser in a thread with no loop and hands back its result
or its error. Same count of tests (34), still no skip on any system.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:04:14 +01:00
feder-crandClaude Opus 5.5 6d23f75229 tests: the popup process case has a browser that starts no process by itself, and asks by name on Linux
test_the_other_site_popup_runs_in_another_process counted every content process
between two reads, so a process the browser starts by itself (the pool refill,
the preloaded New Tab page and, in some countries, a process for a Mozilla
site) was taken for the popup's doing. It now has a browser of its own, on each
transport, with no preallocated processes and no preloaded New Tab page
(test-only prefs), so the count between two reads is the popup's. On Linux it
also asks by name that one of the new processes is the process of localhost.

It still runs on Windows, with no skip: the required suite wrapper.e2e.page
collects this file on both systems with an exact count, which is unchanged (34).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:01:53 +01:00
feder-crandClaude Sonnet 5.5 beff30e822 tests: ask for the processes of a site by its name, never count between two reads
The e2e tests that looked at content processes compared the set of
"Isolated Web Co" processes before and after an action. The browser starts
processes of its own: the pool refill, and a process for a Mozilla site
(webIsolated=https://mozgcp.net) that the New Tab page starts about a second
after its own, with any page. Under load it was born between the two reads:
the same-site control was red in 14 of 30 runs of the whole e2e suite
([P] -> [P, P2]), the cross-site test could pass on that process alone, and
the service-worker test could read it as a process left behind.

With the test-only pref fission.processSiteNames a content process that hosts
a site is named by that site (http://a.test^u on Linux, cut at 15
characters). tests/_processes.py now returns the processes of one site by that
name; the bench and the service-worker test use it. Linux only, as before.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:01:13 +01:00
feder-crandClaude Sonnet 5.5 1382a83540 tests: the fake pip of the wait test is a regular package, so the pip of the environment cannot shadow it
CI (runs 43196645121, 43196645144): 2 tests of the wait for the index failed on every Python of both systems. The shim was a directory with a
__main__.py and no __init__.py: a namespace package, which loses to the regular package `pip` of an environment that has one (a local uv venv
has none, so it passed there). The real pip ran, said "No matching distribution" for 9.9.9 and the shim was called 0 times. Reproduced in a venv with pip;
red without the __init__.py, green with it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:00:36 +01:00
feder-crandClaude Sonnet 5.5 299fc9f5da user-install: the wait asks pip, not the JSON page of the index, and fails saying what is missing; the upgrade test installs the version its listing named
Ledger #476 of 0.50.1: the Linux job failed in test_upgrade_e2e ("the upgrade did not move the wrapper", '0.49.1' != '0.49.1') three
minutes after the upload. The step that waits for the index had asked the per-version JSON endpoint, which answered; the listing of
`pip index versions` had 0.50.1; the `pip install --upgrade` that followed was still served the 0.49.1 page.

The wait now runs `pip download --no-deps --no-cache-dir invisible-playwright==X` (the client and the index the install uses), for at most
ten minutes, and ends in "::error::the index does not have X yet, after N minutes" instead of a warning and a run that fails later. The
upgrade test takes previous and latest from one listing and installs `WRAPPER==latest`. Four unit tests run the script of the step with a
pip that fails until its Nth call; the core's install_job gate still passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 16:00:36 +01:00
feder-crandClaude Sonnet 5.5 fe5cb50ed3 Release 0.51.0: the CHANGELOG and the README say only what is proven (counter: what the package refuses and whose repository counts; the real name of the async class; the popup numbers of the register; Windows memory only; addBinding out)
Markdown only. Following the fact check of the release texts: the launch counter is refused by the package's launcher and server
(not "not optional" for the engine alone) and counted in the engine's repository; preload_newtab names the async class by its real
path and keeps only the Windows numbers that have a saved run, with the engine they were taken on; the protocol mirror line about
Page.addBinding is out (not shown for the pinned engine); the differences section no longer claims a comparison run nobody saved;
the popup known issue states where, with which client, on which engines and with how much load it was seen, with the numbers of the
register, and that the correction is in 0.51.1.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 15:49:06 +01:00
feder-crandClaude Sonnet 5.5 2d1bc68b26 tests: the HTTP/3 test server finds a port that TCP and UDP both bind where the system's picks fall in a refused UDP range
wrapper.e2e.web on the Windows runner (republish run 43230437094) failed three tests with "no port free for both TCP and UDP",
and the pre-push failed the same way on a work machine: 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. The first try is still the system's pick; the others are drawn at random below the dynamic range, as
the witness already does (same constants), and the refusals are named in the error.

Two tests with a fake socket layer (TCP picks 50000, 50001, ...; UDP refuses 50000-50199): the old loop is red on it, this one
finds a number outside the range; and a server that can bind nothing says so after a bounded number of tries. wrapper.unit.udp
goes from 219 to 221 tests (ci/required-suites.json).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 15:12:49 +01:00
feder-crandClaude Sonnet 5.5 3b594b85ed tests: the two tests that ask the resolver trap from the test process say that the test stands for the browser
Since fc10e257ca the trap counts only the questions of a browser process, found by the process that holds the socket in
/proc/net. That is only possible on Linux; on Windows every question counts, so the pre-push (Windows) stayed green
while test_the_trap_counts_a_query_it_is_sent_and_refuses_what_it_cannot_answer failed on Linux (republish run
43230437094, wrapper.unit.udp/linux: 1 failed, 218 passed): the test asks from its own python, which is not a browser,
and the question went to `foreign`. The same holds for the resolv.conf test of the root legs.

Both tests now pass is_browser=lambda pid: True. The trap itself is unchanged, so the realness leg judges the same code.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 14:58:21 +01:00
feder-crandClaude Sonnet 5.5 8d1356cb69 Release 0.51.0: the served launch cannot turn the launch counter off (a client's firefoxUserPrefs, bare or marked, are refused with the core's message); the history says it is no longer possible
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 14:41:19 +01:00
feder-crandClaude Sonnet 5.5 0a5961270a Release 0.51.0: the README says what the launch counter is and how to turn it off; the CHANGELOG says what is known to be wrong (popups opened without a route, as measured)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 14:30:14 +01:00
feder-cr 07b7b74e08 Release 0.51.0: engine firefox-63, pin invisible-core 63.66.0; CHANGELOG for the UDP line 2026-11-12 14:00:10 +01:00
feder-crandClaude Opus 5.5 710ee498ba juggler: an early download finish lives only as long as it can be read
The review of 6a50ad1 found three cases where an entry of _finished_early
stayed for the life of the browser: (a) a download announced while its
context was already closed, whose finish came after; (b) a finish after the
client released the artifact; (c) a finish of a uuid never announced.

The browser now keeps, per announced download, the context it belongs to,
until its finish or the end of that context. A finish whose download was
announced and whose artifact is gone writes nothing; only a finish of a
download not announced yet leaves an early entry, and those are bounded (64,
the oldest dropped first). The end of a context forgets its downloads that
never finished.

Tests, red on 6a50ad1 (4 of 10): (e) gone context, (f) released artifact,
(g) never-announced finishes are bounded, (h) the end of a context forgets.

NOT proven: that the engine ever sends a finish after the end of a context,
or a finish before the announcement. On one connection Juggler says a
download's creation before its end (TargetRegistry.js interceptDownloadRequest
then onDownloadComplete), so the early path is defensive. The e2e of tiny
downloads is a proof of use, not of the order; its docstring says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 13:54:42 +01:00
feder-crandClaude Sonnet 5.5 9883d3f455 juggler: a download that finished before it was announced is finished
BrowserDispatcher._on_download_finished keeps the error of a download whose
artifact does not exist yet; a successful download has no error (None), and
_on_download_created popped it with a None default and tested `is not None`,
so the artifact was never marked finished and save_as, path and failure
waited forever. A module-level sentinel tells "nothing recorded" from
"finished with no error". The entry is also popped before the
unknown-context early return, so it no longer stays in the dict.

Tests: unit file (red on the old code for the success and the gone-context
cases) and a served-browser e2e with ten 300-byte and ten 1-byte downloads.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 13:54:42 +01:00
feder-cr 7c79ba1ed4 Merge remote-tracking branch 'origin/main' into release/0.51.0-prep (#477, #478, #480) 2026-11-12 13:54:41 +01:00
feder-crandClaude Sonnet 5.5 fc10e257ca tests: the resolver trap counts the BROWSER (a browser process and what it starts), not the test process nor the core it runs: the core asks github.com for the latest GeoIP tag as root, the test says the browser asked
Measured on Linux: a process named firefox and its child counted 20 of 20 each; the test's own python and an orphan of the same user foreign 20 of 20 each.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 13:50:37 +01:00
feder-crandClaude Sonnet 5.5 78277565f5 tests: the resolver trap counts the questions of the processes of the test (the socket's inode, the process that holds it, its parents), not of a user; a question of any other process is listed with its pid and command
Runs 43188313516 and 43211837926: on the runner the agent of the runner, as root like the browser under sudo, asks for github.com, api.github.com and its orchestrator
through the trap's /etc/resolv.conf, and a user filter cannot tell it from the browser (6 realness tests red). Measured on Linux, 40 questions of a descendant and
40 of an orphan process of the same user: 40 counted, 40 foreign, each with its pid and command. One whose process cannot be traced is judged by its user, one whose
socket is gone counts as the browser's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 13:38:35 +01:00
feder-crandClaude Sonnet 5.5 0a0d0d689d tests: the sandbox leg finds the tab processes (forked by the fork server, their argv has no 'tab' at the end): the kind comes from the last word, else from the Name in /proc/<pid>/status
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 13:14:07 +01:00
feder-crandClaude Sonnet 5.5 ff02f112fe ci: wrapper.unit.udp counts the three tests of the witness port pick (198)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 12:45:34 +01:00
feder-crandClaude Opus 5.5 016eccab9e tests: the UDP witness binds TCP and UDP on one number even where the system's picks fall in a refused UDP range
Witness("127.0.0.1") failed with WinError 10013 in three unit tests of
wrapper.unit.udp on a Windows work machine, 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 witness asked the
system for a TCP port twenty times, got twenty consecutive numbers inside one
UDP range, and gave up.

Now each try binds TCP and then UDP on the same number, and if either is
refused both are released and another number is tried: the first is the
system's own pick, the others are drawn at random below both Windows'
dynamic range and Linux's ephemeral range, so they are not the next of a
sequence. 200 tries at most, then an error that names the address and the
last refusals. A port asked for is tried once and its refusal raised.

Test, red on the old code (2 of 3): a fake socket layer whose TCP picks are
sequential and whose UDP refuses 50000-50199. Real sockets on that machine,
20 runs of the witness tests each: old 19 of 20 green, new 20 of 20.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:44:58 +01:00
feder-crandClaude Sonnet 5.5 db5c7ef565 ci: the preload_newtab e2e moves to wrapper.e2e.udp (seen green on Windows, 10 runs of 10): udp 43, exit 7
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 12:33:18 +01:00
feder-crandClaude Sonnet 5.5 5459a6b59e ci: wrapper.e2e.udp.sandbox (Linux, a normal user, the browser's sandbox on): the socket process and a tab process must have a seccomp filter, plus the three situations of the UDP line (a proxy with UDP, no proxy, a proxy without UDP with the ICE name by DoH)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 12:11:56 +01:00
feder-crandClaude Sonnet 5.5 483f9af50a tests: the constructor signature knows preload_newtab; the witness takes TCP first (Windows excluded ranges); the preload_newtab e2e (seen green as root on Linux) joins wrapper.e2e.udp.exit (9)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 12:00:55 +01:00
feder-crandClaude Sonnet 5.5 1d33f56100 ci: wrapper.unit.udp counts the three tests of preload_newtab (195); its e2e is in no suite until it has been seen green
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:55:51 +01:00
Federico EliaandClaude Sonnet 5.5 285e3ba93e ci: never cancel a run of main, one run per pull request commit, and test it (#477)
e2e.yml and tests.yml already ran once per commit of a pull request (push is
filtered to main, pull_request to PRs against main), but their concurrency
group was keyed on the ref and cancelled in progress everywhere. For a push to
main the ref is always refs/heads/main, so the next push cancelled the e2e
run of the commit before it, and scripts/e2e_is_green.py refuses a release
whose e2e check-run is `cancelled`. The group is now keyed on the pull request
number and cancels only on pull_request; every other event gets a group
unique to the run, so nothing on main is cancelled or replaced while pending.

user-install.yml had a group keyed on the ref that cancelled its own weekly
run when a manual one started on main; it follows the same rule. publish-wiki
no longer cancels a publish in progress. Triggers, workflow and job names
(`e2e`, `e2e (linux, xvfb)`, `gate`) are unchanged.

tests/test_ci_runs_once_per_commit.py pins the triggers the release reads, the
cancel rule and the hunt cap (max-parallel <= 8), with known-bad inputs for
each checker. It reads the workflows with a small parser because PyYAML is
not a dependency of this package.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:55:02 +01:00
feder-crandClaude Sonnet 5.5 966e2d6a8b launcher: preload_newtab, the option of the core that turns off the preloaded New Tab page
InvisiblePlaywright(preload_newtab=...) (sync, async and launch_server)
hands the core's option of the same name over, only when it is not None:
a wrapper paired with a core that does not know it cannot meet a
TypeError for a caller who never used it. None keeps the retail's
behaviour; False writes browser.newtab.preload false (no privileged-about
process); True says the retail's value aloud; a pref in extra_prefs wins.

Tests: the kwarg reaches the core only when asked and is a parameter of
every entry point; the e2e reads the process types from the engine's log
(MOZ_LOG=Process:5): privilegedabout exists by default and is absent with
the option, on every platform.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:54:21 +01:00
feder-crandClaude Sonnet 5.5 d13a9442c5 tests: a loss is not a drop - behind a proxy that cannot carry the UDP of a PeerConnection, nothing of the browser reaches a witness direct (suite wrapper.e2e.udp.exit)
The e2e that check 'no srflx' cannot tell the fail-closed rule from a leak: at an address nothing routes a datagram sent direct arrives nowhere, exactly as a dropped one.
A witness (_witness.py: a STUN server and a TCP listener at 198.51.100.10, held on lo, reachable by the browser directly) hears who contacts it, and the gateways leave from ANOTHER
documentation address (the exit, 198.51.100.9; the test gateway's TCP now leaves from it too, opt-in: tcp_from_exit). In each fail-closed scenario - a SOCKS5 proxy that refuses UDP, one whose UDP
leaves from another address, one whose relay never answers, an HTTP proxy - the witness hears no datagram and no connection from a source that is not the exit; a send direct is red. The controls
that make the green mean something: the same page with no proxy IS heard by the witness (datagram and connection), and behind a coherent gateway the witness hears the exit only.
Proved in the container on the giro 3 Linux binary (green, 7 tests of the suite). The witness and the gateway's source binding have unit tests (192). Counts: wrapper.e2e.udp.exit 7, wrapper.unit.udp 192.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:42:35 +01:00
feder-cr 2effeb1594 Merge remote-tracking branch 'origin/main' into udp/wrapper-r6 (0.50.1 notes, no_wait_after) 2026-11-12 11:36:56 +01:00
Federico EliaandClaude Fable 5.2 15d7608867 tests: no_wait_after is judged on the order of events, not on seconds (#478)
The test said the click must come back in under 2.5 s while /slow slept 3 s.
That measured the runner: on a loaded one the click alone took longer (2 of 30
runs of the suite, every run on one CPU) with nothing wrong in the product.

/slow is now an answer the server holds until the test lets it go. The click
with no_wait_after=True must come back while the answer is still held (the
order is: click returned, then answered; the url is still the old one). A new
test holds the other half: a plain click on the same link does not come back
until the answer is given, and returns on the new page.

Known-bad input, run before trusting it: the same test with no_wait_after
removed from the click is red on the order (answered, then click returned).

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 11:32:43 +01:00
Federico EliaandClaude Fable 5.2 2d9cf3a82f CHANGELOG 0.50.1: the known differences from stock Playwright, and two fixes the entry had left out (#480)
Under [0.50.1], after the record of its publication:
- Fixed: a popup reaches the client as with Playwright's own Firefox (no limit
  of time, the destination's url, load reachable), and the opener's download
  event comes after the popup's page event.
- Known differences from stock Playwright, each with its measurement: the url
  of a popup that turns into a download, the url of a frame of another site at
  DOMContentLoaded, the longer click of the library client, and back/forward
  restoring the page from the back-forward cache.

Documentation only: no published byte changes.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 11:32:17 +01:00
feder-crandClaude Sonnet 5.5 05420d83ce tests: the resolver trap counts the questions of the user that runs the test, by the owner of the socket (/proc/net), not by name; unit.udp 189
Run 43188313516: on a runner the agent of the runner asks for github.com, api.github.com and its orchestrator through the /etc/resolv.conf the trap
rewrites, and the trap blamed the browser (6 realness tests and 1 DoH test). A question whose socket belongs to another user is answered and
listed in trap.foreign, not counted. The owner is read on receipt, before the answer: measured on Linux, 3000 questions that wait for their answer,
0 unreadable; one that cannot be read counts as the browser's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:21:47 +01:00
feder-crandClaude Sonnet 5.5 03d18c853d tests: the DoH session built by hand launches on a virtual display too, and a test reads every direct InvisiblePlaywright(...) of the DoH and realness files (unit.udp 181)
Run 43188313516: test_a_session_without_a_proxy_resolves_with_the_system_resolver died with "no DISPLAY environment variable specified": it builds its
session by hand (not through _launch) and was not covered. The new test parses the files of the two suites and fails on a construction without headless=.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 11:17:40 +01:00
feder-cr 23b17c33ef Merge remote-tracking branch 'origin/main' into udp/wrapper-r6 (the ledger of 0.50.1) 2026-11-12 11:02:12 +01:00
github-actions[bot]andfeder-cr fb888c09cf record 0.50.1 as published (#476)
Co-authored-by: feder-cr <85809106+feder-cr@users.noreply.github.com>
2026-11-12 10:53:57 +01:00
feder-crandClaude Sonnet 5.5 3f56ac2e69 The old table test expects beacon for TYPE_BEACON, as the pinned driver says
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:43:22 +01:00
feder-crandClaude Sonnet 5.5 8621f0a5d6 request.resource_type agrees with the pinned driver: a beacon is beacon, a CSP report cspreport
The table that turns a Juggler cause into a Playwright resource type was a copy of the driver's and had gone stale: the pinned
driver (1.61, coreBundle.js ffNetworkManager) says `beacon` for TYPE_BEACON and `cspreport` for TYPE_CSP_REPORT; ours said `other`
for both. Measured on cnbc.com and scmp.com, our engine and Playwright's own Firefox side by side: the same POSTs (2 and about 8
per page) are `other` here and `beacon` on stock, so a client or a route filter that looks for beacons saw none.

Test (red on the old table): the driver's own table is read from the installed package and every cause it names must map to the
same type here; the next driver version that changes it fails the test, nothing is updated by hand.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:43:22 +01:00
feder-crandClaude Sonnet 5.5 9956adc386 tests: the chain by name keeps its walk on Windows (exit of the lab on loopback, with the pref) beside the one without the pref (wrapper.e2e.udp.exit, Linux)
d41ea7e moved the whole file to the Linux-only suite. Now the file holds two tests: the walk with an exit that is not loopback and no pref (wrapper.e2e.udp.exit, Linux, root), and the walk with the exit on 127.0.0.2 and media.peerconnection.ice.loopback (wrapper.e2e.udp, Linux and Windows). Selected by node id; wrapper.e2e.udp 41 again; the notes of the two suites say why.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:42:43 +01:00
feder-crandClaude Sonnet 5.5 72997c957c tests: three e2e modules of the UDP line are bound to the engine that carries it, as the others are
test_networkidle_through_a_served_browser_with_routes_e2e.py (red on firefox-61 and 62: its engine fix, 0972db59da, is in the 63), test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py
and test_turn_over_tcp_is_tried_for_real_e2e.py (red before the UDP line) had only pytest.mark.e2e, so the e2e job of main, which fetches the PUBLISHED engine, would run them
against it. They now carry usefixtures(the_udp_line): they skip on an older engine and run on the candidate (REVIEW-63 #14). The collected counts do not change
(21, 1, 2); the ids stay in ci/required-suites.json, and a skip on the candidate is still red there.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:41:44 +01:00
feder-crandClaude Sonnet 5.5 bd853bc040 tests: the QUIC of the gateway test works on Windows: the relay leaves from the host's address, is told by its port, and a send that fails is said; unit tests (unit.udp 176)
On Windows the e2e read h2 on five visits and 'the server saw QUIC from []': the relay of the gateway sent from 127.0.0.1 to an address of its own
host (WinError 10051, nothing sends from loopback to the host's address there) in a timer that ignored every OSError, after logging the datagram as carried.

- the coherent gateway of the h3 test leaves from the host's address on every system (exit_host), and its fake STUN is bound there too (Windows sends
  neither from the host's address to loopback, 10049, nor the reverse); the relay is told from a client that came direct by the PORT it sends from
  (Gateway.exit_ports, H3Server.quic_peer_addrs); it forwards only to this host (forward_only_to): the browser's own QUIC to the Internet stays in the lab.
- Gateway._later records a send that raised (send_errors) and the report of the test shows it; the test asserts there is none.
- the relay's sockets turn SIO_UDP_CONNRESET off on Windows and a ConnectionResetError no longer ends the thread that reads.
- unit tests: a failing send is recorded and reported; a relay that leaves from the host's address reaches a server there, by a port in exit_ports and not
  one of a direct client; the fake STUN answers through it. Red on the old helpers (they have no exit_host/exit_ports/send_errors).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:28:49 +01:00
feder-crandClaude Sonnet 5.5 7a0d55f4ce tests: the DoH, stress and ICE-names e2e always launch on a virtual display (headless=True, as the UDP and realness e2e); the helper that looked at the display of the host is gone; unit tests (unit.udp 177)
A test does not behave differently by the display of the machine it runs on. Replaces the helper of 302af97.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:15:10 +01:00
feder-crandClaude Sonnet 5.5 d867282c99 tests: the chain by name reads its srflx and its relay from the page with a gateway exit that is not loopback, and the loopback pref is gone
The exit of the lab is 198.51.100.9 (documentation, RFC 5737), held on lo with ip addr add for the length of the test; nICEr accepts it as a mapped
address (nr_stun_transport_addr_check rejects only wildcard, loopback and link-local), so the product's own setting is what is under test, not a pref that
is off in production. The page must read a srflx equal to the gateway's exit and the relay candidate of the TURN server it asked.
The file moves to a suite of its own, wrapper.e2e.udp.exit (Linux only, root): adding an address to an interface needs administrator and changes the network
of the host, so the Windows suite does not collect it (a skipped test would turn the verdict red). Chain takes exit_host; the TURN helper test runs for two exits.
Red on the old code: with the 127.0.0.2 exit and no pref the test fails at 0, 65 and 130 ms; green on the giro 3 Linux binary at 130 and 0 ms (container).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:14:02 +01:00
feder-crandClaude Sonnet 5.5 302af97575 tests: the DoH, stress and ICE-names e2e ask for a virtual display on a Linux machine that has none; unit tests (unit.udp 173)
Run 43176569993: 19 of 19 of wrapper.e2e.doh on Linux died at the launch with "no DISPLAY environment variable specified". Those files launched a headed browser without a screen (the runner has none, and the suite runs under sudo). The other e2e launch with headless=True, which is a headed browser on an Xvfb the wrapper starts itself. A machine with a display, and Windows, are left as they are.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 10:09:13 +01:00
feder-cr 47725170de Merge remote-tracking branch 'origin/main' into udp/wrapper-r3-next (0.50.1 is on main)
# Conflicts:
#	src/invisible_playwright/_juggler/server.py
#	tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py
#	tests/test_popup_destinations_e2e.py
#	tests/test_popups_reach_the_client_e2e.py
2026-11-12 09:52:27 +01:00
feder-crandClaude Sonnet 5.5 d56ea298b4 tests: the comment of the first-datagram test says why the core's discovery of the exit fails in the lab (no echo service is reachable), not that a fixed time zone skips it
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:51:58 +01:00
b46e5a32d3 Release 0.50.1: networkidle on a reused page and on a routed served browser, a page handed over when ready (pin invisible-core 62.65.0) (#455)
* docs: the agent links and the command name the repo as it is now

Two things were broken for a reader on main, not one.

Thirteen links pointed at github.com/feder-cr/AIHawk. GitHub redirects a
NAME to the OBJECT that carried it, not to the content: after the September
swaps that name belongs to invisible_dots, which has seven wiki pages, so
AIHawk/wiki/<page> lands on its wiki Home. It answers 200 with different
content, which means a reader who clicks does not find the page and a search
engine sees a soft-404 across about 150 indexed URLs.

Seven occurrences said `uvx aihawk`, a command that does not exist. One sat
in a front-matter description, which is the snippet search engines show, and
one in a block meant to be copied: `claude mcp add stealth -- uvx aihawk`.
The command is invisible-playwright-mcp, on PyPI at 0.70.16.

All eight link targets were checked one by one and resolve to themselves with
the page title, no redirect.

Three things stay as they are, which only reading them showed. The
`pip install invisible-playwright` line matches what this engine's own README
teaches for the library, so the page is consistent rather than broken.
CHANGELOG.md keeps the old name because a changelog entry says what was true
then. And the fixture in scripts/sync_article_pixels.py keeps it because it is
the deliberate wrong case, a pixel for ANOTHER repo.

One sentence went away instead of being renamed: "shipped inside AIHawk" made
sense when AIHawk was the larger product containing the server. The server and
the repository are now the same thing, so "shipped inside itself" was circular.

(cherry picked from commit d9c8e46dce)

* test: the docs name the MCP server's repository and command as they are now

feder-cr/AIHawk now leads to an unrelated repository and answers 200, which no
link checker reports; `uvx aihawk` does not exist. The README and docs/ are
read for both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: the Fission bench counts the processes that host a site, not every new content process

test_same_site_other_port_stays_in_process was red on the e2e of the 0.50.0 commit ("a same-site frame
started a process: [13443]"): the bench counted every `-contentproc ... tab` pid, and the engine starts a
preallocated content process to refill its pool whenever it gets to it. On Linux the engine names a content
process by its remote type (ContentChild::SetProcessName, prctl PR_SET_NAME): "Isolated Web Co" once it
hosts a site of strategy 1, "Web Content" while preallocated. Measured on firefox-62: a cross-site frame
renames a preallocated process and a new "Web Content" refills the pool; a same-site frame changes neither.
The two tests that count processes skip off Linux, where no process carries a name.

Unit test with the measured processes: 3 red on the old bench, 3 green here. e2e on firefox-62 (candidate
#6, Linux): the bench file 17 passed; the two counting tests 15 of 15 runs green.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: a closed context is checked for the processes of its sites, not for every content process

test_closed_contexts_with_a_never_stopping_service_worker_leave_no_process was red on the e2e of the 0.50.0
tag ([2, 2, 2, 5, 5], 5 <= 2). Measured on firefox-62 (Linux), the test's own scenario 10 times with every
process named: no "Isolated Web Co" left after any close; the 3 more are "Web Content", the engine's pool of
preallocated processes filling up behind the closed contexts (5 runs of 10, new pids each time). Not a leak:
the count read the refill.

The helper of the bench moves to tests/_processes.py and both tests use it. The context test counts the
processes that host a site: at least one while the page is open (or the count proves nothing), none a few
seconds after `close` answers (the engine waits for them inside close and kills the ones that stay). Off
Linux it skips, as the bench's two counting tests do: no other system names the process.

Unit tests (tests/unit/test_processes_counts_sites.py) from the measured processes, the closed-context case
included. e2e on firefox-62 (candidate #6, Linux): the context test 10 of 10; run_e2e.py on the two files and
the unit test 18 passed. The old counter, same scenario: 5 of 10 runs would fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Release 0.50.1: 0.50.0 with the process-counting e2e corrected (0.50.0 never reached the index)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: the same-site control puts its frame in the shown page; CHANGELOG: 0.50.0's entry is 0.50.1's

The e2e of #451 saw a new "Isolated Web Co" once after a.test/plain -> a.test/same-site ([10878] -> [10878,
11208]). Not a process of an earlier test: it was created after the first read and only this worker's
descendants are counted. It is the top-level navigation: when the old document may enter the back-forward
cache, the browsing context is replaced (mReplaceBrowsingContext, dom/ipc/ProcessIsolation.cpp) and the new
one may be placed in another process of the same site (dom.ipc.processCount.webIsolated = 4). Measured on
firefox-62 (candidate #6, Linux): 0 of 30 runs alone (bfcache on and off), 0 of 57 under 4 workers. The test
was written for the frame, so the frame is now added to the page already shown and the top never navigates:
20 of 20 runs green.

0.50.0 never reached the index, so the changelog gate refused its heading; its entry now opens 0.50.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* tests: networkidle through a served browser whose context routes every request, on a reused page

launch_server() plus a stock Playwright client, a context route that aborts image/font/media and continues the rest, a
page with sendBeacon, the same font twice, a frame of another site, a worker, redirects, requests the page cancels while a
slow route decides, 100 requests at once, and a slow client that answers concurrently (async). Every shape reaches
networkidle on firefox-62; one page reused for twelve addresses too. The leak that tf-fetch meets on real sites needs
end events the engine loses, which no local page produces: its deterministic red/green is in the core
(tests/test_networkidle_on_a_reused_page.py of invisible-core); this file guards the remote path end to end.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 47182f0cd85fea08fc45e36f1c91d2d570722f14)
(cherry picked from commit e46f2dcf3eb361e6af0fedcdf6e1189f0ac330b6)

* server: the answer to a request the browser has already closed is not an error (Cannot find request), as stock sendMayFail

A page cancels requests while a route is deciding (a fetch aborted, an image replaced, an iframe removed, a beacon with
its document, the favicon of the page a goto just left). The engine takes the request out of its held set at once and the
late continue/abort/fulfill meets "Cannot find request" or NS_BINDING_ABORTED. Stock Playwright sends the interception
commands as may-fail and tells the client nothing; ours passed the error up, the client kept it as the error of the whole
connection and raised it on the NEXT route command, which was then never sent: its request stayed held in the engine, its
handler failed too, and so on down the page. Seen on a real news page: six held requests in a row, one a beacon, and
networkidle never came.

RouteDispatcher._send now treats "Cannot find request" and a closed target as done (still disposed); any other protocol
error still reaches the client.

Tests: the e2e with a plain handler (no try) on a page that removes an iframe whose requests are held (red before:
networkidle never; green after), and a static guard that every op of RouteDispatcher goes through _send and that _send
swallows exactly those two. The same defect was found a month earlier by richardpowellus (#351), with the favicon of the
previous page: his test is added in the next commit.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* tests: the stock Playwright client is required by the networkidle e2e (explicit failure, never a skip); the dev extra pins it

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 91223226f5bba25edff9af0e8b1fd6b5bfea2227)
(cherry picked from commit 612b18c02b95e9b5833d62b6595d4a0ff324aac2)

* tests: answering a route the next navigation already aborted does not raise (the case of #351: the favicon of the page just left)

Sixty sequential routed gotos on a loopback page: 4-12 of them failed on the old server, every failing continue_ being
the previous document's favicon, aborted by the next navigation while the route sat with the handler. Red on main (in-process
path), green with the fix of RouteDispatcher._send.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Release 0.50.1: pin invisible-core 62.64.0; CHANGELOG for the networkidle fixes

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit e63ef8e61ea42e7f8df7c1bde206f3bf86fc18f7)

* A route answer the engine refuses is the engine's business, whatever its wording

The server took one wording ("Cannot find request") of an answer to a closed request as done and passed every other
protocol error up to the client. The engine also says "NS_BINDING_ABORTED
[nsIInterceptedChannel.resetInterceptionWithURI]" when the channel was cancelled while the answer was on its way: the
same event, and the client kept it as the error of the connection and raised it on its next route command.

Stock Playwright sends the three interception commands as may-fail and tells the client nothing, whatever the engine
says. So does RouteDispatcher._send now: every ProtocolError is swallowed, the route is disposed after it.

Tests: the static guard no longer allows a re-raise inside the handlers; a unit test feeds three wordings (red on the
old code for two of them).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* tests: the descriptors of the spawn are asserted by running it, not by reading the core's source

test_the_spawn_keeps_the_two_hardwired_descriptors asserted that the source of the core's _spawn_posix contains
`pass_fds=(its_read, its_write, 3, 4)`. Core 62.64.0 starts the engine with posix_spawn and file actions, so the words are gone
and the test failed on every Linux unit suite although the behaviour is the same (and better).

The test now runs the spawn: a parent with nothing open on 3 and 4 and its pipes far from them launches a program that reads
fd 3 and answers on fd 4 (the contract of nsRemoteDebuggingPipe.cpp), and the answer must come back and the child must hold no
descriptor above 4 of the parent's. Same shape as the core's own test
(test_the_pipe_of_the_engine_reaches_its_fixed_descriptors). No skip: the file is already POSIX-only.

The other tests of the file do not read source text (checked: no getsource/inspect/read_text left).
Ran the parent program on Linux with core 62.64.0 (image tetra-invisible:run1b-final): pong:ping:0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* The page dispatcher waits for Page.ready before the page is handed over (needs invisible-core with Lifecycle.wait_for_page_ready)

Same defect and fix as in the core's page (see the core commit): a goto sent right after new_page could meet the page's initial about:blank.
The pin of invisible-core moves with the core release that carries wait_for_page_ready.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Pin invisible-core==62.65.0 (a page handed over when the engine says it is ready); changelog

The core that carries Lifecycle.wait_for_page_ready is invisible-core 62.65.0 (draft PR invisible_core#238), not on the index yet:
the pin check of this push is skipped on purpose (INVISIBLE_PIN_CHECK=skip).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* tests: the stand-in engine of the registry test says Page.ready, as the real one does (the page is handed over on it)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* tests: new_page and a popup are handed over only when the engine says Page.ready (red without the wait in PageDispatcher, green with it)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* A page is built at once and announced when the engine says Page.ready (the wait inside the constructor held a popup's first request behind a page that did not exist yet, and lost its commit and load)

- PageDispatcher no longer waits in __init__; wait_until_ready() is called by the adoption between the construction and the announcement
  (context 'page' event, newPage answer). A detach while waiting ends the wait; a page that is not ready in time is disposed.
- The main frame's initializer carries what the lifecycle already knows (url, name, load states), as every other frame's does.
- Tests: unit (a popup exists and listens while it waits; what it does before its ready reaches its frame; red on 6a60dce) and e2e
  (a popup of a link, noopener or window.open reaches an in-process and a stock client of a served browser within 2 s, with and
  without a context route; 15 of 16 red on 6a60dce, 16 green).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* tests: the stand-in pages say wait_until_ready; the popup e2e reaches the stock client as the other served tests do

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* tests: the popup reaches the client from another site too (a link, noopener, window.open: 16 more cases, in-process and through a served browser)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* A popup is reported on Page.ready as Playwright's is: no limit and no warning, with the address of the commit that came with the ready

- Stock Playwright 1.62 (measured): a 204 or a silent destination gives no page event, one that answers after 4 s gives it at 4 s with the
  destination already. The adoption of a popup waited 20 s and dropped it with a warning; now only a page a caller asked for
  (newPage) has the 20 s; a popup waits until the engine says Page.ready, the target goes away, or its context closes
  (BrowserDispatcher.end_waits_of), and says nothing.
- The ready and the commit of the document that made the page ready come in the same turn: the page is announced after a round trip to the
  engine (settle_events), so the frame reads the destination at the page event (3 of 4 slow popups said about:blank).
- In-process the slow popup arrived 0.9 s later than stock: it is the humanised click (1.1 s of pointer movement before the click returns),
  the popup arrives 4.02 s after the click in both modes.
- Tests: unit (limit None for a popup and 20 s for a requested page; a popup with no ready ends with its context and says nothing; the
  address at the page event is the commit's) red on b09d620; e2e (204 and silent: no event; 1.5 s: url is the destination; 25 s: reported
  then) in-process and through a served browser: the 25 s ones red on b09d620.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* A download started by a popup that is not announced yet is reported on its opener, as Playwright reports it

- Browser.downloadCreated names the tab the download came from. A tab opened for an attachment (a target=_blank link, a window.open) never gets
  a Page.ready and the engine closes it at once, so it is not among the announced pages and the download was lost: no download event
  anywhere (a21e1de had it, on the popup). Playwright's ffBrowser._onDownloadCreated reports it on the opener of a page that is not
  reported yet; so does this, from the opener recorded when the target was attached (BrowserDispatcher._openers). The abort of the
  navigation that became the download still goes to the page that owns the frame.
- Tests: unit (red on fbceeaf); the e2e of the destinations and of the popup matrix of the fake-web branch (73f1e8d): 16 + 34 cases against
  the reference measured on stock Playwright 1.62 - on fbceeaf 4 of the 16 were red (the download), now 50 of 50 green.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* A popup tells its listeners the load it reached before it was announced; an unannounced frame has no address of its own

- The popup is announced when the engine says Page.ready, which is when its document commits, so its domcontentloaded and load may be said
  before the client has the page: page.on('load') registered in the handler of the page event never fired (Playwright's does, measured by
  the independent run: destinations of 4 s and 25 s). FrameDispatcher.emit records those two states while the page is not announced and
  PageDispatcher.announce says them again right after the page event, in their order and under one lock; the first time they already set
  the state wait_for_load_state reads, so it returns at once. Only popups: a requested page is announced as before.
- The main frame is created with the address the lifecycle knows, '' if it has committed nothing (an attachment's empty tab), not
  about:blank: Playwright says '' there.
- Tests: unit (the two states after the page event, in order; red on 2f153c7); e2e: a listener registered in the handler of the page event
  hears the load of a slow popup, wait_for_load_state in the handler returns in under 2 s (in-process and a stock client over a served
  browser, window.open and link).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* A popup whose target goes away while its page is being built is announced and closed, not waited for for ever

A download's empty tab is closed by the engine within milliseconds; on a loaded machine its page is still being built when the detach arrives.
_handle_detach recorded it as early (nobody in _building to tell) and the adoption then waited for a Page.ready that never comes: the
popup was never announced (test_popup_destinations_e2e, the download on the opener, failed once in a full suite run). The adoption now
looks at the early detaches when it registers the page as waiting.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* A command of the adoption that finds the target's session gone announces and closes the popup, as a detach before the ready does

The independent run on a quiet machine lost one link-into-attachment popup in a hundred: the engine closed the tab WHILE the adoption was
initializing it, answered 'cannot find session' to Page.setInitScripts, and the popup was discarded with a warning - no page event - where
Playwright's is announced and closed. PageDispatcher._build now treats an initialization command that fails because the target or its session
is gone (one test: _target_is_gone) as the same case: the page is built, flagged gone_while_building, and the adoption announces it and closes
it right after. Test: a fake engine answers 'cannot find session' to each command of the adoption in turn (parametrised): the page event and
the close arrive, no warning; red on b05741f for Page.setInitScripts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* tests: the helper of the popup destinations does not shadow the browser fixture (ruff F811)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* tests: the popup tests do not fail on the machine's speed (no 2 s limit)

A runner with four workers delivered a popup in 2.013 s (the limit of the test was 2 s). The verdict of these tests is that the popup arrives with
its address and its load; the wait is generous (30 s) and the check of the time is gone. The wait_for_load_state of the handler is bounded by 8 s.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* The adoption of a target is one explicit state machine, proved over every order of the engine's events

Four patches of the same race (a detach before the ready, during the build, between the build and the wait, a command answered 'cannot find
session') and a fifth the exhaustive test found (a detach while the adoption waits for the main frame of a tab the engine never announced:
the wait went on for 20 s and the popup was discarded; this is the order the runner produced for the download popups: 3 of 4 lost).

- _Adoption: the single record of a target between its attach and its announcement: state (attached, building, waiting, announced), gone
  (set by the engine's detach AT ANY MOMENT), page, opener, context. It replaces _adopting, _building, _openers and _detached_early.
- Every wait of the adoption looks at gone (the main-frame wait polls it), every state change is one method (_enter_building, _enter_waiting,
  _enter_announced), a command that finds the session gone ends in the same place as a detach, a closing context takes away every adoption
  of it in any state (end_waits_of).
- Invariant: an attached target that is not a page a caller asked for gives the client exactly one page event, at its ready or at its
  disappearance (and its close right after), unless its context closed first.
- Test: test_every_order_of_the_events_of_a_popup_gives_one_page_event stops the adoption thread at six points of its own and delivers the
  engine's events (frame, commit, ready, detach, in every prefix) at every one of the eight moments: 635 orders, none sampled. Mutation
  check: without the gone-aware main-frame wait 24 orders break, without the tolerance of the command error 42, without the close after the
  page 374; without the early-gone check of _enter_waiting the adoption hangs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* The adoption keeps a short trace per target and writes it where a popup is dropped or fails

The log of a CI run says that a popup was not announced and not in which order the engine's events came. Each target in flight keeps (in memory,
at most 60 short strings, nothing afterwards) what the engine said (frame, commit, ready, detach) and what the adoption did (building, waiting,
announced), with the milliseconds since the attach. It is written in the warning of a failed adoption, in the error the newPage waiter gets, in
the timeout of a requested page, and in browser._dropped (the last 16 targets dropped with their context).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* The WebGL determinism test says why the browser could not make a context

One run in 31 of the e2e on a loaded Linux runner failed this test with "reason='gl null'" and nothing else: getContext('webgl') gave the page null. The browser
says why in the `webglcontextcreationerror` event (statusMessage: the failure list, e.g. "tryNativeGL (FEATURE_FAILURE_EGL_LOAD_3)", "Initializing WebGL backbuffer
failed.", "GL error 0x505 occurred during OpenGL context initialization"), and each of the paths that can produce null on Linux in our engine writes a different one
(library not loaded, display not initialised, context not created, GL out of memory, backbuffer not allocated). The test reads the event and puts it in the
assertion, and tries webgl2 on a fresh canvas (the old canvas already had the failed type).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* tests: the same-site control of the Fission bench measures the frame, not the process pool

The control counted the processes that host a site between two reads, with the default pool of three preallocated content processes: a pool
process handed to a site after the first read moved the count without the frame having asked for anything ([63248] -> [63248, 63386] on a
four-worker runner; the same family as 5402da4, ff2123e and fef0bc5). The control now runs in a browser with dom.ipc.processPrelaunch.fission.number
at 0, where a process of a site appears only because a site needed one, and says so if the page of the site has no process to compare with.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* The download of a tab that is not announced yet is said after the page event of the tab

The tab opened for an attachment is announced when the engine takes it away, a few milliseconds after it says the download; the download
(reported on the opener) went to the client first, the popup after: the order the other way round from Playwright's, and a client that read
the popup the moment the download arrived found none on a one-CPU machine (the 4 download cases of GitHub, 3 of 4 red; the same on a one-CPU
container: 1, 0, 2 of 50 on a90dadc). The adoption holds the download on its record and says it right after the page event (never lost: also
when the tab is dropped or fails).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* A download is taken with the record's removal in one step, and the opener of a target not announced is remembered: no step of the adoption can lose it

The failure branch said the pending downloads BEFORE it removed the record: a download created between the two found the record, queued on it, and
nobody said it. Taking the pending downloads and removing the record are now one step under the browser's lock, in the three branches
(announced, dropped with its context, failed); the opener of a target that ended without being announced is kept for the last 16 targets, so a
download that comes after the record is gone is still said, on the opener. Test: the download is forced into the gap of the failing adoption
(red on 65f7580: said 0 times, now once).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
2026-11-12 09:51:23 +01:00
feder-crandClaude Sonnet 5.5 e88e664a50 tests: the chain by name allows loopback in ICE, because the lab's exit is 127.0.0.2 and a retail Firefox throws away an answer whose mapped address is loopback
The giro 3 gate was red on test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick. Measured on the giro 3 Linux binary (strace of the socket
that talks to the relay + the gateway's own log): the gateway delivers the TURN server's 401 and then its success (type 0x0103) within 5 ms, the browser
reads both, answers the 401 with credentials, and never accepts the success: it retransmits the same Allocate 5 times in the 2 s of the page. The
success carries XOR-MAPPED-ADDRESS 127.0.0.2 (where the gateway's datagrams leave from, by design of the test) and nICEr rejects a loopback mapped address as
bogus (stun_client_ctx.cpp nr_stun_transport_addr_check) unless the ICE context allows loopback (turn_client_ctx.cpp; the flag is set from
media.peerconnection.ice.loopback in nricectx.cpp). The same TURN server answers a direct browser at a non-loopback address and the allocation completes in
60 ms, so the chain is sound. With the pref the chain test passes at 130 ms of round trip on the giro 3 binary; without it it fails at 0, 65 and 130 ms.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:50:34 +01:00
feder-crandClaude Sonnet 5.5 bacf03ad21 tests: the CONNECT helper of the HTTP proxy tests reads the answer one byte at a time, so the first bytes of the tunnel are not lost with the head; unit test (unit.udp 166)
When the far side wrote and closed at once, the 200 and the first bytes of the tunnel could reach the socket in one segment, and _connect_raw dropped everything after the blank line: the caller read the end of the stream instead of the data (run 43176569993, test_a_connect_to_loopback_is_relayed_and_one_that_would_leave_it_is_refused).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:49:01 +01:00
feder-crandClaude Sonnet 5.5 9357e790b3 tests: the first datagram of a PeerConnection is judged with the session's UDP declared coherent, and the core's own probe is not counted as the engine's association
The giro 3 gate was red on this test: with a fixed time zone the core does not discover the TCP exit, so it cannot compare it with the UDP probe's mapped
address and declares the UDP of the proxy unmeasured; the engine then treats the proxy as a router that drops UDP, asks it for no association and sends
nothing (measured on the giro 3 Linux binary: the gateway saw ONE ASSOCIATE for the whole test, the core's probe; the layer was pushed on the PC's
socket and what was sent was dropped). The test gives the core the gateway's TCP exit as every e2e of the line does (egress_by_proxy), and it no longer counts
the probe's association (the first of the gateway, made before the browser exists) as one that was ready before the PeerConnection - it passed an
engine that asked for none. Green on the giro 3 Linux binary (run 43164943499).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 09:40:33 +01:00
feder-cr 1466ac6433 wrapper: 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; unit tests (unit.page 34) 2026-11-12 09:09:31 +01:00
feder-cr bf5c6dabb3 ci: wrapper.unit.page counts the popup-order test and the changed page tests of release/0.50.1 8049df3 (32) 2026-11-12 09:06:24 +01:00
feder-cr e992255d38 Merge remote-tracking branch 'origin/release/0.50.1' into udp/wrapper-r3-next 2026-11-12 09:04:57 +01:00
feder-crandClaude Sonnet 5.5 8049df3c33 A download is taken with the record's removal in one step, and the opener of a target not announced is remembered: no step of the adoption can lose it
The failure branch said the pending downloads BEFORE it removed the record: a download created between the two found the record, queued on it, and
nobody said it. Taking the pending downloads and removing the record are now one step under the browser's lock, in the three branches
(announced, dropped with its context, failed); the opener of a target that ended without being announced is kept for the last 16 targets, so a
download that comes after the record is gone is still said, on the opener. Test: the download is forced into the gap of the failing adoption
(red on 65f7580: said 0 times, now once).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:58:48 +01:00
feder-cr e4edf5f81f ci: the realness e2e (32) is a required suite, its helpers (24) join wrapper.unit.udp (165) 2026-11-12 08:54:35 +01:00
feder-crandClaude Sonnet 5.5 7a094c3bbc tests: the realness check without a real proxy - six declared exits, the values a page reads, and the judges
The manual check drove the browser through a paid proxy and compared what a page reads with the proxy's exit. This is the
same check against a local SOCKS5 gateway that declares its exit: a local site that tells a connection the gateway opened from
a direct one, FakeDoh for the names, and the core's own geo database as the truth for the zone and the country.

* test_realness_behind_a_declared_exit_e2e.py: one launch per exit (six, in six countries), read by five tests (the address a
  site sees and no connection past the gateway; nothing of the host in the WebRTC candidates and SDP; the names reach the gateway
  and not the system resolver; the zone, the offsets read two ways and a worker; the language of the page, a worker and the
  Accept-Language header against the exit's country), plus the vendored detection page loaded behind the gateway.
* _realness_support.py: the exits, ExitGateway (remembers the ports of the connections it opened), the site, the reads, the judges.
* test_the_realness_helpers.py: the judges and the gateway/site correlation held to golden reads, no browser.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:53:37 +01:00
feder-cr 7272ea8f64 tests: the iptables fallback of the resolver trap is gone (the cause was the trap's own threads holding the port, fixed in 4933f8c); wrapper.unit.udp 141 2026-11-12 08:49:52 +01:00
feder-crandClaude Sonnet 5.5 a70f2fecaf tests: the discovery of the exit of a context stays covered now that the DoH e2e declare it away
The DoH e2e declare the exit the core asks for (their subject is the roads of the browser). The discovery itself keeps its own test: it goes
through the gateway of the context, by name, only to the services of the core, never through another context's gateway, and a gateway that
refuses them never makes the measurement say coherent. wrapper.unit.udp 140 -> 142.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:43:55 +01:00
feder-crandClaude Sonnet 5.5 65f7580182 The download of a tab that is not announced yet is said after the page event of the tab
The tab opened for an attachment is announced when the engine takes it away, a few milliseconds after it says the download; the download
(reported on the opener) went to the client first, the popup after: the order the other way round from Playwright's, and a client that read
the popup the moment the download arrived found none on a one-CPU machine (the 4 download cases of GitHub, 3 of 4 red; the same on a one-CPU
container: 1, 0, 2 of 50 on a90dadc). The adoption holds the download on its record and says it right after the page event (never lost: also
when the tab is dropped or fails).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:42:59 +01:00
feder-crandClaude Sonnet 5.5 4933f8cdba tests: the resolver trap ends its threads before it closes its sockets, so its port is free for the next test (no more "Address already in use" on 127.0.0.1-8:53)
The answering threads sit in accept()/recvfrom(); on Linux a close() from another thread does not wake them and the kernel keeps the socket
bound until the call returns, which it never did: every trap left its address taken, and the eighth trap of a run found all eight taken
(reproduced here in a container: 19 DoH e2e, the 6 tests after the 8th trap are errors; alone, the same file passes). The loops now wake every
0.2 s to look at a flag; the teardown sets it, joins the threads, and then closes the sockets.

- test_a_closed_trap_gives_its_port_back_at_once (wrapper.unit.udp 139 -> 140): a trap on a free port is closed and a second one on the same
  port must bind 127.0.0.1 again; red on the old code on Linux.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:42:36 +01:00
feder-cr bfb67e0c2c tests: a port 53 that cannot be bound is redirected from 127.0.0.2 to a free port (iptables nat OUTPUT), the rules go with the trap 2026-11-12 08:27:48 +01:00
feder-crandClaude Sonnet 5.5 2022ecf32a tests: two connections on one page may nominate a peer-reflexive end; the road is what is judged
On the round 3 gate (Linux, run 43164943499) the nominated pair was host to prflx: the other connection's mDNS name was not resolved yet when its
connectivity check arrived, and the address the check came from is learned as peer-reflexive. That is the same direct local road, so the test accepts
host or prflx at each end, over UDP at both ends, and refuses what is a different road: a relay, a server-reflexive candidate (through the proxy or the
network), or TCP. The open time stays judged against the responder's first retry, and printed beside the retail window.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 08:21:06 +01:00
feder-cr 5ae6833299 tests: the DoH e2e declare the exit the UDP measurement asks for; the gateway's page is reached by an address; e2e.udp is split in e2e.udp and e2e.web; the trap says who holds port 53 2026-11-12 08:19:16 +01:00
feder-crandClaude Sonnet 5.5 a90dadc204 tests: the same-site control of the Fission bench measures the frame, not the process pool
The control counted the processes that host a site between two reads, with the default pool of three preallocated content processes: a pool
process handed to a site after the first read moved the count without the frame having asked for anything ([63248] -> [63248, 63386] on a
four-worker runner; the same family as 5402da4, ff2123e and fef0bc5). The control now runs in a browser with dom.ipc.processPrelaunch.fission.number
at 0, where a process of a site appears only because a site needed one, and says so if the page of the site has no process to compare with.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 07:17:52 +01:00
feder-crandClaude Sonnet 5.5 210161d9b6 The WebGL determinism test says why the browser could not make a context
One run in 31 of the e2e on a loaded Linux runner failed this test with "reason='gl null'" and nothing else: getContext('webgl') gave the page null. The browser
says why in the `webglcontextcreationerror` event (statusMessage: the failure list, e.g. "tryNativeGL (FEATURE_FAILURE_EGL_LOAD_3)", "Initializing WebGL backbuffer
failed.", "GL error 0x505 occurred during OpenGL context initialization"), and each of the paths that can produce null on Linux in our engine writes a different one
(library not loaded, display not initialised, context not created, GL out of memory, backbuffer not allocated). The test reads the event and puts it in the
assertion, and tries webgl2 on a fresh canvas (the old canvas already had the failed type).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 07:16:43 +01:00
feder-crandClaude Sonnet 5.5 1542fede01 The adoption keeps a short trace per target and writes it where a popup is dropped or fails
The log of a CI run says that a popup was not announced and not in which order the engine's events came. Each target in flight keeps (in memory,
at most 60 short strings, nothing afterwards) what the engine said (frame, commit, ready, detach) and what the adoption did (building, waiting,
announced), with the milliseconds since the attach. It is written in the warning of a failed adoption, in the error the newPage waiter gets, in
the timeout of a requested page, and in browser._dropped (the last 16 targets dropped with their context).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 07:16:36 +01:00
feder-crandClaude Sonnet 5.5 5426744bc6 The adoption of a target is one explicit state machine, proved over every order of the engine's events
Four patches of the same race (a detach before the ready, during the build, between the build and the wait, a command answered 'cannot find
session') and a fifth the exhaustive test found (a detach while the adoption waits for the main frame of a tab the engine never announced:
the wait went on for 20 s and the popup was discarded; this is the order the runner produced for the download popups: 3 of 4 lost).

- _Adoption: the single record of a target between its attach and its announcement: state (attached, building, waiting, announced), gone
  (set by the engine's detach AT ANY MOMENT), page, opener, context. It replaces _adopting, _building, _openers and _detached_early.
- Every wait of the adoption looks at gone (the main-frame wait polls it), every state change is one method (_enter_building, _enter_waiting,
  _enter_announced), a command that finds the session gone ends in the same place as a detach, a closing context takes away every adoption
  of it in any state (end_waits_of).
- Invariant: an attached target that is not a page a caller asked for gives the client exactly one page event, at its ready or at its
  disappearance (and its close right after), unless its context closed first.
- Test: test_every_order_of_the_events_of_a_popup_gives_one_page_event stops the adoption thread at six points of its own and delivers the
  engine's events (frame, commit, ready, detach, in every prefix) at every one of the eight moments: 635 orders, none sampled. Mutation
  check: without the gone-aware main-frame wait 24 orders break, without the tolerance of the command error 42, without the close after the
  page 374; without the early-gone check of _enter_waiting the adoption hangs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 07:13:47 +01:00
feder-cr 973927fdb7 tests: the trap-policy test reads the trap fixture in conftest.py (6b moved it there with the lint of the fixtures) 2026-11-12 06:23:06 +01:00
feder-crandClaude Sonnet 5.5 071cf8d697 tests: the fixtures that several e2e files share are in conftest.py, not imported from a sibling file (ruff F811, the lint of the tests job)
A fixture imported from a twin file and then named as a test argument is a redefinition: 60 F811 in the new tests of the UDP line, the
same error that turned the 0.50.1 CI red. The collection does not change: the same 2187 tests (1422 by default), the same setup plan
(fixture order and scope per test, compared with --setup-plan before and after).

- conftest.py: doh, gateway, trap, watcher, pages (DoH e2e), socks5_tcp_only, local_https_page (WebRTC e2e) and browser (the two-transport
  fixture of the popup tests). The heavy imports are inside the bodies, so a run without the e2e extras still collects.
- _doh_support.py (ZONE, Pages) and _socks_servers.py (Socks5TcpOnly, was _Socks5TcpOnly in test_webrtc_realness.py): the plain code the
  fixtures need, in support modules, not in a test file.
- The twin files keep what is not a test argument (the autouse _hermetic_session and the helpers, imported by name); the sibling files
  stop importing the fixtures. The four `# noqa: F811` of test_popup_destinations_e2e.py are gone: ruff passes with --ignore-noqa.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 06:02:15 +01:00
feder-cr 7af5b84954 Merge remote-tracking branch 'origin/release/0.50.1' into udp/wrapper-r3 2026-11-12 05:47:21 +01:00
feder-crandClaude Sonnet 5.5 a18e967675 tests: the popup tests do not fail on the machine's speed (no 2 s limit)
A runner with four workers delivered a popup in 2.013 s (the limit of the test was 2 s). The verdict of these tests is that the popup arrives with
its address and its load; the wait is generous (30 s) and the check of the time is gone. The wait_for_load_state of the handler is bounded by 8 s.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:47:12 +01:00
feder-crandClaude Sonnet 5.5 64dc8d3476 tests: the popup tests do not fail on the machine's speed (no 2 s limit)
A runner with four workers delivered a popup in 2.013 s (the limit of the test was 2 s). The verdict of these tests is that the popup arrives with
its address and its load; the wait is generous (30 s) and the check of the time is gone. The wait_for_load_state of the handler is bounded by 8 s.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:44:57 +01:00
feder-cr bd46760313 ci: wrapper.e2e.udp counts 68 (the three ICE rows of test_webrtc_realness: default, content process asked, no socket process asked; the engine locks both prefs) 2026-11-12 05:29:21 +01:00
feder-crandClaude Sonnet 5.5 2283d40198 tests: a caller that asks for the ICE in the content process, or for no socket process, gets the srflx through the relay all the same (the engine locks both prefs)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:29:12 +01:00
feder-crandClaude Sonnet 5.5 012fc862ef tests: two connections on one page are judged on the road they take, not on the clock of the machine
The test asserted a median of 30-55 ms, the time of a fast machine. On a GitHub runner the same healthy engine takes 67 ms (Windows) and
122 ms (Linux) and the gate was red on both: an absolute time is a verdict on the machine.

Every one of the five cold launches is now judged on what the machine cannot change:
* the data channel opens and echoes;
* each connection gathered a UDP host candidate named by mDNS (a run without UDP is the reserved-port failure: the socket could not bind and
  the connection fell back to TCP);
* the nominated pair, read from the browser's own statistics, is host to host over UDP at both ends (no road through TCP; a succeeded pair
  means the other connection's mDNS name was resolved);
* it opens in less than the responder's first retry (3 s): a name that does not come back opens only at the retry.
The time is printed beside the retail window, as a measure.

Run on the firefox-63 candidate engine: passes, [38, 39, 39, 73, 77] ms.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:23:06 +01:00
feder-cr 8c7e413b68 tests: the resolver trap takes the first loopback address it can bind for port 53 (a hosted runner can hold 127.0.0.1:53) and writes that address in resolv.conf 2026-11-12 05:19:56 +01:00
feder-crandClaude Sonnet 5.5 bbf4019940 tests: the helper of the popup destinations does not shadow the browser fixture (ruff F811)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 05:17:48 +01:00
feder-cr 4e1f2ecf40 tests: the resolver trap says why it could not bind (the error of the socket) 2026-11-12 05:12:04 +01:00
feder-cr 6f9b87c860 ci: test_a_page_that_moves_on_e2e.py is required in wrapper.e2e.page (114): the e2e of the engine fix for a navigation the page overtook 2026-11-12 05:05:54 +01:00
feder-cr a072aa22b8 ci: the page and popup suites count the tests of release/0.50.1 6200bc2 (e2e.page 100, unit.page 24) 2026-11-12 04:40:13 +01:00
feder-cr 328ed0738e Merge remote-tracking branch 'origin/release/0.50.1' into udp/wrapper-r3 2026-11-12 04:39:51 +01:00
feder-crandClaude Sonnet 5.5 6200bc29ed A command of the adoption that finds the target's session gone announces and closes the popup, as a detach before the ready does
The independent run on a quiet machine lost one link-into-attachment popup in a hundred: the engine closed the tab WHILE the adoption was
initializing it, answered 'cannot find session' to Page.setInitScripts, and the popup was discarded with a warning - no page event - where
Playwright's is announced and closed. PageDispatcher._build now treats an initialization command that fails because the target or its session
is gone (one test: _target_is_gone) as the same case: the page is built, flagged gone_while_building, and the adoption announces it and closes
it right after. Test: a fake engine answers 'cannot find session' to each command of the adoption in turn (parametrised): the page event and
the close arrive, no warning; red on b05741f for Page.setInitScripts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 04:10:00 +01:00
feder-crandClaude Sonnet 5.5 b05741f538 A popup whose target goes away while its page is being built is announced and closed, not waited for for ever
A download's empty tab is closed by the engine within milliseconds; on a loaded machine its page is still being built when the detach arrives.
_handle_detach recorded it as early (nobody in _building to tell) and the adoption then waited for a Page.ready that never comes: the
popup was never announced (test_popup_destinations_e2e, the download on the opener, failed once in a full suite run). The adoption now
looks at the early detaches when it registers the page as waiting.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 03:51:28 +01:00
feder-cr 95c7e156ac tests: the first visit of the h3 e2e is h2 because the fixture has no HTTPS record (the retail read h3 first in 3 sessions of 15); the FakeDoh never serves type 65 and the tests assert it 2026-11-12 03:48:26 +01:00
feder-crandClaude Sonnet 5.5 620f969655 A popup tells its listeners the load it reached before it was announced; an unannounced frame has no address of its own
- The popup is announced when the engine says Page.ready, which is when its document commits, so its domcontentloaded and load may be said
  before the client has the page: page.on('load') registered in the handler of the page event never fired (Playwright's does, measured by
  the independent run: destinations of 4 s and 25 s). FrameDispatcher.emit records those two states while the page is not announced and
  PageDispatcher.announce says them again right after the page event, in their order and under one lock; the first time they already set
  the state wait_for_load_state reads, so it returns at once. Only popups: a requested page is announced as before.
- The main frame is created with the address the lifecycle knows, '' if it has committed nothing (an attachment's empty tab), not
  about:blank: Playwright says '' there.
- Tests: unit (the two states after the page event, in order; red on 2f153c7); e2e: a listener registered in the handler of the page event
  hears the load of a slow popup, wait_for_load_state in the handler returns in under 2 s (in-process and a stock client over a served
  browser, window.open and link).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 03:33:32 +01:00
feder-cr adf96a2b15 ci: the drive gate launches through the core (the engine waits for the session's road; bare Playwright never sends it); the declaration test does not resolve an engine 2026-11-12 03:16:20 +01:00
feder-cr 2167538130 ci: the page and popup suites of 0.50.1 are required (wrapper.e2e.page 96, wrapper.unit.page 17), wrapper.unit.udp counts 113 after the merge 2026-11-12 02:56:16 +01:00
feder-cr 440bbb36e6 Merge branch 'release/0.50.1' into udp/wrapper-r3
# Conflicts:
#	src/invisible_playwright/_juggler/server.py
#	tests/test_every_route_command_is_answered_may_fail.py
2026-11-12 02:54:06 +01:00
feder-crandClaude Sonnet 5.5 2f153c76ff A download started by a popup that is not announced yet is reported on its opener, as Playwright reports it
- Browser.downloadCreated names the tab the download came from. A tab opened for an attachment (a target=_blank link, a window.open) never gets
  a Page.ready and the engine closes it at once, so it is not among the announced pages and the download was lost: no download event
  anywhere (a21e1de had it, on the popup). Playwright's ffBrowser._onDownloadCreated reports it on the opener of a page that is not
  reported yet; so does this, from the opener recorded when the target was attached (BrowserDispatcher._openers). The abort of the
  navigation that became the download still goes to the page that owns the frame.
- Tests: unit (red on fbceeaf); the e2e of the destinations and of the popup matrix of the fake-web branch (73f1e8d): 16 + 34 cases against
  the reference measured on stock Playwright 1.62 - on fbceeaf 4 of the 16 were red (the download), now 50 of 50 green.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 02:42:32 +01:00
feder-crandClaude Sonnet 5.5 fbceeafb65 A popup is reported on Page.ready as Playwright's is: no limit and no warning, with the address of the commit that came with the ready
- Stock Playwright 1.62 (measured): a 204 or a silent destination gives no page event, one that answers after 4 s gives it at 4 s with the
  destination already. The adoption of a popup waited 20 s and dropped it with a warning; now only a page a caller asked for
  (newPage) has the 20 s; a popup waits until the engine says Page.ready, the target goes away, or its context closes
  (BrowserDispatcher.end_waits_of), and says nothing.
- The ready and the commit of the document that made the page ready come in the same turn: the page is announced after a round trip to the
  engine (settle_events), so the frame reads the destination at the page event (3 of 4 slow popups said about:blank).
- In-process the slow popup arrived 0.9 s later than stock: it is the humanised click (1.1 s of pointer movement before the click returns),
  the popup arrives 4.02 s after the click in both modes.
- Tests: unit (limit None for a popup and 20 s for a requested page; a popup with no ready ends with its context and says nothing; the
  address at the page event is the commit's) red on b09d620; e2e (204 and silent: no event; 1.5 s: url is the destination; 25 s: reported
  then) in-process and through a served browser: the 25 s ones red on b09d620.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 02:19:46 +01:00
feder-crandClaude Sonnet 5.5 b09d620930 tests: the popup reaches the client from another site too (a link, noopener, window.open: 16 more cases, in-process and through a served browser)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 01:11:02 +01:00
feder-crandClaude Sonnet 5.5 776c00afe2 tests: the stand-in pages say wait_until_ready; the popup e2e reaches the stock client as the other served tests do
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:58:07 +01:00
feder-crandClaude Sonnet 5.5 ba5b51cf91 A page is built at once and announced when the engine says Page.ready (the wait inside the constructor held a popup's first request behind a page that did not exist yet, and lost its commit and load)
- PageDispatcher no longer waits in __init__; wait_until_ready() is called by the adoption between the construction and the announcement
  (context 'page' event, newPage answer). A detach while waiting ends the wait; a page that is not ready in time is disposed.
- The main frame's initializer carries what the lifecycle already knows (url, name, load states), as every other frame's does.
- Tests: unit (a popup exists and listens while it waits; what it does before its ready reaches its frame; red on 6a60dce) and e2e
  (a popup of a link, noopener or window.open reaches an in-process and a stock client of a served browser within 2 s, with and
  without a context route; 15 of 16 red on 6a60dce, 16 green).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:56:01 +01:00
feder-crandClaude Sonnet 5.5 14c24347c5 tests: h3 behind a proxy follows the definitive retail (never h3 at visit 1, h3 within 5 visits, h2 every visit without usable UDP)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:38:20 +01:00
feder-crandClaude Sonnet 5.5 99c7fc93aa ci: the hosts-file e2e is required in wrapper.e2e.doh
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:33:20 +01:00
feder-crandClaude Sonnet 5.5 a61465b2be tests: the engine never reads the host's hosts file, with a proxy or without (MOZ_LOG per process, with a control)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:33:16 +01:00
feder-crandClaude Sonnet 5.5 47536b5e64 tests: the refused-once e2e says what it measures and what it does not
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:33:16 +01:00
feder-crandClaude Sonnet 5.5 4f95aa3797 ci: the resolver-race and DoH-under-stress e2e (wrapper.e2e.doh, 17) and the FakeDoh levers unit tests (wrapper.unit.udp, 110) are required
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:27:45 +01:00
feder-crandClaude Sonnet 5.5 6a60dcebb7 tests: new_page and a popup are handed over only when the engine says Page.ready (red without the wait in PageDispatcher, green with it)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:27:32 +01:00
feder-crandClaude Sonnet 5.5 7927e30679 tests: the refused-once e2e shortens the DNS negative cache, so it measures a temporary block and not Firefox's 60 s failure cache
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:27:13 +01:00
feder-crandClaude Sonnet 5.5 bf2a3c33b0 tests: the DoH of a proxied context when it is slow (2 s per answer) and when it refuses a name once; FakeDoh gains delay_s, delay_names and fail_first (written ahead of the engine)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:27:13 +01:00
feder-crandClaude Sonnet 5.5 03d96a7baa tests: a context with a proxy resolves by DoH through it and a context without one never uses the DoH; the first navigation of a fresh context never asks the system resolver (written ahead of the engine)
The context-only test also asserts that the DoH log holds no name but the proxied context's, that no handshake failed and that the
default context's background lookups reach the system resolver (the trap, where it runs). New race test: eight contexts created
and navigated back-to-back, a launch-proxy variant, and a proxied context beside one without a proxy. The DoH e2e docstrings
follow the per-context rule.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:27:13 +01:00
feder-crandClaude Sonnet 5.5 7db28e4611 tests: the stand-in engine of the registry test says Page.ready, as the real one does (the page is handed over on it)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:21:38 +01:00
feder-crandClaude Sonnet 5.5 f76240893e Pin invisible-core==62.65.0 (a page handed over when the engine says it is ready); changelog
The core that carries Lifecycle.wait_for_page_ready is invisible-core 62.65.0 (draft PR invisible_core#238), not on the index yet:
the pin check of this push is skipped on purpose (INVISIBLE_PIN_CHECK=skip).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:14:02 +01:00
feder-crandClaude Sonnet 5.5 d5c0e410de The page dispatcher waits for Page.ready before the page is handed over (needs invisible-core with Lifecycle.wait_for_page_ready)
Same defect and fix as in the core's page (see the core commit): a goto sent right after new_page could meet the page's initial about:blank.
The pin of invisible-core moves with the core release that carries wait_for_page_ready.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 00:13:19 +01:00
feder-crandClaude Sonnet 5.5 422e675b86 ci: the context-only-proxy DoH e2e (wrapper.e2e.doh, 12) and the host-address helper unit tests (wrapper.unit.udp, 97) are required
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:36:39 +01:00
feder-crandClaude Sonnet 5.5 1c7bcf9dee tests: a context that is the only proxy resolves its names by DoH through it (red while TRR stays mode 0 for context-only proxies, green with engine 9bff9cf8de)
A session launched with no proxy, a context made with its own SOCKS5 gateway, a page at a name only the FakeDoh can resolve: the
name must be asked to the DoH by that gateway, the page reached by address through it, nothing to the DoH directly and no
question about the zone to the resolver of the machine. Review finding 4 (the e2e that was missing).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:33:37 +01:00
feder-crandClaude Sonnet 5.5 84fd375562 ProxyEgressNonVerificabile: the docstring says what goes unconfirmed (timezone and locale), not an address
The engine no longer declares an egress address (the host network is drawn from the seed); only the timezone and the locale are
decided from the egress. Reworded like ProxyEgressDrifted, with a test on the text that fails on the old wording. Review
finding 30.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:33:24 +01:00
feder-crandClaude Sonnet 5.5 d596ee81c8 tests: one helper for the address of this host, computed before any server starts, a host without a default route skips
this_host_address() and its two copies connected a UDP socket to 192.0.2.1 and raised OSError on a host with no default route;
in the chain it was evaluated as an argument after the TURN server, the resolver and the page were already listening, so the
test errored and leaked three listeners instead of skipping. The helper is now tests/_host_address.py (OSError => pytest.skip),
the chain asks it first, and the three copies are gone. Review finding 29.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:33:24 +01:00
feder-crandClaude Sonnet 5.5 66d5090a0b tests: the declared-network e2e no longer sets variables the engine does not read
STEALTHFOX_WEBRTC_PUBLIC_IP and STEALTHFOX_WEBRTC_DISABLE_IPV6 are not read by the engine or the core (the unit test of the
declaration bans them in the environment); the e2e set and deleted them and imported _FAKE_EGRESS only for that. Dead setup
that said the egress still feeds WebRTC. Review finding 27.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:33:24 +01:00
feder-crandClaude Sonnet 5.5 3a1dc8df9b tests: the gather without a proxy and the ICE-name e2e wait for the engine that carries the UDP line
test_the_gather_is_real_without_a_proxy (in wrapper.e2e.udp) had no the_udp_line, unlike the other tests of its file, and the
ICE-name e2e (wrapper.e2e.doh) resolves a name through the proxy of a context, which the engine firefox-63 does. On an older
engine they skip with the reason; on the candidate (firefox-63-candidate) they run, so the exact lists of
ci/required-suites.json are unchanged. The networkidle e2e stays ungated: it needs no proxy and no UDP, and is fixed by the
Python of the core and the wrapper on any engine. Review finding 14.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:33:24 +01:00
feder-crandClaude Sonnet 5.5 5b87926543 ci: the warm-pool and the TURN-over-TCP e2e are required in wrapper.e2e.udp (61 tests)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:29:44 +01:00
feder-crandClaude Sonnet 5.5 b396e055ce A TURN server over TCP is connected to and waited for, direct and behind SOCKS5 (e2e)
A TCP stand-in for a TURN server on this machine's address accepts, reads and closes N ms after the accept; the page asks for a
TURN allocation over TCP. A retail Firefox connects, sends the Allocate request and hears 701 when the server closes (accept
at 48 ms, 701 and the gathering complete at 850 ms with N=800). The candidate engine never connected: no accept, no bytes, 701 within
9-28 ms with the gathering complete, direct and through the gateway alike.

Red on the firefox-63 candidate build; green expected with the engine commit that binds the wildcard of the declared family.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:28:22 +01:00
feder-crandClaude Sonnet 5.5 68bb2b8e8f tests: the first datagram of a PeerConnection does not wait for a UDP association (red on the giro 2 binary: 396 ms)
The pool of UDP associations was warmed only in the process of the HTTP connections (the parent); the sockets of the PeerConnections
are made in the socket process, which found it empty and made its association from scratch: three answered steps before the first
STUN datagram. A gateway that answers every step after 130 ms makes it visible: on the giro 2 binary the first datagram leaves 396 ms
after the birth of the PeerConnection. The test asserts it leaves within 250 ms, and that an association was granted before.

The gateway of the tests now also keeps the wall-clock origin of its times and the instant of every accepted connection.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:27:55 +01:00
feder-crandClaude Sonnet 5.5 c14f2b1e9a ci: the ICE-name e2e is part of wrapper.e2e.doh (11 tests)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:20:42 +01:00
feder-crandClaude Sonnet 5.5 bfedd53850 tests: the ICE server name of a PeerConnection is resolved in the context of its page, by the proxy of that context (red until the resolver carries the OriginAttributes)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:20:03 +01:00
feder-crandClaude Sonnet 5.5 e868714339 tests: the h3 e2e turn off Firefox's check of third-party roots (a self-signed test server stops HTTP/3 otherwise: measured)
The Alt-Svc is learned and the QUIC handshake of validation passes with the override, then Firefox closes the connection itself because the chain
ends in a root it does not know, and every visit stays h2. With network.http.http3.disable_when_third_party_roots_found off the three visits read
h2, h3, h3 (3 runs of 3, no proxy, on the engine of the first round).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:15:44 +01:00
feder-crandClaude Sonnet 5.5 36ecd11e99 tests: the chain by name declares the FakeDoh's own provider (doh.gateway.test): the DoH of Mozilla is HSTS-preloaded and takes no override
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 23:07:23 +01:00
feder-crandClaude Sonnet 5.5 80672c69a3 tests: the fake DoH of the e2e uses a name that is not HSTS-preloaded (doh.gateway.test at 192.0.2.53), declared through extra_prefs
Firefox refuses certificate overrides for HSTS-preloaded/pinned hosts, so a self-signed fake for
mozilla.cloudflare-dns.com could never be accepted. The test now declares its own provider
(network.trr.uri, network.trr.bootstrapAddr) and counts every connection of the browser, including
the background traffic of the default context whose TLS fails by design, at the gateways.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:59:17 +01:00
feder-crandClaude Sonnet 5.5 a21e1decb9 tests: the descriptors of the spawn are asserted by running it, not by reading the core's source
test_the_spawn_keeps_the_two_hardwired_descriptors asserted that the source of the core's _spawn_posix contains
`pass_fds=(its_read, its_write, 3, 4)`. Core 62.64.0 starts the engine with posix_spawn and file actions, so the words are gone
and the test failed on every Linux unit suite although the behaviour is the same (and better).

The test now runs the spawn: a parent with nothing open on 3 and 4 and its pipes far from them launches a program that reads
fd 3 and answers on fd 4 (the contract of nsRemoteDebuggingPipe.cpp), and the answer must come back and the child must hold no
descriptor above 4 of the parent's. Same shape as the core's own test
(test_the_pipe_of_the_engine_reaches_its_fixed_descriptors). No skip: the file is already POSIX-only.

The other tests of the file do not read source text (checked: no getsource/inspect/read_text left).
Ran the parent program on Linux with core 62.64.0 (image tetra-invisible:run1b-final): pong:ping:0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:59:15 +01:00
feder-crandClaude Sonnet 5.5 ecf384a923 ci: the no-proxy gather is a required test of wrapper.e2e.udp (58 tests)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:58:25 +01:00
feder-crandClaude Sonnet 5.5 a8cc2c842e A keepalive fetch is a request of the page for the client, in a real browser
e2e: the page sends a plain fetch, a keepalive fetch (cors and no-cors) and a beacon; the client must hear a `request`
for each and an end for each. Measured on the firefox-62 engine: the server received the keepalive fetches and the client
heard no `request` for them (stock Playwright's Firefox reports them). Red until the engine attributes the request to
its page.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:44:20 +01:00
feder-crandClaude Sonnet 5.5 5da874d67f tests: HTTP/3 is judged on three visits of one page (h2, h3, h3 with UDP free; h2 three times without), as a retail Firefox reads them
Reference: retail 159 Linux, 15 of 15 each way (invisible_WebRTC captures/h3-fallback): with
UDP free the first visit is h2 and the second and third h3; with UDP dropped every visit is
h2 and the later loads are as fast as the first.

- _h3_server: the TCP side speaks HTTP/2 by ALPN (h2 library; HTTP/1.1 only for a client that
  offers nothing else), carrying Alt-Svc: h3; it answered HTTP/1.1 only, so the first visit
  could never read h2. One HTML document over TCP and QUIC; tcp_alpn recorded.
- test_http3_through_the_proxy_e2e: the retail method (one context, three gotos, a pause of 2 s
  after each load, nextHopProtocol of the navigation entry) on six roads: no proxy and a SOCKS5
  with coherent UDP -> h2,h3,h3 (QUIC through the relay, the server never sees this host);
  SOCKS5 that refuses UDP / leaves from another address / never answers (the declared udp is
  asserted) and an HTTP proxy -> h2,h2,h2, no QUIC at the server, no page datagram at the relay,
  visits 2 and 3 no more than 1.5 s slower than visit 1. An h3 on visit 1 is named as an error.
- _udp_line: expected_protocols / judge_visits (the sequence and the judgement, unit-tested).
- test_the_h3_line_helpers (unit): the server really negotiates h2, says Alt-Svc, answers the
  same document over h3; the judge names each mistake.
- ci/required-suites.json: wrapper.e2e.udp 53 -> 57 (the http3 file has 6 tests, was 2).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:43:33 +01:00
feder-crandClaude Sonnet 5.5 f3e3ce164d tests: the e2e of the UDP relay hand the core the STUN server its gateway answers (udp_stun_servers), and the dropped-UDP cases expect the new behaviour
The core now MEASURES the UDP exit of a SOCKS5 proxy before declaring it; only `coherent`
makes the engine send UDP to the relay. A gateway of the tests that is not asked the right
way is declared `no` and its e2e would fail for a reason that is not the product's.

- _socks_servers: MEASURE_NUMBER (the fake STUN by a number of its own, so the measurement
  is told apart from the page's STUN_NUMBER), Gateway.measure_servers, silent_udp() (relay
  granted, STUN never answered -> unmeasured), relay_host on every factory.
- _udp_line (new): measure_servers, egress_by_proxy (the TCP exit of each gateway: a context
  proxy is measured against its own), declared_udp (what the launch measured; absent is not
  `unmeasured`), one place for every e2e.
- test_webrtc_realness: one launch helper behind a gateway; the relay tests, the two-contexts
  and the TURN-over-TCP tests use the exits of their own gateways; the dropped-UDP case is one
  helper with three roads (refused: no, another exit: no, never answered: unmeasured) that
  asserts the declared udp, no srflx, 701, and that the page's UDP never reached the relay.
- test_the_whole_udp_chain_by_name_e2e: the chain is told its own TCP exit (it was a
  documentation address the chain's UDP does not leave from, i.e. `no`) and asserts coherent.
- test_the_udp_line_helpers (unit): the real measurement of the core against each gateway
  and the chain; the helper's list is `ip:port` IPv4 literals the core takes.
- ci/required-suites.json: wrapper.e2e.udp 51 -> 53 (two new tests, listed by name).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:38:12 +01:00
feder-crandClaude Sonnet 5.5 2329dc6c1c wrapper: the STUN servers are a launch parameter kept on the session (udp_stun_servers); the caller never declares udp
- InvisiblePlaywright(..., udp_stun_servers=None) (sync and async) and launch_server(...,
  udp_stun_servers=None) take "ip:port" IPv4 literals (None = the core's two public defaults;
  a name or a bad port raises ValueError naming the parameter) and keep them on the session.
  The launch's geo step uses them, and so does every later new_context(proxy=...): the server
  keeps the list on the browser it launches (the list rides to the server in the launcher's
  composed prefs like the session seed and is taken out before the profile is written), so the
  per-context call needs no new parameter. Nothing of it reaches the browser's environment,
  argv, prefs or pipe (tested).
- The proxy command is built by the core's context_proxy_command / launch_proxy_command: the
  `udp` field is the measurement, never what the caller wrote; configure_proxy(udp=) is gone
  and the launch's measure reaches Browser.setBrowserProxy through the core's per-proxy memory.
- The constructor-signature pin records the new keyword.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:27:14 +01:00
feder-crandClaude Sonnet 5.5 52e520dd92 wrapper: a proxy given to a context declares its measured UDP exit (udp) in Browser.setContextProxy
The core measures where a SOCKS5 proxy's UDP leaves from and the answer is the optional
field `udp` of the proxy declaration. The wrapper hands it on:

- the launcher, the async launcher and launch_server pass the udp their geo step measured
  to configure_proxy(udp=), so it reaches Browser.setBrowserProxy;
- the server's launch (a client that composed no session) declares the proxy with what the
  geo step remembered, never coherent without a measurement;
- BrowserDispatcher._apply_context_options, the one place new_context(proxy=...) of the sync,
  async and remote clients ends in, measures the context proxy BEFORE Browser.setContextProxy
  is sent (the core discovers the TCP exit through it and measures the UDP beside it, once per
  proxy, cached by endpoint and a hash of the credentials) and the result goes in `udp`.

Tests: a recorder in place of the engine, the fake SOCKS5 gateway with a UDP relay and a STUN
server only the relay reaches, declared through STEALTHFOX_UDP_STUN_SERVERS.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:27:13 +01:00
feder-crandClaude Sonnet 5.5 73c070ebb1 wrapper: every context carries the position the core declares for the session
The geo step is asked with the session seed (launcher, async_api, the served
browser, the default session) and the core's SessionGeo.geolocation_override()
(latitude, longitude, accuracy) becomes the standard `geolocation` context
option in _default_context_kwargs: the default context, each new_context /
new_page and each context of a remote client get Browser.setGeolocationOverride
through the existing path (server.py _apply_context_options). A geolocation given by the
caller wins; no coordinates, nothing is sent; the permission is never granted
here. Tests written ahead: tests/test_the_session_position_reaches_every_context.py.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 22:27:00 +01:00
feder-crandClaude Sonnet 5.5 1d564f5732 A route answer the engine refuses is the engine's business, whatever its wording
The server took one wording ("Cannot find request") of an answer to a closed request as done and passed every other
protocol error up to the client. The engine also says "NS_BINDING_ABORTED
[nsIInterceptedChannel.resetInterceptionWithURI]" when the channel was cancelled while the answer was on its way: the
same event, and the client kept it as the error of the connection and raised it on its next route command.

Stock Playwright sends the three interception commands as may-fail and tells the client nothing, whatever the engine
says. So does RouteDispatcher._send now: every ProtocolError is swallowed, the route is disposed after it.

Tests: the static guard no longer allows a re-raise inside the handlers; a unit test feeds three wordings (red on the
old code for two of them).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 21:20:59 +01:00
feder-cr 8c92c764b7 Merge #392 (docs: the agent links and the command name the MCP repo as it is now) into the 0.50.1 release 2026-11-11 20:22:43 +01:00
feder-cr 000fa7a3ad Release 0.50.1: pin invisible-core 62.64.0; CHANGELOG for the networkidle fixes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit e63ef8e61ea42e7f8df7c1bde206f3bf86fc18f7)
2026-11-11 20:22:42 +01:00
6a5b7e014a tests: answering a route the next navigation already aborted does not raise (the case of #351: the favicon of the page just left)
Sixty sequential routed gotos on a loopback page: 4-12 of them failed on the old server, every failing continue_ being
the previous document's favicon, aborted by the next navigation while the route sat with the handler. Red on main (in-process
path), green with the fix of RouteDispatcher._send.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:22:29 +01:00
feder-cr b78c5bb67c tests: the stock Playwright client is required by the networkidle e2e (explicit failure, never a skip); the dev extra pins it
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 91223226f5bba25edff9af0e8b1fd6b5bfea2227)
(cherry picked from commit 612b18c02b95e9b5833d62b6595d4a0ff324aac2)
2026-11-11 20:22:14 +01:00
228576009b server: the answer to a request the browser has already closed is not an error (Cannot find request), as stock sendMayFail
A page cancels requests while a route is deciding (a fetch aborted, an image replaced, an iframe removed, a beacon with
its document, the favicon of the page a goto just left). The engine takes the request out of its held set at once and the
late continue/abort/fulfill meets "Cannot find request" or NS_BINDING_ABORTED. Stock Playwright sends the interception
commands as may-fail and tells the client nothing; ours passed the error up, the client kept it as the error of the whole
connection and raised it on the NEXT route command, which was then never sent: its request stayed held in the engine, its
handler failed too, and so on down the page. Seen on a real news page: six held requests in a row, one a beacon, and
networkidle never came.

RouteDispatcher._send now treats "Cannot find request" and a closed target as done (still disposed); any other protocol
error still reaches the client.

Tests: the e2e with a plain handler (no try) on a page that removes an iframe whose requests are held (red before:
networkidle never; green after), and a static guard that every op of RouteDispatcher goes through _send and that _send
swallows exactly those two. The same defect was found a month earlier by richardpowellus (#351), with the favicon of the
previous page: his test is added in the next commit.

Co-authored-by: Richard Powell <1369873+richardpowellus@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 20:22:14 +01:00
feder-cr bc816cb1ae tests: networkidle through a served browser whose context routes every request, on a reused page
launch_server() plus a stock Playwright client, a context route that aborts image/font/media and continues the rest, a
page with sendBeacon, the same font twice, a frame of another site, a worker, redirects, requests the page cancels while a
slow route decides, 100 requests at once, and a slow client that answers concurrently (async). Every shape reaches
networkidle on firefox-62; one page reused for twelve addresses too. The leak that tf-fetch meets on real sites needs
end events the engine loses, which no local page produces: its deterministic red/green is in the core
(tests/test_networkidle_on_a_reused_page.py of invisible-core); this file guards the remote path end to end.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
(cherry picked from commit 47182f0cd85fea08fc45e36f1c91d2d570722f14)
(cherry picked from commit e46f2dcf3eb361e6af0fedcdf6e1189f0ac330b6)
2026-11-11 20:22:14 +01:00
feder-cr cbd9f5db5b Merge the process-counting e2e (#451) into the 0.50.1 release 2026-11-11 20:15:37 +01:00
feder-crandClaude Opus 5.5 fef0bc5ea7 tests: the same-site control puts its frame in the shown page; CHANGELOG: 0.50.0's entry is 0.50.1's
The e2e of #451 saw a new "Isolated Web Co" once after a.test/plain -> a.test/same-site ([10878] -> [10878,
11208]). Not a process of an earlier test: it was created after the first read and only this worker's
descendants are counted. It is the top-level navigation: when the old document may enter the back-forward
cache, the browsing context is replaced (mReplaceBrowsingContext, dom/ipc/ProcessIsolation.cpp) and the new
one may be placed in another process of the same site (dom.ipc.processCount.webIsolated = 4). Measured on
firefox-62 (candidate #6, Linux): 0 of 30 runs alone (bfcache on and off), 0 of 57 under 4 workers. The test
was written for the frame, so the frame is now added to the page already shown and the top never navigates:
20 of 20 runs green.

0.50.0 never reached the index, so the changelog gate refused its heading; its entry now opens 0.50.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:47:54 +01:00
feder-crandClaude Opus 5.5 2bc12eb80b Release 0.50.1: 0.50.0 with the process-counting e2e corrected (0.50.0 never reached the index)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:59:28 +01:00
feder-crandClaude Opus 5.5 ff2123ef58 tests: a closed context is checked for the processes of its sites, not for every content process
test_closed_contexts_with_a_never_stopping_service_worker_leave_no_process was red on the e2e of the 0.50.0
tag ([2, 2, 2, 5, 5], 5 <= 2). Measured on firefox-62 (Linux), the test's own scenario 10 times with every
process named: no "Isolated Web Co" left after any close; the 3 more are "Web Content", the engine's pool of
preallocated processes filling up behind the closed contexts (5 runs of 10, new pids each time). Not a leak:
the count read the refill.

The helper of the bench moves to tests/_processes.py and both tests use it. The context test counts the
processes that host a site: at least one while the page is open (or the count proves nothing), none a few
seconds after `close` answers (the engine waits for them inside close and kills the ones that stay). Off
Linux it skips, as the bench's two counting tests do: no other system names the process.

Unit tests (tests/unit/test_processes_counts_sites.py) from the measured processes, the closed-context case
included. e2e on firefox-62 (candidate #6, Linux): the context test 10 of 10; run_e2e.py on the two files and
the unit test 18 passed. The old counter, same scenario: 5 of 10 runs would fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:40:29 +01:00
feder-crandClaude Opus 5.5 5402da4d80 tests: the Fission bench counts the processes that host a site, not every new content process
test_same_site_other_port_stays_in_process was red on the e2e of the 0.50.0 commit ("a same-site frame
started a process: [13443]"): the bench counted every `-contentproc ... tab` pid, and the engine starts a
preallocated content process to refill its pool whenever it gets to it. On Linux the engine names a content
process by its remote type (ContentChild::SetProcessName, prctl PR_SET_NAME): "Isolated Web Co" once it
hosts a site of strategy 1, "Web Content" while preallocated. Measured on firefox-62: a cross-site frame
renames a preallocated process and a new "Web Content" refills the pool; a same-site frame changes neither.
The two tests that count processes skip off Linux, where no process carries a name.

Unit test with the measured processes: 3 red on the old bench, 3 green here. e2e on firefox-62 (candidate
#6, Linux): the bench file 17 passed; the two counting tests 15 of 15 runs green.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 13:18:54 +01:00
feder-crandClaude Opus 5.5 c23612e295 test: the docs name the MCP server's repository and command as they are now
feder-cr/AIHawk now leads to an unrelated repository and answers 200, which no
link checker reports; `uvx aihawk` does not exist. The README and docs/ are
read for both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:49:05 +01:00
feder-cr 11b9e08b1a docs: the agent links and the command name the repo as it is now
Two things were broken for a reader on main, not one.

Thirteen links pointed at github.com/feder-cr/AIHawk. GitHub redirects a
NAME to the OBJECT that carried it, not to the content: after the September
swaps that name belongs to invisible_dots, which has seven wiki pages, so
AIHawk/wiki/<page> lands on its wiki Home. It answers 200 with different
content, which means a reader who clicks does not find the page and a search
engine sees a soft-404 across about 150 indexed URLs.

Seven occurrences said `uvx aihawk`, a command that does not exist. One sat
in a front-matter description, which is the snippet search engines show, and
one in a block meant to be copied: `claude mcp add stealth -- uvx aihawk`.
The command is invisible-playwright-mcp, on PyPI at 0.70.16.

All eight link targets were checked one by one and resolve to themselves with
the page title, no redirect.

Three things stay as they are, which only reading them showed. The
`pip install invisible-playwright` line matches what this engine's own README
teaches for the library, so the page is consistent rather than broken.
CHANGELOG.md keeps the old name because a changelog entry says what was true
then. And the fixture in scripts/sync_article_pixels.py keeps it because it is
the deliberate wrong case, a pixel for ANOTHER repo.

One sentence went away instead of being renamed: "shipped inside AIHawk" made
sense when AIHawk was the larger product containing the server. The server and
the repository are now the same thing, so "shipped inside itself" was circular.

(cherry picked from commit d9c8e46dce)
2026-11-06 19:47:58 +01:00
107 changed files with 10787 additions and 1088 deletions

No files matched your search

+56 -8
View File
@@ -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
+4 -1
View File
@@ -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:
+5 -2
View File
@@ -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
+31 -24
View File
@@ -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
+120 -2
View File
@@ -6,7 +6,69 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
## [0.50.0] - 2026-11-11
## [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.
0.50.1 is 0.50.0 with those tests corrected.
### Changed
- Engine firefox-62 through invisible-core 62.63.0, which this version pins: firefox-61 plus Fission
@@ -23,6 +85,22 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
iframe and of its page) run on that engine.
### Fixed
- `goto(wait_until="networkidle")` arrives on a page that is reused for many addresses, and on a served browser whose
context routes every request, as with a stock Firefox. Two causes, both ours. A route answered after the browser had
already closed its request (a fetch the page aborted, an image it replaced, an iframe it removed, a beacon cancelled
with its document) came back to the client as an error, which the client kept for the whole connection and raised on the
next route command; that command was never sent, its request stayed held in the engine, and so on down the page. The
server now takes such an answer as done, whatever wording the engine gives it ("Cannot find request", or "NS_BINDING_ABORTED"
when the channel was cancelled while the answer was on its way), as Playwright's own server does. The same defect was found a month earlier by richardpowellus
(#351), on the favicon of the page a `goto` had just left; his test is part of this release. And the core counted the requests in flight
with one integer per page, never reset by a navigation, so one request whose end never arrived kept every later address
from going idle (invisible-core 62.64.0 keeps them by request id, per document, and does not keep the requests of a
frame that already left: a beacon sent at `pagehide` is announced after its frame is gone).
- A `goto` sent right after `new_page` is no longer "interrupted by another navigation to about:blank" on a loaded machine. The page was
handed to the caller as soon as its main frame was announced, while the engine had not yet committed the page's own initial
`about:blank`; a navigation answered before that commit lost to it. The page is now handed over when the engine says it is
ready (`Page.ready`), as Playwright's own page is (invisible-core 62.65.0, `Lifecycle.wait_for_page_ready`; a page closed before
it was ready ends the wait with an error at once).
- A launch that names no session (Playwright's own `BrowserType.launch` against the server) gets a
session composed the way `InvisiblePlaywright()` composes one: prefs, environment and, behind a
proxy, the egress the page reads as its WebRTC address. It used to come up with Mozilla's
@@ -37,6 +115,45 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
(`geolocation`, `persistent-storage`, `push`, `notifications`, `screen-wake-lock`); any other name
raises `Unknown permission`, as it does there, and a grant with no origin is a grant for every
origin.
- The end-to-end tests that count content processes count the ones that host a site, not every content
process that is new. The engine keeps a pool of preallocated processes and refills it whenever it gets
to it, so a refill landing between two reads looked like a process the test had caused (a same-site
frame, a closed context with a service worker that never stops). Measured on firefox-62: a closed context
leaves no process of its site. On Linux the process is named by the site it hosts; elsewhere these
tests skip.
- A popup (a `target=_blank` link, `window.open`) reaches the client as it does with Playwright's own Firefox: when its
destination answers, with no limit of time, with the destination's address as its url, and with `load` reachable on
it. It used to be given up on after 20 s, could be announced with `about:blank` as its url, and about one in a
hundred was never announced. A destination that never becomes a page (a 204, a server that never answers) is not
announced, as on stock. Measured against stock destination by destination, with answers after 4 s and after 25 s: 18
cases of 18; and 128 popups announced of 128 across the two transports (the library client, a stock client over
`launch_server`).
- For a popup whose answer is a download, the opener's `download` event comes after the popup's `page` event, as on
stock. With little CPU the download could arrive and the page never be announced. Measured on a runner limited to
one CPU: 8 runs red of 10 before, 0 of 10 after.
### Known differences from stock Playwright
Measured against Playwright's own Firefox with the same script, on this version. None of them is a value a page
reads; they are what a script that drives the browser can observe.
- **The url of a popup that turns into a download.** A link or a `window.open` whose answer is an attachment gives, as on
stock, a `page` event, a `download` event on the opener, and a popup that closes at once. The popup's `url` at the `page`
event is `about:blank` here and the empty string on stock. Measured: 8 cases of 8 (link and `window.open`, the library
client and a stock client over `launch_server`), against 4 of 4 on stock.
- **The url of a frame of another site at the page's `DOMContentLoaded`.** A frame of another site runs in another process,
as in a retail Firefox, and commits its navigation after the page's `DOMContentLoaded`; stock Playwright keeps frames in
the page's process. So `frame.url` read right after `goto(..., wait_until="domcontentloaded")` can be the empty string.
After `load` it is always set. Measured, 30 runs each: after `load` the url was there 30 times here and 30 on stock; at
`DOMContentLoaded` once here and 30 times on stock. Wait for `load`, or for the frame's own navigation, before reading it.
- **A click takes longer with the library client.** From `click()` on a link to the `page` event of the popup it opens:
0.8 to 1.7 s more than stock with the library client, and the same as stock (within 0.1 s) with a stock client over
`launch_server`. Measured on 64 popups per transport and on destinations that answer after 4 s and after 25 s. The
same run with `humanize=False` was not measured.
- **Back and forward restore the page from the back-forward cache.** As in a retail Firefox, `go_back` and `go_forward`
bring the page back as it was; Playwright's own Firefox loads it again. So a script that runs when the page loads does
not run again here. Measured on a 17-step journey with the same script on both: on its three back and forward steps
the page's load-time requests were sent again on stock (6 beacons each) and not here (0, 2 and 0, the two being the
ones a page sends when it is left); every step ended on the same page, and the other 14 steps sent the same requests.
## [0.49.1] - 2026-11-10
@@ -2113,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
+512
View File
@@ -36757,6 +36757,518 @@
}
},
"wheel_filename": "invisible_playwright-0.49.1-py3-none-any.whl"
},
{
"published_at": "2026-11-12T09:31:22Z",
"requires_dist": [
"greenlet<4.0.0,>=3.1.1",
"invisible-core==62.65.0",
"psutil>=5.9",
"pyee<14,>=13",
"build>=1; extra == 'dev'",
"cryptography>=41; extra == 'dev'",
"playwright==1.61.0; extra == 'dev'",
"pytest-rerunfailures>=14; extra == 'dev'",
"pytest-timeout>=2; extra == 'dev'",
"pytest-xdist>=3; extra == 'dev'",
"pytest>=7; extra == 'dev'",
"ruff>=0.6; extra == 'dev'",
"websockets>=13; extra == 'dev'",
"websockets>=13; extra == 'remote'"
],
"sdist": {
"digest": "aa0aa40ad9d908ab7d75dc5c523213fae0f12f82651e13f7d0ee1cbff39c4ed5",
"files": {
"LICENSE": "2abb03e63a96918967f383cbc36e3faefe10a47ae20b2cab43212ef965e02f96",
"PKG-INFO": "019ef54b7d89b1dc345b422fcec68f7d159e00cc3b52abaf7d724e8194127b9f",
"README.md": "5eefb8a6a7b61d2fca5ec8d7b72917419a7ff4c23f761bb83db6fe7e39502618",
"docs/README.md": "615a5bb1bef8a7b04e522d10bf8ef94beb410727c6dd81284520f5864ee6d4e2",
"docs/integrations/README.md": "d9d4a01c5ce0b3a94123653bf8e78283113cae0a6ec22ba0bc2a2a77baf8ea19",
"pyproject.toml": "01787157df2e5643fddcdbed10a3f126c597be96f23ccff85333f23595dbe641",
"src/invisible_playwright/THIRD_PARTY_FORK.md": "077a8a09f68a6185080b6cd088224b4a19d7fc957c1335027ed6fa42ac4cbbbc",
"src/invisible_playwright/__init__.py": "4516af737fdbaa0967a359a97b01aa7a3e3d57dae7283ebe5e6ac2381285f3ee",
"src/invisible_playwright/__main__.py": "c6cd277050ead2d11c98b7cbab91ada7d19e495c95e4c86de1f9aaf2b2051d38",
"src/invisible_playwright/_cursor.py": "12975e06bcd6c162f4c38298966f9adaa8d9d2eeb225df3a4984af2c9d29672f",
"src/invisible_playwright/_engine.py": "fabcbd037b52294a5b5201c22382f56714e94aa1edfb834ee2fc8fd7cbf2b3b0",
"src/invisible_playwright/_fpforge/__init__.py": "3e1338f0bac8ce7c61c0b20c87d7824af5d14e3254b8984f5fc811e6c8500681",
"src/invisible_playwright/_geo.py": "6cb7a453ae392bd4724f2d508a7f697d1189d9e05b833cc4b36d70069d18225f",
"src/invisible_playwright/_headless.py": "ceaf85c0a32f92c8c8489fa11756b538feddecc021d4ae22782927171429c2b9",
"src/invisible_playwright/_juggler/__init__.py": "96d6d06dad40f3c5112ab2bf9852c9d273ca891647baaf86e9913a06112db829",
"src/invisible_playwright/_juggler/_marshal.py": "4ddc577bb511eda773aff9ed83d7140d0809d9c850fce9cec1826aafc7719d3f",
"src/invisible_playwright/_juggler/dialogs.py": "5541004829d2484526fc93f11338bfdf9f63f3319e17fc95ea51f61e1b429220",
"src/invisible_playwright/_juggler/dispatcher.py": "6a74e13cb8e23bad410ccca0952e91bf85820d86121e693220f44f4531e25281",
"src/invisible_playwright/_juggler/memprobe.py": "39a5789d960d8e75e4fee27c958f28cf6a8fbe34684d282ba884673db92e69df",
"src/invisible_playwright/_juggler/perimeter.py": "3a2fc6579665db73596b9ae3eaea23091db45827546f3b60887a2ae76753fd58",
"src/invisible_playwright/_juggler/pointer.py": "cc38686ae60d08613b70d5898cec14ba62b67de218748963263a877c057b7ca9",
"src/invisible_playwright/_juggler/remote.py": "ad100601f02c97abd454db579d94b8dc6d90d3c5dac7d413d015cf1d507cafa9",
"src/invisible_playwright/_juggler/server.py": "15f9dc028cffec537cceabdcce3a74346567de9d92aee0c2c037124af5364196",
"src/invisible_playwright/_juggler/transport.py": "c799df2ebaed0f76e7b9c17938d8c0cddde67197f41675390fe6e9020a7ec62d",
"src/invisible_playwright/_juggler/variants.py": "0d72ed4c81affc4288fcc9474b18c59ced5d55ee329e4a64bfd7b2cf6aa77d3b",
"src/invisible_playwright/_juggler/wire.py": "fbe0399da9896031a104bdbe83a7c24a42dd6c264a23bd65d83e8e5f2be9e840",
"src/invisible_playwright/_pin.py": "34840d65c3ce32aa856f55344358a84cf47904471039a0a28d510166c6feda4b",
"src/invisible_playwright/_proxy.py": "dadfd7ad17246521c78c2e67bc60e31e3fc854dcb0924c4067f5d49a9662722e",
"src/invisible_playwright/_pw/LICENSE": "7fab1461b41970ff376f1c9303a637076bfaaeb71cd12dd3a1c44aaf59a1a2b9",
"src/invisible_playwright/_pw/README.md": "3ff2819bfde496151299983c4db167171e3e49933e7cf75613239893b2530570",
"src/invisible_playwright/_pw/__init__.py": "06c3acdadd13e2813fcb95ad91d53ee3885c2b5f473beccc45a579d9ceead70b",
"src/invisible_playwright/_pw/__main__.py": "dcc8e224337e54bb2febd50cc2e3c6db6ad345c2e148fe64612ca64c4dbea469",
"src/invisible_playwright/_pw/_impl/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"src/invisible_playwright/_pw/_impl/__pyinstaller/__init__.py": "5a8c0cfeb2d84ed4287afdec24ffcec60d1ed827b92afdfbd82b2351ffae1c15",
"src/invisible_playwright/_pw/_impl/__pyinstaller/hook-playwright.async_api.py": "d4a8c45554b3ba55e8102f03f576bab6ea4abfb70cdc60095471d504e34a1014",
"src/invisible_playwright/_pw/_impl/__pyinstaller/hook-playwright.sync_api.py": "d4a8c45554b3ba55e8102f03f576bab6ea4abfb70cdc60095471d504e34a1014",
"src/invisible_playwright/_pw/_impl/_api_structures.py": "7117217bc28b93311e0ded2232935bbb3e71cd36a69ace95faa5b5f019b6186d",
"src/invisible_playwright/_pw/_impl/_artifact.py": "3f06f56db387ad34194b9287291843e32ee6b2fbd06417872085ba5cdf58c3d0",
"src/invisible_playwright/_pw/_impl/_assertions.py": "ebfe537ce1c118606f256cf431d8acc55dbf45cec0ff8ce80b7d08189372d584",
"src/invisible_playwright/_pw/_impl/_async_base.py": "411bdbf2019879b7338bfd11291dab77662c4de8c029ce233f6c8c173845e440",
"src/invisible_playwright/_pw/_impl/_browser.py": "96af02910c9bd02ed3747049e4dc83f792b18ab363257bea5bb63e81335b5098",
"src/invisible_playwright/_pw/_impl/_browser_context.py": "c91c6e44a0dbc4e9c0430807561d9b92a73a3b33c406792a71a1362ccf995e46",
"src/invisible_playwright/_pw/_impl/_browser_type.py": "8e8fab1f8253952f971ea941948292e49fa08038e6566e6164ba1db927f16017",
"src/invisible_playwright/_pw/_impl/_cdp_session.py": "da1f31e66ee6a1a47a77412f6efa3e72670835a81d20a42a939cc6043f4c3357",
"src/invisible_playwright/_pw/_impl/_clock.py": "c3868a4cfdad993d99a554e58742f8c1e9f6806d51199e2870916e6c8b2eea2c",
"src/invisible_playwright/_pw/_impl/_connection.py": "0c345f8afd418c42c9722126b4562009922135df050c076ce279481cc9ae2534",
"src/invisible_playwright/_pw/_impl/_console_message.py": "4adcc1921c9ad348a2f796848b2ce92ab625b3f328ed611ac42d6576fe16ac66",
"src/invisible_playwright/_pw/_impl/_credentials.py": "0d5e2ea044d6a0861de54aae29de5f0da8ef871635384f57a111e2d70cd9843e",
"src/invisible_playwright/_pw/_impl/_debugger.py": "17a425f2c82a798098fe08a0a1b92be5fd7ccce0d56af25a6795e80d33aee2bd",
"src/invisible_playwright/_pw/_impl/_dialog.py": "2061f36b8952cd8fcb74c9a9cc9930c3a600eb1e7f6fa4ef1867867f353d14a6",
"src/invisible_playwright/_pw/_impl/_disposable.py": "564a3c3e3e2c5dc8db07727d682e2fb40c0e113e8489cf7fc179ed4aaea2ac87",
"src/invisible_playwright/_pw/_impl/_download.py": "5349c613615cc690593537acbedc83e5a53fd056521358cacaf2a355238efdd4",
"src/invisible_playwright/_pw/_impl/_element_handle.py": "b922cf771522209192727547185c922e9617f94fe55ae7c37ffa99cadf410a45",
"src/invisible_playwright/_pw/_impl/_errors.py": "49407bd6164ab563f82b2bf37863a265555071544dcabedbf7beba8be1b618cd",
"src/invisible_playwright/_pw/_impl/_event_context_manager.py": "55ea0fab5a17acbb3f6f797610cf20a77efcbc7b62e8c19bac53a138f39c7127",
"src/invisible_playwright/_pw/_impl/_fetch.py": "2756ee00ffb7cf8e178af4d9f8d56ab7d06828fce431faa9318e54a2ade55e1f",
"src/invisible_playwright/_pw/_impl/_file_chooser.py": "3efbf6c96f36cb906508330cb09ef5b5e1843e2b1aa95b27a5f85ec4376c8522",
"src/invisible_playwright/_pw/_impl/_form_data.py": "a9ce4cb4f77a06d24d31ea0e81a0e007a965bf33ad848ebed7cf0ad2f40f36b7",
"src/invisible_playwright/_pw/_impl/_frame.py": "0f974f94f52be86e510552900469c219007ba7a5ec05f3fe3a0d5cb78ff42b81",
"src/invisible_playwright/_pw/_impl/_glob.py": "af927c1cc1a33e12094224ca96158964ce2c7ad9f4b4de3ac60e16e0baf9f887",
"src/invisible_playwright/_pw/_impl/_greenlets.py": "27456c0ecfc181a04a6a1245e0f72549129e3af0b611e60607cb5d29f4fe2634",
"src/invisible_playwright/_pw/_impl/_har_router.py": "24fe3134253de1b71a3738348444dea88b78bdd250851ac7cfdac2ffcdef68b8",
"src/invisible_playwright/_pw/_impl/_helper.py": "c866f0dde846d84856404d7b6c72c5fbd5ac41302b1f6ac043016956256c2812",
"src/invisible_playwright/_pw/_impl/_impl_to_api_mapping.py": "ea1e5b8ea94f344a18a6c049e465d45044cfd61c2ef779887f076e675dffa655",
"src/invisible_playwright/_pw/_impl/_input.py": "14ed52c5e5bda7f5d8bde6b67fd651dee8c368344e13d652178d04e975ea1801",
"src/invisible_playwright/_pw/_impl/_js_handle.py": "cbb76fdf29d5087e2f2d04bac5e729bf7905238a9b386f3be9e01a4e2a95406a",
"src/invisible_playwright/_pw/_impl/_json_pipe.py": "c738956081dee483bbc032707553a9f9b3be38750f2ee7916390fa47fb1b19e8",
"src/invisible_playwright/_pw/_impl/_local_utils.py": "93677e1277ef74efcf52630d98a8857c1ea847b6e16757538040ce49e2758490",
"src/invisible_playwright/_pw/_impl/_locator.py": "c4457bbae669d98530a5bfd717619f8fc801a20c35e2e52e39b4f96193fba708",
"src/invisible_playwright/_pw/_impl/_map.py": "606086b53edc29605a5ff0b22147dfc640e38c65089df790063aed9cb89bfaa7",
"src/invisible_playwright/_pw/_impl/_network.py": "6af15cca7afa486ddb3edcea9ed2fdd2104f6ec268612dedf6707453a0c9433d",
"src/invisible_playwright/_pw/_impl/_object_factory.py": "16cf089afe2a37a18c397ac6cc9aebd296db731b6e6fac2a1248cae09585f26e",
"src/invisible_playwright/_pw/_impl/_page.py": "187b110afac50f94766b0b5b40a82c02b895e723c0000fbee7233deb0e08d11e",
"src/invisible_playwright/_pw/_impl/_path_utils.py": "2c0c34e8c14e04d350044e5ecca4d804b4c5f9191a94c450f58e6a3f9d8bcd1c",
"src/invisible_playwright/_pw/_impl/_playwright.py": "7f1771a504561f108c9e0faa9a44f4e4ab8cc13116bbf2686ea1a3b03ede7d52",
"src/invisible_playwright/_pw/_impl/_screencast.py": "3bbef5e66981e9216f27f83428207f61d33d2e371ce2121d195c9ed646d1001f",
"src/invisible_playwright/_pw/_impl/_selectors.py": "8f480ab03977b1d1d703a5519d195e3f3335e0e644cd559501167f39318db354",
"src/invisible_playwright/_pw/_impl/_set_input_files_helpers.py": "a8863bbe7d98520c8770f51b130c69c259ae629a829e1286588da6b16950377e",
"src/invisible_playwright/_pw/_impl/_str_utils.py": "0ff1b72ae6d0dfefc92939fca4cc0c2dcb7efe4fd8e520c72c630a6bd94b0fe3",
"src/invisible_playwright/_pw/_impl/_stream.py": "0f05ac6e14aa97ae37b68986bee03d656e3b1f92944b8aa42b9ad927df1803fa",
"src/invisible_playwright/_pw/_impl/_sync_base.py": "0bfe9eee479bad5295d7b281f20bb306ed652ef74a5053b14c320995a3187af5",
"src/invisible_playwright/_pw/_impl/_tracing.py": "d88db6cdfedaa54ee6435fb7dd5e89b2906ad409374ec0177d17a2bf344d694b",
"src/invisible_playwright/_pw/_impl/_transport.py": "bf158dc47d4bc0cab4a7719c50f628d308d4a54b29c03d19c5e10f2b66980fdf",
"src/invisible_playwright/_pw/_impl/_video.py": "f7002004b2c26d072bd108f9539b8e1b698f917be7b17cd30cc7eb3fb373d6d6",
"src/invisible_playwright/_pw/_impl/_waiter.py": "d8cda0d02e1e92674c4c0a3127229ff87ca4ef214c1682daf3b64ad4268240e0",
"src/invisible_playwright/_pw/_impl/_web_error.py": "238b060de72bdf92b54f771622e9e9739b64240d73e7d573c9125f68a28b64a8",
"src/invisible_playwright/_pw/_impl/_web_storage.py": "7f942aee8cc96bd82ea59b3d0839e8b20e4f44f066343e8640e3180fe001ab70",
"src/invisible_playwright/_pw/_impl/_writable_stream.py": "4a4936a37ee5c783f88d7f6c7bfda2850bcc18867a420581ca16c90e1248047e",
"src/invisible_playwright/_pw/_repo_version.py": "d53af84ac37b99e382129383cbd4ae8f2c78798801ced917b9c0b0e23b34f58e",
"src/invisible_playwright/_pw/async_api/__init__.py": "77bbd2c48813238c42211e1470f66bcf82ec31373f89fbe0670b8cba52aae7d6",
"src/invisible_playwright/_pw/async_api/_context_manager.py": "3bc5660a721ccc9cce317c8b4a15074b88dbbffeddf860b01ca187dbe16d8ad3",
"src/invisible_playwright/_pw/async_api/_generated.py": "b0a5713e9b560387b04bf6410c56b231ec90f0dd7e571f58d2af50013d977f18",
"src/invisible_playwright/_pw/py.typed": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"src/invisible_playwright/_pw/sync_api/__init__.py": "a99ad0ce7f8511de29e3661e9e2c8b2dd5e8c4a0cfe7731de4428367df00c15e",
"src/invisible_playwright/_pw/sync_api/_context_manager.py": "d6300f64c2961ae4d115fac87869b7837f4f17d697d8cf843fd58592530e5c5d",
"src/invisible_playwright/_pw/sync_api/_generated.py": "7881f3918cdeadd2909f82d36cfd993a54664638adf289cb9eb2e3dbd139f045",
"src/invisible_playwright/_reaper.py": "4e87bd00b81805fa3e242ae8c1162c32fa78da4dbc515a9de0647209fab7533c",
"src/invisible_playwright/_session.py": "b57c3ae743e016d10be65ba2b8359e6b0390f94aeb8100af60a8237fcf44d6dd",
"src/invisible_playwright/_version.py": "101d9ed902fb1a3a806f99f220eb10dd73ca656bd8b02f0c507ec338ef14890b",
"src/invisible_playwright/_webgl_personas.py": "bdb1c0d79297f9dc3177f8f530a655bd77b473a1838c4829dc48283e30c380a8",
"src/invisible_playwright/async_api.py": "070bf9f2e3c112353aac788cd04f8fdd70874165eeb505bf547123027b963923",
"src/invisible_playwright/cli.py": "bd742a8f8ce7961ab3f3ee100398f0247a1e0289563d60be56c33ccd17215f87",
"src/invisible_playwright/config.py": "5f48dfcd4cb757787af5c8ff37f2c7a6683ee3f2b4500182dd4c2dd0722a38f3",
"src/invisible_playwright/constants.py": "6be639754df221f5c41fdbe343ae35e9ea4c83297e98f6566250549f19d6c121",
"src/invisible_playwright/download.py": "416db5d579525d7f0802064d8a6929126c6b085dbe0f1c298f02a7a349f000d9",
"src/invisible_playwright/launcher.py": "924d1aeff016e25c8ce4d45d8994a72dab408b697d4ae7b9b74b3fa9e83161ca",
"src/invisible_playwright/prefs.py": "3fabf6f07d9f85cd5ea5bb901dfeedc2c3a41b8e199acd0dc25a11c473004298",
"src/invisible_playwright/py.typed": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"src/invisible_playwright/sync_api.py": "4c42eacfdd306f1b610a54bb54fcd1cbaef3c20dd525e584d3c587c4a846ea6b",
"tests/_canvas_text.py": "46dfb266b5c6f66698f6bc49cb7211e4e8ef81114da2efd9ae3b6d8c8b861c68",
"tests/_pointer_fakes.py": "a9bbb87d7f3df93749d728870ac886c177afb2f6274dd506ebca6bca1e4c32ca",
"tests/_processes.py": "681db6b733a52945492e004fc96cb4eec504346008d14ee2b94eae74ddae42fc",
"tests/_servers.py": "d3e2668c7e4c3d4a2c54304dda334381012e6327838381279fd3d9802e73dd7d",
"tests/conftest.py": "4cee73428e6126524c39cafca82001bc471aa1eec11ef0eab447649be4d11a6c",
"tests/data/canvas_icc_ref/gen_images.py": "b6624a1197289fb69c3383f3c960f1b27a1703c604c5db4415d9bd09fcb204bf",
"tests/data/canvas_icc_ref/index.html": "8927658dd8820b5d9fd11640a86c831ec043831649dc36e4df026b2d8f6228f5",
"tests/data/canvas_icc_ref/refs.json": "c3956caaa578890f24131882440ed94ad9334dc9c2315f94cb7625a388dfb8a7",
"tests/data/canvas_text_ref/index.html": "7da3e2c1349f1c2c7b3aaab9c5055007a571e0e4ab310b28d5691df4ea01ed5e",
"tests/data/canvas_text_ref/refs.json": "2fbe5d5bbe4b9b0ca74d59496395d14c02068ab80cee2f5b3311440a41ce794d",
"tests/data/canvas_text_ref_colors/index.html": "eb0b5bbf8712826bf1ef6e0f466105c31fc3087cae67daae567085d92ae47a0b",
"tests/data/canvas_text_ref_colors/refs.json": "b7da9d351433ee7c1432142eea9751b6ecf910ad76e7a4b7cfaeab17d4d301a6",
"tests/data/pointer_golden.json": "1c1da4b1a064d5266b602623c7297712803fb0615d6bcf9927a4a335721a7498",
"tests/data/pointer_golden_origin.py": "41e2bc0f0317d67d24f12155cadf5cb9a219b84b5fd9c5185083040cbb753c0f",
"tests/data/retail_159_system_theme.json": "2446b904294f6f4d342bd1b64942c345f4d45b8dbc58bfefdf41e45a75fc0f10",
"tests/data/ucrt_css_calc.txt": "9f5e011cb6676f577c0011ad568f20c4fc53e9bc8a2891a1163385d48fb81666",
"tests/data/ucrt_sin_cos_tan.txt": "0f4cf31fa9dad2aafec3554d5f47666b69c0c099b261fcff4b9a410b869ccdfa",
"tests/data/webcodecs_h264.annexb": "6d2bf6221fdf47cc2d0232c8631a74832ce0058098e314ebffdf0ca70347c101",
"tests/data/webcodecs_h264_1080p_bframes.annexb": "04da8f4dcbb8bc0f72749c0170d0684591aa10b9f8d04486a199dff84e0d51be",
"tests/data/webcodecs_h264_1080p_bframes_rgba_sha256.json": "746640ce00911252e3aef486b9981412a2d2b652728220025f1a7fe538a8a8ca",
"tests/engine_process_tree.py": "e949fb5898c9d14cfb76c49507004168585af463a12722296ca6876c7815408a",
"tests/engine_refusal.py": "6ccefd8c51d767a289d908e6aa70b2a194de82ec50f9286440763e5fa77f63cc",
"tests/gates/driver_prefs_rules.json": "7ce0d510b022ab68833f6310e5188868a16fbc04163fe3beacfe087469b9560a",
"tests/gates/prefs_byte_parity.py": "800033a84ac4f4e8877b8043b231473dbfb0cc7e4853fab70e73c9cf7138d936",
"tests/gates/upstream_baseline.json": "d87ea58e2ea92b24b8d5d6f3451f1fc0055825c53e315555d522aed7fa6d273a",
"tests/stroke_shape.py": "f4bb1315338dc4d1b402e2feff1b40ee8cb46358c2d66934c7456a183c5384e3",
"tests/test_a_162_message_is_read_like_a_161_one.py": "793ffb99c62be438f17308e99541f1053378b5aebd4f936d8ae3c48445e1efec",
"tests/test_a_click_makes_one_mousemove_at_its_point.py": "16685cfe4a40fc00d94168c8640478f48ec1943310c280a55a55e0f9459775c9",
"tests/test_a_click_waits_for_the_navigation_it_plans_e2e.py": "45abc557df34897fcd5aeb7bf5c8e74b64197bd09f52a8dcedccabce83968f0c",
"tests/test_a_closed_browser_leaves_the_others_alone_e2e.py": "f8454227ff36dc9413eab6cbe7203f4df15c83df6a8c372fcb6274a5085bf0f3",
"tests/test_a_closed_context_leaves_nothing_in_the_registry.py": "2ce0a2745c8caf8d42a642be8ffcd9e6f01c01247529cbf2efade49c28df1709",
"tests/test_a_closed_page_says_nothing.py": "c8b62cd1f682787830165fb1829f9a17f00a78e974f3a996df7799bb41635792",
"tests/test_a_closed_pipe_is_a_closed_target.py": "55e821fb6b1ffc0479f2c627e96e56484c51d3f4a7af39f735922149137e8885",
"tests/test_a_context_route_disables_the_cache.py": "01c5404c6c4014725ef72412a6662e331ad703cc50607bcdd00b53b702ba2032",
"tests/test_a_context_that_ends_leaves_no_process_e2e.py": "d0ae332cff5631553987f327d9a71e11a5c52bc7364bfb6debf7d803343ff3ec",
"tests/test_a_declared_webgl_extension_survives_its_use_e2e.py": "955e14cf9ab2a0d4774dc77db317d0766be7dc92a32eeaa5b411130ab66ac478",
"tests/test_a_detached_frame_answers_detached.py": "88d8bdd1be494591d8b820ef75b83467eb03db6468bd749b41177b21d6ae572b",
"tests/test_a_dialog_is_a_protocol_object.py": "23b67e1e0b26053407a0c37c8e08aff526c8e83bf62a667e12783b325c7ff4fd",
"tests/test_a_dialog_is_answered_after_a_pause.py": "a9a50b2ec40b3a87a0088f82e1d71a1432c2fc4c84e3cd0029ee83fd640893bc",
"tests/test_a_failed_expect_carries_its_call_log.py": "00c085fc57f814958c3ef49827a2c2bb3a8de7e8c72a551dac191b3073adb9f9",
"tests/test_a_failed_launch_stops_the_display.py": "57cd81e51ba52479311a0f848fa1476336d99e6f0464b07171c6b54809daf33c",
"tests/test_a_field_is_typed_after_a_pause.py": "0551e48eef2085c664c57cd45753518cf9f3fef28fc65ee48b551189c34b3aeb",
"tests/test_a_granted_permission_is_the_one_the_page_asks_for_e2e.py": "4064e99f54ef25dba062e9dbc987f2ac3cab5a22d16c2a579d778af702a84e7d",
"tests/test_a_latin_letter_on_a_cyrillic_persona_e2e.py": "ef8e2f386d6dd55a191118811708944c7a61364d5c97ba0f31083c4338aaf4c5",
"tests/test_a_launch_has_one_deadline.py": "5673d2eceefe6ae757a676e7451568d3c62cdcdb0ee8e80ed152d7a20d3b99de",
"tests/test_a_launch_without_a_session_gets_one.py": "fb0d7da5b692fbd31cf99904e2aab59d8a4a7d79b360257756055f5d2c738a35",
"tests/test_a_launch_without_a_session_gets_one_e2e.py": "3c2769632234d066b4265083457b8622d4a1773684869936b573362101619563",
"tests/test_a_left_documents_body_is_evicted_e2e.py": "b687d3ec5be57f6598d751a8a08f8d968f30908b437df52ff2bd10ef1ba11ac2",
"tests/test_a_missing_system_theme_pref_refuses_the_launch_e2e.py": "14779b0e5c9163046cb9517c089a175e9540ceebd898970f6e9a95e54515680d",
"tests/test_a_mouse_click_makes_one_mousemove_on_its_point_e2e.py": "0ec5339f580d33c5cdc80e1c2b586378895c96c4babd7cbe0435a7e47b930bc2",
"tests/test_a_new_page_waits_for_the_engine.py": "0bd98c3c635b11a094beb5140292ea43c03acff2f12f5b9b3a64667f75d515b6",
"tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py": "cbb23cb5b6df948bb93f60375df27dbffc274e5c4f227502498f66edb32c2a40",
"tests/test_a_page_cannot_probe_the_juggler_e2e.py": "2af4046d7c737e87b2435f334055eb92ed1de817e6b9a8946506814e96376745",
"tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py": "37427be29b72f8e121567d8006877e514eb98621417458544f0493a8f917bca5",
"tests/test_a_page_that_moves_on_e2e.py": "2b9f5fc96675ffc4cafc13d95a131a02e3d5c724a15e10303f3b751ef954b23f",
"tests/test_a_pointer_event_is_handled_before_the_call_returns_e2e.py": "140fc72d3573a73ee9aba40a26b760e45f1a96070efad3cf23fbb300549d492f",
"tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py": "7ada9fc12b6bb64390ce60c0220ddd870fbfb02e5e70d160c38126ddc784dc84",
"tests/test_a_popup_of_a_link_reaches_the_client_e2e.py": "f8170d43749df340ef5447343fbb89a35684df726d6c909d60708a60ca47dc4a",
"tests/test_a_request_and_a_response_are_light.py": "0a0c731037f9b1fbd8868721550f49a113da5e1cfc2f71fff5e75d5e474fe5a1",
"tests/test_a_request_says_what_it_is.py": "9260aaf34c8368168b27a7ff83d2aec03a4b1b3756c0715f948dfbdf909dcb2f",
"tests/test_a_request_says_what_it_is_e2e.py": "914b3da82c1d1427b4b0edd8dd2c8e4b251d35cfa046537987aee3a275e83465",
"tests/test_a_served_browser_answers_a_plain_client_e2e.py": "fcf7d83b12611a7cbeecec9017927b28470b3ac345fcef814603600e0150aa9d",
"tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py": "5e7c7028beaefeb73a9419656d8b9074d438383e05baa7fadc77b00615ff78f9",
"tests/test_a_worker_comes_back_with_its_page_from_the_cache_e2e.py": "2fc5f62d01985dfc8b8f4bab34567f840c592dc2f4ae03404e84f844841890a1",
"tests/test_accept_language_on_the_wire_e2e.py": "3ec7d9da9207a5dc543b898d6bb2bd6c7a5a98d38959a3465447b214873c0c60",
"tests/test_actions_without_a_point.py": "dfd5bff76af799b4d705cec2177c16bd2faf521ccf7ff52b8057a9df4bfc0fa1",
"tests/test_add_script_tag.py": "660393717fd30819a9e673827ebd284e642c95dfe78b4621d84f8aa26f7c7d51",
"tests/test_an_expect_reads_its_value_once.py": "d23d6005eb6bf20307b010afce91b8b6f2128d3743dc76b264ef47ed5a3c3d43",
"tests/test_an_isolated_page_and_the_next_e2e.py": "0f5752c07037602abc91c2f5d43894cf451d9521d0b57e0d0b024954b327cfd1",
"tests/test_async_api.py": "bc23db7f37b4f3616c95ac531e10b5e269dae3dae4badfbc8ab64b1260d11fb9",
"tests/test_backcompat.py": "d283cb213019a76953e65dd451c9f9dfaafb7625ddc38b68d806be49ba8545b1",
"tests/test_browser_output_is_drained.py": "f450c8f6df7c74f5f96bbced7dcaf8b10a02df8500018897bfad36cffb26d4d2",
"tests/test_build.py": "30fff1ce6fd17c1d81874fc6db7253a745a403d30e536cf6ed7186533584e13a",
"tests/test_bypass_csp_e2e.py": "8cfae28f4acdd2d6e7bed95a8117bbac00064cb9d3cee2c39ebf9b7d16099078",
"tests/test_caller_world_handles_e2e.py": "815c1c6b472c0554f9d5c6a6977f62e53bf76218d82972b92834535eeec0e291",
"tests/test_canvas_icc_readback_is_windows_e2e.py": "33581d7bd96049ee091ca0e0cc96d7299bce6cdbbc1d2fc26b25a62a4dd82875",
"tests/test_canvas_reads_as_drawn.py": "95444935965f00f7db3668e1b61ceb2be74a864b16b6288283c877e7fc68c0bf",
"tests/test_canvas_render_stealth.py": "fb43cfd2cf77c91fdb836d1b9cce874c16486df9ceae0ba89e999fdd8ad2c14e",
"tests/test_canvas_text_colors_and_cleartype_is_windows_e2e.py": "952cb93909e346d5ef1022786c9bdd41bb680604b0aeea55b931efab5de2fb48",
"tests/test_canvas_text_is_windows_e2e.py": "a9bff36ad9106c811a61622591869de3c9402909d7fe163d28dda4d6dace2940",
"tests/test_ci_downloads_are_authenticated.py": "04bef9dcb53092d2bff696c8ebc77dd9238e66ae80b204b707944fe82da547fb",
"tests/test_ci_drive_gate_first_run.py": "e12fe2f0142c61647782c25bc0ff299ab36d731f2c53a78d71cf9b4d76319819",
"tests/test_ci_host_gate.py": "328cf30c2dcd45fa7ef8349981952d530c9d448883a370a4f4e8611b54e24adf",
"tests/test_cli.py": "5c9ab4707b35d99deeb0b3af8735ad8ab38bd79588729b251e32684c210fb9eb",
"tests/test_click_rhythm.py": "ad3850f11e5ed2a66c2b65caee3f48931cff406c30b8ab1a24b59617a298fa95",
"tests/test_context_locale_e2e.py": "f53d5227bf3feed7577c2b5c9303d0e602c38af704cfbcd4d3784197d6420719",
"tests/test_context_locale_is_a_list.py": "c238bbb6b9cd1b684c781237294d148540af6c83b930312cb9fd90bc0ab901e9",
"tests/test_core_pin.py": "85c4baf6afef4f3df928547d82e651c8bc8f5262717adc82a8bcce341d00bc46",
"tests/test_cross_origin_iframe.py": "b0a5143df52090a66dc78dd62a572a8aad101feb86b47a7d422ed5f3e4949096",
"tests/test_css_calc_is_windows_e2e.py": "066bf710bbd4513bac29d07c59633a95adf5f641151b70fe0576a417df0f447f",
"tests/test_cursor_dispatch.py": "9d55a333f175c38d0005d183c72eddaa68d64ca5e2689f69af732b06700b2b7f",
"tests/test_cursor_wiring.py": "d9d918cf3d22139ebfea9a4f654e4cf7f60f6023ee07760af9f32846b8bda66d",
"tests/test_detectors_e2e.py": "476fa9fd40bfb3d1e544a950efa7251f70a5eb650598ffc7912015d438cbf6e4",
"tests/test_docs_name_the_mcp_repo_as_it_is.py": "f0598a3c43928ae4be9560ce8c960c38a486c1d4ba628e9ff2bfdf44d5c19835",
"tests/test_download_is_intercepted_e2e.py": "f31c8aceb14f8f9aaf194bb3a81ea77b305fa712361befc090d643cd66522f63",
"tests/test_drag_motion.py": "8c7e2c00f35c3f6018d5c621f52677af53331fbae89bf18be1f0b84c0e38ece8",
"tests/test_e2e.py": "60fe4aad2e8fb6b146f09c590eb18037bcd8dfd009e2c29cacb217c882b001d6",
"tests/test_e2e_hermetic.py": "6ff72fb72345fc1f766edc63f741818c708a805b1041d18cc1bf7bddfce3dc91",
"tests/test_element_handle_actions.py": "a32fcaed7ebbed8a0e67477460c847084a05cca8bfd7e93072f8c5be371068b3",
"tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py": "3a7e3cd3ffeb285843d1e457a52199c9490851a5756ad307f2a5b076a91c5f1d",
"tests/test_every_page_draws_its_own_acts.py": "9d5ac998f45c71a037234b437173180d9da9a38d5ebbd4bc14d3105c3e73a25b",
"tests/test_every_refusal_is_declared.py": "07d0669781c9576a76c1090731f6906708e72bdf65371384c5ade362d574694a",
"tests/test_every_route_command_is_answered_may_fail.py": "15359fc307e1dfdfb73e74bd1965b72a7d7de53dc9b07b7f5e10d0bc6ea820e2",
"tests/test_file_chooser.py": "a5d759ebd1dce310ba25f7b1d76de26dd34f7df0ec7ac98414aad886e6637a31",
"tests/test_fingerprint_consistency.py": "aaf372f742cc251e38635eb89be662436616a75aacd17602328cc933397ca0e8",
"tests/test_fingerprint_surface.py": "20d2d936f925610a448a74d8b47cf6ecded48532e99ae9ad6d490bc016fab816",
"tests/test_first_launch_from_a_new_path.py": "e3d61cc2a8fc893a34058cf05204f9bfd8cbc93fa7544733b5aa5cafd044a45d",
"tests/test_fission_identity_parity_e2e.py": "3e78b149e6f8c366a7ac6442bfbeddde2f0190c906315055e2702df350abbbe4",
"tests/test_fission_iframe_crash_e2e.py": "faa39a6c7b2437534b9fb0a3f5cd17c8afa4f15a93283be327dea2f7235760d5",
"tests/test_fission_strategy1_bench.py": "2b8086622668c46dea68b718f3d56d28a5cd8efe3c95d384d903e050edd9322e",
"tests/test_fixtures_name_why_the_package_is_missing.py": "acaa7120c5d8d411c14b3c533fe424f10c4cf4c3af481f4966d64f1dcf97a221",
"tests/test_fontconfig_reads_nothing_of_the_host_linux_e2e.py": "16a19b971195da28d83ddad9eab66559ded67e7d41b0288d2015e9442918b6e6",
"tests/test_fork.py": "61ec15a3a4d98d68a16a09f2654cb8383a842b8432c5a24c2d1eb4f26dc7e573",
"tests/test_frame_dispatch.py": "022d39016b9090770c47bee09aa6622f4780d2c2a2b5f1d6ac812fdc3c308bf2",
"tests/test_frames_outlive_the_back_forward_cache_e2e.py": "75409e7e4b7d4259db5ece525042f6507884e05e1d2306ed7e33e39d8c904e7b",
"tests/test_goto_and_every_way_it_is_stopped_e2e.py": "9e0f04f8cc9e4860405348c5ae7ebe8f9478aaf9753db62b6b0f2c9971b53e60",
"tests/test_goto_follows_the_base_url.py": "bd4867905bbf341333d6d84927452276a0c5595e96f4ce192251796fb13677a0",
"tests/test_goto_networkidle_after_spa_e2e.py": "cb925e058d74d9f2fe660fdb39a29ddcc6bf6fd3cd3c32a7c774b85ba0435ec5",
"tests/test_goto_script_redirect_e2e.py": "285b39f4b2a90e306496a4a4b88d4a5cbd741c5399a3464e85853f24aa138596",
"tests/test_goto_to_the_same_url_e2e.py": "c92e12718ce10d27cbe7ac31ed91ceca74055f55520c3925823690e52ac645fd",
"tests/test_hidden_desktop.py": "47a969028a6c914c30afc67635684df6864e90815535d64bad1b9175d67900b6",
"tests/test_hidden_display_linux.py": "101be6358fd7dcc2fea46fe992c2d12cf08b0ec99513ef76a0cfdad0c89314e6",
"tests/test_hook_wiring.py": "b06a8d0c747c695987086128cc4946e6baf2afbdd953f340cb1d0270c8bd88cd",
"tests/test_ignore_https_errors_e2e.py": "3a2371e70076ab1ae8a7f0ad5785a641870637138579e8cf82118adb4e5b3904",
"tests/test_imports.py": "75a5c1f77d26fe675e4ef3f75df3aa6b2fbce516d32cd9f5764ea5370b3f6d7c",
"tests/test_injected_node_surface.py": "679ffa5115456351c7d9fade457ddc30a66e9d238e5cefe38b8ad152d69702ae",
"tests/test_input_is_born_before_the_page_sees_it_e2e.py": "899a83fedaac86d972f0bacf620695b84eab85b0a2937a431d48a22e09ce6350",
"tests/test_integration.py": "fc0de15d7d5109214d2716f3d7cc8900affe4da7312444a47c940a2a807a02d5",
"tests/test_juggler_actions.py": "c3671df1b561fc0c6b6dc99ee38f7635044d2ffd243b309a03895d7796aad011",
"tests/test_juggler_connection.py": "aa2bb990598281dcf1da2a7b3e220b023bd1dac644d76e4231c7fcb402dad571",
"tests/test_juggler_event_buffer.py": "f34862efe358c800bd556be4f7b71a13962ec5151155898ba009323c47848a9f",
"tests/test_juggler_event_listeners.py": "b0c46de6baa2312c2cb6818f8b34f95a071b3a3125551b1c5b203a3e8b46b888",
"tests/test_juggler_injected.py": "704d9bc1d94adb8e352af07b4b7b1d859234f4fcd128b3fc85c115fd11ace7ed",
"tests/test_juggler_lifecycle_e2e.py": "194c0417fa62be04845bc665493d98357d65cff2616ca8d580813c5ce6723c7c",
"tests/test_juggler_lives_in_the_core.py": "e14acc31eb3c31499f4270b5eb5e06ffbd89bd97892b4b5e796fd80b4d5e1885",
"tests/test_juggler_posix_pipe.py": "e26156bc3ee89d9c8213ce88ea45402a4c084b78212e735cea0a818885d423ed",
"tests/test_juggler_transport.py": "94926063b6dd031e2fb3853f84ddca82b0a23ddf4ba86881b3e140996d01744a",
"tests/test_key_delay_reaches_the_keyboard.py": "64c6d61fb89af183c3656fc7a0e3dc98110490e156c1372ed9c86fe72f45306f",
"tests/test_keyboard_rhythm.py": "d72fc1ad7e485d2baf2202b2c6efc6710e0966e61d851420915b7e93436a75b5",
"tests/test_launch_counters_run_on_github.py": "c7f322c5797d9af0dcd7ac83ebd538f238b9b2f518334b47e5050f24df566948",
"tests/test_launcher_config.py": "7328fe5a194fa051ea9aefac542722535a2986b9ffc118fc9f1bd44b9c618c91",
"tests/test_launcher_helpers.py": "42cabbdee3900603c657239a47ebfc475915130a3d98b8b4ba1f00f6791124a0",
"tests/test_long_session_e2e.py": "96cd8fd6bb5ec76d56574d9bfb1bea0a3803dde55f7ed261f91ff6922f5e064a",
"tests/test_math_sin_cos_tan_are_windows_e2e.py": "5fe114d1ca5a71a8eeedc1af0ffdf2fcdd58590c0ab9a8be42b95b4343fa9145",
"tests/test_mouse.py": "3e9a9e98210a07d3f84a01ff3680f80725d5854f306817b71c95af8380cc77a6",
"tests/test_mouse_events_keep_their_values_e2e.py": "4dd384e06e48209ea0da70d52cff077f614f8ecf0a307e1a1dbdbf59d21e96c5",
"tests/test_navigation_across_processes_e2e.py": "7fb8ee5fa2e8575bcdd8a8f3775ee04e36bfb6afb6a5da093448be2ecd027e71",
"tests/test_navigation_response.py": "acbc9a69ee5264602da1f9d05bf3f9a3759e7d848ac987deba278627db3a9e52",
"tests/test_nested_frame_actions.py": "ba8a9a15c21ffdd8e23f24f76c1749e08a52e1f14a0efc23c1833a42bfd28c7b",
"tests/test_networkidle_reaches_the_client_e2e.py": "bdbaa90dfde6c5f3dcb6e6f87b84adf88d0a4ac55ec7f4aae76251586d3c2f18",
"tests/test_networkidle_through_a_served_browser_with_routes_e2e.py": "8e52257cc7baa1c2235a7be45341fc2c8d9a48622f0107c814d60e0a2b5e4702",
"tests/test_new_page_defaults.py": "e74367f3e008e5345c8391070bce0ac857395a47b2aa69ca69d6376926d3c4ce",
"tests/test_no_override_leaves_the_persona_scheme.py": "322673c457f34c71b68007b885008e11fc97eae4a5aa0c20449e51aba71e51d4",
"tests/test_oop_frame_element.py": "dbb8ada9914f0a275eadef034dad6d2b47f3fa72ceba51b8cedbd7fea808650e",
"tests/test_oop_frame_geometry.py": "983ffa905815068dae15b72bc846e0e6280f6663412ab03272fea4b800476a35",
"tests/test_page_number_follows_the_call.py": "1a133413ac5b3e179504ccef4f71fc3e7cd595f0d40cbcbb253a763e8d49d8ba",
"tests/test_persistent_profile_keeps_state.py": "c6d11fde906d4a0d8c94c124c7b7fdb436420efc7460a51a4cfbc31ceb911059",
"tests/test_pin.py": "e297f630a7c281d951c536cd7e683ce9daaefed78afafbeb6c9f91410f6a7a85",
"tests/test_pin_dicts_are_valid.py": "a6bbc441942cd5772a1a0d3a0b3b69540c2ae1b9f955fcd70b052e47cb68a0eb",
"tests/test_pinning_doc.py": "50a620a3b9fd9077eeda7806bf891f8a138aa5f9ba3dba7fd5f9d12b1b4fbd48",
"tests/test_pointer_position.py": "c2132d7ea8b1b8f628d262d2df2246d70d213723adc5a1f8ab5be91482041d1a",
"tests/test_pointer_server.py": "465bea4cc589cd7fbe2ab3bbe9e743c12605eb8c70fe9e71a4d3e7cfd78d33bf",
"tests/test_popup_adoption_unit.py": "ee9c2b940346cc0ab71151bdbb0b0ab988983df961847d3c548996c7e03ce4ab",
"tests/test_popup_destinations_e2e.py": "be48dd93315a5e61a57a564ec5c30968dd6415baa80334595c89e27cadd37043",
"tests/test_popup_pages.py": "77565b4e39dc9fdcd61a85aa6be8b693aede93abde93a6fbab49bd0a3d9a87e2",
"tests/test_popups_reach_the_client_e2e.py": "9943d34049afd5b7eb74c01594efad50c1d611561bad19625c8fbf06ed0ab576",
"tests/test_prefs_composition_arm.py": "46b1cbe17704554c32069ef5d4ddf0c47a1b9a0890ead4d35db63303ee6ae2f2",
"tests/test_protocol_names_are_declared.py": "d9fb8913d290c8a61bf461a2198a3e6fbe2c1a81f6a6f6384280595c97ee290e",
"tests/test_proxy_http_auth_e2e.py": "884f978221e7f968c43b2bf7261da93aac37049572aa563a27af153722701b0a",
"tests/test_proxy_reaches_the_browser.py": "0207492fa0deced67f973f6895ae490e09fc9c6e0ba81bb6213047de65cd9b37",
"tests/test_proxy_socks_auth_e2e.py": "c3445d5fb0ad1cf0bfac31b768d29ee4698a51f3b816e6c7019f6b14ec2c01c0",
"tests/test_publish_gate_wiring.py": "fa53659cf27c6a29bd3a8922c922942ece0cc782e9a8aa717b5cc781da976613",
"tests/test_pyproject_names_real_paths.py": "a142fd2737ac94e3f965ad7d9bb40297fb3a9016379baf1b756a62b72be92bf1",
"tests/test_readme_claims.py": "0407f77f5c08c66a55a0f8fcac0857881c55c04cea8163ae1482018df5aa9e11",
"tests/test_reaper.py": "000e4639d86868f05a7f6be4abc38d2eb59d74045a73aceb5c0aca2a6d29dd93",
"tests/test_release_e2e.py": "50a465bf5899b5a235f6bda52c22e9417f463579e5d997f2eeec5d5f93281478",
"tests/test_release_notes_install.py": "e0a6024ef78995e9650bccf0bcc7a72727b6bb6fb32f21f38b467c105f37e5fa",
"tests/test_request_gc_uses_the_page_session.py": "1a574bf6aa857a139548142211b05b34705fa15fa08fe0abe6e4be7a194ac3aa",
"tests/test_requestless_navigation.py": "7768a47cb3e0ef51a2112dc19f7ba3e980e681e10150cef9258476b67f6fbd7b",
"tests/test_route_abort_code.py": "6ec26ec73dce79161a7b2446955ef4c6d1697d1431a8402c3027fe1c5ef28209",
"tests/test_route_e2e.py": "2662f2a0bd11b7e18e1bd09abca905316afbdec04d1ef8734c7cbfbd57602cd3",
"tests/test_route_header_order_e2e.py": "a5e58720c0dddd3a1090b565064170b1213bdc9061484e5eb9193a94fba8e1ea",
"tests/test_route_post_data_e2e.py": "e7daf770547f860b88ad4364d425d8ab9de251c9e730789c6a6bbec915d18fb5",
"tests/test_route_sends_a_navigation_elsewhere_e2e.py": "278fb9fa637586066c7352bafbab7c0ab0a6482e387e9fac2ee5a24053d1f8af",
"tests/test_route_superseded_e2e.py": "733e6f8f478fd9d9fa8a045ed42625eb600881fc68d3d9ba16eaa4d234ce96b8",
"tests/test_same_document_goto_e2e.py": "5b9d613098a7d1e78e475bdc95da03ee0d89f2835aca2adb31944bc302238d9f",
"tests/test_same_document_navigation.py": "642e1e50e45e566ef35b3fbde191b9b561fca06b25505c09f0f5e9fe3172d0e6",
"tests/test_screencast.py": "e15bfa667b758ea66f8e0e208060aad3111441af451f7ba6ff2d29355de938a9",
"tests/test_screencast_stop_e2e.py": "a6b96377db6bc6476de8b1b0c598c6d312a77fef27d2f9706fddd736cd9d1592",
"tests/test_screenshot_looks_where_you_are.py": "1ba51fad0e1f44e9a52a2fa479f970a213762b275802f98c2f6a714e47f7aaa0",
"tests/test_screenshot_of_text_returns_linux_e2e.py": "dd910029cc5c70c2c85d64576fa12fe4767070ef0c0f03189ec398f131901e93",
"tests/test_scroll_into_view.py": "d5c91487c90f2252470986f7efc8fc7bd01b85fb40b45fddc597dc191fa75b09",
"tests/test_scroll_only_if_needed_e2e.py": "b78ed5fcb9a596d63c68ceecb77ecdf92e744a6a64b16dc7b17b88dde9929125",
"tests/test_seal_binary_path.py": "364e418085eee9568e7fd0381a579296c151495932c1101f3b41c8c728188656",
"tests/test_seal_floor.py": "8271836753ac6351ee8746b93b1f3e3f222c13c19800e46ffd8cc40d08384acf",
"tests/test_seal_playwright_range.py": "34f818aa423ca30c24534ae27e1dcfaa34e7167a840ccf92e614cf3632735ff5",
"tests/test_seal_wire_version.py": "ce208cb450ba067a07e0eb7eceb3c0677a6037b499b5e8abde67c438a1c62fb2",
"tests/test_service_worker.py": "994c7d80a60dd60d8fa2f0d3b48e851e80e7ad1bed2ca3c9aeb30edc5470de09",
"tests/test_service_worker_controller_e2e.py": "0255a83cb1a507203def00e673250fbd9e61ad4bbadf6f77a2112ba734c7d94f",
"tests/test_service_worker_options.py": "c7c18e2d67ae7983ba2c113e88001e982c70c5297eae5ea2fde24e8085a53496",
"tests/test_service_workers_blocked.py": "e1b3abbcad571d821e26e60a0bf316ec212b22547b5874a7e0d2a9e4529d407c",
"tests/test_session_transport.py": "60c413770e0ea78bd01bae528818c0cb51dcf262ca9712a4a0bf87aac3620675",
"tests/test_set_input_files_payloads.py": "2653c2e20f6bf7bc86c9575c4a05ac402581753bd771a02da212e420bdf51dcb",
"tests/test_set_offline_e2e.py": "d2c1dd8d673be53a4042a20263737163a4a26b9ed1d551203fa7f19d966eae69",
"tests/test_shadow_trusted_input.py": "97a46078aef6b23f9496c41b023dd7af1e034091be705aaa805b42804c13e1df",
"tests/test_strict_and_force.py": "a3586ad41f4260a0f016a93838cda2e45b6eb4b2b488c3a0af95ab429eaa4d68",
"tests/test_suite_boundaries.py": "9e554a4fe13c1475bd879b342e6f92780819614faf02dc884e4cc04bb734bae6",
"tests/test_system_fonts_and_colors_are_windows_e2e.py": "a181f29f9fdf6b650e3ed37016b0dc8f791245404c6af5e3cebd67b9c68e74d6",
"tests/test_the_argument_does_not_rewrite_the_expression.py": "bfd094b08582355c60d6e2d8df8b2cf39a5f3134f7dc492d06f1fed8b24b9c69",
"tests/test_the_callers_code_is_not_counted_e2e.py": "94649ee17fa7fab96cf88c98a4d5f8829077009daf95b0fc9fbc1ec140109375",
"tests/test_the_callers_code_runs_once.py": "5a3d86180bd11ab1e9433905c2f99485269c7dfe6cf3c75a5530cf7d94384a01",
"tests/test_the_callers_code_runs_once_e2e.py": "8e5c57cd2eb1c619657caeee567cdf86d52cf755c86496b7d0f69631bbf299ef",
"tests/test_the_changelog_covers_this_version.py": "3cfd227ac69901ab7cfe5a3286d5c3dbfdc1322b15279521253b1b733c159af3",
"tests/test_the_device_enumeration_takes_the_declared_time_e2e.py": "41703d9174483ef2d36885ed41ea20b06a7122f842f9f1e2ab4abf024c724965",
"tests/test_the_e2e_run_stops_at_the_first_engine_refusal.py": "0f29e035ee261be18d2d7d2250c6da072e7a35ea024525be4eeb6716d0dd0772",
"tests/test_the_engine_processes_of_a_test_come_from_its_tree.py": "32f45d4e7af16761dec0257fae360f9fa241fc5f37b3ff8d9453318c6f40c693",
"tests/test_the_favicon_stays_out_of_sight_e2e.py": "f43b3228799188db000834c28e43e2abe25ebdc7cef1caf3463beb22b1e6ea0a",
"tests/test_the_floor_says_the_installer_of_this_environment.py": "baa238883691235250b426537e95e9da6bd68749073bd980b392bd050d83536a",
"tests/test_the_keyboard_follows_the_session_language.py": "a745ec07a7020f4df8a6f1d3101b3efaccd9937a7f7abb573b6d349e2af86f95",
"tests/test_the_names_of_a_permission_are_the_engines.py": "e59caecfc07bbbd7fa574e098e730dfa28baacca7d5a0180709cd9d6bb72b9da",
"tests/test_the_registry_collects_the_oldest_like_playwright.py": "f4c549ee9c39dfc44471b5e846434d18d9d1ae401a24280a775e31058c50cc70",
"tests/test_the_remote_server_memory_probe_and_trim.py": "7ca2ba422495a82b74533bef96490f53cd1368fd61675e1273e8a478ffd8f4b3",
"tests/test_the_remote_server_serves_the_protocol.py": "4409637dd017ab92bc5d46384e2ec616b88d756f5ffbd5bf9f612453d5d3cefb",
"tests/test_the_scheme_is_the_personas_e2e.py": "5c9e2cfeb388b6794049fdb7ed42f36563e2455e92891b5b0207734dea27a92d",
"tests/test_the_server_is_exported_and_the_readme_shows_it.py": "fb666592d1574036c6a3d1536f43605a906eddeb094537064de6b46dcb780df5",
"tests/test_the_version_describes_the_code.py": "6db64fe0b6d59c073f5b64ffb0c175260f7552bdb89f61abd70ca6c7b46a9fa5",
"tests/test_the_wire_is_json.py": "8641bd15ea0c71d0fb2be6cbdb1bd088dcd70ad7d47b7278fa88630825f08b31",
"tests/test_timeout_zero_is_no_limit.py": "f4b7dc56a2b5840fc6daf0ea1dea22a8d9798d20febf8261a46a5b6e70d1ebaf",
"tests/test_trial_does_not_act.py": "5b836b82b7cf3e6f41814d9c6505cba637da2f1740f140eb64a24997826d429a",
"tests/test_typing_a_character_without_a_key_e2e.py": "2018dec5589d58ce1cbb320bd2fc2e7372d5bebf092fa24ef6e8c782b3f4f4f4",
"tests/test_ua_widget_not_selectable.py": "564e389fe06bdcbeedebb27352b2b705d60428463120619f96b6b59ce322d794",
"tests/test_upgrade_e2e.py": "30a86f4a809a8b0ddb3b7b512f6de06b45e5fb8498e64454166b7c0d63d83ca1",
"tests/test_version.py": "b22609f731743835f3f681ed3227aa2e5d8462a166dfd9934440b744344914a6",
"tests/test_version_is_not_taken.py": "254661fd419fc5df2957c01238e333e9be32391ff719b9a11292a864f232d8be",
"tests/test_voices_e2e.py": "87fd3347584b42f4ebaa33343d1ac57aa9965484005d025aa6173cf2e58d7c61",
"tests/test_wait_for_function.py": "c819e5dff8c0b2d60d503b61027dfac4c602ea9f429eaad9b8f46cd8feebcceb",
"tests/test_wait_for_timeout.py": "9f1ee4b14e315532f4e0e2c113d537ef943ca0a11587b347ccde4f4a33fa9373",
"tests/test_web_fonts_of_closed_contexts_e2e.py": "6f0733b723e6a68d11804fe6ad2de7e18bdc97c19ebbbb17c3ee3bcc90b4c531",
"tests/test_webcodecs_h264_bframe_pts_order_e2e.py": "cf1bba6a6a2f9cb992ac19469f16f01cc595513a08e6b08d967b2e47b009839e",
"tests/test_webcodecs_h264_software_decode_ignores_hardware_request_e2e.py": "895244928d162640e902c2166b348bb5ca3816a415842373ca70617c3da3ae9f",
"tests/test_webcodecs_h264_without_host_libavcodec_linux_e2e.py": "3b2295ee1ab9fd5761cb7bf4c64cba2e23eed20b0c8a1419d3bb54b0e5313072",
"tests/test_webgl2_exists_without_host_mesa_linux_e2e.py": "4808bc74cc6e058161fe0251ae54e927f699df4301d141fb98c18dafab1858ef",
"tests/test_webgl_blending_rounds_once_e2e.py": "e9ea08f6c632902787ec2fc4cf591bbcc7b5eb71e85ee81e752b1483fde6646b",
"tests/test_webgl_dot_has_the_declared_gpu_s_bits_e2e.py": "e5d1240a4a6414102c7e521c1dfc1e2d3938f7348ffdcd735a7f94a03ba1c65f",
"tests/test_webgl_draws_on_the_engine_s_own_gl_e2e.py": "9b8c284e2f49d0a83ee2d76fe95ab0773a075d9cb8f0fb4ca80ba6da9027adf2",
"tests/test_webgl_mediump_is_full_precision_e2e.py": "a8c4c8a07c55c672cb3519fb44a3b1de316c5aa757829d6fb82a01cbbff42668",
"tests/test_webgl_noise_active.py": "1a820cb9dd67e9fa4c909beab8ce2eeefb0da3eb81b178275dac017afdcb83e6",
"tests/test_webrtc_realness.py": "dff600d40e38970c8bd956a9ee582f7f2ed165dfcd837225327c8744d0a10bbe",
"tests/unit/test_canvas_icc_refs.py": "1ce5972836116263ddf12057e07f131a01f9b324582137a857738c792ae8e025",
"tests/unit/test_canvas_text_colors_refs.py": "42c32ec2f231e28d91f58cef9a7fdbd229e1bf40767b2e00cfa62e56cbaec2ed",
"tests/unit/test_canvas_text_refs.py": "f7b792d6bfda02ec0f3c0c880a99cc693f8413b1a135912f545134417d56a554",
"tests/unit/test_compare_canvas_text_runs.py": "908d9f26343d90af081eb18957d2b16a158415d0340c9dfcb48b8c2d45f129b0",
"tests/unit/test_config_public.py": "83e065e991a542c7937df190c9467ac4fc177e50e15a3a75d06701f4aa1f1254",
"tests/unit/test_engine_at_least.py": "cce6f5301096fe1c30e57c64b2f0a3c688f7f90f5e1a92d0018a099170a7514d",
"tests/unit/test_fontconfig_criterion.py": "d730e744f26aa3826f6a7ac02f3f4f37f7513b70ce1440b9c1e2c79505287041",
"tests/unit/test_processes_counts_sites.py": "0e25503e7f962fbcce943f22eaec7fb9ed26f970b2700a36fb4c346497f49d67",
"tests/unit/test_theme_refusal_drop.py": "b00cf36b87df2c09760ee031fc2013d8edeaeb48796a5b8a7dcf9d5fcc9169bc",
"tests/vendor/README.md": "551b2c2337690f908914ef1a7a1ed2385bdde5ddf444ae1410d9cee464403681",
"tests/vendor/botd-2.0.0.esm.js": "f438ed251dc7414ece9d4a2b6941441ad9ffae1a1905817f5f0c7366e701dd86",
"tests/vendor/creepjs-10aa672.js": "80f43f364bd973bc03cb5b82de033ce28b2bbb145cb04237632a46ef040a92be",
"tests/vendor/fingerprintjs-5.2.0.umd.min.js": "a8de5ead580c42d2e2b01a5752aa08da510852230971aa18554d67cd5de5775b",
"tests/vendor/fpscanner-1.0.6.es.js": "5680b88e6075fceab5343d31b43dcb1892a98cff072d37084efdd244fd2cb809",
"tests/webfont_probe.py": "0e4e8997343de023d288ff0adeac0bb4f88c940f7e55c24585f187e3823da10c"
}
},
"sdist_filename": "invisible_playwright-0.50.1.tar.gz",
"seal_tag": "",
"version": "0.50.1",
"wheel": {
"digest": "1d78262d21c293ecbdb624ee8e386ed3c60658aa7662d87d2a5e270dde4d9c0c",
"files": {
"<dist-info>/METADATA": "019ef54b7d89b1dc345b422fcec68f7d159e00cc3b52abaf7d724e8194127b9f",
"<dist-info>/WHEEL": "da266b2640c891e0e1d24f528a428ca85b913feb9aea66f822bd40b04478044c",
"<dist-info>/entry_points.txt": "f07941bc791c2c31375755627886bfe11ba2d83df7b2522064f84be8299ee3a3",
"<dist-info>/licenses/LICENSE": "2abb03e63a96918967f383cbc36e3faefe10a47ae20b2cab43212ef965e02f96",
"invisible_playwright/THIRD_PARTY_FORK.md": "077a8a09f68a6185080b6cd088224b4a19d7fc957c1335027ed6fa42ac4cbbbc",
"invisible_playwright/__init__.py": "4516af737fdbaa0967a359a97b01aa7a3e3d57dae7283ebe5e6ac2381285f3ee",
"invisible_playwright/__main__.py": "c6cd277050ead2d11c98b7cbab91ada7d19e495c95e4c86de1f9aaf2b2051d38",
"invisible_playwright/_cursor.py": "12975e06bcd6c162f4c38298966f9adaa8d9d2eeb225df3a4984af2c9d29672f",
"invisible_playwright/_engine.py": "fabcbd037b52294a5b5201c22382f56714e94aa1edfb834ee2fc8fd7cbf2b3b0",
"invisible_playwright/_fpforge/__init__.py": "3e1338f0bac8ce7c61c0b20c87d7824af5d14e3254b8984f5fc811e6c8500681",
"invisible_playwright/_geo.py": "6cb7a453ae392bd4724f2d508a7f697d1189d9e05b833cc4b36d70069d18225f",
"invisible_playwright/_headless.py": "ceaf85c0a32f92c8c8489fa11756b538feddecc021d4ae22782927171429c2b9",
"invisible_playwright/_juggler/__init__.py": "96d6d06dad40f3c5112ab2bf9852c9d273ca891647baaf86e9913a06112db829",
"invisible_playwright/_juggler/_marshal.py": "4ddc577bb511eda773aff9ed83d7140d0809d9c850fce9cec1826aafc7719d3f",
"invisible_playwright/_juggler/dialogs.py": "5541004829d2484526fc93f11338bfdf9f63f3319e17fc95ea51f61e1b429220",
"invisible_playwright/_juggler/dispatcher.py": "6a74e13cb8e23bad410ccca0952e91bf85820d86121e693220f44f4531e25281",
"invisible_playwright/_juggler/memprobe.py": "39a5789d960d8e75e4fee27c958f28cf6a8fbe34684d282ba884673db92e69df",
"invisible_playwright/_juggler/perimeter.py": "3a2fc6579665db73596b9ae3eaea23091db45827546f3b60887a2ae76753fd58",
"invisible_playwright/_juggler/pointer.py": "cc38686ae60d08613b70d5898cec14ba62b67de218748963263a877c057b7ca9",
"invisible_playwright/_juggler/remote.py": "ad100601f02c97abd454db579d94b8dc6d90d3c5dac7d413d015cf1d507cafa9",
"invisible_playwright/_juggler/server.py": "15f9dc028cffec537cceabdcce3a74346567de9d92aee0c2c037124af5364196",
"invisible_playwright/_juggler/transport.py": "c799df2ebaed0f76e7b9c17938d8c0cddde67197f41675390fe6e9020a7ec62d",
"invisible_playwright/_juggler/variants.py": "0d72ed4c81affc4288fcc9474b18c59ced5d55ee329e4a64bfd7b2cf6aa77d3b",
"invisible_playwright/_juggler/wire.py": "fbe0399da9896031a104bdbe83a7c24a42dd6c264a23bd65d83e8e5f2be9e840",
"invisible_playwright/_pin.py": "34840d65c3ce32aa856f55344358a84cf47904471039a0a28d510166c6feda4b",
"invisible_playwright/_proxy.py": "dadfd7ad17246521c78c2e67bc60e31e3fc854dcb0924c4067f5d49a9662722e",
"invisible_playwright/_pw/LICENSE": "7fab1461b41970ff376f1c9303a637076bfaaeb71cd12dd3a1c44aaf59a1a2b9",
"invisible_playwright/_pw/README.md": "3ff2819bfde496151299983c4db167171e3e49933e7cf75613239893b2530570",
"invisible_playwright/_pw/__init__.py": "06c3acdadd13e2813fcb95ad91d53ee3885c2b5f473beccc45a579d9ceead70b",
"invisible_playwright/_pw/__main__.py": "dcc8e224337e54bb2febd50cc2e3c6db6ad345c2e148fe64612ca64c4dbea469",
"invisible_playwright/_pw/_impl/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"invisible_playwright/_pw/_impl/__pyinstaller/__init__.py": "5a8c0cfeb2d84ed4287afdec24ffcec60d1ed827b92afdfbd82b2351ffae1c15",
"invisible_playwright/_pw/_impl/__pyinstaller/hook-playwright.async_api.py": "d4a8c45554b3ba55e8102f03f576bab6ea4abfb70cdc60095471d504e34a1014",
"invisible_playwright/_pw/_impl/__pyinstaller/hook-playwright.sync_api.py": "d4a8c45554b3ba55e8102f03f576bab6ea4abfb70cdc60095471d504e34a1014",
"invisible_playwright/_pw/_impl/_api_structures.py": "7117217bc28b93311e0ded2232935bbb3e71cd36a69ace95faa5b5f019b6186d",
"invisible_playwright/_pw/_impl/_artifact.py": "3f06f56db387ad34194b9287291843e32ee6b2fbd06417872085ba5cdf58c3d0",
"invisible_playwright/_pw/_impl/_assertions.py": "ebfe537ce1c118606f256cf431d8acc55dbf45cec0ff8ce80b7d08189372d584",
"invisible_playwright/_pw/_impl/_async_base.py": "411bdbf2019879b7338bfd11291dab77662c4de8c029ce233f6c8c173845e440",
"invisible_playwright/_pw/_impl/_browser.py": "96af02910c9bd02ed3747049e4dc83f792b18ab363257bea5bb63e81335b5098",
"invisible_playwright/_pw/_impl/_browser_context.py": "c91c6e44a0dbc4e9c0430807561d9b92a73a3b33c406792a71a1362ccf995e46",
"invisible_playwright/_pw/_impl/_browser_type.py": "8e8fab1f8253952f971ea941948292e49fa08038e6566e6164ba1db927f16017",
"invisible_playwright/_pw/_impl/_cdp_session.py": "da1f31e66ee6a1a47a77412f6efa3e72670835a81d20a42a939cc6043f4c3357",
"invisible_playwright/_pw/_impl/_clock.py": "c3868a4cfdad993d99a554e58742f8c1e9f6806d51199e2870916e6c8b2eea2c",
"invisible_playwright/_pw/_impl/_connection.py": "0c345f8afd418c42c9722126b4562009922135df050c076ce279481cc9ae2534",
"invisible_playwright/_pw/_impl/_console_message.py": "4adcc1921c9ad348a2f796848b2ce92ab625b3f328ed611ac42d6576fe16ac66",
"invisible_playwright/_pw/_impl/_credentials.py": "0d5e2ea044d6a0861de54aae29de5f0da8ef871635384f57a111e2d70cd9843e",
"invisible_playwright/_pw/_impl/_debugger.py": "17a425f2c82a798098fe08a0a1b92be5fd7ccce0d56af25a6795e80d33aee2bd",
"invisible_playwright/_pw/_impl/_dialog.py": "2061f36b8952cd8fcb74c9a9cc9930c3a600eb1e7f6fa4ef1867867f353d14a6",
"invisible_playwright/_pw/_impl/_disposable.py": "564a3c3e3e2c5dc8db07727d682e2fb40c0e113e8489cf7fc179ed4aaea2ac87",
"invisible_playwright/_pw/_impl/_download.py": "5349c613615cc690593537acbedc83e5a53fd056521358cacaf2a355238efdd4",
"invisible_playwright/_pw/_impl/_element_handle.py": "b922cf771522209192727547185c922e9617f94fe55ae7c37ffa99cadf410a45",
"invisible_playwright/_pw/_impl/_errors.py": "49407bd6164ab563f82b2bf37863a265555071544dcabedbf7beba8be1b618cd",
"invisible_playwright/_pw/_impl/_event_context_manager.py": "55ea0fab5a17acbb3f6f797610cf20a77efcbc7b62e8c19bac53a138f39c7127",
"invisible_playwright/_pw/_impl/_fetch.py": "2756ee00ffb7cf8e178af4d9f8d56ab7d06828fce431faa9318e54a2ade55e1f",
"invisible_playwright/_pw/_impl/_file_chooser.py": "3efbf6c96f36cb906508330cb09ef5b5e1843e2b1aa95b27a5f85ec4376c8522",
"invisible_playwright/_pw/_impl/_form_data.py": "a9ce4cb4f77a06d24d31ea0e81a0e007a965bf33ad848ebed7cf0ad2f40f36b7",
"invisible_playwright/_pw/_impl/_frame.py": "0f974f94f52be86e510552900469c219007ba7a5ec05f3fe3a0d5cb78ff42b81",
"invisible_playwright/_pw/_impl/_glob.py": "af927c1cc1a33e12094224ca96158964ce2c7ad9f4b4de3ac60e16e0baf9f887",
"invisible_playwright/_pw/_impl/_greenlets.py": "27456c0ecfc181a04a6a1245e0f72549129e3af0b611e60607cb5d29f4fe2634",
"invisible_playwright/_pw/_impl/_har_router.py": "24fe3134253de1b71a3738348444dea88b78bdd250851ac7cfdac2ffcdef68b8",
"invisible_playwright/_pw/_impl/_helper.py": "c866f0dde846d84856404d7b6c72c5fbd5ac41302b1f6ac043016956256c2812",
"invisible_playwright/_pw/_impl/_impl_to_api_mapping.py": "ea1e5b8ea94f344a18a6c049e465d45044cfd61c2ef779887f076e675dffa655",
"invisible_playwright/_pw/_impl/_input.py": "14ed52c5e5bda7f5d8bde6b67fd651dee8c368344e13d652178d04e975ea1801",
"invisible_playwright/_pw/_impl/_js_handle.py": "cbb76fdf29d5087e2f2d04bac5e729bf7905238a9b386f3be9e01a4e2a95406a",
"invisible_playwright/_pw/_impl/_json_pipe.py": "c738956081dee483bbc032707553a9f9b3be38750f2ee7916390fa47fb1b19e8",
"invisible_playwright/_pw/_impl/_local_utils.py": "93677e1277ef74efcf52630d98a8857c1ea847b6e16757538040ce49e2758490",
"invisible_playwright/_pw/_impl/_locator.py": "c4457bbae669d98530a5bfd717619f8fc801a20c35e2e52e39b4f96193fba708",
"invisible_playwright/_pw/_impl/_map.py": "606086b53edc29605a5ff0b22147dfc640e38c65089df790063aed9cb89bfaa7",
"invisible_playwright/_pw/_impl/_network.py": "6af15cca7afa486ddb3edcea9ed2fdd2104f6ec268612dedf6707453a0c9433d",
"invisible_playwright/_pw/_impl/_object_factory.py": "16cf089afe2a37a18c397ac6cc9aebd296db731b6e6fac2a1248cae09585f26e",
"invisible_playwright/_pw/_impl/_page.py": "187b110afac50f94766b0b5b40a82c02b895e723c0000fbee7233deb0e08d11e",
"invisible_playwright/_pw/_impl/_path_utils.py": "2c0c34e8c14e04d350044e5ecca4d804b4c5f9191a94c450f58e6a3f9d8bcd1c",
"invisible_playwright/_pw/_impl/_playwright.py": "7f1771a504561f108c9e0faa9a44f4e4ab8cc13116bbf2686ea1a3b03ede7d52",
"invisible_playwright/_pw/_impl/_screencast.py": "3bbef5e66981e9216f27f83428207f61d33d2e371ce2121d195c9ed646d1001f",
"invisible_playwright/_pw/_impl/_selectors.py": "8f480ab03977b1d1d703a5519d195e3f3335e0e644cd559501167f39318db354",
"invisible_playwright/_pw/_impl/_set_input_files_helpers.py": "a8863bbe7d98520c8770f51b130c69c259ae629a829e1286588da6b16950377e",
"invisible_playwright/_pw/_impl/_str_utils.py": "0ff1b72ae6d0dfefc92939fca4cc0c2dcb7efe4fd8e520c72c630a6bd94b0fe3",
"invisible_playwright/_pw/_impl/_stream.py": "0f05ac6e14aa97ae37b68986bee03d656e3b1f92944b8aa42b9ad927df1803fa",
"invisible_playwright/_pw/_impl/_sync_base.py": "0bfe9eee479bad5295d7b281f20bb306ed652ef74a5053b14c320995a3187af5",
"invisible_playwright/_pw/_impl/_tracing.py": "d88db6cdfedaa54ee6435fb7dd5e89b2906ad409374ec0177d17a2bf344d694b",
"invisible_playwright/_pw/_impl/_transport.py": "bf158dc47d4bc0cab4a7719c50f628d308d4a54b29c03d19c5e10f2b66980fdf",
"invisible_playwright/_pw/_impl/_video.py": "f7002004b2c26d072bd108f9539b8e1b698f917be7b17cd30cc7eb3fb373d6d6",
"invisible_playwright/_pw/_impl/_waiter.py": "d8cda0d02e1e92674c4c0a3127229ff87ca4ef214c1682daf3b64ad4268240e0",
"invisible_playwright/_pw/_impl/_web_error.py": "238b060de72bdf92b54f771622e9e9739b64240d73e7d573c9125f68a28b64a8",
"invisible_playwright/_pw/_impl/_web_storage.py": "7f942aee8cc96bd82ea59b3d0839e8b20e4f44f066343e8640e3180fe001ab70",
"invisible_playwright/_pw/_impl/_writable_stream.py": "4a4936a37ee5c783f88d7f6c7bfda2850bcc18867a420581ca16c90e1248047e",
"invisible_playwright/_pw/_repo_version.py": "d53af84ac37b99e382129383cbd4ae8f2c78798801ced917b9c0b0e23b34f58e",
"invisible_playwright/_pw/async_api/__init__.py": "77bbd2c48813238c42211e1470f66bcf82ec31373f89fbe0670b8cba52aae7d6",
"invisible_playwright/_pw/async_api/_context_manager.py": "3bc5660a721ccc9cce317c8b4a15074b88dbbffeddf860b01ca187dbe16d8ad3",
"invisible_playwright/_pw/async_api/_generated.py": "b0a5713e9b560387b04bf6410c56b231ec90f0dd7e571f58d2af50013d977f18",
"invisible_playwright/_pw/py.typed": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"invisible_playwright/_pw/sync_api/__init__.py": "a99ad0ce7f8511de29e3661e9e2c8b2dd5e8c4a0cfe7731de4428367df00c15e",
"invisible_playwright/_pw/sync_api/_context_manager.py": "d6300f64c2961ae4d115fac87869b7837f4f17d697d8cf843fd58592530e5c5d",
"invisible_playwright/_pw/sync_api/_generated.py": "7881f3918cdeadd2909f82d36cfd993a54664638adf289cb9eb2e3dbd139f045",
"invisible_playwright/_reaper.py": "4e87bd00b81805fa3e242ae8c1162c32fa78da4dbc515a9de0647209fab7533c",
"invisible_playwright/_session.py": "b57c3ae743e016d10be65ba2b8359e6b0390f94aeb8100af60a8237fcf44d6dd",
"invisible_playwright/_version.py": "101d9ed902fb1a3a806f99f220eb10dd73ca656bd8b02f0c507ec338ef14890b",
"invisible_playwright/_webgl_personas.py": "bdb1c0d79297f9dc3177f8f530a655bd77b473a1838c4829dc48283e30c380a8",
"invisible_playwright/async_api.py": "070bf9f2e3c112353aac788cd04f8fdd70874165eeb505bf547123027b963923",
"invisible_playwright/cli.py": "bd742a8f8ce7961ab3f3ee100398f0247a1e0289563d60be56c33ccd17215f87",
"invisible_playwright/config.py": "5f48dfcd4cb757787af5c8ff37f2c7a6683ee3f2b4500182dd4c2dd0722a38f3",
"invisible_playwright/constants.py": "6be639754df221f5c41fdbe343ae35e9ea4c83297e98f6566250549f19d6c121",
"invisible_playwright/download.py": "416db5d579525d7f0802064d8a6929126c6b085dbe0f1c298f02a7a349f000d9",
"invisible_playwright/launcher.py": "924d1aeff016e25c8ce4d45d8994a72dab408b697d4ae7b9b74b3fa9e83161ca",
"invisible_playwright/prefs.py": "3fabf6f07d9f85cd5ea5bb901dfeedc2c3a41b8e199acd0dc25a11c473004298",
"invisible_playwright/py.typed": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"invisible_playwright/sync_api.py": "4c42eacfdd306f1b610a54bb54fcd1cbaef3c20dd525e584d3c587c4a846ea6b"
}
},
"wheel_filename": "invisible_playwright-0.50.1-py3-none-any.whl"
}
],
"schema": 1
+11 -6
View File
@@ -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
@@ -233,11 +238,11 @@ invisible-playwright version # wrapper, core and engine versions, and where the
**If you would rather prompt than script.** This page is the engine, as a Python
library. Two ways to use it without writing code, both one line: from an MCP client
you already have (Claude Code, Claude Desktop, Cursor),
`claude mcp add stealth -- uvx aihawk`, see
[the MCP server page](https://github.com/feder-cr/AIHawk/wiki/mcp-server); or with an
`claude mcp add stealth -- uvx invisible-playwright-mcp`, see
[the MCP server page](https://github.com/feder-cr/invisible_playwright_mcp/wiki/mcp-server); or with an
interface and a model included, needing only an OpenRouter key,
`uvx aihawk ui --openrouter-key sk-or-...`, see
[AIHawk](https://github.com/feder-cr/AIHawk). Same engine underneath, and the second
`uvx invisible-playwright-mcp ui --openrouter-key sk-or-...`, see
[invisible_playwright_mcp](https://github.com/feder-cr/invisible_playwright_mcp). Same engine underneath, and the second
is a client of the first.
All of it reads better, and is searchable, in
@@ -281,8 +286,8 @@ two around it are how most people reach it:
- **[invisible_core](https://github.com/feder-cr/invisible_core)** - seed to
fingerprint to preferences, plus proxy and geolocation. This package pins it.
- **[AIHawk](https://github.com/feder-cr/AIHawk)** - this engine as an MCP
server (`uvx aihawk`, for any client that brings its own
- **[invisible_playwright_mcp](https://github.com/feder-cr/invisible_playwright_mcp)** - this engine as an MCP
server (`uvx invisible-playwright-mcp`, for any client that brings its own
model) and, in the same package, an interface with a model included, from
one command. The interface is a client of the server, with no private path
to the browser.
+9 -3
View File
@@ -1,5 +1,11 @@
[
{"id": "wrapper.e2e.udp", "giro": "G2", "os": ["linux", "windows"], "min_tests": 51, "exact": true, "tests": ["tests/test_the_whole_udp_chain_by_name_e2e.py", "tests/test_declared_host_network_e2e.py", "tests/test_http3_through_the_proxy_e2e.py", "tests/test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_e2e.py", "tests/test_networkidle_through_a_served_browser_with_routes_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"], "marker": "e2e", "needs_root": false, "note": "Needs the candidate binary (STEALTHFOX_E2E_BINARY) and the engine that carries the UDP line. 51 = 1+7+2+1+21 from the five files + 19 from the 8 UDP-line tests of test_webrtc_realness.py (parametrized)."},
{"id": "wrapper.e2e.doh", "giro": "G2", "os": ["linux", "windows"], "min_tests": 8, "exact": true, "tests": ["tests/test_doh_through_the_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.unit.udp", "giro": "G1", "os": ["linux", "windows"], "min_tests": 92, "exact": true, "tests": ["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"], "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.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": 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)."}
]
+3 -3
View File
@@ -1,6 +1,6 @@
---
title: "AI agent retry loops trip rate limits, not fingerprints"
description: "Retry and re-plan loops multiply requests into a volume signal; throttling belongs in the agent loop. This page moved to the AIHawk wiki."
description: "Retry and re-plan loops multiply requests into a volume signal; throttling belongs in the agent loop. This page moved to the invisible_playwright_mcp wiki."
parent: "AI Agents and Frameworks"
grand_parent: "Guides"
nav_order: 17
@@ -9,10 +9,10 @@ nav_order: 17
# AI agent retry loops trip rate limits, not fingerprints
This page moved to the AIHawk wiki, where the agent-experience content now
This page moved to the invisible_playwright_mcp wiki, where the agent-experience content now
lives:
**[Agent retry loops trip rate limits, not fingerprints](https://github.com/feder-cr/AIHawk/wiki/agent-retry-loops-rate-limits)**
**[Agent retry loops trip rate limits, not fingerprints](https://github.com/feder-cr/invisible_playwright_mcp/wiki/agent-retry-loops-rate-limits)**
The one-paragraph version: an agent that retries and re-plans multiplies its
requests, and volume is scored server-side against your address and account.
+3 -3
View File
@@ -1,6 +1,6 @@
---
title: "Why AI browser agents have their own timing signal"
description: "An LLM loop emits machine-regular action gaps and instant pointer jumps - a behavioral signal no fingerprint fixes. This page moved to the AIHawk wiki."
description: "An LLM loop emits machine-regular action gaps and instant pointer jumps - a behavioral signal no fingerprint fixes. This page moved to the invisible_playwright_mcp wiki."
parent: "AI Agents and Frameworks"
grand_parent: "Guides"
nav_order: 10
@@ -9,10 +9,10 @@ nav_order: 10
# Why AI browser agents have their own timing signal
This page moved to the AIHawk wiki, where the agent-experience content now
This page moved to the invisible_playwright_mcp wiki, where the agent-experience content now
lives:
**[The timing signal AI agents give off](https://github.com/feder-cr/AIHawk/wiki/ai-agent-timing-signal)**
**[The timing signal AI agents give off](https://github.com/feder-cr/invisible_playwright_mcp/wiki/ai-agent-timing-signal)**
The short version it still owes you here: a think-act loop pauses for model
latency, and that pause repeats with a regularity no human produces. The
+1 -1
View File
@@ -224,7 +224,7 @@ this whole page is about.
one. Pick on the agent loop, then fix the machine, then consider the engine.
**Is there any agent route to an engine-level fingerprint?** Two, and they are not
equivalent. `uvx aihawk` launches through the engine, so the
equivalent. `uvx invisible-playwright-mcp` launches through the engine, so the
seeded profile and the humanised pointer come with it. Microsoft's own Playwright
MCP server takes a browser and an executable path, which runs the engine but
carries no `firefox_user_prefs`, so every session on a given build shares one
+3 -3
View File
@@ -1,6 +1,6 @@
---
title: "browser-use gets detected: what you can and cannot change"
description: "browser-use drives Chrome over CDP. What BrowserProfile lets you change and what stays out of reach. This page moved to the AIHawk wiki."
description: "browser-use drives Chrome over CDP. What BrowserProfile lets you change and what stays out of reach. This page moved to the invisible_playwright_mcp wiki."
parent: "AI Agents and Frameworks"
grand_parent: "Guides"
nav_order: 2
@@ -9,10 +9,10 @@ nav_order: 2
# browser-use gets detected: what you can and cannot change
This page moved to the AIHawk wiki, where the agent-experience content now
This page moved to the invisible_playwright_mcp wiki, where the agent-experience content now
lives:
**[browser-use getting blocked: what you can and cannot change](https://github.com/feder-cr/AIHawk/wiki/browser-use-getting-blocked)**
**[browser-use getting blocked: what you can and cannot change](https://github.com/feder-cr/invisible_playwright_mcp/wiki/browser-use-getting-blocked)**
The unchanged short answer: browser-use exposes a real set of levers
(`executable_path`, `user_data_dir`, `proxy`, `headless`, `args`), all of
@@ -1,6 +1,6 @@
---
title: "Computer-use agents and browser fingerprint detection"
description: "Clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. This page moved to the AIHawk wiki."
description: "Clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. This page moved to the invisible_playwright_mcp wiki."
parent: "AI Agents and Frameworks"
grand_parent: "Guides"
nav_order: 6
@@ -9,10 +9,10 @@ nav_order: 6
# Computer-use agents and browser fingerprint detection
This page moved to the AIHawk wiki, retargeted at the question people
This page moved to the invisible_playwright_mcp wiki, retargeted at the question people
actually search:
**[Claude computer use detected as a bot](https://github.com/feder-cr/AIHawk/wiki/claude-computer-use-detected-as-bot)**
**[Claude computer use detected as a bot](https://github.com/feder-cr/invisible_playwright_mcp/wiki/claude-computer-use-detected-as-bot)**
The core of it, kept here in brief: a coordinate-clicking agent never
generates the DOM-automation tells, so `navigator.webdriver` advice mostly
+5 -5
View File
@@ -20,7 +20,7 @@ Playwright, or not to touch Firefox, at all.
These pages are for developers wiring an agent to this engine. The
agent-experience side - what to run, which agent products compare how, what to
check when an agent gets blocked - lives on the
[AIHawk wiki](https://github.com/feder-cr/AIHawk/wiki), the agent built on this
[invisible_playwright_mcp wiki](https://github.com/feder-cr/invisible_playwright_mcp/wiki), the agent built on this
same engine.
## Framework integrations
@@ -34,15 +34,15 @@ same engine.
## Computer-use and screenshot agents
- [Back a computer-use agent with a real browser engine](back-computer-use-agent-real-browser.md) - implement the screenshot-and-click Computer interface over an invisible_playwright page, and its honest limits.
- [Computer-use agents and browser fingerprint detection](computer-use-agents-browser-detection.md) - clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. (Moved to the AIHawk wiki; the page here points across.)
- [Computer-use agents and browser fingerprint detection](computer-use-agents-browser-detection.md) - clicking by pixel makes driver flags moot; the engine fingerprint and action rhythm stay checkable. (Moved to the invisible_playwright_mcp wiki; the page here points across.)
- [DOM-reading vs screenshot agents: which stealth helps](dom-reading-vs-screenshot-agents.md) - which stealth signal helps depends on whether the agent reads DOM or clicks pixels.
## How AI agents get detected
- [AI browser agents and stealth: what fits and what does not](ai-browser-agents-stealth.md) - most agents drive Chromium over CDP, so a stealth Firefox does not drop in.
- [browser-use gets detected: what you can and cannot change](browser-use-detection.md) - browser-use drives Chrome over CDP: what BrowserProfile changes, what stays out of reach. (Moved to the AIHawk wiki; the page here points across.)
- [Why AI browser agents have their own timing signal](ai-agent-timing-signal.md) - a think-act loop emits machine-regular gaps and instant pointer jumps no fingerprint fixes. (Moved to the AIHawk wiki; the page here points across.)
- [AI agent retry loops trip rate limits, not fingerprints](agent-retry-loops-rate-limits.md) - retry and re-plan loops multiply requests into a volume signal; throttle in the agent loop. (Moved to the AIHawk wiki; the page here points across.)
- [browser-use gets detected: what you can and cannot change](browser-use-detection.md) - browser-use drives Chrome over CDP: what BrowserProfile changes, what stays out of reach. (Moved to the invisible_playwright_mcp wiki; the page here points across.)
- [Why AI browser agents have their own timing signal](ai-agent-timing-signal.md) - a think-act loop emits machine-regular gaps and instant pointer jumps no fingerprint fixes. (Moved to the invisible_playwright_mcp wiki; the page here points across.)
- [AI agent retry loops trip rate limits, not fingerprints](agent-retry-loops-rate-limits.md) - retry and re-plan loops multiply requests into a volume signal; throttle in the agent loop. (Moved to the invisible_playwright_mcp wiki; the page here points across.)
- [Playwright 1.62 Ships MCP In the Box](playwright-162-built-in-mcp.md) - the MCP server and a new playwright-cli are now bundled into core, runnable via `npx playwright mcp` with no separate install.
## Running agents at scale and on servers
+2 -2
View File
@@ -22,8 +22,8 @@ the thing it describes, and several of them record something we got wrong first.
- **[Integrations](integrations/)** - running this inside Scrapy, Crawlee, Robot
Framework, CodeceptJS, test runners and Playwright MCP, including which frameworks
it does not fit and why.
- **[The agent on top](https://github.com/feder-cr/AIHawk/wiki)** - this engine also
drives [AIHawk](https://github.com/feder-cr/AIHawk), an AI agent you instruct in
- **[The agent on top](https://github.com/feder-cr/invisible_playwright_mcp/wiki)** - this engine also
drives [invisible_playwright_mcp](https://github.com/feder-cr/invisible_playwright_mcp), an AI agent you instruct in
plain language; its wiki covers the agent layer the way this one covers the
browser: comparisons, blocked agents, and task guides.
+5 -6
View File
@@ -1,6 +1,6 @@
---
title: "Using invisible_playwright with Microsoft's Playwright MCP"
description: "There is a server for this engine, inside AIHawk: uvx aihawk. This page is for people already committed to Microsoft's playwright-mcp, and says exactly what that route costs."
description: "There is a server for this engine: uvx invisible-playwright-mcp. This page is for people already committed to Microsoft's playwright-mcp, and says exactly what that route costs."
parent: "Integrations"
nav_order: 7
---
@@ -8,13 +8,12 @@ nav_order: 7
# Using invisible_playwright with Microsoft's Playwright MCP
**There is a server for this engine:**
[`aihawk`](https://github.com/feder-cr/AIHawk/wiki/mcp-server),
shipped inside AIHawk.
[`invisible-playwright-mcp`](https://github.com/feder-cr/invisible_playwright_mcp/wiki/mcp-server).
One line, and it carries the seeded profile and the humanised pointer that the
route on this page cannot:
```bash
claude mcp add stealth -- uvx aihawk
claude mcp add stealth -- uvx invisible-playwright-mcp
```
This page is for the other case: you are already committed to Microsoft's
@@ -122,8 +121,8 @@ knowing before you trust the session.
## Short answers to the questions that lead here
**Is there an MCP server for this project?** Yes:
[`aihawk`](https://github.com/feder-cr/AIHawk/wiki/mcp-server),
`uvx aihawk`. It launches through the engine, so the seeded
[`invisible-playwright-mcp`](https://github.com/feder-cr/invisible_playwright_mcp/wiki/mcp-server),
`uvx invisible-playwright-mcp`. It launches through the engine, so the seeded
profile and the humanised pointer come with it.
Microsoft's own `playwright-mcp` also accepts `--browser firefox` together with
+2 -2
View File
@@ -189,8 +189,8 @@ supply a clean IP, human pacing, and session reuse for the layers a browser cann
[how to test whether the browser itself is the problem](how-to-test-bot-detection.md), and
[rate limiting your scraper so volume stops being the signal](how-to-rate-limit-your-scraper-playwright.md).
If the traffic is produced by an AI agent rather than a script, the pacing and
retry layers have their own failure modes, mapped on the AIHawk wiki:
[why does my AI agent get blocked?](https://github.com/feder-cr/AIHawk/wiki/why-does-my-ai-agent-get-blocked)
retry layers have their own failure modes, mapped on the invisible_playwright_mcp wiki:
[why does my AI agent get blocked?](https://github.com/feder-cr/invisible_playwright_mcp/wiki/why-does-my-ai-agent-get-blocked)
---
+2 -2
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "invisible_playwright"
version = "0.50.0"
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.63.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
+19 -34
View File
@@ -3,8 +3,20 @@
A raw `firefox --screenshot` proves nothing about automation: a juggler-less
binary renders a screenshot just fine and ships broken (firefox-8 did exactly
that). This DRIVES the binary the way users will - Playwright launches it over
the juggler pipe and exercises real paths.
that). This DRIVES the binary the way users will - the wrapper (and the core under
it) launches it over the juggler pipe and exercises real paths.
⛔ THROUGH THE CORE, NOT THROUGH BARE PLAYWRIGHT. Since firefox-63 the engine holds
every channel that asks the proxy service until the client has said how the
session leaves the host (`Browser.setBrowserProxy`, or the explicit
`Browser.setNoBrowserProxy` of a session without a proxy): nothing may leave the
host before that. Stock Playwright sends the first only when it is given a proxy,
so a bare `p.firefox.launch_persistent_context(executable_path=...)` navigates
nowhere: run 43134774602, `Page.goto: Timeout 30000ms` on every leg, three
attempts. The core's launch sends the decision FIRST, and declares the first run
(terms of use, pre-onboarding) that this script used to copy into user.js, so
the copy is gone with it. The job installs the core under test (core_ref, from
git) and the wrapper, and seals the binary, before this script runs.
Three levels (see `--click` / `--full`):
@@ -60,31 +72,9 @@ Exit 0 + "DRIVE GATE OK ..." on success; non-zero with a reason on failure.
from __future__ import annotations
import http.server
import json
import shutil
import socketserver
import sys
import tempfile
import threading
from pathlib import Path
# ⛔ THE FIRST RUN IS DECLARED HERE, A COPY OF THE CORE'S, written into the
# profile's user.js. Since firefox-55 the engine leaves Mozilla's first-run
# lines and invisible_core declares the state (terms of use accepted long ago,
# pre-onboarding off). This job installs only Playwright, so nothing declared
# it: measured 2026-11-02 on run 41388672849, Windows showed the terms-of-use
# modal ("the page did not handle mouse event") and Linux opened
# https://www.mozilla.org/en-US/privacy/firefox/ in a second tab (the legacy
# data-reporting flow) ("Unexpected number of tabs in the new window: 2").
# Upstream Playwright sends its own defaults in Browser.enable, which this
# engine refuses, so a raw launch runs on Mozilla's lines alone. With these
# three in user.js, both legs drive. tests/test_ci_drive_gate_first_run.py
# ties the copy to the core.
FIRST_RUN = {
"browser.preonboarding.enabled": False,
"termsofuse.acceptedVersion": 4,
"termsofuse.acceptedDate": "1785573000000",
}
HTML = (
"<!doctype html><html><head><title>dt</title></head><body>"
@@ -155,16 +145,12 @@ def _drive(exe: str, url: str, level: str) -> str:
"""One run. `level` is "smoke", "click" or "full". Returns the UA."""
interacts = level in ("click", "full")
full = level == "full"
from playwright.sync_api import sync_playwright
from invisible_playwright import InvisiblePlaywright
# A user.js is read at startup, before the window that would carry the
# modal; a persistent context is the only way to hand Playwright a profile.
profile_dir = Path(tempfile.mkdtemp(prefix="ci-drive-gate-"))
(profile_dir / "user.js").write_bytes(
"".join("user_pref(%s, %s);\n" % (json.dumps(k), json.dumps(v))
for k, v in sorted(FIRST_RUN.items())).encode("utf-8"))
with sync_playwright() as p:
ctx = p.firefox.launch_persistent_context(str(profile_dir), executable_path=exe, headless=True)
# The core declares the first run and sends the session's road before anything else; the seal of the binary is
# INVISIBLE_SEAL_FILE (the job sets it), and `binary_path` is the binary under test.
with InvisiblePlaywright(seed=42, binary_path=exe, headless=True, humanize=False) as browser:
ctx = browser.new_context()
try:
page = ctx.new_page()
resp = page.goto(url, wait_until="load")
@@ -192,7 +178,6 @@ def _drive(exe: str, url: str, level: str) -> str:
inter["plugins"] = page.evaluate("() => navigator.plugins instanceof PluginArray")
finally:
ctx.close()
shutil.rmtree(profile_dir, ignore_errors=True)
# SMOKE asserts (always).
assert "Firefox" in ua, f"unexpected UA (binary not driving correctly): {ua!r}"
@@ -189,7 +189,8 @@ def _headers_array(raw) -> List[Dict[str, str]]:
#: Juggler's `cause` and `internalCause` are `nsIContentPolicy` constant names
#: (`causeTypeToString` in NetworkObserver.js), so they arrive as
#: `TYPE_XMLHTTPREQUEST`, never `xmlhttprequest`. This is the table the
#: Playwright driver's ffNetworkManager uses for the same event.
#: Playwright driver's ffNetworkManager uses for the same event (the pinned driver's table is read by
#: tests/test_resource_types_match_the_pinned_driver.py: a beacon is `beacon`, a CSP report `cspreport`).
_CAUSE_TO_RESOURCE_TYPE = {
"TYPE_INVALID": "other", "TYPE_OTHER": "other",
"TYPE_SCRIPT": "script", "TYPE_IMAGE": "image",
@@ -198,8 +199,8 @@ _CAUSE_TO_RESOURCE_TYPE = {
"TYPE_REFRESH": "document", "TYPE_XBL": "other", "TYPE_PING": "other",
"TYPE_XMLHTTPREQUEST": "xhr", "TYPE_OBJECT_SUBREQUEST": "other",
"TYPE_DTD": "other", "TYPE_FONT": "font", "TYPE_MEDIA": "media",
"TYPE_WEBSOCKET": "websocket", "TYPE_CSP_REPORT": "other",
"TYPE_XSLT": "other", "TYPE_BEACON": "other", "TYPE_FETCH": "fetch",
"TYPE_WEBSOCKET": "websocket", "TYPE_CSP_REPORT": "cspreport",
"TYPE_XSLT": "other", "TYPE_BEACON": "beacon", "TYPE_FETCH": "fetch",
"TYPE_IMAGESET": "image", "TYPE_WEB_MANIFEST": "manifest",
}
_INTERNAL_CAUSE_TO_RESOURCE_TYPE = {
+10 -2
View File
@@ -721,10 +721,12 @@ def _launch_params(session: Any, *, virtual_display: bool, headless: bool,
from invisible_playwright._reaper import SessionToken
geo = prepare_session_geo(session._timezone, session._proxy,
session._locale_requested)
session._locale_requested, seed=session.seed,
udp_stun_servers=session._udp_stun_servers)
session._timezone = geo.timezone
session._locale = geo.locale
session._webrtc_egress_ip = geo.egress_ip
session._geolocation = geo.geolocation_override()
executable = resolve_executable(session._binary_path)
pw_headless = bool(headless)
if not headless and virtual_display:
@@ -767,6 +769,7 @@ def launch_server(host: str = DEFAULT_HOST, port: int = 0, *,
humanize: Any = False,
motion_budget_s: Optional[float] = None,
show_cursor: Optional[bool] = None,
preload_newtab: Optional[bool] = None,
locale: str = "auto",
timezone: str = "",
extra_args: Optional[List[str]] = None,
@@ -777,6 +780,7 @@ def launch_server(host: str = DEFAULT_HOST, port: int = 0, *,
context_options_override: bool = False,
launch_timeout_ms: Optional[int] = 60000,
on_engine_closed: Optional[Callable[[], None]] = None,
udp_stun_servers: Optional[List[str]] = None,
) -> RemoteServer:
"""Launch ONE browser and serve it on a WebSocket; return when it listens
and the browser is ready.
@@ -805,6 +809,9 @@ def launch_server(host: str = DEFAULT_HOST, port: int = 0, *,
`context_options_override=True`.
on_engine_closed called, from another thread, when the engine dies
(not when `close()` ends it).
udp_stun_servers where a SOCKS5 proxy's UDP exit is measured from: "ip:port" IPv4 literals, None for the
two public defaults. Kept on the session, so the launch and every context proxy a client
later gives measure from the same list. Python only: nothing reaches the browser.
The engine is the sealed one (`ensure_binary`, INVISIBLE_PLAYWRIGHT_ENGINE_DIR)
and the launch FAILS if the version it reports is not the seal's.
"""
@@ -817,7 +824,8 @@ def launch_server(host: str = DEFAULT_HOST, port: int = 0, *,
seed, pin=pin, headless=headless, proxy=proxy, extra_args=extra_args,
humanize=humanize, locale=locale, timezone=timezone,
extra_prefs=extra_prefs, binary_path=binary_path,
show_cursor=show_cursor)
show_cursor=show_cursor, udp_stun_servers=udp_stun_servers,
preload_newtab=preload_newtab)
notes: List[str] = []
server = _SharedServer()
endpoint: Optional[RemoteEndpoint] = None
+467 -58
View File
@@ -36,9 +36,10 @@ import pathlib
import sys
import tempfile
import threading
import collections
import time
import warnings
from typing import Any, Callable, Dict, List, Optional
from typing import Tuple, Any, Callable, Dict, List, Optional
from invisible_core.juggler import PageActs, popup_number
from invisible_core.juggler import connection as juggler
@@ -70,6 +71,7 @@ from ._marshal import (_js_number, _as_script, _button, _caller_timeout,
# here for the length of one fix. Two readings of what a proxy is would be
# the same duplication that produced the defect, one layer down.
from invisible_core import SessionLocale, parse_proxy
from invisible_core._udp_exit import context_proxy_command, launch_proxy_command, stun_servers
from invisible_core import write_user_js
from invisible_core.juggler import (SessionFiles, domain_matches, host_of,
@@ -178,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.
@@ -237,6 +248,12 @@ POINTER_PREF = "invisible.server.pointer"
#: out here like the three above: the profile a launch writes is a composed
#: session, or the server composes one (`session_for_launch`).
COMPOSED_PREF = "invisible.server.composed"
#: WHERE THE SESSION MEASURES A SOCKS5 PROXY'S UDP EXIT FROM (`udp_stun_servers=` of the launch, "ip:port" joined by
#: commas). Like the seed it rides in the prefs the launcher composes, because that dict is the one thing that
#: reaches this server from the session, and it is taken out in `op_launch` before the profile is written: it is
#: a parameter of the Python launch, never a browser declaration. The server keeps it on the browser, so the launch
#: and every later `new_context(proxy=...)` measure with the SAME list.
UDP_STUN_PREF = "invisible.server.udp_stun_servers"
#: The persona's keyboards, as Windows writes its input profiles (LANGID:KLID
#: joined by semicolons, the language's first), decided by the core from the
#: session's language AND country (`keyboard.profiles_for`). Server-only, like
@@ -264,11 +281,38 @@ def take_session_motion(prefs: Dict) -> tuple:
budget_ms = rest.pop(MOTION_BUDGET_PREF, None)
rest.pop(POINTER_PREF, None)
rest.pop(COMPOSED_PREF, None)
rest.pop(UDP_STUN_PREF, None)
return (rest,
(None if seed is None else int(seed)),
(None if budget_ms is None else int(budget_ms) / 1000.0))
def session_udp_stun_servers(prefs: Dict) -> Optional[list]:
"""The STUN servers the launcher named (`UDP_STUN_PREF`), validated again, or None for the defaults. Read
BEFORE `take_session_motion` takes the key out."""
value = prefs.get(UDP_STUN_PREF)
if not value:
return None
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).
@@ -298,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
@@ -966,6 +1011,16 @@ class FrameDispatcher(Dispatcher):
#: closed, and a script that handles "detached" (an iframe a framework removed) never saw it.
detached = False
def emit(self, method: str, params: Optional[Dict] = None) -> None:
if method == "loadstate" and params and params.get("add") in ("domcontentloaded", "load"):
page = self.page
with page._announce_lock:
if not page._announced:
page._said_before_announcement.append((self, dict(params)))
super().emit(method, params)
return
super().emit(method, params)
def detach(self) -> None:
"""The frame left the page: its handles go (their frame is no more), the frame itself stays and refuses."""
self.detached = True
@@ -2484,11 +2539,13 @@ class RouteDispatcher(Dispatcher):
# error up; the client kept it as the error of the whole connection and raised it on the NEXT route command,
# which was never sent: its request stayed held in the engine, its handler failed too, and so on down the page
# (measured on a real news page: six held requests in a row, one a beacon, networkidle never).
# ⛔ EVERY protocol error of the three commands, not one wording of it. The engine says "Cannot find request" when
# the request left its held set first, and "NS_BINDING_ABORTED [nsIInterceptedChannel.resetInterceptionWithURI]"
# when the channel was cancelled while the answer was on its way: the same event, two messages. Stock's
# `sendMayFail` swallows both, and a list of the wordings we have met would fail on the next one.
try:
result = self.request.page.send(command, params)
except juggler.ProtocolError as exc:
if "Cannot find request" not in str(exc):
raise
except juggler.ProtocolError:
result = None
except juggler.TargetClosedError:
result = None # the page went away: nothing is held any more
@@ -2548,6 +2605,76 @@ class RouteDispatcher(Dispatcher):
# ── page ────────────────────────────────────────────────────────────────────
class _Adoption:
"""ONE ENGINE TARGET ON ITS WAY TO THE CLIENT: the single record of where it is, and the only thing an event about it may change.
attached - the engine said `Browser.attachedToTarget`; nothing is built yet
building - the adoption thread is making the `PageDispatcher` (init scripts, replay, the main frame)
waiting - the page is built and waits for the engine's `Page.ready` (a popup: for as long as the engine takes)
announced - the client was told of the page (`page` event); it lives in the registries
and `gone`, set by the engine's `Browser.detachedFromTarget` AT ANY MOMENT, whatever the state.
⛔ THE INVARIANT, which `test_every_order_of_the_events_of_a_popup_gives_one_page_event` proves over EVERY order of attach, frame,
commit, ready, detach and of the adoption's own steps: a target that was attached and is not a page a caller asked for gives the client
EXACTLY ONE `page` event, at its ready or at its disappearance (and its close right after, if it disappeared), unless its context closed
first. The adoption never decides alone that a target is lost: every wait it makes looks at `gone`, every command it sends that finds
the session gone ends in the same place as a detach. This replaces four patches of the same race (a detach before the ready, during
the build, between the build and the wait, and a command answered 'cannot find session').
"""
__slots__ = ("target_id", "opener", "context_id", "requested", "state", "gone", "page", "session", "trace", "t0", "downloads")
#: What the engine says about a target that the trace keeps (the events of its page's birth and of its disappearance).
TRACED = ("Page.frameAttached", "Page.navigationStarted", "Page.navigationCommitted", "Page.navigationAborted",
"Page.ready", "Page.frameDetached", "Browser.detachedFromTarget")
def __init__(self, target_id: str, opener: Optional["PageDispatcher"], context_id: Optional[str] = None,
session: Optional[str] = None) -> None:
self.target_id = target_id
self.opener = opener
self.context_id = context_id
self.session = session
#: ⛔ A SHORT TRACE OF THE TARGET, IN MEMORY: what the engine said and what the adoption did, with the milliseconds since the attach.
#: It costs a list of at most 60 short strings per target in flight and nothing afterwards; it is written in the warning and in the
#: error when a popup is not announced or is dropped, so that a red run on a machine nobody can look at explains itself (the order
#: of the events is what decides the outcome of an adoption).
self.t0 = time.monotonic()
self.trace: List[str] = ["attached +0ms"]
#: The `download` events for the opener of a tab not announced yet, in order: said right after the `page` event of the tab, as
#: Playwright's server says them (the popup is reported, then the download of the opener).
self.downloads: List = []
self.requested: Optional[bool] = None
self.state = "attached"
self.gone = False
self.page: Optional["PageDispatcher"] = None
def note(self, what: str) -> None:
if len(self.trace) < 60:
self.trace.append("%s +%dms" % (what, int((time.monotonic() - self.t0) * 1000)))
def trace_text(self) -> str:
return "events of the target: " + ", ".join(self.trace)
def _with_trace(failure: BaseException, trace: str) -> BaseException:
"""The same failure, its message followed by the trace of the target (the class is kept when it can be built from a message)."""
if trace in str(failure) or "events of the target" in str(failure):
return failure
try:
return type(failure)("%s [%s]" % (failure, trace))
except Exception:
return RuntimeError("%s [%s]" % (failure, trace))
def _target_is_gone(error: BaseException) -> bool:
"""Whether a failed command failed because the target or its session no longer exists (the engine closed the tab under it)."""
if isinstance(error, juggler.TargetClosedError):
return True
text = str(error).lower()
return "cannot find session" in text or "target closed" in text or "session closed" in text
class PageDispatcher(Dispatcher):
TYPE = "Page"
#: No hand until `_build` gives it one: a page without it acts as the
@@ -2601,8 +2728,10 @@ class PageDispatcher(Dispatcher):
def __init__(self, server, context: "BrowserContextDispatcher",
session: str, target_id: str, number: int,
opener: Optional["PageDispatcher"] = None) -> None:
opener: Optional["PageDispatcher"] = None, is_gone=None) -> None:
self.context = context
#: Whether the engine has taken the target away (the adoption's record says so): every wait of the build looks at it.
self._is_gone = is_gone or (lambda: False)
#: True while `page.route()` holds this page's requests. The context
#: keeps its own flag: a request is offered to the page's handlers
#: first, and the client falls through to the context's.
@@ -2656,6 +2785,14 @@ class PageDispatcher(Dispatcher):
# replay.
self._held: Optional[List] = []
self._held_lock = threading.Lock()
#: ⛔ THE `domcontentloaded` AND `load` OF A POPUP THAT ARE SAID BEFORE IT IS ANNOUNCED. The page is built at once and announced when
#: the engine says Page.ready, which is also when its document commits, so the document may have loaded before the client hears
#: of the page: a `page.on("load")` registered in the handler of the `page` event would never fire. Playwright's own page is
#: reported after its ready and the listener hears the load. Those two states are said again right after the announcement, in
#: their order (the first time they set the state the client reads, so `wait_for_load_state` returns at once).
self._announce_lock = threading.RLock()
self._announced = False
self._said_before_announcement: List = []
self.lifecycle = Lifecycle(conn, session)
self.injected = InjectedScript(conn, session)
conn.add_listener(self._route_juggler_event)
@@ -2669,10 +2806,34 @@ class PageDispatcher(Dispatcher):
self.injected.detach()
raise
def _main_frame_unless_gone(self) -> str:
"""The main frame id, waiting for the engine to announce it - for as long as the target exists. A tab that is closed before the
engine announced its frame (a download's) never will: the wait ends at once and a frame of our own name keeps the object whole."""
waited = 0.0
while True:
try:
return self.lifecycle.wait_for_main_frame(timeout=0.1)
except TimeoutError:
waited += 0.1
if self._is_gone():
self.gone_while_building = True
return "gone-" + str(self.target_id)
if waited >= 20.0:
raise
def _build(self, server, context: "BrowserContextDispatcher",
session: str, conn, opener: Optional["PageDispatcher"]) -> None:
"""The rest of the construction, under `__init__`'s cleanup."""
self.injected.install()
# ⛔ A TARGET THAT GOES AWAY WHILE ITS PAGE IS BEING INITIALIZED (a download's empty tab, closed by the engine within milliseconds)
# makes the engine answer "cannot find session" to the command. That is the detach-before-ready case again, caught a step later:
# the page is still built, flagged gone, and announced and closed as Playwright's is - not discarded with a warning.
self.gone_while_building = False
try:
self.injected.install()
except Exception as failure:
if not _target_is_gone(failure):
raise
self.gone_while_building = True
self.actions = context.browser.actions_for_page(
session, self.lifecycle, self.injected, self.number)
#: The viewport as the client was told it (the initializer's, then
@@ -2727,10 +2888,18 @@ class PageDispatcher(Dispatcher):
#: to answer after a reader's pause, see `dialogs.plan_answer_ms`.
self._dialogs_open: Dict[str, Any] = {}
self._dialogs_seen = 0
self.main_frame_id = self.lifecycle.wait_for_main_frame(timeout=20.0)
self.main_frame_id = self._main_frame_unless_gone()
# ⛔ The Frame is created BEFORE the Page and adopted after: the Page
# initializer has to name a mainFrame the client can already resolve.
self.frame = FrameDispatcher(server, self, self.main_frame_id)
# ⛔ WITH WHAT THE LIFECYCLE ALREADY KNOWS OF IT, as every other frame is made (`frame_for`): the initializer is a snapshot, and
# a popup commits and loads on its own time - what it did between its attach and this line was heard by the lifecycle and by
# nobody that tells the client.
known = self.lifecycle.frame(self.main_frame_id)
self.frame = FrameDispatcher(
server, self, self.main_frame_id,
url=getattr(known, "url", "") or "",
name=getattr(known, "name", "") or "",
load_states=sorted(getattr(known, "states", []) or []) or None)
viewport = self.viewport_size
# `pageNumber` is ours, not Playwright's: the number the page's
# rhythms are drawn under (`pointer.py` and the actions' nonce read it
@@ -2776,6 +2945,38 @@ class PageDispatcher(Dispatcher):
def wait_until_ready(self, timeout: float = 20.0) -> None:
"""Return once the engine has said `Page.ready`; the caller announces the page to the client after it.
⛔ ANNOUNCED READY, BUT BUILT AT ONCE. Playwright's own page is reported as new on Page.ready (FFPage), and not before: the engine
commits the page's initial about:blank after the frame is announced, and a `goto` sent before that commit is 'interrupted by
another navigation to about:blank'. That is what the wait is for. It is NOT done inside the constructor, because the page has
to exist while it waits: the first request of a popup opened by a link is held by a route (the context's, the served browser's)
until the page's own routing answers it, and a popup whose commit waits for that answer never becomes ready if the page that
would answer it is not built yet. Built, the page also follows the commit and the `load` that come with its own ready; built
after them, the client would be told a frame of `about:blank` that is loaded already and never hears the `load`.
"""
self.lifecycle.wait_for_page_ready(timeout=timeout)
def announce(self, context: "BrowserContextDispatcher", replay: bool) -> None:
"""Tell the client of the page (the context's `page` event) and, for a popup, say again the load states it reached before:
under one lock, so a state said live in between waits for the ones that came first."""
with self._announce_lock:
context.emit("page", {"page": self.channel})
earlier, self._said_before_announcement = self._said_before_announcement, []
self._announced = True
if replay:
for frame, params in earlier:
if not frame.detached:
frame.emit("loadstate", params)
def settle_events(self) -> None:
"""Return once every event the engine sent before this call has been handled: its reply comes after them, on one stream."""
try:
self.conn.send("Browser.getInfo", {}, timeout=5.0)
except Exception:
pass
def _install_events(self) -> None:
"""Turn Juggler events into protocol events.
@@ -4130,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.
@@ -4358,6 +4562,7 @@ class BrowserContextDispatcher(Dispatcher):
# whose only context it is. `Browser.removeBrowserContext` on it
# would make Juggler's `destroy()` unregister the default from its
# maps and leave a browser that no command can address.
self.browser.end_waits_of(self)
for page in list(self.pages):
try:
page.announce_closed()
@@ -4380,6 +4585,7 @@ class BrowserContextDispatcher(Dispatcher):
# sets `is_closed()` and fires `page.on("close")` from that event, so
# a page belonging to a closed context stayed "open" forever, and any
# code waiting for it to close waited for good.
self.browser.end_waits_of(self)
for page in list(self.pages):
try:
page.announce_closed()
@@ -4405,8 +4611,12 @@ class BrowserDispatcher(Dispatcher):
conn: Any, version: str, session_seed: Any = None,
motion_budget_s: Any = None,
service_workers_enabled: bool = True,
layout: str = "us", pointer_draws: bool = False) -> None:
layout: str = "us", pointer_draws: bool = False,
udp_stun_servers: Optional[list] = None) -> None:
self.conn = conn
#: Where this session measures a proxy's UDP exit from (the launch's `udp_stun_servers`, "ip:port"
#: strings; None = the two public defaults): the launch and every context proxy use the same list.
self.udp_stun_servers = udp_stun_servers
#: Whether this browser's pages walk the pointer onto their targets
#: (`pointer.py`): the launcher chose the Python generator. Off for a
#: browser built without saying so, which acts as the caller wrote.
@@ -4484,19 +4694,22 @@ class BrowserDispatcher(Dispatcher):
# constructor has fully run.
self._targets_lock = threading.Lock()
self._page_targets: Dict[str, PageDispatcher] = {}
#: Targets whose adoption thread is still building. `op_new_page`
#: waits on these instead of building a second dispatcher.
self._adopting: set = set()
#: Every target between its attach and its announcement, by id, ONE record each (`_Adoption`): where it is (attached, building,
#: waiting for its ready, announced), whether the engine took it away, its page, its opener. `op_new_page` waits on these
#: instead of building a second dispatcher; a download of a tab not announced yet is attributed through it.
self._adoptions: Dict[str, _Adoption] = {}
#: The last 16 targets that were NOT announced (dropped with their context, or failed), with their trace: for whoever looks.
self._dropped: "collections.deque" = collections.deque(maxlen=16)
#: The opener of the targets whose adoption ended WITHOUT announcing them while the engine still had the target (at most the last
#: 16): a download that comes after the record is gone is still said on the opener (it is never lost, whichever step of the
#: adoption it falls between). The entry lives until the engine detaches the target (`_handle_detach`), and none is made for a
#: target already detached: no download can come from it any more.
self._gone_openers: "collections.OrderedDict" = collections.OrderedDict()
#: Adoption failures, by target. The `newPage` waiter re-raises (and
#: pops) them; capped because a spontaneous popup nobody waits for
#: must not grow this for the life of the browser.
self._adopt_errors: Dict[str, Exception] = {}
#: Targets detached BEFORE their adoption finished (a popup closed
#: faster than it attached). The adoption still emits `page` first and
#: the close right after, so the client always sees them in order.
#: Ending the page - registries, session, listeners - is
#: `announce_closed`'s job alone: see `_page_over`.
self._detached_early: set = set()
#: Ending the page - registries, session, listeners - is `announce_closed`'s job alone: see `_page_over`.
#: ⛔ HOW A NEW TARGET LEARNS ITS PAGE NUMBER (see `_spawn_adoption`).
#: `Browser.newPage` requests sent and not yet answered, by context;
#: and the number each answered request named for its target, until
@@ -4531,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
@@ -4613,6 +4832,12 @@ class BrowserDispatcher(Dispatcher):
self._pages_ready.wait(left)
def _route_browser_event(self, method: str, params: Dict, session) -> None:
if session and method in _Adoption.TRACED:
with self._targets_lock:
for adoption in self._adoptions.values():
if adoption.session == session:
adoption.note(method.split(".", 1)[1])
break
if method == "Browser.attachedToTarget":
info = params.get("targetInfo") or {}
with self._sessions_ready:
@@ -4702,10 +4927,10 @@ class BrowserDispatcher(Dispatcher):
with self._targets_lock:
if not self._adopt_enabled:
return
if target_id in self._page_targets or target_id in self._adopting:
if target_id in self._page_targets or target_id in self._adoptions:
return
self._adopting.add(target_id)
opener = self._page_targets.get(opener_id) if opener_id else None
self._adoptions[target_id] = _Adoption(target_id, opener, browser_context_id, session_id)
if opener is not None:
opener.popups_opened += 1
number: Optional[int] = popup_number(opener.number,
@@ -4722,44 +4947,141 @@ class BrowserDispatcher(Dispatcher):
daemon=True, name="invpw-adopt-%s" % target_id[:8])
thread.start()
# ── the states of an adoption: the ONLY places a record changes state. Each is one method so that a test can stop the adoption thread
# between any two of them and deliver an event of the engine there.
def _enter_building(self, adoption: "_Adoption", requested: bool) -> None:
with self._targets_lock:
adoption.requested = requested
adoption.state = "building"
adoption.note("building")
def _enter_waiting(self, adoption: "_Adoption", page: "PageDispatcher") -> bool:
"""The page is built and is registered as waiting for its ready. Returns whether the engine took the target away meanwhile - the
detach that came before this line found no page to tell, and a wait now would be for ever."""
with self._targets_lock:
adoption.page = page
adoption.state = "waiting"
adoption.note("waiting" + (" (gone while building)" if page.gone_while_building else ""))
return adoption.gone or page.gone_while_building
def _enter_announced(self, adoption: "_Adoption", page: "PageDispatcher", context: "BrowserContextDispatcher") -> Tuple[bool, List]:
"""The client is told of the page, and the page is registered. Returns whether the engine took the target away before this
point (the close is announced right after the page, so the client always sees the page before its close) and the downloads that
waited for the page to be announced."""
page.announce(context, replay=not adoption.requested)
with self._targets_lock:
adoption.state = "announced"
adoption.note("announced" + (" (gone)" if adoption.gone else ""))
gone = adoption.gone
self._adoptions.pop(adoption.target_id, None)
pending = self._take_downloads(adoption)
self._page_targets[adoption.target_id] = page
context.pages.append(page)
self._pages_ready.notify_all()
return gone, pending
def _remember_opener(self, adoption: Optional["_Adoption"]) -> None:
"""Under `_targets_lock`, in the step that removes the record of a target that is NOT announced."""
if adoption is not None and adoption.opener is not None and not adoption.gone:
self._gone_openers[adoption.target_id] = adoption.opener
while len(self._gone_openers) > 16:
self._gone_openers.popitem(last=False)
@staticmethod
def _take_downloads(adoption: Optional["_Adoption"]) -> List:
"""The downloads that waited for the tab to be announced, taken IN THE SAME STEP (under `_targets_lock`) as the removal of the record: a
download that arrives after that step finds no record and is said at once, one that arrived before is in this list - none can fall
between the two and be queued for nobody."""
if adoption is None:
return []
pending, adoption.downloads = adoption.downloads, []
return pending
@staticmethod
def _say_downloads(pending: List) -> None:
"""Say them on the opener, in order (never lost: also when the tab is dropped or its adoption fails)."""
for origin, payload in pending:
try:
origin.emit("download", payload)
except Exception:
pass
def _adopt_target(self, target_id: str, session_id: Optional[str],
browser_context_id: Optional[str],
opener: Optional[PageDispatcher],
number: Optional[int]) -> None:
"""Build the `PageDispatcher` for one engine target, then announce it.
"""Build the `PageDispatcher` for one engine target, then announce it, along the states of its `_Adoption`.
A popup goes through EXACTLY the same construction as a `newPage`
page - lifecycle, injected script, buffered-event replay, cursor acts -
so it behaves like any other page and carries no observable marker of
how it was opened. Stealth is preserved by doing nothing special.
⛔ A PAGE A CALLER ASKED FOR (`Browser.newPage`) WAITS AT MOST 20 s FOR ITS Page.ready, AND FAILS LOUDLY; A POPUP WAITS AS LONG AS
THE ENGINE TAKES, AND SAYS NOTHING. That is Playwright's own: its popup is reported on Page.ready and not before, with no limit - a
destination that answers 204 or never answers gives no `page` event at all (measured, stock Playwright 1.62 and its Firefox: none in
30 s), one that answers after 25 s gives it at 25 s. The wait ends when the target goes away or its context closes.
"""
with self._targets_lock:
adoption = self._adoptions.get(target_id)
page = None
requested = number is None
try:
self._enter_building(adoption, requested)
if number is None:
number = self._number_of_requested(
target_id, browser_context_id, timeout=60.0)
session = session_id or self.session_for(target_id, timeout=20.0)
context = self._context_for_popup(browser_context_id)
page = PageDispatcher(self.server, context, session, target_id,
number, opener=opener)
# ⛔ `page` BEFORE the registration, on purpose. A detach racing
# this build is recorded as early (see `_handle_detach`) and the
# close is announced right after, so the client always sees the
# page before its close - never a close for a page it has not met.
context.emit("page", {"page": page.channel})
with self._targets_lock:
self._adopting.discard(target_id)
self._page_targets[target_id] = page
context.pages.append(page)
early = target_id in self._detached_early
if early:
self._detached_early.discard(target_id)
self._pages_ready.notify_all()
if early:
number, opener=opener, is_gone=lambda: adoption.gone)
gone = self._enter_waiting(adoption, page)
try:
if not gone:
page.wait_until_ready(timeout=20.0 if requested else None)
except TimeoutError as late:
raise TimeoutError("%s [%s]" % (late, adoption.trace_text())) from None
except juggler.TargetClosedError:
# Gone before it was ready (a download's empty tab, a popup the site closed at once): announced and closed right
# after, as Playwright's is.
gone = True
if gone and not requested and context.disposed:
# Its context closed while it waited for a ready that never came: it was never announced and is not now.
page.announce_closed()
with self._targets_lock:
adoption.note("dropped: its context closed")
self._dropped.append((target_id, adoption.trace_text()))
self._adoptions.pop(target_id, None)
self._remember_opener(adoption)
pending = self._take_downloads(adoption)
self._pages_ready.notify_all()
self._say_downloads(pending)
return
# ⛔ THE EVENTS THAT COME WITH THE READY ARE APPLIED FIRST. The engine says Page.ready and, in the same turn, the commit of
# the document that made the page ready: announced between the two, the page tells its client `about:blank` (3 of 4 popups
# to a slow destination, measured) where Playwright's says the destination. A round trip to the engine comes back after
# everything it sent before it.
page.settle_events()
# ⛔ `page` BEFORE the registration, on purpose: the client always sees the page before its close, never a close for a page it
# has not met.
gone_at_announce, pending = self._enter_announced(adoption, page, context)
self._say_downloads(pending)
if gone_at_announce:
page.announce_closed()
except Exception as failure:
if page is not None:
# Built and never announced (not ready in time): its listeners and its object on the client go.
try:
page.announce_closed()
except Exception:
pass
with self._targets_lock:
self._adopting.discard(target_id)
self._detached_early.discard(target_id)
trace = adoption.trace_text() if adoption is not None else "no record of the target"
self._dropped.append((target_id, trace))
self._adoptions.pop(target_id, None)
self._remember_opener(adoption)
pending = self._take_downloads(adoption)
failure = _with_trace(failure, trace)
self._adopt_errors[target_id] = failure
while len(self._adopt_errors) > 64:
self._adopt_errors.pop(next(iter(self._adopt_errors)))
@@ -4774,6 +5096,7 @@ class BrowserDispatcher(Dispatcher):
except Exception:
pass
self._pages_ready.notify_all()
self._say_downloads(pending)
try:
if session_id:
self.forget(session_id)
@@ -4821,17 +5144,48 @@ class BrowserDispatcher(Dispatcher):
"Browser.attachedToTarget for it" % (target_id, timeout))
self._pages_ready.wait(left)
def end_waits_of(self, context: "BrowserContextDispatcher") -> None:
"""A context is closing: every target of it still on its way to the client is taken away (`gone`, in whichever state it is) and
the pages that already wait for a Page.ready that never came stop waiting."""
with self._targets_lock:
waiting = []
for a in self._adoptions.values():
if a.context_id == context.context_id:
a.gone = True
if a.state == "waiting" and a.page is not None:
waiting.append(a.page)
for page in waiting:
try:
page.lifecycle.detach()
except Exception:
pass
def _handle_detach(self, target_id: Optional[str],
session_id: Optional[str]) -> None:
"""The engine reports a target gone: an engine-side close (or a popup
that died before it finished attaching). Never blocks the reader."""
"""The engine reports a target gone: an engine-side close (or a popup that died before it finished attaching). Never blocks the
reader.
A target still on its way to the client (attached, building or waiting for its ready) only gets `gone` set on its record, and a
page that is already waiting is told: its wait ends. The adoption thread does the rest, in whichever state it is - there is no
state in which this event is lost."""
if not target_id:
return
waiting = None
with self._targets_lock:
# The target is gone: nothing comes from it any more, so the opener kept for its downloads goes too.
self._gone_openers.pop(target_id, None)
adoption = self._adoptions.get(target_id)
if adoption is not None:
adoption.gone = True
adoption.note("detach seen in state " + adoption.state)
if adoption.state == "waiting":
waiting = adoption.page
page = self._page_targets.get(target_id)
if page is None and target_id in self._adopting:
self._detached_early.add(target_id)
return
if adoption is not None:
if waiting is not None:
# Built and waiting for its Page.ready: the wait ends now (TargetClosedError) and the adoption announces the page closed.
waiting.lifecycle.detach()
return
if page is None:
# A target that never became a page: only its buffered events
# and its session entry are left to drop.
@@ -5016,7 +5370,13 @@ class BrowserDispatcher(Dispatcher):
# a context whose proxy cannot be expressed must not come back usable.
if params.get("proxy"):
try:
proxy = parse_proxy(params["proxy"]).as_engine_command()
# ⛔ MEASURED BEFORE IT IS SENT. The proxy's UDP exit (does its UDP leave from the address of its TCP?)
# travels in this very command, as `udp`, and without it the engine drops the UDP of every SOCKS5
# proxy. The core discovers the TCP exit through the proxy and measures the UDP beside it, once per
# proxy (cached by endpoint, a hash of the credentials and the servers), from the STUN servers the
# SESSION was launched with: this is the ONE place a context's proxy is applied, for the sync and
# async clients and for a remote one alike. A `udp` key in what the caller wrote is not read.
proxy = context_proxy_command(params["proxy"], self.udp_stun_servers)
except ValueError as exc:
raise ProtocolException(
"new_context(proxy=...) cannot be applied: %s" % exc)
@@ -5120,15 +5480,30 @@ class BrowserDispatcher(Dispatcher):
def _on_download_created(self, params: Dict) -> None:
context = next((c for c in self.contexts
if c.context_id == params.get("browserContextId")), None)
page = self._page_targets.get(params.get("pageTargetId"))
target = params.get("pageTargetId")
with self._targets_lock:
announced = self._page_targets.get(target)
adoption = self._adoptions.get(target)
# The page whose frame the download came from: announced, or built and waiting for its Page.ready.
page = announced or (adoption.page if adoption is not None else None)
# ⛔ THE PAGE THE DOWNLOAD IS REPORTED ON. A download that starts in a new tab (a `target=_blank` link or a `window.open` to a
# `Content-Disposition: attachment`) comes from a tab the client has not been told of: the tab waits for a Page.ready that never
# comes and is closed by the engine at once. Playwright reports it on the OPENER in that case (ffBrowser._onDownloadCreated:
# "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:
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
# a `goto` or a click waiting on it waited out its timeout.
@@ -5137,7 +5512,7 @@ class BrowserDispatcher(Dispatcher):
# starting')); the lifecycle is fed the same abort. A frame whose
# current navigation already committed is left alone: the
# download came from a click or a script, not from a load.
frame = page.lifecycle.frame(params.get("frameId"))
frame = page.lifecycle.frame(params.get("frameId")) if page is not None else None
if (frame is not None and frame.navigation
and frame.navigation not in frame.aborted
and not any(c[1] == frame.navigation
@@ -5145,19 +5520,48 @@ class BrowserDispatcher(Dispatcher):
page.lifecycle._on_event("Page.navigationAborted", {
"frameId": frame.id, "navigationId": frame.navigation,
"errorText": "Download is starting"})
page.emit("download", {"url": params.get("url") or "",
"suggestedFilename": params.get("suggestedFileName") or "",
"artifact": artifact.channel})
if early is not None:
if origin is not None:
payload = {"url": params.get("url") or "",
"suggestedFilename": params.get("suggestedFileName") or "",
"artifact": artifact.channel}
deferred = False
with self._targets_lock:
# ⛔ AFTER THE `page` EVENT OF THE TAB, NOT BEFORE IT. The download of a tab that is not announced yet is said on its
# opener, and the tab is announced a few milliseconds after the engine says the download (the adoption thread announces
# it when the tab goes away): said at once, the client got the download first and the popup after, the order the
# other way round from Playwright's, and a client that reads the popup the moment the download arrives found none
# on a loaded machine.
if announced is None and adoption is not None and self._adoptions.get(target) is adoption:
adoption.downloads.append((origin, payload))
deferred = True
if not deferred:
origin.emit("download", payload)
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
@@ -5308,6 +5712,8 @@ class BrowserTypeDispatcher(Dispatcher):
# `conn.close` has waited for the browser to exit.
launch_prefs, session_env = session_for_launch(
params.get("firefoxUserPrefs") or {}, executable, params.get("proxy"))
# Read BEFORE `take_session_motion` takes it out: it never reaches the profile.
udp_stun_servers = session_udp_stun_servers(launch_prefs)
environment = _launch_environment(params.get("env"))
named = {e["name"] for e in params.get("env") or []}
environment.update({k: v for k, v in session_env.items() if k not in named})
@@ -5358,7 +5764,9 @@ class BrowserTypeDispatcher(Dispatcher):
proxy = None
if params.get("proxy"):
try:
proxy = parse_proxy(params["proxy"]).as_engine_command()
# The measure is the one the launch's geo step remembered for this proxy and these servers (nothing is
# asked of the network here): `unmeasured` when there is none, never a claimed `coherent`.
proxy = launch_proxy_command(params["proxy"], udp_stun_servers)
except ValueError as exc:
raise ProtocolException("launch(proxy=...) cannot be applied: "
"%s" % exc)
@@ -5387,7 +5795,8 @@ class BrowserTypeDispatcher(Dispatcher):
# The persona's keyboard: the one a Windows install gives the
# session's language in its country (German in Switzerland
# types on the Swiss keyboard).
layout=keyboard_layout, pointer_draws=pointer_draws)
layout=keyboard_layout, pointer_draws=pointer_draws,
udp_stun_servers=udp_stun_servers)
except BaseException:
conn.close()
raise
+55 -9
View File
@@ -26,7 +26,7 @@ from ._cursor import (ENGINE_BINARY,
enable_for as _enable_cursor_engine,
max_seconds_for as _cursor_max_seconds)
from ._engine import resolve_executable
from ._juggler.server import COMPOSED_PREF, MOTION_BUDGET_PREF, POINTER_PREF, SESSION_SEED_PREF
from ._juggler.server import COMPOSED_PREF, MOTION_BUDGET_PREF, POINTER_PREF, SESSION_SEED_PREF, UDP_STUN_PREF
from typing import Any, Dict, Optional
from invisible_core import compose_session_prefs, context_geometry, make_virtual_display
@@ -65,11 +65,22 @@ __all__ = ["build_prefs", "true_headless_requested", "TRUE_HEADLESS_ENV",
TRUE_HEADLESS_ENV = "INVPW_TRUE_HEADLESS"
def session_geo(timezone: str, proxy: Optional[Dict[str, str]], locale: Any):
def udp_stun_list(servers: Optional[Any]) -> Optional[list]:
"""The `udp_stun_servers=` of a launch, validated by the core ("ip:port" IPv4 literals; a name or a bad port
raises ValueError naming the parameter) and normalised to "ip:port" strings; None for the two public defaults."""
if servers is None:
return None
from invisible_core._udp_exit import stun_servers
return ["%s:%d" % server for server in stun_servers(servers)]
def session_geo(timezone: str, proxy: Optional[Dict[str, str]], locale: Any,
seed: Optional[int] = None):
"""`invisible_core.prepare_session_geo`, the one network step of composing a
session (the egress IP). One name, so a hermetic test replaces it alone."""
session (the egress IP). One name, so a hermetic test replaces it alone.
The seed places the session on the map (the declared position)."""
from invisible_core import prepare_session_geo
return prepare_session_geo(timezone, proxy, locale)
return prepare_session_geo(timezone, proxy, locale, seed=seed)
def default_session(executable: Optional[str] = None,
@@ -83,8 +94,10 @@ def default_session(executable: Optional[str] = None,
What `server.session_for_launch` gives a launch that names no session."""
from .launcher import InvisiblePlaywright
session = InvisiblePlaywright(binary_path=executable, humanize=False, proxy=proxy or None)
geo = session_geo(session._timezone, session._proxy, session._locale_requested)
geo = session_geo(session._timezone, session._proxy, session._locale_requested,
seed=session.seed)
session._timezone, session._locale = geo.timezone, geo.locale
session._geolocation = geo.geolocation_override()
prefs = session._build_prefs()
env = build_env(network_declared=declared_network(session), profile=session._profile,
executable=executable, base_env={})
@@ -185,6 +198,8 @@ def build_prefs(
humanize: Any,
show_cursor: Optional[bool] = None,
session_seed: Optional[int] = None,
udp_stun_servers: Optional[Any] = None,
preload_newtab: Optional[bool] = None,
) -> Dict[str, Any]:
"""Fingerprint prefs plus the humanize toggle, which is always set explicitly.
@@ -232,6 +247,9 @@ def build_prefs(
humanize=(_cursor_max_seconds(humanize)
if cursor_engine == ENGINE_BINARY else False),
show_cursor=show_cursor,
# Handed to the core only when asked: a core that does not know the option is never called with it,
# so a caller who does not use it cannot meet a TypeError from a pairing with an older core.
**({} if preload_newtab is None else {"preload_newtab": preload_newtab}),
).prefs
# ⛔ THE TYPING SEED RIDES IN THE PREFS AND NEVER REACHES THE PROFILE.
#
@@ -268,6 +286,10 @@ def build_prefs(
# The persona's keyboards are in the prefs already: the core declares them
# with the language and country (invisible_core.prefs._apply_locale).
prefs[COMPOSED_PREF] = True
# ⛔ THE STUN SERVERS OF THE UDP-EXIT MEASUREMENT ride here for the server only (`UDP_STUN_PREF`): `op_launch`
# takes the key out before the profile is written, as it does the seed. Not written when the launch named none.
if udp_stun_servers:
prefs[UDP_STUN_PREF] = ",".join(udp_stun_servers)
if session_seed is not None and humanize:
prefs[SESSION_SEED_PREF] = int(session_seed)
prefs[POINTER_PREF] = cursor_engine == ENGINE_PYTHON
@@ -303,9 +325,9 @@ class ProxyEgressNonVerificabile(RuntimeError):
This is not drift and it is not parity: it is absence of measurement. A
proxy that does not answer the probe for several checks in a row is not a
proxy that holds, it is a proxy we are flying blind on while the engine
keeps declaring to every page an address that nobody is confirming any
more.
proxy that holds, it is a proxy we are flying blind on while the timezone
and the locale, decided from the egress at launch, go on being declared
to every page with nobody confirming the egress they came from any more.
"""
@@ -386,9 +408,21 @@ class CommonLaunch:
`_lifetime_guard`, `_locale` (the core's SessionLocale, None until
`__enter__` decides it), `_profile`, `_session_token`, `_show_cursor`,
`_network_declared`, `_timezone` and `_virtual_display` in their own
`__init__`. They already did, identically, which is why this works at all.
`__init__`; `_geolocation` (the position the session declares, the
``geolocation`` object of a context, None until `__enter__` decides it
and when the exit has no point) is the class default below. They already did, identically, which is why this works at all.
"""
#: The position this session declares to the engine
#: (``SessionGeo.geolocation_override()``: latitude, longitude, accuracy),
#: or None. Set by `__enter__` from the egress, like `_timezone`.
_geolocation: Optional[Dict[str, float]] = None
#: Where this session measures a SOCKS5 proxy's UDP exit from: the ``udp_stun_servers=`` of the launch, as
#: "ip:port" strings (validated by the core), or None for the two public defaults. Kept on the session so the
#: launch geo step and the browser's later context proxies use the same list.
_udp_stun_servers: Optional[list] = None
def _resolve_headless(self) -> bool:
"""Translate the user's ``headless`` flag.
@@ -444,6 +478,16 @@ class CommonLaunch:
# None before __enter__ has decided.
if self._locale is not None:
kwargs["locale"] = self._locale.primary
# The position the core declares for this machine. It travels as the
# standard `geolocation` context option, so the engine gets
# `Browser.setGeolocationOverride` for EVERY context (the default one
# and each `new_context`/`new_page`), a caller's own `geolocation=`
# wins like any other default, and the PERMISSION is not granted here:
# the page's grant (the caller's `grant_permissions`) is what makes the
# engine answer. The override belongs to each context (Juggler keys it
# by `browserContextId`), so a context that closes takes its own with it.
if self._geolocation is not None:
kwargs["geolocation"] = dict(self._geolocation)
return kwargs
def _build_env(self, prefs: Dict[str, Any]) -> Dict[str, str]:
@@ -482,6 +526,8 @@ class CommonLaunch:
humanize=self._humanize,
show_cursor=self._show_cursor,
session_seed=self.seed,
udp_stun_servers=self._udp_stun_servers,
preload_newtab=self._preload_newtab,
)
def _arm_cursor_engine(self, owner: Any) -> None:
+10 -2
View File
@@ -4,7 +4,7 @@ from __future__ import annotations
import asyncio
import time
from pathlib import Path
from typing import Any, Dict, Optional, Union
from typing import Any, Dict, Optional, Sequence, Union
from invisible_playwright._pw.async_api import Browser, BrowserContext, Playwright, async_playwright
from invisible_playwright._pw._impl._browser_context import page_number_reserved
@@ -37,6 +37,8 @@ class InvisiblePlaywright(_session.CommonLaunch):
profile_dir: Optional[Union[str, Path]] = None,
prep_recaptcha: bool = False,
show_cursor: Optional[bool] = None,
udp_stun_servers: Optional[Sequence[str]] = None,
preload_newtab: Optional[bool] = None,
) -> None:
# See sync launcher: `zoom.stealth.fpp.hw_seed` is int32_t - clamp.
# One place decides the seed, and a profile directory remembers it
@@ -45,6 +47,8 @@ class InvisiblePlaywright(_session.CommonLaunch):
self._pin = pin
self._headless = headless
self._proxy = proxy
# See the sync launcher: validated now, kept for the launch and for every context proxy.
self._udp_stun_servers = _session.udp_stun_list(udp_stun_servers)
self._extra_args = list(extra_args or [])
self._humanize = humanize
# See the sync launcher: who draws the cursor path (this package by
@@ -59,6 +63,8 @@ class InvisiblePlaywright(_session.CommonLaunch):
# it.
self._show_cursor = (None if show_cursor is None
else bool(show_cursor))
self._preload_newtab = (None if preload_newtab is None
else bool(preload_newtab))
# What the caller ASKED for: "auto" or a tag. The decision is the
# core's, made in __enter__ from the egress (prepare_session_geo),
# and there is none before it.
@@ -109,11 +115,13 @@ class InvisiblePlaywright(_session.CommonLaunch):
# session keeps the core's DECISION (a SessionLocale). See the sync
# launcher.
_geo = await asyncio.to_thread(
prepare_session_geo, self._timezone, self._proxy, self._locale_requested
prepare_session_geo, self._timezone, self._proxy, self._locale_requested,
seed=self.seed, udp_stun_servers=self._udp_stun_servers,
)
self._timezone = _geo.timezone
self._locale = _geo.locale
self._webrtc_egress_ip = _geo.egress_ip
self._geolocation = _geo.geolocation_override()
# binary_path= never reaches ensure_binary(), so the engine check lives
# on the resolved executable rather than inside the fetcher.
executable = resolve_executable(self._binary_path)
+19 -2
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
import time
from pathlib import Path
from typing import Any, Dict, Optional, Union
from typing import Any, Dict, Optional, Sequence, Union
from invisible_playwright._pw.sync_api import Browser, BrowserContext, Playwright, sync_playwright
@@ -101,6 +101,8 @@ class InvisiblePlaywright(_session.CommonLaunch):
profile_dir: Optional[Union[str, Path]] = None,
prep_recaptcha: bool = False,
show_cursor: Optional[bool] = None,
udp_stun_servers: Optional[Sequence[str]] = None,
preload_newtab: Optional[bool] = None,
) -> None:
"""
Args:
@@ -157,6 +159,13 @@ class InvisiblePlaywright(_session.CommonLaunch):
page = ctx.new_page()``. First run creates the dir;
subsequent runs reuse it. Pair with a stable ``seed=`` to
also pin the fingerprint identity across runs.
preload_newtab: The New Tab page a retail Firefox keeps preloaded in a
process of its own (about 200 MB, and a Mozilla site's process
beside it). Default ``None``: the core writes nothing and the
retail's behaviour stays. ``False`` is a declaration of yours:
the core writes ``browser.newtab.preload`` false and neither
process is born. ``True`` says the retail's value aloud. A
``browser.newtab.preload`` in ``extra_prefs`` wins over it.
show_cursor: Draw the pointer where the automation is, so a
person watching the screen can follow the session - the
Windows arrow, with the package logo's green halo around it.
@@ -185,6 +194,10 @@ class InvisiblePlaywright(_session.CommonLaunch):
self._pin = pin
self._headless = headless
self._proxy = proxy
# Where a SOCKS5 proxy's UDP exit is measured from ("ip:port" IPv4 literals; None = the two public
# defaults). Validated now, kept on the session for the launch AND for every context proxy; a parameter of
# this Python launch only: nothing of it is put in the browser's environment, argv, prefs or pipe.
self._udp_stun_servers = _session.udp_stun_list(udp_stun_servers)
self._extra_args = list(extra_args or [])
self._humanize = humanize
# Who draws the cursor path: this package (default), the browser
@@ -205,6 +218,8 @@ class InvisiblePlaywright(_session.CommonLaunch):
# it.
self._show_cursor = (None if show_cursor is None
else bool(show_cursor))
self._preload_newtab = (None if preload_newtab is None
else bool(preload_newtab))
# What the caller ASKED for: "auto" or a tag. The decision is the
# core's, made in __enter__ from the egress (prepare_session_geo),
# and there is none before it.
@@ -257,10 +272,12 @@ class InvisiblePlaywright(_session.CommonLaunch):
# The language is decided in the same call, from the same egress: the
# core resolves "auto" and applies Firefox's language table, and this
# session keeps the DECISION (a SessionLocale), never a tag of its own.
_geo = prepare_session_geo(self._timezone, self._proxy, self._locale_requested)
_geo = prepare_session_geo(self._timezone, self._proxy, self._locale_requested,
seed=self.seed, udp_stun_servers=self._udp_stun_servers)
self._timezone = _geo.timezone
self._locale = _geo.locale
self._webrtc_egress_ip = _geo.egress_ip
self._geolocation = _geo.geolocation_override()
# binary_path= never reaches ensure_binary(), so the engine check lives
# on the resolved executable rather than inside the fetcher.
executable = resolve_executable(self._binary_path)
+164 -31
View File
@@ -2,18 +2,23 @@
Hermetic: loopback only, no DNS, no internet. Nothing here knows about the product.
What a proxied session declares (core-19) is that every name the browser resolves goes to the DoH of Firefox
(``network.trr.mode`` 3), at ``https://mozilla.cloudflare-dns.com/dns-query``, found with no DNS at the address
``network.trr.bootstrapAddr`` (162.159.61.4), and that the DoH request is a channel like any other, so it leaves
THROUGH the proxy of the context of the lookup. A test of that needs three things this file builds:
What the core declares (core-19), for every session, is the DoH of Firefox at
``https://mozilla.cloudflare-dns.com/dns-query``, found with no DNS at the address ``network.trr.bootstrapAddr``
(162.159.61.4). A test does NOT impersonate that host: Firefox refuses a certificate override for an HSTS-preloaded or
pinned host (``mozilla.cloudflare-dns.com`` is one), so a self-signed certificate for it can never be accepted, whatever
``ignore_https_errors`` says. The test declares its own provider instead, through the core's ``extra_prefs`` overlay:
``network.trr.uri`` = ``https://doh.gateway.test/dns-query`` (a ``.test`` name, never preloaded) and
``network.trr.bootstrapAddr`` = ``192.0.2.53`` (TEST-NET-1, so nothing real is addressed). With a proxy the engine turns it on (``network.trr.mode`` 3, derived from the proxies it receives, never
written by the core), so every name the browser resolves goes to it; the DoH request is a channel like any other, so it
leaves THROUGH the proxy of the context of the lookup. A test of that needs three things this file builds:
* :class:`FakeDoh` - the DoH server. RFC 8484 (POST ``application/dns-message`` and GET ``?dns=base64url``) over TLS
with a certificate for ``mozilla.cloudflare-dns.com`` and ``127.0.0.1``, written by hand: the question is parsed from
with a certificate for ``doh.gateway.test`` and ``127.0.0.1``, written by hand: the question is parsed from
its labels and the answer is built byte by byte (header, the question copied, one A record, TTL 30). It answers
HTTP/2 when the ``h2`` package is importable and ALPN selects it (Firefox's TRR speaks h2), HTTP/1.1 otherwise.
Every query is recorded as ``(name, qtype, via)``.
* :class:`DohGateway` - a SOCKS5 gateway (the ``Gateway`` of ``_socks_servers``) whose CONNECT to the DoH address
(``162.159.61.4:443``, or ``mozilla.cloudflare-dns.com:443`` by name) is handed to the FakeDoh of the test, with the
(``192.0.2.53:443``, or ``doh.gateway.test:443`` by name) is handed to the FakeDoh of the test, with the
gateway's name as ``via``; every other CONNECT to a loopback address is relayed for real. It never resolves a name
itself and never reaches a non-loopback address: a CONNECT that asks for one is refused and recorded, so a test run
cannot leak anything and cannot be mistaken for leaking.
@@ -42,22 +47,29 @@ from _socks_servers import EXIT, Gateway, WEB_NAME, WHOAMI4, WHOAMI6
try: # the HTTP/2 side needs it; a test that wants h2 says pytest.importorskip("h2")
import h2.config
import h2.connection
import h2.errors
import h2.events
import h2.exceptions
H2_AVAILABLE = True
except ImportError: # pragma: no cover - depends on the environment
H2_AVAILABLE = False
#: The host name of the DoH the session declares, and the address it is found at without DNS.
DOH_HOST = "mozilla.cloudflare-dns.com"
DOH_BOOTSTRAP = "162.159.61.4"
#: The host name of the DoH the TEST declares (``network.trr.uri``) and the address it is found at without DNS
#: (``network.trr.bootstrapAddr``). Not the core's default provider: that host is HSTS-preloaded/pinned, so Firefox
#: refuses any certificate override for it and a fake could never be accepted. A ``.test`` name is on no preload list;
#: 192.0.2.0/24 is TEST-NET-1 (RFC 5737), reserved for documentation, so the address cannot reach anything real.
DOH_HOST = "doh.gateway.test"
DOH_BOOTSTRAP = "192.0.2.53"
DOH_PORT = 443
DOH_PATH = "/dns-query"
#: The two prefs that make a session use the FakeDoh as its provider (applied with ``extra_prefs``).
DOH_PROVIDER_PREFS = {"network.trr.uri": "https://%s%s" % (DOH_HOST, DOH_PATH),
"network.trr.bootstrapAddr": DOH_BOOTSTRAP}
#: Every CONNECT target the gateways hand to the FakeDoh.
DOH_TARGETS = frozenset({(DOH_BOOTSTRAP, DOH_PORT), (DOH_HOST, DOH_PORT)})
QTYPE_A, QTYPE_AAAA = 1, 28
RCODE_OK, RCODE_NXDOMAIN, RCODE_REFUSED = 0, 3, 5
QTYPE_A, QTYPE_AAAA, QTYPE_HTTPS = 1, 28, 65
RCODE_OK, RCODE_SERVFAIL, RCODE_NXDOMAIN, RCODE_REFUSED = 0, 2, 3, 5
DOH_TTL = 30
@@ -162,7 +174,7 @@ def make_certificate(directory: Path, dns_names: Tuple[str, ...] = (DOH_HOST,),
_REASONS = {200: "OK", 400: "Bad Request", 404: "Not Found", 405: "Method Not Allowed",
415: "Unsupported Media Type"}
415: "Unsupported Media Type", 503: "Service Unavailable"}
class DohQuery(NamedTuple):
@@ -171,6 +183,33 @@ class DohQuery(NamedTuple):
via: str
#: The ways :class:`FakeDoh` can refuse a query (``fail_first``). All three are failures of the lookup for Firefox's TRR:
#: ``close`` ends the exchange with no answer (an h2 stream reset, or a closed connection over HTTP/1.1): a failure of
#: the CHANNEL, the kind ``TRRService::ConfirmationContext::RecordTRRStatus`` counts (``NS_FAILED(channelStatus)``);
#: ``http503`` answers an HTTP error (``TRR_SERVER_RESPONSE_ERR``); ``servfail`` answers a well-formed DNS message with
#: rcode 2 (``TRR_RCODE_FAIL``).
FAILURE_KINDS = ("close", "http503", "servfail")
class DohAnswer(NamedTuple):
"""What the FakeDoh did with one query: ``outcome`` is ``"answered"`` or a failure kind, ``delay`` the seconds
between the arrival of the query and the moment its answer (or its refusal) was sent."""
name: str
qtype: int
via: str
outcome: str
delay: float
class _Reply(NamedTuple):
status: int
body: bytes
content_type: str
delay: float = 0.0
close: bool = False # no answer at all: reset the stream / close the connection
record: Optional[Tuple[str, int, str, str]] = None # (name, qtype, via, outcome), logged when it is sent
class FakeDoh:
"""A DoH server on 127.0.0.1 (its own port, ``via`` ``"direct"``) that also serves any socket a gateway hands it.
@@ -179,11 +218,32 @@ class FakeDoh:
package is importable.
"""
def __init__(self, names: Optional[Dict[str, str]] = None, *, h2: Optional[bool] = None):
def __init__(self, names: Optional[Dict[str, str]] = None, *, h2: Optional[bool] = None,
delay_s: float = 0.0, delay_names: Optional[Dict[str, float]] = None,
fail_first: Optional[Dict[str, str]] = None):
self.names: Dict[str, str] = {k.lower(): v for k, v in (names or {}).items()}
self.offers_h2 = H2_AVAILABLE if h2 is None else (h2 and H2_AVAILABLE)
#: Latency of EVERY answer, in seconds (each response is held that long after its query arrived, not only the
#: connection set-up); ``delay_names`` overrides it per name (a name or any name under it). Both can be changed
#: while the server runs. Over h2 the answers are held independently, so the A and the AAAA of one lookup come
#: back together after the delay, not one after the other.
self.delay_s = delay_s
self.delay_names: Dict[str, float] = {k.lower().rstrip("."): v for k, v in (delay_names or {}).items()}
#: ``{name: kind}`` (kind in :data:`FAILURE_KINDS`): the FIRST query of each type (A, AAAA...) for ``name`` is
#: refused in that way; every later one is served as usual. Can be changed while the server runs.
self.fail_first: Dict[str, str] = {k.lower().rstrip("."): v for k, v in (fail_first or {}).items()}
for kind in self.fail_first.values():
if kind not in FAILURE_KINDS:
raise ValueError("unknown failure kind %r, expected one of %s" % (kind, FAILURE_KINDS))
#: What was done with every query, in the order it was SENT (see :class:`DohAnswer`).
self.answers: List[DohAnswer] = []
self._failed: Set[Tuple[str, int]] = set()
#: Every query, in order.
self.queries: List[DohQuery] = []
#: The names for which this server answered a type 65 (HTTPS) query WITH DATA. It never does: the retail Firefox reads
#: h3 at its first visit when the DNS answer carries that record, so a test that expects h2 first (the h3 e2e) asserts
#: that this stays empty, and says so if the server learns to serve it.
self.https_served: List[str] = []
#: Every TLS connection served: (via, negotiated protocol).
self.connections: List[Tuple[str, str]] = []
#: The TLS handshakes that did not complete (a client that refused the certificate): (via, error).
@@ -215,6 +275,11 @@ class FakeDoh:
"""The set of roads (gateway names) a name was asked by."""
return {q.via for q in self.queries_for(name, qtype)}
def answers_for(self, name: str, qtype: Optional[int] = None) -> List[DohAnswer]:
name = name.lower().rstrip(".")
with self._lock:
return [a for a in self.answers if a.name == name and (qtype is None or a.qtype == qtype)]
def seen_names(self) -> List[str]:
with self._lock:
return sorted({q.name for q in self.queries})
@@ -279,13 +344,24 @@ class FakeDoh:
pass
return len(victims)
def _answer(self, via: str, method: str, target: str, content_type: str,
body: bytes) -> Tuple[int, bytes, str]:
"""(status, body, content type) of one HTTP request, recording the DNS query it carries."""
def bad(status: int) -> Tuple[int, bytes, str]:
def _delay_of(self, name: str) -> float:
for key, seconds in self.delay_names.items():
if name == key or name.endswith("." + key):
return seconds
return self.delay_s
def _record(self, record: Optional[Tuple[str, int, str, str]], received: float) -> None:
"""Log that an answer is being sent now (``received`` is the monotonic time its query arrived)."""
if record is not None:
with self._lock:
self.answers.append(DohAnswer(*record, time.monotonic() - received))
def _answer(self, via: str, method: str, target: str, content_type: str, body: bytes) -> _Reply:
"""What to send for one HTTP request, recording the DNS query it carries."""
def bad(status: int) -> _Reply:
with self._lock:
self.bad_requests.append((via, method, target, status))
return status, b"", "text/plain"
return _Reply(status, b"", "text/plain")
split = urlsplit(target)
if split.path != DOH_PATH:
@@ -311,7 +387,24 @@ class FakeDoh:
with self._lock:
self.queries.append(DohQuery(query.name, query.qtype, via))
names = dict(self.names)
return 200, answer_for(names, query), "application/dns-message"
kind = self.fail_first.get(query.name)
if kind is not None and (query.name, query.qtype) in self._failed:
kind = None
elif kind is not None:
self._failed.add((query.name, query.qtype))
delay = self._delay_of(query.name)
record = (query.name, query.qtype, via, kind or "answered")
if kind == "close":
return _Reply(0, b"", "", delay, True, record)
if kind == "http503":
return _Reply(503, b"", "text/plain", delay, False, record)
if kind == "servfail":
return _Reply(200, build_response(query, RCODE_SERVFAIL), "application/dns-message", delay, False, record)
message = answer_for(names, query)
if query.qtype == QTYPE_HTTPS and struct.unpack("!H", message[6:8])[0] > 0:
with self._lock:
self.https_served.append(query.name)
return _Reply(200, message, "application/dns-message", delay, False, record)
def _serve_h1(self, tls: ssl.SSLSocket, via: str) -> None:
buffer = b""
@@ -335,7 +428,14 @@ class FakeDoh:
return
buffer += chunk
body, buffer = buffer[:length], buffer[length:]
status, payload, content_type = self._answer(via, method, target, headers.get("content-type", ""), body)
received = time.monotonic()
reply = self._answer(via, method, target, headers.get("content-type", ""), body)
if reply.delay:
time.sleep(reply.delay)
self._record(reply.record, received)
if reply.close:
return
status, payload, content_type = reply.status, reply.body, reply.content_type
close = headers.get("connection", "").lower() == "close"
tls.sendall(("HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %d\r\nCache-Control: max-age=%d\r\n"
"%s\r\n" % (status, _REASONS.get(status, "Status"), content_type, len(payload), DOH_TTL,
@@ -349,10 +449,43 @@ class FakeDoh:
connection.initiate_connection()
tls.sendall(connection.data_to_send())
streams: Dict[int, dict] = {}
#: Answers being held back: (due monotonic time, stream id, reply, monotonic time the query arrived). One thread
#: reads, holds and writes, so the TLS socket never has a reader and a writer at once, and the answers of one
#: connection are held independently of each other (the A and the AAAA of a lookup both wait ``delay``).
held: List[Tuple[float, int, _Reply, float]] = []
tls.settimeout(0.05)
last_activity = time.monotonic()
def send(stream_id: int, reply: _Reply, received: float) -> None:
self._record(reply.record, received)
try:
if reply.close:
connection.reset_stream(stream_id, error_code=h2.errors.ErrorCodes.INTERNAL_ERROR)
else:
connection.send_headers(stream_id, [
(":status", str(reply.status)), ("content-type", reply.content_type),
("content-length", str(len(reply.body))), ("cache-control", "max-age=%d" % DOH_TTL)])
connection.send_data(stream_id, reply.body, end_stream=True)
except h2.exceptions.H2Error: # the client reset the stream while its answer was held
pass
while True:
data = tls.recv(65536)
now = time.monotonic()
for item in [h for h in held if h[0] <= now]:
held.remove(item)
send(item[1], item[2], item[3])
pending = connection.data_to_send()
if pending:
tls.sendall(pending)
try:
data = tls.recv(65536)
except (socket.timeout, ssl.SSLWantReadError):
if not held and time.monotonic() - last_activity > 60:
return
continue
if not data:
return
last_activity = time.monotonic()
for event in connection.receive_data(data):
if isinstance(event, h2.events.RequestReceived):
streams[event.stream_id] = {"headers": dict(event.headers), "body": b""}
@@ -362,20 +495,19 @@ class FakeDoh:
elif isinstance(event, h2.events.StreamEnded):
request = streams.pop(event.stream_id)
headers = request["headers"]
status, payload, content_type = self._answer(
received = time.monotonic()
reply = self._answer(
via, headers.get(":method", ""), headers.get(":path", ""),
headers.get("content-type", ""), request["body"])
connection.send_headers(event.stream_id, [
(":status", str(status)), ("content-type", content_type),
("content-length", str(len(payload))), ("cache-control", "max-age=%d" % DOH_TTL)])
connection.send_data(event.stream_id, payload, end_stream=True)
if reply.delay:
held.append((received + reply.delay, event.stream_id, reply, received))
else:
send(event.stream_id, reply, received)
elif isinstance(event, h2.events.StreamReset):
streams.pop(event.stream_id, None)
held[:] = [h for h in held if h[1] != event.stream_id]
elif isinstance(event, h2.events.ConnectionTerminated):
return
pending = connection.data_to_send()
if pending:
tls.sendall(pending)
def close(self) -> None:
self._closed = True
@@ -591,8 +723,9 @@ def _recv_exact(s: socket.socket, n: int) -> bytes:
__all__ = [
"DOH_BOOTSTRAP", "DOH_HOST", "DOH_PATH", "DOH_PORT", "DOH_TARGETS", "DOH_TTL", "H2_AVAILABLE", "QTYPE_A",
"QTYPE_AAAA", "RCODE_NXDOMAIN", "RCODE_OK", "RCODE_REFUSED", "DohGateway", "DohQuery", "FakeDoh", "Query",
"DOH_BOOTSTRAP", "DOH_HOST", "DOH_PATH", "DOH_PORT", "DOH_PROVIDER_PREFS", "DOH_TARGETS", "DOH_TTL", "H2_AVAILABLE", "QTYPE_A",
"QTYPE_AAAA", "QTYPE_HTTPS", "RCODE_NXDOMAIN", "RCODE_OK", "RCODE_REFUSED", "RCODE_SERVFAIL", "DohAnswer", "DohGateway", "DohQuery",
"FAILURE_KINDS", "FakeDoh", "Query",
"answer_for", "build_response", "encode_query", "is_loopback", "make_certificate", "parse_query", "pump",
"relay", "wait_until",
]
+44
View File
@@ -0,0 +1,44 @@
"""Support of the DoH e2e files and of the fixtures of conftest.py that serve them (no pytest in here)."""
from __future__ import annotations
import http.server
import threading
from _servers import LocalServer
#: The zone of the FakeDoh: every name a test uses, all pointing at the loopback where the page server is.
ZONE = {"page-a.test": "127.0.0.1", "page-b.test": "127.0.0.1", "page-c.test": "127.0.0.1",
"stun-a.test": "127.0.0.1"}
class Pages:
"""A local HTTP server: every path answers a page that says which Host it was asked for."""
def __init__(self):
outer = self
self.hits = []
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self): # noqa: N802
host = self.headers.get("Host", "")
outer.hits.append((host, self.path))
body = ("<!doctype html><title>page</title><body>HOST=%s</body>" % host).encode()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
self._server = LocalServer(("127.0.0.1", 0), Handler)
self.port = self._server.server_address[1]
threading.Thread(target=self._server.serve_forever, daemon=True).start()
def url(self, name):
return "http://%s:%d/" % (name, self.port)
def close(self):
self._server.shutdown()
self._server.server_close()
+147 -46
View File
@@ -1,23 +1,27 @@
"""A local HTTPS server that speaks HTTP/3 as well, reached by its address.
The same port answers TCP (TLS, HTTP/1.1, with an `Alt-Svc: h3` header) and UDP (QUIC, HTTP/3, aioquic), with a self-signed
certificate for the address it is given. It records, for every QUIC connection, the address the packets came from: a
connection that comes from anywhere but the relay of a gateway on this host (127.0.0.1) did not go through the proxy.
The same port answers TCP (TLS, HTTP/2 by ALPN with an `Alt-Svc: h3` header, HTTP/1.1 for a client that offers nothing
else) and UDP (QUIC, HTTP/3, aioquic), with a self-signed certificate for the address it is given. The TCP side speaks HTTP/2
because that is what a real site does: the FIRST visit of a page reads `h2`, and only after the Alt-Svc it carries may a
later one read `h3` (retail Firefox 159, native DNS in loopback: h2, h3, h3; behind a proxy h3 within a few visits, and at the first one when the DNS answer carries the HTTPS record: 3 sessions of 15 in the third run). It records, for every QUIC connection, the address the packets
came from: a connection that comes from anywhere but the relay of a gateway on this host (127.0.0.1) did not go through
the proxy.
Needs `aioquic` (pip install aioquic); a test that wants it imports it with `pytest.importorskip`.
Needs `aioquic` and `h2` (pip install aioquic h2; the dev extra installs both).
"""
from __future__ import annotations
import asyncio
import datetime
import http.server
import ipaddress
import random
import socket
import socketserver
import ssl
import tempfile
import threading
from pathlib import Path
from typing import List
from typing import List, Tuple
def _certificate(address: str, directory: Path):
@@ -41,8 +45,127 @@ def _certificate(address: str, directory: Path):
return cert_path, key_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."""
def handle(self):
owner = self.server.owner
try:
self.request.settimeout(10)
tls = owner._tls.wrap_socket(self.request, server_side=True)
except (ssl.SSLError, OSError):
return
try:
tls.settimeout(60)
alpn = tls.selected_alpn_protocol() or "http/1.1"
owner.tcp_alpn.append(alpn)
if alpn == "h2":
self._h2(tls, owner)
else:
self._http1(tls, owner)
except (ssl.SSLError, OSError):
pass
finally:
try:
tls.close()
except OSError:
pass
@staticmethod
def _h2(tls, owner):
import h2.config
import h2.connection
import h2.events
import h2.exceptions
conn = h2.connection.H2Connection(config=h2.config.H2Configuration(client_side=False, header_encoding="utf-8"))
conn.initiate_connection()
tls.sendall(conn.data_to_send())
while True:
data = tls.recv(65536)
if not data:
return
try:
events = conn.receive_data(data)
except h2.exceptions.ProtocolError:
tls.sendall(conn.data_to_send())
return
for event in events:
if isinstance(event, h2.events.RequestReceived):
owner.tcp_requests.append(dict(event.headers).get(":path", ""))
conn.send_headers(event.stream_id, [
(":status", "200"), ("content-type", "text/html; charset=utf-8"),
("content-length", str(len(PAGE))), ("alt-svc", owner.alt_svc),
("access-control-allow-origin", "*")])
conn.send_data(event.stream_id, PAGE, end_stream=True)
elif isinstance(event, h2.events.DataReceived):
conn.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
elif isinstance(event, h2.events.ConnectionTerminated):
return
out = conn.data_to_send()
if out:
tls.sendall(out)
@staticmethod
def _http1(tls, owner):
head = b""
while b"\r\n\r\n" not in head:
chunk = tls.recv(4096)
if not chunk:
return
head += chunk
parts = head.split(b"\r\n", 1)[0].split(b" ")
owner.tcp_requests.append(parts[1].decode("latin-1") if len(parts) > 1 else "")
tls.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: %d\r\n"
b"Alt-Svc: %s\r\nAccess-Control-Allow-Origin: *\r\nConnection: close\r\n\r\n%s"
% (len(PAGE), owner.alt_svc.encode(), PAGE))
class H3Server:
"""TCP+TLS and QUIC on one port of `address`."""
"""TCP+TLS (HTTP/2) and QUIC (HTTP/3) on one port of `address`."""
def __init__(self, address: str):
from aioquic.asyncio import serve
@@ -55,52 +178,28 @@ class H3Server:
self.address = address
#: The address each QUIC connection came from.
self.quic_peers: List[str] = []
#: The same peers with the port they sent from: (address, port). On a machine where a gateway's relay sends from an address of
#: this host (Windows cannot send from 127.0.0.1 to it) the address cannot tell the relay from a client that came direct; its port can.
self.quic_peer_addrs: List[Tuple[str, int]] = []
#: The paths of the requests that were answered over HTTP/3, and over TCP.
self.h3_requests: List[str] = []
self.tcp_requests: List[str] = []
#: The ALPN each TCP connection negotiated ("h2", or "http/1.1").
self.tcp_alpn: List[str] = []
self._dir = tempfile.TemporaryDirectory()
cert, key = _certificate(address, Path(self._dir.name))
server = self
class Handler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
timeout = 5
def do_GET(self):
server.tcp_requests.append(self.path)
body = b"tcp ok"
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(body)))
self.send_header("Alt-Svc", 'h3=":%d"; ma=3600' % server.port)
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
# One port for both: the TCP port first, then the same number for UDP.
for _ in range(50):
tcp = http.server.ThreadingHTTPServer((address, 0), Handler)
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
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(str(cert), str(key))
context.set_alpn_protocols(["http/1.1"])
tcp.socket = context.wrap_socket(tcp.socket, server_side=True)
tcp.daemon_threads = True
#: What the TCP answer says about HTTP/3: the same port, for an hour.
self.alt_svc = 'h3=":%d"; ma=3600' % port
self._tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
self._tls.load_cert_chain(str(cert), str(key))
self._tls.set_alpn_protocols(["h2", "http/1.1"])
tcp.owner = self
self._tcp = tcp
threading.Thread(target=tcp.serve_forever, daemon=True).start()
@@ -112,16 +211,18 @@ class H3Server:
def quic_event_received(self, event):
if isinstance(event, ProtocolNegotiated):
self._http = H3Connection(self._quic)
server.quic_peers.append(self._quic._network_paths[0].addr[0])
peer = self._quic._network_paths[0].addr
server.quic_peers.append(peer[0])
server.quic_peer_addrs.append((peer[0], peer[1]))
if self._http is not None:
for http_event in self._http.handle_event(event):
if isinstance(http_event, HeadersReceived):
headers = dict(http_event.headers)
server.h3_requests.append(headers.get(b":path", b"").decode())
self._http.send_headers(http_event.stream_id, [
(b":status", b"200"), (b"content-type", b"text/plain"),
(b":status", b"200"), (b"content-type", b"text/html; charset=utf-8"),
(b"access-control-allow-origin", b"*")])
self._http.send_data(http_event.stream_id, b"h3 ok", end_stream=True)
self._http.send_data(http_event.stream_id, PAGE, end_stream=True)
self.transmit()
configuration = QuicConfiguration(is_client=False, alpn_protocols=H3_ALPN)
+22
View File
@@ -0,0 +1,22 @@
"""The address of this host that a relay or a server of an e2e test binds to: ONE helper for every test that needs it."""
import socket
import pytest
def this_host_address() -> str:
"""The IPv4 address this host sends from (the one of its default route, as a real gateway's relay has a routable one:
a loopback relay only suits a client whose UDP socket is not bound to an interface, and an engine's ICE sockets are).
No packet is sent.
A host with no default route (a container or a CI runner without a network, a laptop offline) has no such address: the
test cannot pass by design there, so it SKIPS. Call it BEFORE starting any server of the test, so that nothing is left
listening when it skips."""
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
probe.connect(("192.0.2.1", 9))
return probe.getsockname()[0]
except OSError:
pytest.skip("no default route: no LAN address to bind the relay")
finally:
probe.close()
+1 -1
View File
@@ -4,7 +4,7 @@ The counterpart of :class:`_doh_servers.DohGateway` for the ``http`` scheme:
* a request without a valid ``Proxy-Authorization: Basic`` gets ``407`` with ``Proxy-Authenticate: Basic`` (the
connection is closed, as many real proxies do); the right credentials get through;
* ``CONNECT`` to the DoH address (``162.159.61.4:443`` or ``mozilla.cloudflare-dns.com:443``) is answered ``200``
* ``CONNECT`` to the DoH address (``192.0.2.53:443`` or ``doh.gateway.test:443``) is answered ``200``
and handed to the FakeDoh with ``via=name``; ``CONNECT`` to a loopback address is relayed for real; any other
CONNECT is refused (``403``) and recorded;
* a plain ``GET http://host:port/path`` (the form a browser sends to an HTTP proxy for an ``http`` page: the NAME
+248 -23
View File
@@ -8,7 +8,7 @@ question put to the resolver of the machine.
It also lists the names of every descendant it saw, which is how a test shows that no helper process
(crash reporter, updater...) was ever started. Descendants of THIS process only, so parallel workers do not see
each other's browsers.
* :class:`ResolverTrap` listens on 127.0.0.1:53 (UDP and TCP, and ::1 when it can) and points ``/etc/resolv.conf``
* :class:`ResolverTrap` listens on 127.0.0.1:53 (or the first of 127.0.0.2... it can bind: see TRAP_ADDRESSES) (UDP and TCP, and ::1 when it can) and points ``/etc/resolv.conf``
at it for as long as it runs, restoring the file byte for byte at the end, so every question that reaches the
resolver of the machine is counted as ``(name, qtype)``. It needs Linux, root and a writable resolv.conf:
``ResolverTrap.available`` says so and ``ResolverTrap.reason`` says why not. The trap answers from ``answers``
@@ -165,22 +165,207 @@ def _trap_capability() -> Tuple[bool, str]:
return True, ""
#: The loopback addresses the trap tries for port 53, in order. A hosted runner can have something on 127.0.0.1:53 or on the
#: wildcard of that port (systemd-resolved holds 127.0.0.53 and 127.0.0.54): every 127.x.x.x is loopback on Linux, so the trap
#: takes the first one it can bind and writes THAT address into /etc/resolv.conf (a resolv.conf names no port). With a free
#: port (port=0) only 127.0.0.1 is used.
TRAP_ADDRESSES = ("127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.5", "127.0.0.6", "127.0.0.7", "127.0.0.8")
def _who_holds(port: int) -> str:
"""What the machine says about the sockets of `port` (Linux: ss), for the message of a trap that could not bind."""
import subprocess
for command in (["ss", "-H", "-lntup"], ["netstat", "-lntup"]):
try:
done = subprocess.run(command, capture_output=True, text=True, timeout=10)
except (OSError, subprocess.SubprocessError):
continue
lines = [line for line in done.stdout.splitlines() if (":%d " % port) in line]
return "; held by: " + (" | ".join(lines) if lines else "nothing listed by %s" % command[0])
return "; no ss or netstat to say who holds it"
class Asker(NamedTuple):
"""Who sent a question to the trap: the user, the process (None when its socket could not be traced) and its command."""
uid: int
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) < 10 or ":" not in fields[1]:
continue
try:
if int(fields[1].rsplit(":", 1)[1], 16) == port:
return int(fields[7]), int(fields[9])
except ValueError:
continue
return None
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])
names = ("udp6" if six else "udp",) if protocol == "udp" else ("tcp6" if six else "tcp",)
for name in names:
try:
with open("/proc/net/" + name, encoding="utf-8") as table:
row = row_from_proc_net(table.read(), int(peer[1]))
except OSError:
continue
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."""
"""A resolver on loopback that counts what it is asked. See the module docstring.
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):
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).
self.address = "127.0.0.1"
self.rewrite_resolv_conf = rewrite_resolv_conf
#: 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, 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 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`.
self._threads: List[threading.Thread] = []
self._ending = threading.Event()
self._original: Optional[bytes] = None
self._running = False
#: Why the last bind attempt failed (the error of the socket), for the message when none succeeds.
self._bind_error: Optional[OSError] = None
# --- what a test reads ---------------------------------------------------------------------------------------
def names(self) -> List[str]:
@@ -194,7 +379,12 @@ class ResolverTrap:
def describe(self) -> str:
with self._lock:
return ", ".join("%s/%d (%s)" % q for q in self.queries) or "nothing"
seen = ", ".join("%s/%d (%s)" % q for q in self.queries) or "nothing"
if 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 -------------------------------------------------------------------------------------------------
def __enter__(self) -> "ResolverTrap":
@@ -206,7 +396,7 @@ class ResolverTrap:
self._original = RESOLV_CONF.read_bytes()
# In place, not by rename: in a container the file is often a bind mount.
with open(RESOLV_CONF, "wb") as f:
f.write(b"nameserver 127.0.0.1\noptions timeout:1 attempts:1\n")
f.write(("nameserver %s\noptions timeout:1 attempts:1\n" % self.address).encode("ascii"))
except BaseException:
self._restore()
raise
@@ -222,6 +412,15 @@ class ResolverTrap:
with open(RESOLV_CONF, "wb") as f:
f.write(self._original)
self._original = None
# ⛔ THE THREADS END BEFORE THE SOCKETS ARE CLOSED. A thread blocked in accept() or recvfrom() is not woken by a close()
# of its socket from another thread (Linux): the kernel keeps the socket, still bound, until the call returns, and the
# call never returns. The port stayed taken after the test, and the NEXT trap found 127.0.0.1-8:53 "already in use"
# one address per test, until all eight were gone (run 43164943499; here: the eighth trap of a run of 19 tests).
# The answering loops therefore wake up every 0.2 s to look at `_ending`, and the socket is closed once they are gone.
self._ending.set()
for t in self._threads:
t.join(2.0)
self._threads = []
for s in self._sockets:
try:
s.close()
@@ -234,27 +433,36 @@ class ResolverTrap:
discarded: List[socket.socket] = [] # closed at the end, so a failed attempt's port is not handed out again
made: List[socket.socket] = []
try:
for attempt in range(200):
made = self._bind_once(discarded)
addresses = TRAP_ADDRESSES if self.port != 0 else TRAP_ADDRESSES[:1]
for address in addresses:
for attempt in range(200):
made = self._bind_once(discarded, address)
if made:
break
if self.port != 0:
break
if made:
break
if self.port != 0:
self.address = address
break
if not made:
raise OSError("the resolver trap found no port it could bind for TCP and UDP")
raise OSError("the resolver trap found no port it could bind for TCP and UDP (port %d on %s; the last error: %s)%s"
% (self.port, ", ".join(addresses), self._bind_error, _who_holds(self.port)))
finally:
for s in discarded:
s.close()
self._sockets += made
for s in made:
s.settimeout(0.2)
target = self._serve_udp if s.type == socket.SOCK_DGRAM else self._serve_tcp
threading.Thread(target=target, args=(s,), daemon=True).start()
t = threading.Thread(target=target, args=(s,), daemon=True)
self._threads.append(t)
t.start()
def _bind_once(self, discarded: List[socket.socket]) -> List[socket.socket]:
def _bind_once(self, discarded: List[socket.socket], address: str = "127.0.0.1") -> List[socket.socket]:
"""One attempt: the sockets bound, or [] after putting what it opened in ``discarded``."""
made: List[socket.socket] = []
port = self.port
for family, host, required in ((socket.AF_INET, "127.0.0.1", True), (socket.AF_INET6, "::1", False)):
for family, host, required in ((socket.AF_INET, address, True), (socket.AF_INET6, "::1", False)):
pair: List[socket.socket] = [] # this family's TCP and UDP, kept or dropped together
try:
# TCP first: Windows keeps big excluded ranges and hands out ephemeral ports in sequence, so a
@@ -270,7 +478,8 @@ class ResolverTrap:
udp = socket.socket(family, socket.SOCK_DGRAM)
pair.append(udp)
udp.bind((host, port))
except OSError:
except OSError as exc:
self._bind_error = exc
discarded += pair
if required:
discarded += made
@@ -281,24 +490,38 @@ class ResolverTrap:
return made
# --- answering -----------------------------------------------------------------------------------------------
def _respond(self, message: bytes, protocol: str) -> Optional[bytes]:
def _respond(self, message: bytes, protocol: str, peer=None) -> Optional[bytes]:
try:
query = parse_query(message)
except ValueError:
return 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:
self.queries.append(DohQuery(query.name, query.qtype, protocol))
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)
def _serve_udp(self, sock: socket.socket) -> None:
while True:
while not self._ending.is_set():
try:
data, peer = sock.recvfrom(4096)
except socket.timeout:
continue
except OSError:
return
response = self._respond(data, "udp")
response = self._respond(data, "udp", peer)
if response is not None:
try:
sock.sendto(response, peer)
@@ -306,14 +529,16 @@ class ResolverTrap:
pass
def _serve_tcp(self, listener: socket.socket) -> None:
while True:
while not self._ending.is_set():
try:
conn, _ = listener.accept()
conn, peer = listener.accept()
except socket.timeout:
continue
except OSError:
return
threading.Thread(target=self._tcp_conversation, args=(conn,), daemon=True).start()
threading.Thread(target=self._tcp_conversation, args=(conn, peer), daemon=True).start()
def _tcp_conversation(self, conn: socket.socket) -> None:
def _tcp_conversation(self, conn: socket.socket, peer=None) -> None:
try:
conn.settimeout(5)
while True:
@@ -327,7 +552,7 @@ class ResolverTrap:
if not chunk:
return
message += chunk
response = self._respond(message, "tcp")
response = self._respond(message, "tcp", peer)
if response is None:
return
conn.sendall(struct.pack("!H", len(response)) + response)
+88
View File
@@ -0,0 +1,88 @@
"""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.
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.
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
import os
import sys
import pytest
#: 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 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()
for proc in processes:
try:
if engine_dir is not None and not os.path.normcase(proc.exe()).startswith(os.path.normcase(engine_dir)):
continue
name, cmd = proc.name(), proc.cmdline()
except psutil.Error:
continue
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, 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"):
pytest.skip("only Linux names a content process by the site it hosts; %s names none" % sys.platform)
try:
children = psutil.Process(root_pid).children(recursive=True)
except psutil.Error:
return set()
return site_pids(children, site, engine_dir)
+392
View File
@@ -0,0 +1,392 @@
"""What the tests of "the page behind a declared exit" share: the exits, a gateway that tells a local site which of its
connections came through it, the page's reads, and the judges that turn what was read into sentences.
THE QUESTION. A person who buys a proxy expects every site to see ONE place: the address of its exit, the time zone of that
address, the language of that country, no trace of the machine the browser runs on. The check used to be made by hand, through a
paid proxy, against pages on the internet. Here the proxy is a local SOCKS5 gateway that DECLARES its exit
(``Gateway.tcp_exit``, the address it answers to "what is my address"), and the pages are local ones that read the same values a
page on the internet reads.
THE TRUTH FOR THE ZONE AND THE COUNTRY is the core's own offline geo database (``invisible_core._geo.ip_to_timezone`` and
``ip_to_country``), not a second service: the tests ask whether the browser's pages say what the core's database says about the
declared exit, which is the path ``prepare_session_geo`` takes. Whether the database is right about the world is not asked here.
THE ADDRESSES BELOW ARE PUBLIC, and each one is an address whose zone and country the geo database knows (the tests need that:
a documentation address has no zone). They are built from parts so that no dotted public address stands in a file.
Nothing here opens a browser. ``test_the_realness_helpers.py`` holds the judges and the gateway to what they say.
"""
from __future__ import annotations
import http.server
import ipaddress
import re
import socket
import threading
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple
from zoneinfo import ZoneInfo
from _doh_servers import DOH_TARGETS, DohGateway, is_loopback, relay
from _servers import LocalServer
from _socks_servers import WEB_NAME, WHOAMI4, WHOAMI6
from test_webrtc_realness import candidates, host_candidates, is_mdns, srflx_candidates
def _address(*parts: int) -> str:
return ".".join(str(part) for part in parts)
#: Six declared exits, each an address whose zone and country the geo database knows, on four continents: a zone west of UTC
#: with daylight saving, a zone with a half-hour offset, one east of the date line's neighbours, a southern-hemisphere zone whose
#: daylight saving runs the other way, and two in Europe/South America. The zone the tests expect is asked of the database at
#: test time; only the address is fixed here.
EXITS: Dict[str, str] = {
"germany": _address(1, 178, 10, 5),
"japan": _address(1, 0, 16, 5),
"india": _address(1, 6, 0, 5),
"australia": _address(1, 0, 4, 5),
"brazil": _address(1, 178, 32, 5),
"united_states": _address(1, 32, 239, 5),
}
#: The names the pages are reached by. The FakeDoh answers them with the loopback where the site is, so the only way to the site
#: is a name resolved by DoH through the gateway and a CONNECT by address.
SITE_NAME = "exit-site.test"
ZONE_NAMES = {SITE_NAME: "127.0.0.1"}
#: Two instants a page reads its offset at: 15 January and 15 July 2025, noon UTC, in milliseconds. One is in the northern
#: winter and one in the northern summer, so a zone whose daylight saving is wrong in one hemisphere reads a wrong offset at one
#: of them.
INSTANTS_MS = (1736942400000, 1752580800000)
#: What a retail Firefox reports as the name of a zone for which ICU keeps an older canonical name. The database says the first,
#: a retail browser in that zone prints the second (or the first): either is the zone of the exit.
ZONE_NAMES_OF_A_RETAIL_FIREFOX: Dict[str, Tuple[str, ...]] = {
"Asia/Kolkata": ("Asia/Kolkata", "Asia/Calcutta"),
}
#: The primary language subtags that are plausible for the country of an exit: the national language of the country and
#: English, which a Firefox of any country can carry (the English build is the commonest one everywhere). A country that is not
#: in the table is checked for the agreement of the reads with one another only.
PLAUSIBLE_PRIMARY: Dict[str, Set[str]] = {
"US": {"en", "es"}, "GB": {"en"}, "CA": {"en", "fr"}, "AU": {"en"}, "NZ": {"en"}, "IE": {"en"}, "ZA": {"en", "af"},
"IN": {"en", "hi"}, "SG": {"en", "zh"}, "DE": {"de", "en"}, "AT": {"de", "en"}, "CH": {"de", "fr", "it", "en"},
"FR": {"fr", "en"}, "BE": {"fr", "nl", "en"}, "NL": {"nl", "en"}, "IT": {"it", "en"}, "ES": {"es", "ca", "en"},
"PT": {"pt", "en"}, "BR": {"pt", "en"}, "MX": {"es", "en"}, "AR": {"es", "en"}, "CL": {"es", "en"}, "CO": {"es", "en"},
"JP": {"ja", "en"}, "KR": {"ko", "en"}, "CN": {"zh", "en"}, "TW": {"zh", "en"}, "PL": {"pl", "en"}, "SE": {"sv", "en"},
"NO": {"nb", "nn", "no", "en"}, "DK": {"da", "en"}, "FI": {"fi", "en"}, "RU": {"ru", "en"}, "UA": {"uk", "ru", "en"},
"TR": {"tr", "en"},
}
# ---------------------------------------------------------------------------------------------------------- the gateway
class ExitGateway(DohGateway):
"""A gateway that declares an exit AND remembers the local port of every connection it opened for a page.
A real proxy's exit is the address a site sees as the peer of its connection. On loopback every peer is 127.0.0.1, so the
gateway says which connections are its own instead: ``upstream_ports`` holds the source port of each connection it opened
to a loopback server, recorded BEFORE it answers the CONNECT, so the server (which is asked only after the browser has the
answer) always finds it. A connection of the browser that did not come through the gateway has a port that is not there:
to the site it is a direct connection, a leak."""
def __init__(self, *args: Any, **kwargs: Any):
self.upstream_ports: Set[int] = set()
self._ports_lock = threading.Lock()
super().__init__(*args, **kwargs)
def came_through(self, source_port: int) -> bool:
with self._ports_lock:
return source_port in self.upstream_ports
def _connect(self, c: socket.socket, host: str, port: int) -> None:
special = (host, port) in DOH_TARGETS or (host, port) in (WHOAMI4, WHOAMI6, (WEB_NAME, 80))
if special or not is_loopback(host):
super()._connect(c, host, port)
return
self.connects.append((host, port))
try:
upstream = socket.create_connection((host, port), timeout=10)
except OSError:
self._send(c, self._reply(5))
return
with self._live_lock:
self._live.append(upstream)
with self._ports_lock:
self.upstream_ports.add(upstream.getsockname()[1])
self._send(c, self._reply(0))
try:
relay(c, upstream, self.rtt / 2 if self.tcp_data_delay else 0.0)
finally:
upstream.close()
# ------------------------------------------------------------------------------------------------------------- the reads
#: What a page and a worker read, as ONE function: the worker's source is made from it, so the two cannot drift. The offset is
#: read two ways: from the clock of the page (``getTimezoneOffset``) and from the wall clock ``Intl`` prints for the zone the
#: page itself names (the difference with UTC). ``0 - x`` and not ``-x``, so that a zero is +0 on the wire.
READ_JS = """() => {
const instants = %s;
const zone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
const ahead = (t) => {
const p = {};
for (const x of new Intl.DateTimeFormat('en-US', {timeZone: zone, hourCycle: 'h23', year: 'numeric', month: 'numeric',
day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric'}).formatToParts(new Date(t))) p[x.type] = x.value;
return Math.round((Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour %% 24, +p.minute, +p.second) - t) / 60000);
};
return {
zone,
offsets_by_date: instants.map((t) => 0 - new Date(t).getTimezoneOffset()),
offsets_by_intl: instants.map(ahead),
language: navigator.language,
languages: [...navigator.languages],
intl: new Intl.DateTimeFormat().resolvedOptions().locale,
};
}""" % list(INSTANTS_MS)
#: The page: asks the site what address it sees, makes one fetch (the header the site receives from a fetch), reads, and has a
#: dedicated worker read the same and fetch once (the header of a worker's request).
PAGE_JS = """async () => {
const read = %s;
const ip = (await (await fetch('/ip', {cache: 'no-store'})).text()).trim();
await (await fetch('/fetch', {cache: 'no-store'})).text();
const own = read();
const worker = await new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('the worker never answered')), 20000);
const w = new Worker('/worker.js');
w.onmessage = (e) => { clearTimeout(timer); resolve(e.data); };
w.onerror = (e) => { clearTimeout(timer); reject(new Error('worker error: ' + e.message)); };
w.postMessage(0);
});
return {ip, page: own, worker};
}""" % READ_JS
WORKER_JS = ("const read = %s;\nonmessage = async () => {\n await (await fetch('/worker-fetch', {cache: 'no-store'})).text();\n"
" postMessage(read());\n};\n" % READ_JS)
# --------------------------------------------------------------------------------------------------------------- the site
@dataclass(frozen=True)
class Arrival:
"""One request the site received: the path, the source port of the connection, and whether the gateway opened it."""
path: str
source: str
via_gateway: bool
accept_language: Optional[str]
class Site:
"""The local site: ``/ip`` says which address the site sees (the exit the gateway declares, or ``DIRECT <address>`` for a
connection the gateway did not open), ``/fetch`` and ``/worker-fetch`` only count, ``/worker.js`` is the worker."""
def __init__(self, gateway: ExitGateway):
outer = self
self.gateway = gateway
self.arrivals: List[Arrival] = []
self._lock = threading.Lock()
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self) -> None: # noqa: N802
path = self.path.split("?")[0]
host, port = self.client_address[:2]
through = outer.gateway.came_through(port)
with outer._lock:
outer.arrivals.append(Arrival(path, "%s:%d" % (host, port), through, self.headers.get("Accept-Language")))
if path == "/ip":
body, kind = (outer.gateway.tcp_exit if through else "DIRECT %s" % host).encode(), "text/plain"
elif path == "/worker.js":
body, kind = WORKER_JS.encode(), "text/javascript"
elif path == "/":
body, kind = b"<!doctype html><title>exit</title><body>exit</body>", "text/html; charset=utf-8"
else:
body, kind = b"ok", "text/plain"
self.send_response(200)
self.send_header("Content-Type", kind)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def log_message(self, *args: Any) -> None:
pass
self._server = LocalServer(("127.0.0.1", 0), Handler)
self.port = self._server.server_address[1]
threading.Thread(target=self._server.serve_forever, daemon=True).start()
def url(self, name: str = SITE_NAME, path: str = "/") -> str:
return "http://%s:%d%s" % (name, self.port, path)
def headers_of(self, *paths: str) -> Dict[str, Optional[str]]:
"""The Accept-Language of the LAST request of each path (None when the request carried none or never came)."""
with self._lock:
seen = list(self.arrivals)
return {path: next((a.accept_language for a in reversed(seen) if a.path == path), None) for path in paths}
def close(self) -> None:
self._server.shutdown()
self._server.server_close()
# ------------------------------------------------------------------------------------------------------- the host's own
def host_addresses() -> Set[str]:
"""Every address of every interface of this machine, normalised (loopback and link-local included). ``psutil`` is a
dependency of the package, and answers the same on Linux and on Windows."""
import psutil
found: Set[str] = set()
for addresses in psutil.net_if_addrs().values():
for entry in addresses:
if entry.family in (socket.AF_INET, socket.AF_INET6):
try:
found.add(ipaddress.ip_address(entry.address.split("%")[0]).compressed)
except ValueError:
continue
return found
_IPV4_WORD = re.compile(r"(?<![0-9A-Za-z.])(?:\d{1,3}\.){3}\d{1,3}(?![0-9A-Za-z.])")
_IPV6_WORD = re.compile(r"(?<![0-9A-Za-z:])(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}(?![0-9A-Za-z:])")
def addresses_in(text: str) -> List[ipaddress._BaseAddress]:
"""Every IPv4 and IPv6 address written in ``text`` (a name such as ``<uuid>.local`` is none)."""
found = []
for token in _IPV4_WORD.findall(text) + _IPV6_WORD.findall(text):
try:
found.append(ipaddress.ip_address(token))
except ValueError:
continue
return found
# -------------------------------------------------------------------------------------------------------------- the judges
def ip_problems(ip_seen: str, arrivals: Sequence[Arrival], direct: Sequence[str], exit_ip: str, connects: Sequence[Tuple[str, int]],
site_port: int) -> List[str]:
"""What is wrong with "the site sees the exit and nothing reached it, or the network, directly"."""
problems: List[str] = []
if ip_seen != exit_ip:
problems.append("the page was told its address is %r, the gateway's declared exit is %r" % (ip_seen, exit_ip))
if not arrivals:
problems.append("the site received no request at all")
outside = [a for a in arrivals if not a.via_gateway]
if outside:
problems.append("the site received %d request(s) on connections the gateway did not open (a direct connection): %s"
% (len(outside), [(a.path, a.source) for a in outside]))
if ("127.0.0.1", site_port) not in connects:
problems.append("the gateway never saw a CONNECT to the site, it saw %s" % list(connects))
if direct:
problems.append("the browser opened connections past the gateway: %s" % list(direct))
return problems
def webrtc_problems(probe: Dict[str, Any], exit_ip: str, host: Iterable[str]) -> List[str]:
"""What of this machine, or what incoherent with the exit, the candidates and the SDP of a gather show."""
lines = list(probe.get("candidates") or [])
sdp = probe.get("sdp") or ""
cands = candidates(lines)
problems: List[str] = []
if not cands:
return ["the gather produced no candidate at all (%s)" % probe.get("errors")]
raw = [c["address"] for c in host_candidates(cands) if not is_mdns(c["address"])]
if raw:
problems.append("host candidates that are not mDNS names: %s" % raw)
six = [c["address"] for c in cands if ":" in c["address"] and not is_mdns(c["address"])]
if six and ipaddress.ip_address(exit_ip).version == 4:
problems.append("IPv6 candidates behind an IPv4 exit: %s" % six)
reflexive = sorted({c["address"] for c in srflx_candidates(cands)})
if reflexive and reflexive != [exit_ip]:
problems.append("the server-reflexive candidate is %s, the exit is %s" % (reflexive, exit_ip))
written = addresses_in(sdp + "\n" + "\n".join(lines))
private = sorted({str(a) for a in written if a.version == 4 and not a.is_unspecified and (a.is_private or a.is_link_local
or a.is_loopback)})
if private:
problems.append("private or loopback IPv4 addresses in the SDP or the candidates: %s" % private)
mine = set(host)
own = sorted({a.compressed for a in written if a.compressed in mine})
if own:
problems.append("addresses of this machine's interfaces in the SDP or the candidates: %s" % own)
return problems
def acceptable_zones(zone: str) -> Tuple[str, ...]:
return ZONE_NAMES_OF_A_RETAIL_FIREFOX.get(zone, (zone,))
def expected_offsets(zone: str) -> List[int]:
"""The minutes a zone is ahead of UTC at each of :data:`INSTANTS_MS`, from the system tz database (``zoneinfo``)."""
info = ZoneInfo(zone)
return [int(datetime.fromtimestamp(t / 1000, tz=info).utcoffset().total_seconds() // 60) for t in INSTANTS_MS]
def timezone_problems(reads: Dict[str, Dict[str, Any]], zone: str) -> List[str]:
"""``reads`` maps a scope name (page, worker) to what :data:`READ_JS` returned there; every scope must say ``zone`` and the
offsets of ``zone`` at both instants, read both ways."""
problems: List[str] = []
want = expected_offsets(zone)
for scope, read in reads.items():
if read.get("zone") not in acceptable_zones(zone):
problems.append("%s: Intl says the zone is %r, the exit's is %s" % (scope, read.get("zone"), zone))
for way in ("offsets_by_date", "offsets_by_intl"):
if read.get(way) != want:
problems.append("%s: %s are %s, the offsets of %s at the two instants are %s" % (scope, way, read.get(way), zone, want))
return problems
def _tags(header: str) -> List[str]:
return [part.split(";")[0].strip() for part in header.split(",") if part.strip()]
def language_problems(reads: Dict[str, Dict[str, Any]], headers: Dict[str, Optional[str]], country: Optional[str]) -> List[str]:
"""The language of a session as everything a site can read says it: ``reads`` (page, worker), the Accept-Language of the
requests (``headers``, by path), and the plausibility of the primary language for ``country``."""
problems: List[str] = []
page = reads["page"]
languages = page.get("languages") or []
if not languages:
return ["navigator.languages is empty"]
primary = languages[0]
if page.get("language") != primary:
problems.append("navigator.language is %r, navigator.languages starts with %r" % (page.get("language"), primary))
for scope, read in reads.items():
if read.get("intl") != primary:
problems.append("%s: the Intl locale is %r, the language is %r" % (scope, read.get("intl"), primary))
if scope != "page":
for key in ("language", "languages"):
if read.get(key) != page.get(key):
problems.append("%s: %s is %r, the page's is %r" % (scope, key, read.get(key), page.get(key)))
for path, header in headers.items():
if header is None:
problems.append("%s: the request carried no Accept-Language" % path)
elif _tags(header) != languages:
problems.append("%s: Accept-Language is %r, navigator.languages is %s" % (path, header, languages))
table = PLAUSIBLE_PRIMARY.get(country or "")
if table is not None and primary.split("-")[0].lower() not in table:
problems.append("the language %r is not plausible for %s (plausible: %s)" % (primary, country, sorted(table)))
return problems
@dataclass
class Observation:
"""Everything one launch behind one declared exit showed, as plain data (the browser and the servers are closed)."""
label: str
exit_ip: str
zone: str
country: Optional[str]
ip_seen: str = ""
reads: Dict[str, Dict[str, Any]] = field(default_factory=dict)
arrivals: List[Arrival] = field(default_factory=list)
headers: Dict[str, Optional[str]] = field(default_factory=dict)
probe: Dict[str, Any] = field(default_factory=dict)
connects: List[Tuple[str, int]] = field(default_factory=list)
site_port: int = 0
direct: List[str] = field(default_factory=list)
watched: int = 0
host: Set[str] = field(default_factory=set)
doh_vias: Dict[str, Set[str]] = field(default_factory=dict)
doh_connects: List[Tuple[str, int]] = field(default_factory=list)
gateway_name: str = ""
trap_ran: bool = False
trap_queries: List[str] = field(default_factory=list)
datagrams: List[Tuple[str, int]] = field(default_factory=list)
+215 -21
View File
@@ -5,7 +5,7 @@ test) starts one with ``with coherent() as gw:`` and points the product at
``gw.server`` (``socks5://127.0.0.1:<port>``), with ``gw.credentials`` when the
gateway asks for a user and password.
The three gateways are the three things a real one can be:
The gateways are the things a real one can be:
* :func:`coherent` - TCP CONNECT works, UDP ASSOCIATE is granted, and the relay
carries a STUN binding request to a fake STUN server that answers with the
@@ -15,6 +15,15 @@ The three gateways are the three things a real one can be:
7 ("command not supported"), the way a residential gateway does.
* :func:`mismatched` - UDP ASSOCIATE is granted and STUN answers, but with an
address DIFFERENT from the TCP exit: the disagreement a detector looks for.
* :func:`silent_udp` - UDP ASSOCIATE is granted and the relay carries datagrams, but
no STUN server ever answers (a router that drops UDP behind a working handshake): the core's
measurement ends in ``unmeasured``.
THE CORE MEASURES THE UDP EXIT of a SOCKS5 proxy before it declares it to the browser (``invisible_core._udp_exit``: a STUN
Binding through the proxy's ASSOCIATE, compared with the TCP exit). A test that wants the relay to be used hands the core
this gateway's measurement server, ``udp_stun_servers=gw.measure_servers`` (``MEASURE_NUMBER``: the fake STUN server by a
documentation NUMBER of its own, so the datagrams of the measurement are told apart from those of the page, which asks
``STUN_NUMBER``). The measurement is a UDP ASSOCIATE of its own: :attr:`Gateway.associates` and :attr:`Gateway.datagrams` count it.
Everything is on loopback, so the "exit address" is made observable and
controllable instead of real: the TCP exit is what the gateway's fake "what is
@@ -36,11 +45,12 @@ ASSOCIATE, the relay or the round trip.
from __future__ import annotations
import os
import select
import socket
import struct
import threading
import time
from typing import List, Optional, Tuple
from typing import List, Optional, Set, Tuple
#: The name the product's STUN probe sends through the relay. The relay maps it
#: to the fake STUN server; every other destination is forwarded for real.
@@ -51,8 +61,14 @@ STUN_PORT = 19302
#: address (RFC 5737, TEST-NET-2), unroutable: the only road to it is the relay, which maps it to the fake STUN
#: server. (A copy of invisible_core's tests/_socks_servers.py with this one addition.)
STUN_NUMBER = "198.51.100.5"
#: The same fake STUN server by ANOTHER number: where the core's own measurement of the UDP exit asks (``udp_stun_servers``),
#: so that what the measurement sent through the relay is never mistaken for what the page sent. Documentation address too.
MEASURE_NUMBER = "198.51.100.6"
#: A page the gateway serves itself, for a test that loads one through the proxy (a name nothing else resolves).
WEB_NAME = "page.test"
#: The same page by an address (RFC 5737 TEST-NET-3): since the browser resolves names itself and connects by address, a
#: test that loads the gateway's page through a SOCKS gateway names it by this one.
WEB_ADDRESS = "203.0.113.80"
#: The echo endpoints the product asks for its TCP exit.
WHOAMI4 = ("api.ipify.org", 80)
WHOAMI6 = ("api6.ipify.org", 80)
@@ -73,12 +89,14 @@ def _recv_exact(s: socket.socket, n: int) -> bytes:
class FakeStun:
"""A UDP STUN server that answers every binding request with ``mapped_ip``."""
def __init__(self, mapped_ip: str, mapped_port: int = 40000):
def __init__(self, mapped_ip: str, mapped_port: int = 40000, bind_host: str = "127.0.0.1"):
self.mapped_ip = mapped_ip
self.mapped_port = mapped_port
self.requests = 0
self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._sock.bind(("127.0.0.1", 0))
# On the address the relay sends from: Windows sends neither from an address of the host to loopback (WinError 10049) nor
# from loopback to an address of the host (10051), so a relay that leaves from the host's address needs its STUN there too.
self._sock.bind((bind_host, 0))
self.address: Tuple[str, int] = self._sock.getsockname()
self._thread = threading.Thread(target=self._serve, daemon=True)
self._thread.start()
@@ -112,9 +130,12 @@ class Gateway:
def __init__(self, *, udp: str, tcp_exit: str, udp_exit: str,
user: Optional[str] = None, password: Optional[str] = None,
relay_host: str = "127.0.0.1", rtt_ms: int = 0,
exit_host: str = "127.0.0.1", tcp_data_delay: bool = False):
exit_host: str = "127.0.0.1", tcp_data_delay: bool = False, stun_answers: bool = True,
tcp_from_exit: bool = False):
assert udp in ("relay", "refuse")
self.udp = udp
#: False: the relay carries the datagrams but the fake STUN server is mute (its requests are dropped).
self.stun_answers = stun_answers
#: The round trip to this gateway, in seconds: every answer on the control connection waits for it, and each
#: datagram the relay carries waits half of it each way. A real gateway is not on loopback.
self.rtt = rtt_ms / 1000.0
@@ -125,23 +146,38 @@ class Gateway:
#: The local address the relay's datagrams leave from (the source a server behind the gateway sees). Another
#: loopback address makes a client that sent direct (from 127.0.0.1) tell apart from one that used the relay.
self.exit_host = exit_host
#: Whether the TCP connections the gateway opens for a CONNECT also leave from ``exit_host`` (as its datagrams do): a server that
#: is reachable DIRECT then tells a connection of the proxy from a connection of the browser by the source.
self.tcp_from_exit = tcp_from_exit
#: Whether each chunk of a forwarded TCP stream also waits half the round trip (a far gateway), as the datagrams do.
self.tcp_data_delay = tcp_data_delay
self.tcp_exit = tcp_exit
self.user, self.password = user, password
self.stun = FakeStun(udp_exit)
self.stun = FakeStun(udp_exit, bind_host="127.0.0.1" if exit_host.startswith("127.") else exit_host)
#: Every CONNECT, as (host, port), in order.
self.connects: List[Tuple[str, int]] = []
#: Every UDP ASSOCIATE request, answered or refused.
self.associates = 0
#: When the gateway started: the origin of the times below.
self.t0 = time.monotonic()
#: The same instant on the wall clock (seconds since the epoch), to compare with what a page reads from Date.now().
self.wall0 = time.time()
#: Every TCP connection the gateway accepted (a SOCKS handshake starts with one), as seconds from t0.
self.accepted: List[float] = []
#: Every UDP ASSOCIATE that was granted, as [start, end] seconds from t0; end is None until it was answered.
self.associations: List[List[Optional[float]]] = []
#: Every datagram the relay carried out, as (host as sent, port, address type, seconds from t0).
self.datagram_log: List[Tuple[str, int, int, float]] = []
#: Every datagram the relay carried out, as (host, port, payload).
self.datagrams: List[Tuple[str, int, bytes]] = []
#: The local port of the socket each granted association sends from: what a server behind the gateway sees as the port
#: of the relay, and what tells a datagram that went by the relay from one that came direct from this host.
self.exit_ports: List[int] = []
#: A datagram the relay could not send (a socket that raised): said here and in the report of a test, never mute.
self.send_errors: List[str] = []
#: The hosts the relay forwards a datagram to (the fake STUN server aside); None: any host. A test that sends from an
#: address of this host keeps its lab closed: the browser's own background QUIC does not leave the machine.
self.forward_only_to: Optional[Set[str]] = None
self._listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._listener.bind(("127.0.0.1", 0))
@@ -155,6 +191,12 @@ class Gateway:
def server(self) -> str:
return "socks5://127.0.0.1:%d" % self.port
@property
def measure_servers(self) -> List[str]:
"""The ``udp_stun_servers`` of a launch behind this gateway: where the core measures its UDP exit, in the
form the parameter takes (``"ip:port"``, an IPv4 literal)."""
return ["%s:%d" % (MEASURE_NUMBER, STUN_PORT)]
@property
def credentials(self) -> dict:
return ({"username": self.user, "password": self.password}
@@ -192,6 +234,7 @@ class Gateway:
conn, _ = self._listener.accept()
except OSError:
return
self.accepted.append(time.monotonic() - self.t0)
threading.Thread(target=self._handle, args=(conn,), daemon=True).start()
def _greet(self, c: socket.socket) -> bool:
@@ -261,6 +304,20 @@ class Gateway:
"""Where a CONNECT that is not a special one really goes. A subclass maps a name to a local server."""
return host, port
def _open_upstream(self, target: Tuple[str, int]) -> socket.socket:
"""The TCP connection of a CONNECT: from ``exit_host`` when ``tcp_from_exit``, else from wherever the system chooses."""
if not self.tcp_from_exit:
return socket.create_connection(target, timeout=10)
up = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
up.settimeout(10)
up.bind((self.exit_host, 0))
up.connect(target)
except OSError:
up.close()
raise
return up
def _connect(self, c: socket.socket, host: str, port: int) -> None:
self.connects.append((host, port))
if host.lower() in self.whoami_names and port == WHOAMI4[1]:
@@ -273,7 +330,7 @@ class Gateway:
if (host, port) == WHOAMI6:
self._send(c, self._reply(4)) # no IPv6 exit
return
if (host, port) == (WEB_NAME, 80): # a page that only the gateway can reach
if (host, port) in ((WEB_NAME, 80), (WEB_ADDRESS, 80)): # a page that only the gateway can reach
self._send(c, self._reply(0))
_ = c.recv(4096)
body = b"<html><body>behind the gateway</body></html>"
@@ -281,7 +338,7 @@ class Gateway:
b"Connection: close\r\n\r\n%s" % (len(body), body))
return
try:
up = socket.create_connection(self._target(host, port), timeout=10)
up = self._open_upstream(self._target(host, port))
except OSError:
self._send(c, self._reply(5))
return
@@ -314,19 +371,22 @@ class Gateway:
up.close()
# --- the UDP side --------------------------------------------------------
def _later(self, fn) -> None:
"""Run ``fn`` after half the round trip (at once on loopback), ignoring a socket that is already closed."""
def _later(self, fn, what: str = "a datagram") -> None:
"""Run ``fn`` after half the round trip (at once on loopback). A send that fails is RECORDED in ``send_errors`` (a
silent one hid that Windows cannot send from 127.0.0.1 to an address of its own host: WinError 10051), except on a gateway
that is already closed."""
def run() -> None:
try:
fn()
except OSError:
pass
except OSError as e:
if not self._closed:
self.send_errors.append("%s: %s %s" % (what, type(e).__name__, e))
threading.Timer(self.rtt / 2, run).start() if self.rtt else run()
def _deliver(self, relay: socket.socket, to: Tuple[str, int], host: str, port: int, payload: bytes) -> None:
"""Wrap ``payload`` as coming from ``host``:``port`` (an IPv4 literal) and send it back to the client."""
data = b"\x00\x00\x00\x01" + socket.inet_aton(host) + struct.pack("!H", port) + payload
self._later(lambda: relay.sendto(data, to))
self._later(lambda: relay.sendto(data, to), "the answer to the client")
def _route(self, host: str, dport: int, atyp: int, payload: bytes, out_port: int,
answer) -> Optional[Tuple[Tuple[str, int], Optional[Tuple[str, int]]]]:
@@ -336,10 +396,14 @@ class Gateway:
``reported_as`` is the address the client is told the reply came from (None: the real source). A subclass may also
answer by itself with ``answer(host, port, data)``. By default the fake STUN server, by name or by number, is
mapped and everything else is forwarded for real."""
if (host, dport) in ((STUN_NAME, STUN_PORT), (STUN_NUMBER, STUN_PORT)):
if (host, dport) in ((STUN_NAME, STUN_PORT), (STUN_NUMBER, STUN_PORT), (MEASURE_NUMBER, STUN_PORT)):
if not self.stun_answers:
return None
# A real server answers from the address it was asked at; the fake STUN server is mapped, so its reply is
# reported as from the asked address (only when that was a literal: a name has no address to report).
return self.stun.address, ((host, dport) if atyp == 1 else None)
if self.forward_only_to is not None and host not in self.forward_only_to:
return None
return (host, dport), None
def _associate(self, c: socket.socket) -> None:
@@ -353,6 +417,12 @@ class Gateway:
relay.bind((self.relay_host, 0))
out = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
out.bind((self.exit_host, 0))
self.exit_ports.append(out.getsockname()[1])
if hasattr(socket, "SIO_UDP_CONNRESET"):
# Windows: an ICMP "port unreachable" to a send makes the NEXT recvfrom raise WinError 10054 and, uncaught, ends the
# thread that reads: a relay that stops carrying answers because one datagram found nobody. Off, as a real relay has it.
for sock in (relay, out):
sock.ioctl(socket.SIO_UDP_CONNRESET, False)
client: List[Optional[Tuple[str, int]]] = [None]
#: Where a mapped destination really is -> the address the client is told it answered from.
asked_at: dict = {}
@@ -366,6 +436,8 @@ class Gateway:
while True:
try:
d, peer = relay.recvfrom(65536)
except ConnectionResetError:
continue
except OSError:
return
if len(d) < 10 or d[2] != 0:
@@ -389,12 +461,14 @@ class Gateway:
target, reported = routed
if reported is not None:
asked_at[target] = reported
self._later(lambda p=payload, t=target: out.sendto(p, t))
self._later(lambda p=payload, t=target: out.sendto(p, t), "the datagram to %s:%d" % target)
def outbound() -> None: # world -> client
while True:
try:
d, src = out.recvfrom(65536)
except ConnectionResetError:
continue
except OSError:
return
if client[0] is None:
@@ -422,22 +496,142 @@ OTHER_EXIT = "198.51.100.4"
def coherent(*, exit_ip: str = EXIT, user: Optional[str] = None,
password: Optional[str] = None, relay_host: str = "127.0.0.1", rtt_ms: int = 0) -> Gateway:
password: Optional[str] = None, relay_host: str = "127.0.0.1", rtt_ms: int = 0,
exit_host: str = "127.0.0.1") -> Gateway:
"""TCP and UDP both work, and both leave from ``exit_ip``."""
return Gateway(udp="relay", tcp_exit=exit_ip, udp_exit=exit_ip,
user=user, password=password, relay_host=relay_host, rtt_ms=rtt_ms)
user=user, password=password, relay_host=relay_host, rtt_ms=rtt_ms, exit_host=exit_host)
def tcp_only(*, exit_ip: str = EXIT, user: Optional[str] = None,
password: Optional[str] = None) -> Gateway:
password: Optional[str] = None, relay_host: str = "127.0.0.1", exit_host: str = "127.0.0.1") -> Gateway:
"""TCP works; UDP ASSOCIATE is refused with reply code 7."""
return Gateway(udp="refuse", tcp_exit=exit_ip, udp_exit=exit_ip,
user=user, password=password)
user=user, password=password, relay_host=relay_host, exit_host=exit_host)
def mismatched(*, tcp_exit: str = EXIT, udp_exit: str = OTHER_EXIT,
user: Optional[str] = None, password: Optional[str] = None) -> Gateway:
user: Optional[str] = None, password: Optional[str] = None, relay_host: str = "127.0.0.1",
exit_host: str = "127.0.0.1") -> Gateway:
"""UDP is granted and STUN answers, with an address that is not the TCP exit."""
assert udp_exit != tcp_exit
return Gateway(udp="relay", tcp_exit=tcp_exit, udp_exit=udp_exit,
user=user, password=password)
user=user, password=password, relay_host=relay_host, exit_host=exit_host)
def silent_udp(*, exit_ip: str = EXIT, user: Optional[str] = None, password: Optional[str] = None,
relay_host: str = "127.0.0.1", exit_host: str = "127.0.0.1") -> Gateway:
"""TCP works and UDP ASSOCIATE is granted, but no STUN request is ever answered: the core's measurement is
``unmeasured``."""
return Gateway(udp="relay", tcp_exit=exit_ip, udp_exit=exit_ip, user=user, password=password,
relay_host=relay_host, exit_host=exit_host, stun_answers=False)
# ----------------------------------------------------------------------------------------------------------------
# A tiny TCP-only SOCKS5 server for the e2e tests (the fixture `socks5_tcp_only` of conftest.py makes one).
# ----------------------------------------------------------------------------------------------------------------
class Socks5TcpOnly:
"""Minimal SOCKS5: no-auth, CONNECT (TCP) relayed, UDP ASSOCIATE refused.
Reproduces a residential TCP-only proxy: pages load over TCP, but WebRTC's
UDP path is dead - which (for a no-camera page in default_address_only mode)
is exactly what made the default-route probe fail and ICE return zero
candidates before Fix C.
"""
def __init__(self):
self._srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._srv.bind(("127.0.0.1", 0))
self._srv.listen(16)
self.port = self._srv.getsockname()[1]
self.udp_associate_attempts = 0
self._stop = False
self._t = threading.Thread(target=self._serve, daemon=True)
self._t.start()
def _serve(self):
while not self._stop:
try:
conn, _ = self._srv.accept()
except OSError:
break
threading.Thread(target=self._handle, args=(conn,), daemon=True).start()
def _recv_exact(self, sock, n):
buf = b""
while len(buf) < n:
chunk = sock.recv(n - len(buf))
if not chunk:
return None
buf += chunk
return buf
def _handle(self, conn):
try:
head = self._recv_exact(conn, 2)
if not head or head[0] != 0x05:
conn.close()
return
nmethods = head[1]
self._recv_exact(conn, nmethods)
conn.sendall(b"\x05\x00") # no-auth
req = self._recv_exact(conn, 4)
if not req:
conn.close()
return
ver, cmd, _, atyp = req
if atyp == 0x01:
addr = socket.inet_ntoa(self._recv_exact(conn, 4))
elif atyp == 0x03:
ln = self._recv_exact(conn, 1)[0]
addr = self._recv_exact(conn, ln).decode("ascii", "ignore")
elif atyp == 0x04:
addr = socket.inet_ntop(socket.AF_INET6, self._recv_exact(conn, 16))
else:
conn.close()
return
port = struct.unpack("!H", self._recv_exact(conn, 2))[0]
if cmd != 0x01: # not CONNECT (e.g. UDP ASSOCIATE) → refuse
self.udp_associate_attempts += 1
conn.sendall(b"\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00") # cmd not supported
conn.close()
return
try:
upstream = socket.create_connection((addr, port), timeout=15)
except OSError:
conn.sendall(b"\x05\x04\x00\x01\x00\x00\x00\x00\x00\x00") # host unreachable
conn.close()
return
conn.sendall(b"\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00") # success
self._relay(conn, upstream)
except Exception:
try:
conn.close()
except Exception:
pass
def _relay(self, a, b):
try:
while True:
r, _, _ = select.select([a, b], [], [], 30)
if not r:
break
for s in r:
data = s.recv(65536)
if not data:
return
(b if s is a else a).sendall(data)
finally:
for s in (a, b):
try:
s.close()
except Exception:
pass
def close(self):
self._stop = True
try:
self._srv.close()
except Exception:
pass
+30 -13
View File
@@ -28,17 +28,20 @@ The names and the addresses are RFC 2606 / RFC 5737: nothing in a test can be mi
"""
from __future__ import annotations
import contextlib
import hashlib
import hmac
import json
import socket
import struct
import subprocess
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Dict, List, Optional, Tuple
from _doh_servers import DohGateway, FakeDoh
from _host_address import this_host_address
from _socks_servers import WHOAMI4, Gateway
TURN_NAME = "turn.relay-only.test"
@@ -49,21 +52,31 @@ TURN_PORT = 3478
RELAYED = ("198.51.100.7", 50000)
#: Where the gateway's datagrams come from. A browser that sends direct comes from 127.0.0.1.
EXIT_HOST = "127.0.0.2"
#: The exit of a lab that a browser accepts as a real one: a documentation address (RFC 5737, TEST-NET-2, like the TURN server's) that
#: the host holds on its loopback interface (`lab_exit_address`). A mapped address in 127/8 is thrown away by nICEr as bogus.
LAB_EXIT = "198.51.100.9"
MAGIC = 0x2112A442
PASSWORD = "qwerty"
REALM = "hermetic"
NONCE = "6e6f6e6365"
def this_host_address() -> str:
"""The address of this host that a socket bound to an interface can send from: the relay's BND.ADDR (a loopback relay
only suits a client whose UDP socket is not bound to an interface, and an engine's ICE sockets are)."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
@contextlib.contextmanager
def lab_exit_address(address: str = LAB_EXIT):
"""Hold ``address`` on the loopback interface for the length of the block (Linux, root: ``ip addr add``), so that a gateway can send
from it and a browser reads it as a real exit. It FAILS, never skips, when it cannot (a missing root is a failure of the host the
suite was given): the suite that uses it is listed for Linux only."""
listing = subprocess.run(["ip", "-4", "-o", "addr", "show", "dev", "lo"], capture_output=True, text=True, check=False)
held = (" %s/" % address) in listing.stdout
if not held:
done = subprocess.run(["ip", "addr", "add", "%s/32" % address, "dev", "lo"], capture_output=True, text=True, check=False)
if done.returncode != 0:
raise RuntimeError("cannot hold %s on lo (needs root and iproute2 on Linux): %s" % (address, (done.stderr or done.stdout).strip()))
try:
s.connect(("192.0.2.1", 9))
return s.getsockname()[0]
yield address
finally:
s.close()
if not held:
subprocess.run(["ip", "addr", "del", "%s/32" % address, "dev", "lo"], capture_output=True, text=True, check=False)
# ── STUN / TURN wire ───────────────────────────────────────────────────────────
@@ -161,13 +174,17 @@ class Chain(DohGateway):
#: What the product asks "what is my address" of: answered with the exit.
whoami_names = ("api.ipify.org", "ifconfig.me", "icanhazip.com")
def __init__(self, *, rtt_ms: int = 130, relay_host: Optional[str] = None) -> None:
def __init__(self, *, rtt_ms: int = 130, relay_host: Optional[str] = None, exit_host: str = EXIT_HOST) -> None:
# The address of this host first: on a host with no default route the test skips, with no server started yet.
relay_host = relay_host or this_host_address()
#: Where the gateway's datagrams and connections leave from: what the TURN server hears and what the page must read as its srflx.
self.exit_ip = exit_host
self.turn = TurnServer()
self.doh = FakeDoh({TURN_NAME: TURN_IP, PAGE_NAME: "127.0.0.1"})
self.page = Page(self)
super().__init__("chain", self.doh, udp="relay", tcp_exit=EXIT_HOST, udp_exit=EXIT_HOST,
relay_host=relay_host or this_host_address(), rtt_ms=rtt_ms,
exit_host=EXIT_HOST, tcp_data_delay=True)
super().__init__("chain", self.doh, udp="relay", tcp_exit=exit_host, udp_exit=exit_host,
relay_host=relay_host, rtt_ms=rtt_ms,
exit_host=exit_host, tcp_data_delay=True)
def close(self) -> None:
super().close()
@@ -187,7 +204,7 @@ class Chain(DohGateway):
if (atyp == 1 and dport != 53 and len(payload) >= 20 and payload[:2] == b"\x00\x01"
and struct.unpack("!I", payload[4:8])[0] == MAGIC):
# a STUN binding request to anyone else: answered by the gateway, with the exit as the mapped address
answer(host, dport, _message(0x0101, payload[8:20], _attr(0x0020, _xor_addr(EXIT_HOST, out_port))))
answer(host, dport, _message(0x0101, payload[8:20], _attr(0x0020, _xor_addr(self.exit_ip, out_port))))
return None # a name, port 53, anything else: dropped (and in datagram_log)
# --- what a failed test says ----------------------------------------------
@@ -311,7 +328,7 @@ class Page:
parts = cand.split()
ip, port = (parts[4], int(parts[5])) if len(parts) > 5 else ("", 0)
seen = [(a[0], a[1]) for a in chain.turn.allocations]
ok = bool(seen) and (ip, port) in seen and ip == EXIT_HOST
ok = bool(seen) and (ip, port) in seen and ip == chain.exit_ip
outer.verdicts.append({"srflx": "%s:%d" % (ip, port), "seen_by_the_turn": ["%s:%d" % s for s in seen], "ok": ok})
body = json.dumps({"ok": ok}).encode()
self.send_response(200)
+173
View File
@@ -0,0 +1,173 @@
"""What the e2e tests of the UDP line share: the STUN servers the core measures from, the TCP exit of each gateway, what the
launch declared, and the sequence of protocols a page reads on each road.
THE CORE MEASURES THE UDP EXIT of a SOCKS5 proxy before it declares it (``invisible_core._udp_exit``): a STUN Binding sent
through the ASSOCIATE of the proxy to a list of servers, compared with the TCP exit it discovers through the same proxy. Only
``udp: coherent`` makes the engine send UDP to the relay; ``no`` and ``unmeasured`` are "a router that drops UDP" (HTTP/3
too). The list of servers is the explicit launch parameter ``udp_stun_servers`` (``"ip:port"``, IPv4 literals), so a hermetic
test points the measurement at the fake STUN server only its gateway's relay reaches. The caller never declares ``udp``.
Nothing here opens a browser; the unit test ``test_the_udp_line_helpers.py`` holds it to what it says.
"""
from __future__ import annotations
import ipaddress
from typing import Any, Callable, Dict, List, Optional, Sequence
#: How much slower than the first visit a later visit may load, in milliseconds, on the roads where UDP does not work. A
#: retail Firefox on a network that drops UDP loads the later visits as fast as the first (15 of 15 sessions, h2/h2/h2): an h3
#: attempt that waits for a timeout before it falls back to h2 would be seconds.
LOAD_MARGIN_MS = 1500
#: The visits of one page in one context, by kind of road. With NO proxy and the native DNS the retail is measured in loopback
#: and is exact: h2, h3, h3 over three visits. BEHIND A PROXY the names are resolved by DoH, the browser learns the Alt-Svc
#: from the first answer and the retail (Windows 159, DoH forced like our core, 15 sessions per condition) takes its time to
#: move to h3: with UDP free h2/h2/h3 in 9 sessions, h2/h2/h2 in 4 and h2/h3/h3 in 2 in the first runs, and h3 already on the
#: first visit (h3, h2, h2) in 3 sessions of 15 in the third, when the DNS answer carried the HTTPS record; so the page is
#: visited up to ``PROXY_VISITS`` times, and every proxy road makes the same number of visits (a road where UDP is dropped
#: reads h2 on all of them, as the retail does in 15 of 15: the one outcome that repeats). The fixture's first visit is h2
#: because it is reached by an address (no HTTPS record exists), not because the retail never reads h3 first.
DIRECT_VISITS = 3
PROXY_VISITS = 5
#: The roads. ``direct``: no proxy, native DNS. ``socks5_coherent``: a SOCKS5 proxy whose UDP the core measured coherent (UDP
#: free behind the proxy). The others are "a router that drops UDP": a SOCKS5 proxy that refuses UDP, whose UDP leaves
#: elsewhere or that never answers; or an HTTP proxy.
_DIRECT_ROAD = "direct"
_H3_PROXY_ROAD = "socks5_coherent"
_H2_ROADS = ("socks5_no_udp", "socks5_mismatched", "socks5_unmeasured", "http_proxy")
ROADS = (_DIRECT_ROAD, _H3_PROXY_ROAD) + _H2_ROADS
def _literal(entry: Any) -> str:
"""``"ip:port"`` of an IPv4 literal and a port, or ValueError (the form the launch parameter takes)."""
host, sep, port = str(entry).rpartition(":")
if not sep or ipaddress.ip_address(host).version != 4 or not 1 <= int(port) <= 65535:
raise ValueError("%r is not an \"ip:port\" IPv4 literal" % (entry,))
return "%s:%s" % (ipaddress.ip_address(host), int(port))
def measure_servers(gateway: Any) -> List[str]:
"""The ``udp_stun_servers=`` of a launch behind ``gateway``: the server its relay answers for the core's measurement.
One place, so that no test writes a list of its own."""
return [_literal(entry) for entry in gateway.measure_servers]
def egress_by_proxy(*gateways: Any, direct: Optional[str] = None) -> Callable[..., str]:
"""A replacement for ``invisible_core._geo.discover_egress_ip``: the TCP exit of the proxy it is asked about, which is
the one the gateway reports (no local gateway can answer the product's HTTPS question as itself). One gateway or
several (a session proxy and a context proxy have each their own); the UDP probe that follows is NOT replaced, it runs
through the relay for real. ``direct`` answers the discovery made with no proxy. An unknown proxy fails loudly."""
exits = {gateway.server: gateway.tcp_exit for gateway in gateways}
def discover(proxy: Optional[Dict[str, Any]] = None, *_args: Any, **_kwargs: Any) -> str:
if not proxy:
if direct is None:
raise AssertionError("the TCP exit was asked with no proxy and the test gave none")
return direct
server = proxy.get("server") if isinstance(proxy, dict) else None
if server not in exits:
raise AssertionError("the TCP exit of %r was asked and no gateway of the test owns it: %s" % (server, sorted(exits)))
return exits[server]
return discover
def declared_udp(proxy: Dict[str, Any], servers: Sequence[str]) -> str:
"""The ``udp`` the launch measured for ``proxy`` with ``servers``: ``coherent``, ``no`` or ``unmeasured``. It is what the
core remembered for the proxy (and declares to the engine); an AssertionError when the launch measured nothing, so
``unmeasured`` cannot be mistaken for an absent measurement."""
from invisible_core import _udp_exit
from invisible_core._proxy import parse_proxy
endpoint = parse_proxy(proxy)
key = _udp_exit.cache_key(endpoint, _udp_exit.stun_servers(list(servers)))
entry = _udp_exit._cache.get(key)
if entry is None:
raise AssertionError("the launch measured nothing for %r with %s" % (proxy.get("server"), list(servers)))
return entry[1]
def visits_for(road: str) -> int:
"""How many times the page is visited on ``road``: three with no proxy, :data:`PROXY_VISITS` behind any proxy."""
if road == _DIRECT_ROAD:
return DIRECT_VISITS
if road in ROADS:
return PROXY_VISITS
raise KeyError("no such road: %r (roads: %s)" % (road, ", ".join(ROADS)))
def expected_protocols(road: str) -> str:
"""What a retail Firefox reads (``nextHopProtocol`` of the document) over the visits of ``road``, as a sentence."""
visits = visits_for(road)
if road == _DIRECT_ROAD:
return "h2, h3, h3 over %d visits (no proxy, native DNS)" % visits
if road == _H3_PROXY_ROAD:
return ("h2 on the first visit, then h3 from a later visit on and h3 on every one after it, within %d visits "
"(retail with DoH and UDP free: h2/h2/h3 in 9 of 15, h2/h2/h2 in 4, h2/h3/h3 in 2, and h3 first in 3 of 15 in the "
"third run when the DNS answer carries the HTTPS record; this fixture has none: h2 first)" % visits)
return "h2 on every one of %d visits, as fast as the first (retail with UDP dropped: h2/h2/h2 in 15 of 15)" % visits
def no_https_record(host: str, doh: Any = None) -> List[str]:
"""What is wrong with the claim "the first visit of this fixture is h2", as sentences; an empty list when nothing is.
The retail reads h3 at the first visit when the DNS answer for the site carries the HTTPS record (type 65): the third
retail run did in 3 sessions of 15. The fixture reads h2 first only if no such record can reach the browser: the server
is reached by an ADDRESS (no name, no lookup), and the FakeDoh, when one is in the path, has never served a type 65 with
data (``FakeDoh.https_served``)."""
problems: List[str] = []
try:
ipaddress.ip_address(host.strip("[]"))
except ValueError:
problems.append("the server is reached by the name %r: its DNS answer could carry an HTTPS record, and the retail "
"reads h3 at the first visit when it does" % host)
served = list(getattr(doh, "https_served", ())) if doh is not None else []
if served:
problems.append("the FakeDoh served an HTTPS record (type 65) for %s: the first visit may read h3, as the retail does"
% sorted(set(served)))
return problems
def judge_visits(road: str, protocols: Sequence[str], walls_ms: Sequence[float]) -> List[str]:
"""What is wrong with the visits of one page on ``road``, as sentences; an empty list when nothing is.
``protocols`` is the ``nextHopProtocol`` of each visit and ``walls_ms`` the time ``page.goto`` took to the load event;
both have :func:`visits_for` entries. The rules, from the retail:
* ``direct``: exactly h2, h3, h3.
* ``socks5_coherent``: the first visit is h2 (the fixture is reached by an address: no HTTPS record exists, so nothing
tells the browser about h3 before the first connection; the retail itself reads h3 first when the DNS answer carries
the record, so this is a rule of the fixture, checked with :func:`no_https_record`); every later visit is h2 or h3, but once one is h3 all the following are (h3 never goes back to h2); and at
least one visit is h3 (it is NOT required at the second: h2/h2/h3 is the commonest retail sequence).
* the roads where UDP is dropped: h2 on every visit, and no visit loads more than :data:`LOAD_MARGIN_MS` slower than the
first (a fallback that waits for a timeout is a tell)."""
problems: List[str] = []
protocols, walls_ms = list(protocols), list(walls_ms)
visits = visits_for(road)
said = "a retail Firefox reads %s on this road" % expected_protocols(road)
if len(protocols) != visits:
problems.append("%d protocols for %d visits: %s" % (len(protocols), visits, protocols))
if len(walls_ms) != visits:
problems.append("%d load times for %d visits: %s" % (len(walls_ms), visits, walls_ms))
if protocols and protocols[0] == "h3":
problems.append("visit 1 read h3: in this fixture nothing had told the browser yet that the server speaks h3 (no "
"name, no HTTPS record): something told it, or the fixture changed")
if len(protocols) == visits:
if road == _DIRECT_ROAD:
if protocols != ["h2", "h3", "h3"]:
problems.append("the protocols of the %d visits are %s, %s" % (visits, protocols, said))
elif road == _H3_PROXY_ROAD:
first = protocols.index("h3") if "h3" in protocols else None
if first is None:
problems.append("none of the %d visits read h3: %s, %s" % (visits, protocols, said))
elif set(protocols) - {"h2", "h3"} or protocols[0] != "h2" or "h2" in protocols[first:]:
problems.append("the protocols of the %d visits are %s, %s" % (visits, protocols, said))
elif protocols != ["h2"] * visits:
problems.append("the protocols of the %d visits are %s, %s" % (visits, protocols, said))
if len(walls_ms) == visits and road in _H2_ROADS:
for number in range(2, visits + 1):
if walls_ms[number - 1] > walls_ms[0] + LOAD_MARGIN_MS:
problems.append("visit %d loaded in %d ms against %d ms for visit 1 (more than %d ms slower): an h3 attempt "
"that waited for a timeout before the fallback" % (number, walls_ms[number - 1], walls_ms[0], LOAD_MARGIN_MS))
return problems
+135
View File
@@ -0,0 +1,135 @@
"""A witness: a STUN server (UDP) and a TCP listener on ONE local address and port, that writes down who contacted it.
What it is for: a datagram or a connection a browser sends DIRECT, around its proxy, is invisible in a laboratory whose servers sit at
documentation addresses that nothing routes (a leak and a drop look the same: nothing arrives). The witness stands at an address the
browser can reach directly (a documentation address held on ``lo``, see ``_turn_chain.lab_exit_address``), so a leak ARRIVES, from a
source that is not the exit of the proxy, and a test can tell a leak from a drop. It answers a STUN Binding Request with the source it
saw, so a road that works also gives the page a server-reflexive candidate.
``udp`` is every datagram as (source ip, source port, length); ``tcp`` is every connection as (source ip, source port).
"""
from __future__ import annotations
import random
import socket
import sys
import struct
import threading
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:
self.address = address
self.udp: List[Tuple[str, int, int]] = []
self.tcp: List[Tuple[str, int]] = []
self._lock = threading.Lock()
self._closed = False
# 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, wanted))
chosen = tcp.getsockname()[1]
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp.bind((address, chosen))
tcp.listen(16)
return udp, tcp, chosen
except OSError as exc:
if port:
tcp.close()
if udp is not None:
udp.close()
raise
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]:
with self._lock:
return {"udp": list(self.udp), "tcp": list(self.tcp)}
def heard_from_other_than(self, allowed: Iterable[str]) -> Dict[str, list]:
"""What the witness heard from a source that is not one of ``allowed`` (the exit of the proxy): a direct send."""
ok = set(allowed)
heard = self.heard()
return {"udp": [h for h in heard["udp"] if h[0] not in ok], "tcp": [h for h in heard["tcp"] if h[0] not in ok]}
@property
def target(self) -> str:
return "%s:%d" % (self.address, self.port)
# --- serving ----------------------------------------------------------------------------------------------------
def close(self) -> None:
self._closed = True
for s in (self._udp, self._tcp):
try:
s.close()
except OSError:
pass
def __enter__(self) -> "Witness":
return self
def __exit__(self, *exc) -> None:
self.close()
def _serve_udp(self) -> None:
while not self._closed:
try:
data, peer = self._udp.recvfrom(2048)
except ConnectionResetError:
continue
except OSError:
return
with self._lock:
self.udp.append((peer[0], peer[1], len(data)))
if len(data) >= 20 and data[0:2] == b"\x00\x01" and data[4:8] == _MAGIC:
xport = struct.pack("!H", peer[1] ^ 0x2112)
xaddr = bytes(a ^ b for a, b in zip(socket.inet_aton(peer[0]), _MAGIC))
attr = struct.pack("!HH", 0x0020, 8) + b"\x00\x01" + xport + xaddr
try:
self._udp.sendto(b"\x01\x01" + struct.pack("!H", len(attr)) + _MAGIC + data[8:20] + attr, peer)
except OSError:
pass
def _serve_tcp(self) -> None:
while not self._closed:
try:
conn, peer = self._tcp.accept()
except OSError:
return
with self._lock:
self.tcp.append((peer[0], peer[1]))
try:
conn.close()
except OSError:
pass
+146
View File
@@ -343,3 +343,149 @@ def fixture_server():
finally:
httpd.shutdown()
httpd.server_close()
# ======================================================================================================================
# Fixtures shared by several e2e files. They live here, not in one file that the others import from: an imported fixture
# that a test then names as an argument is a redefinition (ruff F811, the lint of the `tests` job).
# ======================================================================================================================
@pytest.fixture
def doh():
import h2 # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
from _doh_servers import FakeDoh
from _doh_support import ZONE
server = FakeDoh(ZONE)
yield server
server.close()
@pytest.fixture
def gateway(doh):
from _doh_servers import DohGateway
made = []
def make(name, **kwargs):
gw = DohGateway(name, doh, **kwargs)
made.append(gw)
return gw
yield make
for gw in made:
gw.close()
@pytest.fixture
def trap():
"""The resolver trap, counting every question the machine's resolver is asked.
None only where it cannot run AND the gate does not require it (a developer's machine). With INVPW_REQUIRE_TRAP=1
(the gate's Linux leg) a trap that is unavailable or whose port 53 cannot be bound is a failure with its reason."""
import _trap_policy
from _leaks import ResolverTrap
if not ResolverTrap.available:
why = _trap_policy.failure(None, False, ResolverTrap.reason)
if why:
pytest.fail(why)
yield None
return
resolver = ResolverTrap()
try:
resolver.__enter__()
except OSError as exc: # port 53 taken (another worker holds the trap)
why = _trap_policy.failure(None, True, bind_error=exc)
if why:
pytest.fail(why)
yield None
return
try:
yield resolver
finally:
resolver.__exit__(None, None, None)
@pytest.fixture
def watcher(firefox_binary):
"""Started BEFORE the test body, so before any launch; stopped by the test or here."""
from pathlib import Path
from _leaks import Watcher
w = Watcher(match=("firefox", Path(firefox_binary).stem.lower())).start()
yield w
w.stop()
@pytest.fixture
def pages():
from _doh_support import Pages
server = Pages()
yield server
server.close()
@pytest.fixture
def socks5_tcp_only():
from _socks_servers import Socks5TcpOnly
srv = Socks5TcpOnly()
yield srv
srv.close()
@pytest.fixture
def local_https_page():
"""A trivial localhost page (used by the no-proxy srflx test)."""
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class H(BaseHTTPRequestHandler):
#: A silent socket no longer pins a thread down: after five seconds it drops.
timeout = 5
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.end_headers()
self.wfile.write(b"<html><body>wrtc</body></html>")
def log_message(self, *a):
pass
httpd = ThreadingHTTPServer(("127.0.0.1", 0), H)
httpd.daemon_threads = True
threading.Thread(target=httpd.serve_forever, daemon=True).start()
yield f"http://127.0.0.1:{httpd.server_address[1]}/"
httpd.shutdown()
@pytest.fixture(scope="module", params=["in-process", "stock-client"])
def browser(request, firefox_binary):
"""One browser per transport for the whole file (the popup tests of two files use it)."""
import importlib
if request.param == "in-process":
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(binary_path=firefox_binary, headless=True) as b:
yield b
return
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:
b = p.firefox.connect(server.ws_endpoint)
try:
yield b
finally:
b.close()
finally:
server.close()
@@ -20,15 +20,21 @@ Known-bad inputs, each run against this file before it was trusted:
* click and press without `_waiting_after` -> the form and the Enter tests go
red on a 157 engine (no request, the old URL);
* `_waiting_after` that ignores `noWaitAfter` -> the last test goes red: the
click waits for the slow page.
* `_waiting_after` that ignores `noWaitAfter` -> the `no_wait_after` test goes
red: the click comes back after the held answer, not before it.
**No clock in the last two tests.** `/slow` is an answer the server HOLDS until
the test lets it go, and what is asserted is the order of two events: the click
coming back, and the server answering. A limit in seconds (the click "in under
2.5 s") measured the runner: on a loaded one the click alone took longer and
the test went red with nothing wrong (2 of 30 suite runs, and every run on one
CPU).
"""
from __future__ import annotations
import http.server
import socket
import threading
import time
import pytest
@@ -38,7 +44,18 @@ FORM = (b"<form method='POST' action='/post'>"
b"<a id='slow' href='/slow'>slow</a>")
def _serve():
class _Held:
"""The answer to `/slow`, held by the server until `release` is set, and the order in which things happened."""
GIVES_UP_AFTER = 25 # seconds; only so that a click that wrongly waits ends, and the test fails on the order
def __init__(self):
self.arrived = threading.Event()
self.release = threading.Event()
self.order = []
def _serve(held=None):
sock = socket.socket()
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
@@ -55,8 +72,10 @@ def _serve():
self.wfile.write(body)
def do_GET(self):
if self.path == "/slow":
time.sleep(3)
if self.path == "/slow" and held is not None:
held.arrived.set()
held.release.wait(held.GIVES_UP_AFTER)
held.order.append("answered")
self._page(FORM if self.path == "/" else b"<title>%s</title>" % self.path.encode())
def do_POST(self):
@@ -101,18 +120,55 @@ def test_a_click_that_submits_a_form_returns_on_the_posted_page(firefox_binary):
@pytest.mark.e2e
def test_no_wait_after_returns_without_waiting_for_the_navigation(firefox_binary):
"""The click comes back while the server is still holding the answer of the page it navigates to."""
from invisible_playwright import InvisiblePlaywright
srv, url = _serve()
held = _Held()
srv, url = _serve(held)
try:
with InvisiblePlaywright(seed=4242, binary_path=firefox_binary,
headless=True) as browser:
page = browser.new_context().new_page()
page.goto(url, wait_until="load", timeout=30_000)
started = time.monotonic()
page.click("#slow", no_wait_after=True, timeout=30_000)
assert time.monotonic() - started < 2.5, (
"no_wait_after=True waited for the navigation")
held.order.append("click returned")
assert held.order == ["click returned"], (
"no_wait_after=True waited for the navigation: %r" % held.order)
assert page.url == url, "the page moved on with its answer still held: %s" % page.url
held.release.set()
page.wait_for_url(url + "slow", timeout=30_000)
assert held.order == ["click returned", "answered"], held.order
finally:
held.release.set()
srv.shutdown()
@pytest.mark.e2e
def test_a_plain_click_on_the_same_link_stays_until_the_held_answer_is_given(firefox_binary):
"""The other half, which makes the test above mean something: without `no_wait_after` the same click does NOT come
back while the answer is held. The answer is let go only once the request has reached the server, from another
thread, and the click returns after it, already on the new page."""
from invisible_playwright import InvisiblePlaywright
held = _Held()
srv, url = _serve(held)
def let_go_once_asked():
if held.arrived.wait(30):
held.order.append("let go")
held.release.set()
threading.Thread(target=let_go_once_asked, daemon=True).start()
try:
with InvisiblePlaywright(seed=4242, binary_path=firefox_binary,
headless=True) as browser:
page = browser.new_context().new_page()
page.goto(url, wait_until="load", timeout=30_000)
page.click("#slow", timeout=30_000)
held.order.append("click returned")
assert held.order == ["let go", "answered", "click returned"], (
"a plain click came back before the answer of its navigation: %r" % held.order)
assert page.url == url + "slow", page.url
finally:
held.release.set()
srv.shutdown()
@@ -73,6 +73,8 @@ class ScriptedJuggler(EventListeners):
self.dispatch_event("Runtime.executionContextCreated", {
"executionContextId": "e%s%s" % (target, world),
"auxData": {"frameId": "f" + target, "name": world}}, session)
# the real engine says so once the page's initial about:blank is done; the page is handed over on it
self.dispatch_event("Page.ready", {}, session)
return {"targetId": target}
if method == "Page.close":
target = next(t for t, s in self.sessions.items() if s == session)
@@ -0,0 +1,249 @@
"""A proxy given to a context declares where its UDP leaves from, MEASURED before the command is sent.
The core measures the UDP exit of a SOCKS5 proxy (`invisible_core._udp_exit`: UDP ASSOCIATE, then a STUN Binding request
with ICE's retransmissions, compared with the TCP exit it discovers through the same proxy) and the answer is the
optional field ``udp`` of ``Browser.setContextProxy``: ``coherent``, ``no`` or ``unmeasured``. Without it the engine
drops the UDP of every SOCKS5 proxy, so a context that is given its own proxy would never get a server-reflexive
candidate. The caller never declares it: a ``udp`` key in the dict of a proxy is not read.
``new_context(proxy=...)`` of the sync client, of the async client and of a remote one all end in
``BrowserDispatcher._apply_context_options``: one place, tested here with a recorder in place of the engine. The
gateway is the fake of ``_socks_servers`` (a SOCKS5 server with a UDP relay and a STUN server only the relay reaches).
THE STUN SERVERS ARE A PARAMETER OF THE LAUNCH: ``InvisiblePlaywright(..., udp_stun_servers=[...])`` and
``launch_server(..., udp_stun_servers=[...])`` ("ip:port" IPv4 literals; None = the two public defaults). The session
keeps the list, the launch's geo step and every later context proxy use it, and none of it reaches the browser: not its
environment, argv, prefs or pipe.
"""
from __future__ import annotations
import logging
import os
import sys
import pytest
from _socks_servers import EXIT, STUN_NUMBER, STUN_PORT, coherent, mismatched, tcp_only
from invisible_core import _geo, _udp_exit
from invisible_core.juggler.connection import EventListeners
from invisible_playwright import _session
from invisible_playwright._juggler.server import (BrowserDispatcher, Server, UDP_STUN_PREF,
session_udp_stun_servers, take_session_motion)
pytestmark = pytest.mark.unit
#: The fake STUN server only the gateway's relay reaches, in the form the launch parameter takes.
STUN = ["%s:%d" % (STUN_NUMBER, STUN_PORT)]
class _Connection(EventListeners):
def __init__(self, gateways=()):
super().__init__()
self.sent = []
self.datagrams_before = {}
self._gateways = gateways
def startup_send(self, method, params=None):
return self.send(method, params, timeout=None)
def send(self, method, params=None, session=None, timeout=30):
# How many datagrams the relays had carried when each command was sent: the measure comes BEFORE it.
self.datagrams_before[len(self.sent)] = sum(len(g.datagrams) for g in self._gateways)
self.sent.append((method, params))
return {"browserContextId": "CTX"}
@pytest.fixture(autouse=True)
def _fresh(monkeypatch):
monkeypatch.setattr(_udp_exit, "_cache", {})
# The fake gateway answers the exit question the way the product asks it (api.ipify.org through socks5h), but
# these tests are about the measurement, so the TCP exit is the gateway's own declaration.
monkeypatch.setattr(_geo, "discover_egress_ip", lambda proxy=None, **kw: EXIT)
def _apply(options, gateways=(), stun=STUN):
conn = _Connection(gateways)
dispatcher = BrowserDispatcher(Server(), None, conn, "151.0", udp_stun_servers=stun)
conn.sent.clear()
dispatcher._apply_context_options("CTX", options)
return conn
def _context_proxy(conn):
found = [(i, p) for i, (m, p) in enumerate(conn.sent) if m == "Browser.setContextProxy"]
assert len(found) == 1, conn.sent
return found[0]
def test_a_coherent_socks5_context_proxy_declares_coherent_after_it_was_measured():
with coherent() as gw:
conn = _apply({"proxy": gw.proxy}, [gw])
index, params = _context_proxy(conn)
assert params["udp"] == "coherent"
assert params["type"] == "socks" and params["browserContextId"] == "CTX"
assert conn.datagrams_before[index] >= 1, "the Binding request was sent before the command"
assert gw.associates == 1
def test_a_udp_that_leaves_from_another_address_declares_no():
with mismatched() as gw:
assert _context_proxy(_apply({"proxy": gw.proxy}, [gw]))[1]["udp"] == "no"
def test_a_proxy_that_refuses_udp_declares_no():
with tcp_only() as gw:
assert _context_proxy(_apply({"proxy": gw.proxy}, [gw]))[1]["udp"] == "no"
@pytest.mark.parametrize("scheme", ["http", "https", "socks4"])
def test_a_proxy_that_is_not_socks5_declares_no_field_and_opens_no_connection(scheme):
with coherent() as gw:
proxy = {"server": "%s://127.0.0.1:%d" % (scheme, gw.port)}
params = _context_proxy(_apply({"proxy": proxy}, [gw]))[1]
assert "udp" not in params
assert gw.associates == 0 and not gw.connects
def test_the_caller_never_declares_udp_on_a_context_proxy():
"""Red on the code that read the key: a caller-written `coherent` for a proxy whose UDP exits elsewhere (or
is refused) must come out as what was MEASURED."""
with tcp_only() as gw:
assert _context_proxy(_apply({"proxy": dict(gw.proxy, udp="coherent")}, [gw]))[1]["udp"] == "no"
with mismatched() as gw:
assert _context_proxy(_apply({"proxy": dict(gw.proxy, udp="coherent")}, [gw]))[1]["udp"] == "no"
def test_one_proxy_is_measured_once_however_many_contexts_are_given_it():
with coherent() as gw:
for _ in range(3):
assert _context_proxy(_apply({"proxy": dict(gw.proxy)}, [gw]))[1]["udp"] == "coherent"
assert gw.associates == 1
def test_the_cache_is_keyed_without_the_secret():
with coherent(user="a", password="hunter2-zzz") as gw:
_apply({"proxy": gw.proxy}, [gw])
assert _udp_exit._cache
for key in _udp_exit._cache:
assert "hunter2-zzz" not in repr(key)
def test_the_credentials_are_used_on_the_socket_and_nowhere_else(caplog):
user, password = "u-7c1e4b9a02", "p-3d5f8a6e41"
env_before = dict(os.environ)
with coherent(user=user, password=password) as gw:
with caplog.at_level(logging.DEBUG):
params = _context_proxy(_apply({"proxy": gw.proxy}, [gw]))[1]
assert params["udp"] == "coherent"
text = "\n".join(r.getMessage() + repr(r.args) + str(r.exc_info) for r in caplog.records)
assert user not in text and password not in text
assert dict(os.environ) == env_before
assert not [a for a in sys.argv if user in a or password in a]
def test_a_context_without_its_own_proxy_measures_nothing():
with coherent() as gw:
conn = _apply({}, [gw])
assert not [m for m, _ in conn.sent if m == "Browser.setContextProxy"]
assert gw.associates == 0
def test_a_context_proxy_that_cannot_be_read_is_refused_and_nothing_is_measured():
from invisible_playwright._juggler.server import ProtocolException as Refusal
with coherent() as gw:
with pytest.raises(Refusal):
_apply({"proxy": {"server": "ftp://127.0.0.1:%d" % gw.port}}, [gw])
assert gw.associates == 0
def test_a_browser_built_without_a_list_measures_from_the_two_defaults():
conn = _Connection()
assert BrowserDispatcher(Server(), None, conn, "151.0").udp_stun_servers is None
# the launch: the list is a parameter of the session, kept on it, never given to the browser ------------------
def test_the_session_keeps_the_list_the_launch_named_and_the_server_gets_it():
from invisible_playwright import InvisiblePlaywright
from invisible_playwright.async_api import InvisiblePlaywright as AsyncInvisiblePlaywright
expected = ["198.51.100.5:19302", "203.0.113.9:3478"]
for cls in (InvisiblePlaywright, AsyncInvisiblePlaywright):
session = cls(seed=1, udp_stun_servers=["198.51.100.5:19302", ("203.0.113.9", 3478)])
assert session._udp_stun_servers == expected
assert cls(seed=1)._udp_stun_servers is None
def test_a_bad_list_is_refused_by_every_public_entry_point():
import inspect
from invisible_playwright import InvisiblePlaywright
from invisible_playwright._juggler.remote import launch_server
from invisible_playwright.async_api import InvisiblePlaywright as AsyncInvisiblePlaywright
for cls in (InvisiblePlaywright, AsyncInvisiblePlaywright):
with pytest.raises(ValueError, match="udp_stun_servers"):
cls(seed=1, udp_stun_servers=["stun.example.org:3478"])
assert "udp_stun_servers" in inspect.signature(launch_server).parameters
def test_the_server_takes_the_list_out_of_the_prefs_before_the_profile():
prefs = {"a.b": 1, UDP_STUN_PREF: "198.51.100.5:19302,203.0.113.9:3478"}
assert session_udp_stun_servers(prefs) == ["198.51.100.5:19302", "203.0.113.9:3478"]
rest, _seed, _budget = take_session_motion(prefs)
assert UDP_STUN_PREF not in rest and rest == {"a.b": 1}
assert session_udp_stun_servers({"a.b": 1}) is None
def test_op_launch_reads_the_list_before_the_prefs_are_cleaned_and_writes_a_profile_without_it():
import inspect
from invisible_playwright._juggler import server
source = inspect.getsource(server.BrowserTypeDispatcher.op_launch)
assert source.index("session_udp_stun_servers(launch_prefs)") < source.index("take_session_motion(launch_prefs)")
assert source.index("take_session_motion(launch_prefs)") < source.index("write_user_js(")
assert "launch_proxy_command(params[\"proxy\"], udp_stun_servers)" in source
assert "parse_proxy(params[\"proxy\"]).as_engine_command()" not in source
def test_every_entry_point_hands_the_list_to_the_geo_step():
"""The sync launcher, the async launcher and `launch_server` call `prepare_session_geo` with the session's list."""
import ast
import importlib
import inspect
for module in ("launcher", "async_api", "_juggler.remote"):
source = inspect.getsource(importlib.import_module("invisible_playwright." + module))
tree = ast.parse(source)
calls = [n for n in ast.walk(tree) if isinstance(n, ast.Call)
and getattr(n.func, "id", None) == "prepare_session_geo"]
# (the async launcher passes the function to `asyncio.to_thread`: its keywords are on that call)
calls += [n for n in ast.walk(tree) if isinstance(n, ast.Call)
and getattr(n.func, "attr", None) == "to_thread"
and any(getattr(a, "id", None) == "prepare_session_geo" for a in n.args)]
assert calls, module
for call in calls:
assert "udp_stun_servers" in [k.arg for k in call.keywords], module
def test_no_stun_address_reaches_the_browsers_environment_argv_prefs_or_pipe():
from invisible_core import decide_session_locale
from invisible_playwright import InvisiblePlaywright
servers = ["198.51.100.5:19302", "203.0.113.9:3478"]
session = InvisiblePlaywright(seed=7, udp_stun_servers=servers, binary_path="firefox")
session._timezone, session._locale = "Asia/Tokyo", decide_session_locale("en-US")
prefs = session._build_prefs()
assert session_udp_stun_servers(prefs) == servers # the server's own key is there...
env = _session.build_env(network_declared="v4=198.51.100.7;v6=0", profile=session._profile,
executable=None, base_env={})
# ...and what the engine is given: the prefs after the server took its own keys out, the environment, the pipe.
browser_prefs, _seed, _budget = take_session_motion(prefs)
pipe = repr(_udp_exit.launch_proxy_command({"server": "socks5://10.0.0.1:1080"}, servers))
given = repr(browser_prefs) + repr(env) + pipe
for needle in servers + ["198.51.100.5", "203.0.113.9"]:
assert needle not in given, needle
assert not [k for k in env if "STUN" in k.upper()]
# the launch of a client that composed no session ----------------------------------------------------------
def test_a_hand_made_launch_proxy_cannot_claim_a_coherent_udp():
"""`launch(proxy={..., "udp": "coherent"})` through a bare client: nothing was measured, so `unmeasured`."""
with mismatched() as gw:
command = _udp_exit.launch_proxy_command(dict(gw.proxy, udp="coherent"), STUN)
assert command["udp"] == "unmeasured"
@@ -7,10 +7,16 @@ four such contexts left four more processes (8 web content processes at the end
BrowserContext now waits a few seconds for the processes of its container once its pages are gone, and kills the
ones that stay.
The test closes five such contexts in a row and counts the web content processes under the engine after each.
The first context may add ONE process that is not the leak (the engine starts a spare content process when the
first page takes one, and Linux keeps it), so the count after the fifth must not be above the count after the
SECOND: a flat line from there on (on the old engine every context adds one: [4, 5, 6, 7, 8]).
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 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.
@@ -27,11 +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 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>")
@@ -59,24 +67,6 @@ def _serve():
return server, "http://127.0.0.1:%d" % server.server_address[1]
def _web_processes(root_pid):
import psutil
found = set()
try:
children = psutil.Process(root_pid).children(recursive=True)
except psutil.Error:
return found
for process in children:
try:
command = " ".join(process.cmdline())
except psutil.Error:
continue
if "-contentproc" in command and command.rstrip().endswith(" tab"):
found.add(process.pid)
return found
class _Client:
"""The few calls of Playwright's protocol this test needs, over the served WebSocket."""
@@ -112,10 +102,14 @@ 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, SITE)
async def drive():
counts = []
opened, left = [], []
async with connect(launched.ws_endpoint, max_size=None) as ws:
client = _Client(ws)
await client.start()
@@ -123,21 +117,18 @@ def test_closed_contexts_with_a_never_stopping_service_worker_leave_no_process(f
context, frame = await client.new_page()
await client.call(frame, "goto", {"url": "%s/?i=%d" % (base, i), "waitUntil": "load", "timeout": 30000})
await asyncio.sleep(1.0) # the worker is registered, its install loop is running
await client.call(context, "close")
deadline = time.time() + 10
settled = None
while time.time() < deadline: # the count after the close, once it stops moving
now = _web_processes(launched.process.pid)
if settled is not None and len(now) == settled:
break
settled = len(now)
await asyncio.sleep(1.0)
counts.append(len(_web_processes(launched.process.pid)))
return counts
opened.append(len(sites()))
await client.call(context, "close") # the engine waits for the context's processes, then kills
deadline = time.time() + 5
while sites() and time.time() < deadline:
await asyncio.sleep(0.25)
left.append(len(sites()))
return opened, left
try:
counts = asyncio.run(drive())
opened, left = asyncio.run(drive())
finally:
launched.close()
server.shutdown()
assert counts[4] <= counts[1], "web content processes after each closed context: %r" % (counts,)
assert all(opened), "a page with no process for its site: the count proves nothing (%r)" % (opened,)
assert left == [0] * 5, "processes of a site left after each closed context: %r" % (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"]
@@ -39,7 +39,8 @@ def display(monkeypatch):
vd = RecordingDisplay()
geo = types.SimpleNamespace(timezone="Europe/Rome",
locale=SessionLocale.of("it-IT"),
egress_ip=None)
egress_ip=None,
geolocation_override=lambda: None)
def refuse(**_kw):
raise FontManifestMismatch("the engine does not carry these faces")
@@ -52,7 +53,7 @@ def display(monkeypatch):
monkeypatch.setattr(_session, "resolve_executable", lambda _p: "firefox")
monkeypatch.setattr(_session, "build_env", refuse)
for mod in (launcher, async_api):
monkeypatch.setattr(mod, "prepare_session_geo", lambda *_a: geo)
monkeypatch.setattr(mod, "prepare_session_geo", lambda *_a, **_k: geo)
monkeypatch.setattr(mod, "resolve_executable", lambda _p: "firefox")
monkeypatch.setattr(launcher, "sync_playwright", no_playwright)
monkeypatch.setattr(async_api, "async_playwright", no_playwright)
@@ -0,0 +1,84 @@
"""A `fetch(..., {keepalive: true})` is a request of the page: the client hears `request` and its end.
Stock Playwright's Firefox reports the keepalive fetch of a page like any other request: `page.on("request")` fires, and
`requestfinished` follows. Here the server saw the request and the client heard nothing, so a client that follows the page's
network by those events (tf-fetch's network recorder does) never knew the request existed.
The page asks for the same address four ways. `plain` is the control (a fetch without keepalive), `keepalive` and
`beacon` are the two that the engine runs in the parent process, and each must give exactly one `request` and one end.
"""
from __future__ import annotations
import threading
from http.server import BaseHTTPRequestHandler
import pytest
from _servers import LocalServer
pytestmark = pytest.mark.e2e
PAGE = b"""<!doctype html><title>keepalive</title><script>
addEventListener('load', () => {
fetch('/seen/plain', {method: 'POST', body: 'x'});
fetch('/seen/keepalive', {method: 'POST', body: 'x', keepalive: true});
fetch('/seen/keepalive-nocors', {keepalive: true, mode: 'no-cors'});
navigator.sendBeacon('/seen/beacon', 'x');
});
</script>"""
class _Handler(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def _answer(self, body, ctype="text/plain"):
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == "/":
self._answer(PAGE, "text/html; charset=utf-8")
else:
self._answer(b"ok")
def do_POST(self):
self.rfile.read(int(self.headers.get("Content-Length") or 0))
self._answer(b"ok")
@pytest.fixture
def site():
srv = LocalServer(("127.0.0.1", 0), _Handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
try:
yield "http://127.0.0.1:%d" % srv.server_address[1]
finally:
srv.shutdown()
srv.server_close()
@pytest.mark.parametrize("route", [False, True])
def test_every_request_of_the_page_reaches_the_client_with_its_end(firefox_binary, site, route):
from invisible_playwright import InvisiblePlaywright
started, ended = [], []
with InvisiblePlaywright(seed=4261, binary_path=firefox_binary, headless=True) as browser:
context = browser.new_context()
if route:
context.route("**/*", lambda r: r.continue_())
page = context.new_page()
page.on("request", lambda r: started.append(r.url.replace(site, "")))
page.on("requestfinished", lambda r: ended.append(r.url.replace(site, "")))
page.on("requestfailed", lambda r: ended.append(r.url.replace(site, "")))
page.goto(site + "/", wait_until="load")
page.wait_for_timeout(2000) # the client is a sync one: events are delivered while it calls the browser
seen = sorted(u for u in started if u.startswith("/seen/"))
assert seen == ["/seen/beacon", "/seen/keepalive", "/seen/keepalive-nocors", "/seen/plain"], \
"the client heard these requests: %r" % started
assert sorted(u for u in ended if u.startswith("/seen/")) == seen, \
"requests without an end for the client: %r" % sorted(set(seen) - set(ended))
@@ -105,13 +105,14 @@ def test_a_bare_launch_behind_a_proxy_is_composed_through_it(firefox_binary, mon
from invisible_core._geo import SessionGeo
from invisible_playwright import _session
from invisible_playwright._pw.sync_api import sync_playwright
from test_webrtc_realness import _PROBE_JS, _Socks5TcpOnly, candidates, host_is_mdns
from _socks_servers import Socks5TcpOnly
from test_webrtc_realness import _PROBE_JS, candidates, host_is_mdns
egress = "203.0.113.7"
monkeypatch.delenv("STEALTHFOX_WEBRTC_NETWORK", raising=False)
measured = []
def through_the_proxy(timezone, proxy, locale):
def through_the_proxy(timezone, proxy, locale, **_kw):
measured.append(proxy)
return SessionGeo("America/New_York", egress,
locale=decide_session_locale("en-US"))
@@ -132,7 +133,7 @@ def test_a_bare_launch_behind_a_proxy_is_composed_through_it(firefox_binary, mon
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Page)
threading.Thread(target=httpd.serve_forever, daemon=True).start()
socks = _Socks5TcpOnly()
socks = Socks5TcpOnly()
try:
with sync_playwright() as p:
browser = p.firefox.launch(executable_path=firefox_binary, headless=True,
+12 -1
View File
@@ -51,11 +51,22 @@ class _SlowEngine(EventListeners):
class _Page:
def __init__(self, server, context, session, target_id, number, opener=None):
def __init__(self, server, context, session, target_id, number, opener=None, is_gone=None):
self.target_id = target_id
self.number = number
self.channel = {"guid": "page-" + target_id}
gone_while_building = False
def wait_until_ready(self, timeout=20.0):
pass # the engine of this test says Page.ready at once
def settle_events(self):
pass
def announce(self, context, replay):
context.emit("page", {"page": self.channel})
def announce_closed(self):
pass
@@ -0,0 +1,581 @@
"""A page is handed over to the client only once the engine says Page.ready.
NO BROWSER HERE: the real dispatchers over a scripted Juggler connection (the one of the registry test) whose pages announce their
frame at birth and say `Page.ready` only when the test tells them to, as the real engine does after its transient about:blank
navigations.
⛔ THE KNOWN-BAD INPUT. The engine commits the page's initial about:blank AFTER it announces the frame; a `goto` sent in between is
'interrupted by another navigation to about:blank'. A wrapper that hands the page over on the main frame alone (no wait for
Page.ready) returns `new_page()` while the engine is still in that window; so does the adoption of a popup.
Known-bad: with the wait for Page.ready removed (a21e1de), the first two tests fail - the page is delivered before Page.ready; with
the wait INSIDE the constructor (7db28e4..6a60dce), the last two fail - a popup opened by a link has its first request held by a
route until its page answers, so a page that is only built once it is ready never becomes ready, and what the engine says between
the commit and the ready (the commit itself, the `load`) is said to a page that does not exist yet and is lost; the client's popup
then has no `load` to wait for. The page is BUILT at once and ANNOUNCED when ready.
"""
from __future__ import annotations
import threading
import time
import pytest
from invisible_playwright._juggler import remote
from invisible_playwright._juggler.server import FrameDispatcher, LocalUtilsDispatcher
from test_a_closed_context_leaves_nothing_in_the_registry import ScriptedJuggler
pytestmark = pytest.mark.unit
#: how long a page that must NOT be delivered yet is watched
WATCH = 0.4
class LateReadyJuggler(ScriptedJuggler):
"""The engine of the registry test, except that Page.ready is held back until `say_ready(session)`."""
def __init__(self):
super().__init__()
self.held = {}
self.released = set()
self.queued = []
def dispatch_event(self, method, params, session=None):
if method == "Page.ready" and session not in self.released:
self.held[session] = (method, params)
return None
return super().dispatch_event(method, params, session)
def send(self, method, params=None, session=None, timeout=30):
if method == "Browser.getInfo":
# a reply comes after everything the engine sent before it: the events queued as "sent with the ready" arrive first
queued, self.queued = self.queued, []
for event, event_params, event_session in queued:
super().dispatch_event(event, event_params, event_session)
return {}
return super().send(method, params, session, timeout)
def say_ready(self, session):
self.released = set(self.released) | {session}
method, params = self.held.pop(session)
super().dispatch_event(method, params, session)
def popup_born(self, opener_target, context_id, n):
"""A target the opener opened: attached and framed, but not ready."""
target, session = "p%d" % n, "ps%d" % n
self.sessions[target] = session
self.dispatch_event("Browser.attachedToTarget", {
"sessionId": session,
"targetInfo": {"targetId": target, "type": "page", "openerId": opener_target,
"browserContextId": context_id}}, None)
self.dispatch_event("Page.frameAttached", {"frameId": "f" + target, "parentFrameId": None}, session)
for world in ("", "utility"):
self.dispatch_event("Runtime.executionContextCreated", {
"executionContextId": "e%s%s" % (target, world),
"auxData": {"frameId": "f" + target, "name": world}}, session)
self.dispatch_event("Page.ready", {}, session)
return target, session
@pytest.fixture
def late_browser():
server = remote._SharedServer()
browser_type = remote.SharedBrowserType(server)
LocalUtilsDispatcher(server)
conn = LateReadyJuggler()
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
yield browser
for session in list(conn.held):
conn.say_ready(session)
time.sleep(0.1)
for context in list(browser.contexts):
try:
server.handle({"guid": context.guid, "method": "close", "params": {}})
except Exception:
pass
server.shutdown()
def _new_context(browser):
server = browser.server
return server.object(server.handle(
{"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
def test_new_page_returns_only_after_page_ready(late_browser):
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
answer = {}
def new_page():
answer["reply"] = server.handle(
{"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
worker = threading.Thread(target=new_page, daemon=True)
worker.start()
deadline = time.monotonic() + 5
while not conn.held and time.monotonic() < deadline:
time.sleep(0.01)
assert conn.held, "the page was never born in the scripted engine"
worker.join(WATCH)
assert worker.is_alive() and "reply" not in answer, (
"new_page() returned before the engine said Page.ready: the page would be handed over inside the window where a goto is "
"interrupted by the engine's own about:blank")
assert not context.pages, "the page was registered before it was ready"
(session,) = conn.held
conn.say_ready(session)
worker.join(5)
assert not worker.is_alive() and "reply" in answer, "new_page() did not return after Page.ready"
assert len(context.pages) == 1
def test_a_popup_is_announced_only_after_page_ready(late_browser):
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
# the opener: ready at once
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
assert len(context.pages) == 1
opener_target = next(iter(conn.sessions))
announced = []
original = context.emit
def spy(event, params=None):
if event == "page":
announced.append(time.monotonic())
return original(event, params)
context.emit = spy
target, session = conn.popup_born(opener_target, context.context_id, 1)
time.sleep(WATCH)
assert not announced and len(context.pages) == 1, (
"the popup was announced before the engine said Page.ready for it")
conn.say_ready(session)
deadline = time.monotonic() + 5
while not announced and time.monotonic() < deadline:
time.sleep(0.01)
assert announced, "the popup was never announced after Page.ready"
assert len(context.pages) == 2
def _unannounced_page(browser, session):
return next(o for o in browser.server._objects.values()
if o.TYPE == "Page" and getattr(o, "session", None) == session)
def test_a_popup_exists_and_listens_while_it_waits_for_its_ready(late_browser):
"""The first request of a popup opened by a link is held by a route until its page answers: the page must be built to answer."""
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
target, session = conn.popup_born(opener_target, context.context_id, 1)
deadline = time.monotonic() + 5
page = None
while page is None and time.monotonic() < deadline:
try:
page = _unannounced_page(late_browser, session)
except StopIteration:
time.sleep(0.01)
assert page is not None, "the popup was not built while the engine had not said Page.ready: nothing answers its first request"
time.sleep(0.2)
assert page._held is None, "the popup is built but does not listen: the events of its birth are held"
assert len(context.pages) == 1, "and it was announced before it was ready"
def test_what_a_popup_does_before_its_ready_reaches_its_frame(late_browser, monkeypatch):
"""The engine says Page.ready at the commit of the popup's first document; the `load` follows at once. Both reach the client."""
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
said = []
original = FrameDispatcher.emit
def spy(self, event, params=None):
said.append((self.frame_id, event, params))
return original(self, event, params)
monkeypatch.setattr(FrameDispatcher, "emit", spy)
target, session = conn.popup_born(opener_target, context.context_id, 1)
frame_id = "f" + target
url = "http://127.0.0.1/popup"
conn.dispatch_event("Page.navigationStarted", {"frameId": frame_id, "navigationId": "n1", "url": url}, session)
conn.dispatch_event("Page.navigationCommitted", {"frameId": frame_id, "navigationId": "n1", "url": url, "name": ""}, session)
conn.dispatch_event("Page.eventFired", {"frameId": frame_id, "name": "DOMContentLoaded"}, session)
conn.dispatch_event("Page.eventFired", {"frameId": frame_id, "name": "load"}, session)
conn.say_ready(session)
deadline = time.monotonic() + 5
while len(context.pages) < 2 and time.monotonic() < deadline:
time.sleep(0.01)
assert len(context.pages) == 2, "the popup was never announced"
popup = context.pages[1]
assert popup.frame.url == url, "the frame of the popup was told about:blank: its commit was said to a page that did not exist"
heard = set(popup.frame.initializer["loadStates"])
heard |= {params["add"] for fid, event, params in said
if fid == frame_id and event == "loadstate" and params and "add" in params}
assert "load" in heard, ("the client's frame never heard `load` of the popup (heard %s): wait_for_url(until=load) would wait for ever"
% sorted(heard))
def test_a_popup_waits_for_its_ready_without_a_limit_and_a_requested_page_for_twenty_seconds(late_browser, monkeypatch):
"""Playwright's popup is reported on Page.ready with no limit (a destination that answers after 25 s gives the event at 25 s); the
page a caller asked for waits 20 s and fails."""
from invisible_playwright._juggler.server import PageDispatcher
waited = []
original = PageDispatcher.wait_until_ready
def spy(self, timeout=20.0):
waited.append(timeout)
return original(self, timeout)
monkeypatch.setattr(PageDispatcher, "wait_until_ready", spy)
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
conn.popup_born(opener_target, context.context_id, 1)
deadline = time.monotonic() + 5
while len(waited) < 2 and time.monotonic() < deadline:
time.sleep(0.01)
assert waited == [20.0, None], "a requested page waits 20 s, a popup without a limit: %r" % (waited,)
def test_a_popup_that_never_gets_its_ready_ends_with_its_context_and_says_nothing(late_browser):
"""204, a server that never answers: no ready, no `page` event, no warning; closing the context ends the wait."""
import warnings
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
announced = []
original = context.emit
context.emit = lambda event, params=None: (announced.append(event) if event == "page" else None, original(event, params))[1]
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
conn.popup_born(opener_target, context.context_id, 1)
time.sleep(0.5)
assert not announced, "a popup with no ready was announced"
assert any(a.state == "waiting" for a in late_browser._adoptions.values()), "the popup is not waiting"
server.handle({"guid": context.guid, "method": "close", "params": {}})
deadline = time.monotonic() + 5
while late_browser._adoptions and time.monotonic() < deadline:
time.sleep(0.01)
assert not late_browser._adoptions, "closing the context did not end the wait of the popup"
time.sleep(0.2)
assert not announced, "a popup of a closed context was announced"
assert not [w for w in caught if "adoption" in str(w.message)], [str(w.message) for w in caught]
def test_a_popup_is_announced_with_the_address_of_the_commit_that_came_with_its_ready(late_browser):
"""The engine says Page.ready and, in the same turn, the commit of the document: the client is told the page after the commit, so
the url it reads at the `page` event is the destination, as Playwright's is (3 of 4 popups said about:blank)."""
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
urls = []
original = context.emit
def spy(event, params=None):
if event == "page":
page = next(o for o in server._objects.values() if o.TYPE == "Page" and o.channel == params["page"])
urls.append(page.frame.url)
return original(event, params)
context.emit = spy
target, session = conn.popup_born(opener_target, context.context_id, 1)
frame_id = "f" + target
url = "http://127.0.0.1/slow"
deadline = time.monotonic() + 5
while not any(o.TYPE == "Page" and getattr(o, "session", None) == session for o in server._objects.values()) and time.monotonic() < deadline:
time.sleep(0.01)
conn.queued.append(("Page.navigationStarted", {"frameId": frame_id, "navigationId": "n1", "url": url}, session))
conn.queued.append(("Page.navigationCommitted", {"frameId": frame_id, "navigationId": "n1", "url": url, "name": ""}, session))
conn.say_ready(session) # the commit follows in the stream: it is delivered with the round trip that comes back after it
deadline = time.monotonic() + 5
while not urls and time.monotonic() < deadline:
time.sleep(0.01)
assert urls == [url], "the popup was announced with %r, not with the address of the commit that came with its ready" % (urls,)
def test_a_download_started_by_a_popup_that_is_not_announced_is_reported_on_its_opener_after_the_popup(late_browser):
"""`<a target=_blank href=file>` with `Content-Disposition: attachment`: the new tab never gets a Page.ready and the engine closes it at
once. Playwright reports the download on the OPENER (ffBrowser._onDownloadCreated) and the popup before it; looking only among the
announced pages lost the download, and saying it at once put it before the popup (a client that read the popup the moment the
download arrived found none on a loaded machine)."""
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
opener = next(o for o in server._objects.values() if o.TYPE == "Page" and o.target_id == opener_target)
order = []
original_opener = opener.emit
opener.emit = lambda event, params=None: (order.append(event), original_opener(event, params))[1]
original_context = context.emit
context.emit = lambda event, params=None: (order.append("context:" + event), original_context(event, params))[1]
target, session = conn.popup_born(opener_target, context.context_id, 1)
deadline = time.monotonic() + 5
while not (target in late_browser._adoptions and late_browser._adoptions[target].state == "waiting") and time.monotonic() < deadline:
time.sleep(0.01)
conn.dispatch_event("Browser.downloadCreated", {
"uuid": "u1", "browserContextId": context.context_id, "pageTargetId": target, "frameId": "f" + target,
"url": "http://127.0.0.1/file", "suggestedFileName": "f.bin"}, None)
assert "download" not in order, "the download was said before the popup it came from: %r" % (order,)
conn.dispatch_event("Browser.detachedFromTarget", {"targetId": target, "sessionId": session}, None) # the tab is closed
deadline = time.monotonic() + 5
while "download" not in order and time.monotonic() < deadline:
time.sleep(0.01)
assert "download" in order, "the download of the popup was not reported on its opener: %r" % (order,)
assert order.index("context:page") < order.index("download"), "the download came before the popup: %r" % (order,)
def test_the_load_of_a_popup_said_before_its_announcement_is_said_again_right_after_it(late_browser, monkeypatch):
"""A listener registered in the handler of the `page` event (`page.on("load")`) hears the load of a popup in Playwright, because the
page is reported after its ready and the load follows. Here the document may have loaded before the client hears of the page: the
two states are said again after the announcement, in order, and the first time they already set the state `wait_for_load_state`
reads."""
from invisible_playwright._juggler import dispatcher as base
trace = []
original = base.Dispatcher.emit
def spy(self, method, params=None):
if method == "page":
trace.append("page")
elif getattr(self, "TYPE", "") == "Frame" and method == "loadstate" and params and "add" in params:
trace.append(params["add"])
return original(self, method, params)
monkeypatch.setattr(base.Dispatcher, "emit", spy)
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
target, session = conn.popup_born(opener_target, context.context_id, 1)
deadline = time.monotonic() + 5
while not (target in late_browser._adoptions and late_browser._adoptions[target].state == "waiting") and time.monotonic() < deadline:
time.sleep(0.01)
frame_id, url = "f" + target, "http://127.0.0.1/slow"
conn.dispatch_event("Page.navigationStarted", {"frameId": frame_id, "navigationId": "n1", "url": url}, session)
conn.dispatch_event("Page.navigationCommitted", {"frameId": frame_id, "navigationId": "n1", "url": url, "name": ""}, session)
conn.dispatch_event("Page.eventFired", {"frameId": frame_id, "name": "DOMContentLoaded"}, session)
conn.dispatch_event("Page.eventFired", {"frameId": frame_id, "name": "load"}, session)
del trace[:] # what is said from here on: the ready, the announcement, the replay
conn.say_ready(session)
deadline = time.monotonic() + 5
while trace.count("load") < 1 and time.monotonic() < deadline:
time.sleep(0.01)
time.sleep(0.2)
assert "page" in trace, trace
after = trace[trace.index("page") + 1:]
assert after == ["domcontentloaded", "load"], "after the announcement the client heard %r" % (after,)
def test_a_popup_whose_target_goes_away_while_its_page_is_being_built_is_announced_and_closed(late_browser, monkeypatch):
"""A download's empty tab closes within milliseconds; on a loaded machine the page of the popup is still being built when the engine
detaches it. That detach went by with nobody to tell, and the wait for a ready that never comes went on for ever: the popup was never
announced (the full suite failed once on it)."""
from invisible_playwright._juggler.server import PageDispatcher
original_init = PageDispatcher.__init__
def slow_init(self, *args, **kwargs):
time.sleep(0.4) # the build is slower than the detach
return original_init(self, *args, **kwargs)
monkeypatch.setattr(PageDispatcher, "__init__", slow_init)
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
monkeypatch.undo() # the opener is built at normal speed
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
monkeypatch.setattr(PageDispatcher, "__init__", slow_init)
opener_target = next(iter(conn.sessions))
announced, closed = [], []
original = context.emit
context.emit = lambda event, params=None: (announced.append(event) if event == "page" else None, original(event, params))[1]
target, session = conn.popup_born(opener_target, context.context_id, 1)
conn.dispatch_event("Browser.detachedFromTarget", {"targetId": target, "sessionId": session}, None)
deadline = time.monotonic() + 5
while "page" not in announced and time.monotonic() < deadline:
time.sleep(0.01)
assert "page" in announced, "the popup that went away while its page was being built was never announced"
@pytest.mark.parametrize("command", ["Page.setInitScripts", "Browser.getInfo"])
def test_a_command_of_the_adoption_that_finds_the_session_gone_announces_and_closes_the_popup(late_browser, command, monkeypatch):
"""The tab goes away WHILE the adoption initializes it: the engine answers 'cannot find session' to a command of the adoption. Like a
detach before the ready, that ends in the page announced and closed (Playwright's does), never in a discard with a warning: the
download of a link into a new tab was lost one time in a hundred (independent run, quiet machine)."""
import warnings
from invisible_core.juggler.connection import ProtocolError
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
original_send = conn.send
def send(method, params=None, session=None, timeout=30):
if method == command and session not in (None, "s1"):
raise ProtocolError('%s: ERROR: cannot find session with id "%s"' % (method, session))
return original_send(method, params, session, timeout)
monkeypatch.setattr(conn, "send", send)
announced = []
original = context.emit
context.emit = lambda event, params=None: (announced.append(event) if event == "page" else None, original(event, params))[1]
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
target, session = conn.popup_born(opener_target, context.context_id, 1)
if command == "Browser.getInfo":
conn.say_ready(session) # this one is asked once the page is ready
else:
conn.dispatch_event("Browser.detachedFromTarget", {"targetId": target, "sessionId": session}, None)
deadline = time.monotonic() + 5
while "page" not in announced and time.monotonic() < deadline:
time.sleep(0.01)
time.sleep(0.2)
assert "page" in announced, "the popup whose session was gone was discarded instead of announced"
assert not [w for w in caught if "adoption" in str(w.message)], [str(w.message) for w in caught]
def test_a_popup_that_is_dropped_or_fails_leaves_the_trace_of_what_the_engine_said(late_browser, monkeypatch):
"""The log of a red run on a machine nobody can look at does not say in which order the events came: the adoption keeps a short trace
per target and writes it in the warning of a failed adoption and in the record of the dropped ones."""
import warnings
from invisible_playwright._juggler.server import PageDispatcher
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
# 1. dropped with its context
target, session = conn.popup_born(opener_target, context.context_id, 1)
deadline = time.monotonic() + 5
while not (target in late_browser._adoptions and late_browser._adoptions[target].state == "waiting") and time.monotonic() < deadline:
time.sleep(0.01)
server.handle({"guid": context.guid, "method": "close", "params": {}})
deadline = time.monotonic() + 5
while not late_browser._dropped and time.monotonic() < deadline:
time.sleep(0.01)
assert late_browser._dropped, "a popup dropped with its context left no trace"
dropped_target, text = late_browser._dropped[-1]
assert dropped_target == target
for word in ("attached", "frameAttached", "building", "waiting", "dropped: its context closed"):
assert word in text, "the trace of the dropped popup lacks %r: %s" % (word, text)
# 2. a failed adoption writes it in its warning
context2 = _new_context(late_browser)
def boom(self, *args, **kwargs):
raise ValueError("boom")
conn.released = {"s1", "s2"}
monkeypatch.setattr(PageDispatcher, "__init__", boom)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
conn.popup_born(opener_target, context2.context_id, 2)
deadline = time.monotonic() + 5
while not [w for w in caught if "adoption" in str(w.message)] and time.monotonic() < deadline:
time.sleep(0.01)
messages = [str(w.message) for w in caught if "adoption" in str(w.message)]
assert messages and "events of the target" in messages[0] and "attached" in messages[0], messages
def test_a_download_that_comes_while_the_adoption_fails_is_said_once_on_the_opener(late_browser, monkeypatch):
"""The adoption of a popup fails; the engine says the download of that tab in the step between the moment the adoption looks for its
pending downloads and the moment it removes its record (forced here: right after the first time the adoption thread lets go of the
browser's lock once it has failed). The download queued on a record that is about to vanish was said by nobody. It is said, once, on the
opener: taking the pending ones and removing the record are ONE step, and the opener of a target not announced is remembered."""
import warnings
from invisible_playwright._juggler.server import PageDispatcher
server, conn = late_browser.server, late_browser.conn
context = _new_context(late_browser)
conn.released = {"s1"}
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(iter(conn.sessions))
opener = next(o for o in server._objects.values() if o.TYPE == "Page" and o.target_id == opener_target)
said = []
original_emit = opener.emit
opener.emit = lambda event, params=None: (said.append(event), original_emit(event, params))[1]
state = {"failing": False, "delivered": False}
target = "p1"
def deliver():
state["delivered"] = True
late_browser._on_download_created({
"uuid": "u9", "browserContextId": context.context_id, "pageTargetId": target, "frameId": "f" + target,
"url": "http://127.0.0.1/file", "suggestedFileName": "f.bin"})
class Tracked:
def __init__(self, inner):
self.inner = inner
def __enter__(self):
self.inner.acquire()
return self
def __exit__(self, *exc):
self.inner.release()
if state["failing"] and not state["delivered"] and threading.current_thread().name.startswith("invpw-adopt-p1"):
deliver()
def acquire(self, *a, **k):
return self.inner.acquire(*a, **k)
def release(self):
return self.inner.release()
def boom(self, *args, **kwargs):
state["failing"] = True
raise ValueError("boom")
monkeypatch.setattr(PageDispatcher, "__init__", boom)
monkeypatch.setattr(late_browser, "_targets_lock", Tracked(late_browser._targets_lock))
with warnings.catch_warnings(record=True):
warnings.simplefilter("always")
conn.popup_born(opener_target, context.context_id, 1)
deadline = time.monotonic() + 5
while not state["delivered"] and time.monotonic() < deadline:
time.sleep(0.01)
time.sleep(0.2)
assert state["delivered"], "the adoption never failed"
assert said.count("download") == 1, "the download that came while the adoption failed was said %d times: %r" % (said.count("download"), said)
def test_the_opener_of_a_target_the_engine_already_took_away_is_not_remembered(late_browser):
"""A download cannot come from a target that is detached: no entry is made for it (the table of openers is for the targets the
engine still has when their adoption ends without announcing them)."""
from types import SimpleNamespace
gone = SimpleNamespace(target_id="t-gone", opener="o-1", gone=True)
with late_browser._targets_lock:
late_browser._remember_opener(gone)
assert "t-gone" not in late_browser._gone_openers
def test_the_opener_of_a_failed_adoption_lives_until_the_target_detaches_and_the_cap_holds(late_browser):
from types import SimpleNamespace
alive = SimpleNamespace(target_id="t-alive", opener="o-2", gone=False)
with late_browser._targets_lock:
late_browser._remember_opener(alive)
assert late_browser._gone_openers.get("t-alive") == "o-2", "the opener of a failed adoption was not remembered"
late_browser._handle_detach("t-alive", "s-alive")
assert "t-alive" not in late_browser._gone_openers, "the entry outlived the detach of its target"
for number in range(20):
with late_browser._targets_lock:
late_browser._remember_opener(SimpleNamespace(target_id="t%d" % number, opener="o", gone=False))
assert len(late_browser._gone_openers) == 16 and "t0" not in late_browser._gone_openers and "t19" in late_browser._gone_openers
@@ -0,0 +1,176 @@
"""A popup is reported on Page.ready, as Playwright's own is: with no limit, and with the destination's address already.
Measured against stock Playwright 1.62 and its Firefox (in-process, 2 runs of each, never in disagreement):
* a destination that answers 204, or never answers: NO `page` event in 30 s (nothing commits, the engine never says Page.ready);
* a destination that answers after 4 s: the event at 4.08 s, with `url` already the destination and `load` in the same millisecond.
Here: the same two, in-process and through a served browser driven by a stock client, and a destination that answers after 25 s (the
wrapper dropped a popup that was not ready in 20 s, with a warning); the address read at the `page` event is the destination.
Red on b09d620: the popup of the slow destination reads `about:blank` at the event (the commit comes in the same turn as the ready and
was applied after the page was announced), and the one that answers after 25 s was dropped at 20 s.
"""
from __future__ import annotations
import threading
import time
from http.server import BaseHTTPRequestHandler
import pytest
from _servers import LocalServer
pytestmark = pytest.mark.e2e
class _Handler(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
path, _, query = self.path.partition("?")
if path == "/nocontent":
self.send_response(204)
self.send_header("Content-Length", "0")
self.end_headers()
return
if path == "/slow":
ms = int(query.split("ms=")[1].split("&")[0]) if "ms=" in query else 0
time.sleep(ms / 1000.0)
body = b"<!doctype html><html><head><title>slow</title></head><body>slow</body></html>"
else:
body = (b"<!doctype html><html><head><title>opener</title></head><body>"
b"<button id=open204 onclick=\"window.open('/nocontent','_blank')\">open</button>"
b"<a id=link204 href=/nocontent target=_blank>link</a>"
b"<button id=open1500 onclick=\"window.open('/slow?ms=1500','_blank')\">open</button>"
b"<a id=link1500 href='/slow?ms=1500' target=_blank>link</a>"
b"<button id=open25000 onclick=\"window.open('/slow?ms=25000','_blank')\">open</button>"
b"</body></html>")
try:
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
except OSError: # the browser left before a slow answer
pass
@pytest.fixture
def site():
srv = LocalServer(("127.0.0.1", 0), _Handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
try:
yield "http://127.0.0.1:%d/" % srv.server_address[1]
finally:
srv.shutdown()
srv.server_close()
def _stock_client(module):
import importlib
try:
return importlib.import_module(module)
except ImportError as exc: # pragma: no cover - only in a broken environment
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc, pytrace=False)
def _drive(mode, firefox_binary, body):
"""Run body(context, page) in-process or through a served browser driven by a stock client."""
if mode == "in-process":
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, humanize=False) as b:
ctx = b.new_context()
body(ctx, ctx.new_page())
ctx.close()
return
from invisible_playwright._juggler.remote import launch_server
sync_playwright = _stock_client("playwright.sync_api").sync_playwright
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)
ctx = browser.new_context()
body(ctx, ctx.new_page())
ctx.close()
browser.close()
finally:
server.close()
MODES = ["in-process", "served"]
@pytest.mark.parametrize("mode", MODES)
@pytest.mark.parametrize("opener", ["#open204", "#link204"])
def test_a_destination_that_commits_nothing_gives_no_popup_event(firefox_binary, site, mode, opener):
def body(ctx, page):
page.goto(site, wait_until="load", timeout=30000)
seen = []
ctx.on("page", lambda p: seen.append(p))
page.click(opener)
time.sleep(6)
assert not seen, "a popup whose destination commits nothing was reported (Playwright's is not)"
assert len(ctx.pages) == 1
_drive(mode, firefox_binary, body)
@pytest.mark.parametrize("mode", MODES)
@pytest.mark.parametrize("opener", ["#open1500", "#link1500"])
def test_a_slow_popup_is_reported_with_the_address_of_its_destination(firefox_binary, site, mode, opener):
def body(ctx, page):
page.goto(site, wait_until="load", timeout=30000)
with page.expect_popup(timeout=20000) as info:
page.click(opener)
assert info.value.url == site + "slow?ms=1500", "the popup was reported with %r" % info.value.url
info.value.close()
_drive(mode, firefox_binary, body)
@pytest.mark.parametrize("mode", MODES)
def test_a_popup_whose_destination_answers_after_25_seconds_is_reported_then(firefox_binary, site, mode):
def body(ctx, page):
page.goto(site, wait_until="load", timeout=30000)
t0 = time.monotonic()
with page.expect_popup(timeout=45000) as info:
page.click("#open25000")
took = time.monotonic() - t0
assert 24.0 < took < 40.0, "reported after %.1f s" % took
assert info.value.url == site + "slow?ms=25000"
info.value.close()
_drive(mode, firefox_binary, body)
@pytest.mark.parametrize("mode", MODES)
@pytest.mark.parametrize("opener", ["#open1500", "#link1500"])
def test_a_listener_registered_in_the_page_handler_hears_the_load_of_the_popup(firefox_binary, site, mode, opener):
"""Stock Playwright: `context.on("page", lambda p: p.on("load", ...))` fires for a popup that loads after the event (4 s and 25 s
destinations); the popup is reported when its ready comes, which is when its document commits, so the load may be said before the
client has the page. `wait_for_load_state` in the same handler returns at once."""
def body(ctx, page):
page.goto(site, wait_until="load", timeout=30000)
heard, waited = [], []
def on_page(popup):
popup.on("load", lambda p: heard.append(time.monotonic()))
t = time.monotonic()
popup.wait_for_load_state("load", timeout=10000)
waited.append(time.monotonic() - t)
ctx.on("page", on_page)
with page.expect_popup(timeout=20000) as info:
page.click(opener)
deadline = time.monotonic() + 5
while not heard and time.monotonic() < deadline:
page.wait_for_timeout(50)
assert heard, "the listener registered in the handler of the page event never heard the load of the popup"
assert waited and waited[0] < 8.0, "wait_for_load_state in the handler took %r" % (waited,) # at once; the limit is the machine's
info.value.close()
_drive(mode, firefox_binary, body)
@@ -0,0 +1,136 @@
"""A tab opened by a link (`target=_blank`, with or without `noopener`) or by `window.open` reaches the client, in-process and
through a served browser driven by a stock Playwright client, with and without a context route holding the requests.
⛔ THE KNOWN-BAD INPUT. The page is handed to the client when the engine says `Page.ready`; the engine says it at the commit of the
popup's first document. Waiting for it INSIDE the construction of the page (7db28e4..6a60dce) broke two ways, each found by a run:
* the first request of a popup is held by the context's route until the page answers it, and a page that is built only once it is
ready never answers: `adoption of target ... failed: the page was not ready in 20s` on the server, `Timeout 15000ms exceeded while
waiting for event "page"` on the client (a stock client, a served browser, a route that continues every request);
* in-process, the commit and the `load` that come with the ready were said to a page that did not exist: `popup.wait_for_url(url)`
timed out on `load` (5 tests of test_popup_pages.py).
The page is now BUILT at once and ANNOUNCED when ready.
"""
from __future__ import annotations
import threading
import time
from http.server import BaseHTTPRequestHandler
import pytest
from _servers import LocalServer
pytestmark = pytest.mark.e2e
POPUP = b"<!doctype html><html><head><title>popup</title></head><body><h1>popup</h1></body></html>"
class _Handler(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
path = self.path.split("?")[0]
if path == "/popup":
body = POPUP
else:
# the same server by another NAME is another site: the document lands in another process (Fission)
port = self.server.server_address[1]
other = ("http://localhost:%d/popup" % port).encode()
body = (b"<!doctype html><html><head><title>opener</title></head><body>"
b"<a id=link href=/popup target=_blank>link</a>"
b"<a id=noopener href=/popup target=_blank rel=noopener>noopener</a>"
b"<button id=open onclick=\"window.open('/popup','_blank')\">open</button>"
b"<button id=open-noopener onclick=\"window.open('/popup','_blank','noopener')\">open</button>"
b"<a id=xlink href=" + other + b" target=_blank>cross-site link</a>"
b"<a id=xnoopener href=" + other + b" target=_blank rel=noopener>cross-site noopener</a>"
b"<button id=xopen onclick=\"window.open('" + other + b"','_blank')\">open</button>"
b"<button id=xopen-noopener onclick=\"window.open('" + other + b"','_blank','noopener')\">open</button>"
b"</body></html>")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
@pytest.fixture
def site():
srv = LocalServer(("127.0.0.1", 0), _Handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
try:
yield "http://127.0.0.1:%d/" % srv.server_address[1]
finally:
srv.shutdown()
srv.server_close()
def _stock_client(module):
"""The stock Playwright client, a pinned dev dependency: its absence is a broken environment, not a reason to skip."""
import importlib
try:
return importlib.import_module(module)
except ImportError as exc: # pragma: no cover - only in a broken environment
pytest.fail("the stock Playwright client is missing (%s): install the wrapper with its dev extra" % exc, pytrace=False)
OPENERS = ["#link", "#noopener", "#open", "#open-noopener", "#xlink", "#xnoopener", "#xopen", "#xopen-noopener"]
def _router(delay_s):
def route(route):
time.sleep(delay_s) # a client that decides: the popup's first request waits for it
route.continue_()
return route
def _check(page, popup_of, site, opener):
page.goto(site, wait_until="load", timeout=30000)
# The verdict is that the popup arrives, with its address and its load: how long it takes depends on the machine (a runner with four
# workers took 2.0 s once), so no time limit here beyond a generous wait.
with page.expect_popup(timeout=30000) as info:
page.click(opener)
popup = info.value
popup.wait_for_load_state("load", timeout=5000)
expected = (site.replace("127.0.0.1", "localhost") if opener.startswith("#x") else site) + "popup"
assert popup.url == expected
assert popup.title() == "popup"
assert popup in page.context.pages
popup.close()
@pytest.mark.parametrize("routed", [False, True], ids=["plain", "routed"])
@pytest.mark.parametrize("opener", OPENERS)
def test_a_popup_reaches_an_in_process_client(firefox_binary, site, opener, routed):
from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, humanize=False) as b:
ctx = b.new_context()
if routed:
ctx.route("**/*", _router(0.05))
page = ctx.new_page()
_check(page, None, site, opener)
ctx.close()
@pytest.mark.parametrize("routed", [False, True], ids=["plain", "routed"])
@pytest.mark.parametrize("opener", OPENERS)
def test_a_popup_reaches_a_stock_client_of_a_served_browser(firefox_binary, site, opener, routed):
from invisible_playwright._juggler.remote import launch_server
sync_playwright = _stock_client("playwright.sync_api").sync_playwright # a stock client, as production uses
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)
ctx = browser.new_context()
if routed:
ctx.route("**/*", _router(0.05))
page = ctx.new_page()
_check(page, None, site, opener)
ctx.close()
browser.close()
finally:
server.close()
@@ -0,0 +1,154 @@
"""A LOSS IS NOT A DROP: behind a proxy that cannot carry the UDP of a PeerConnection, nothing of the browser reaches a server direct.
The fail-closed rule of the UDP line is "the UDP of a PeerConnection behind a proxy that carries none goes NOWHERE: not to the relay, and
never direct, around the proxy". The e2e that check "no srflx" cannot tell the rule from a leak: in a laboratory whose servers sit at
documentation addresses nothing routes, a datagram sent direct arrives nowhere, exactly as a dropped one. Here the STUN server and the TCP
TURN listener of the page (a WITNESS, ``_witness.py``) stand at an address the browser CAN reach directly (a documentation address held
on ``lo``: root, Linux, the suite ``wrapper.e2e.udp.exit``), and the gateways leave from ANOTHER such address, the exit. So:
* in each fail-closed scenario - a proxy that refuses UDP, one whose UDP leaves from another address than its TCP, one whose relay never
answers, an HTTP proxy - the witness hears NO datagram from anyone and NO connection from a source that is not the exit; a send direct
fails this test;
* the controls, which are what makes the green mean something: the same page with NO proxy is heard by the witness (the laboratory does
see a direct send), and behind a coherent gateway the witness hears the datagrams from the EXIT only (the relay is seen too).
"""
from __future__ import annotations
import pytest
import _turn_chain as chain_mod
from _doh_servers import FakeDoh
from _host_address import this_host_address
from _http_proxy import HttpProxy
from _socks_servers import EXIT, OTHER_EXIT, Gateway
from _udp_line import declared_udp, egress_by_proxy, measure_servers
from _witness import Witness
from test_webrtc_realness import _e2e_binary, _launch, _launch_behind # noqa: F401
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
#: Where the witness stands: a documentation address (RFC 5737, TEST-NET-2) held on lo, reachable by the browser directly.
WITNESS_ADDRESS = "198.51.100.10"
#: The exit of the gateways (the address their datagrams and connections leave from): another documentation address on lo.
EXIT_ADDRESS = chain_mod.LAB_EXIT
#: How long the page waits after the offer: the first retransmissions of STUN and TURN (0, 0.1, 0.3, 0.7, 1.5, 3.1 s) have all been sent.
WAIT_MS = 5000
_PROBE_JS = """async (target) => {
const pc = new RTCPeerConnection({iceServers: [
{urls: ['stun:' + target]},
{urls: ['turn:' + target + '?transport=udp'], username: 'u', credential: 'p'},
{urls: ['turn:' + target + '?transport=tcp'], username: 'u', credential: 'p'}]});
pc.createDataChannel('x');
const found = [];
pc.onicecandidate = (e) => { if (e.candidate) found.push(e.candidate.candidate); };
await pc.setLocalDescription(await pc.createOffer());
await new Promise((resolve) => setTimeout(resolve, %d));
return found;
}""" % WAIT_MS
@pytest.fixture
def witness():
with chain_mod.lab_exit_address(EXIT_ADDRESS), chain_mod.lab_exit_address(WITNESS_ADDRESS):
w = Witness(WITNESS_ADDRESS)
try:
yield w
finally:
w.close()
def _gateway(**kw) -> Gateway:
"""A SOCKS5 gateway whose datagrams and connections leave from the exit address, with a relay on this host's address."""
kw.setdefault("tcp_exit", EXIT)
kw.setdefault("udp_exit", EXIT)
return Gateway(relay_host=this_host_address(), exit_host=EXIT_ADDRESS, tcp_from_exit=True, **kw)
def _gather(page_launcher, w: Witness):
with page_launcher() as browser:
page = browser.new_context().new_page()
page.goto("about:blank")
return page.evaluate(_PROBE_JS, w.target)
# (id, how the gateway is made, what the core must have declared for its UDP)
SOCKS_SCENARIOS = [
("the_proxy_refuses_udp", lambda: _gateway(udp="refuse"), "no"),
("the_udp_of_the_proxy_leaves_from_another_address", lambda: _gateway(udp="relay", udp_exit=OTHER_EXIT), "no"),
("the_relay_never_answers", lambda: _gateway(udp="relay", stun_answers=False), "unmeasured"),
]
@pytest.mark.parametrize("make,declared", [(m, d) for _i, m, d in SOCKS_SCENARIOS], ids=[i for i, _m, _d in SOCKS_SCENARIOS])
def test_behind_a_socks5_proxy_that_cannot_carry_the_udp_nothing_is_sent_direct(monkeypatch, witness, make, declared):
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
from invisible_core import _geo
gateway = make()
try:
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(gateway))
found = _gather(lambda: _launch_behind(gateway, binary_path=binary), witness)
assert declared_udp(gateway.proxy, measure_servers(gateway)) == declared, "the scenario is not the one it says"
finally:
gateway.close()
leaked = witness.heard_from_other_than([EXIT_ADDRESS])
assert not witness.heard()["udp"], (
"the witness heard a datagram behind a proxy that carries no UDP: %s (the exit is %s)" % (witness.heard()["udp"], EXIT_ADDRESS))
assert not leaked["tcp"], "a connection to the witness did not come from the proxy's exit: %s" % (leaked["tcp"],)
assert not [c for c in found if " typ srflx " in c or " typ relay " in c], "a candidate that nothing allocated: %s" % (found,)
def test_behind_an_http_proxy_nothing_is_sent_direct(monkeypatch, witness):
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
from invisible_core import _geo
doh = FakeDoh({})
proxy = HttpProxy("http-proxy", doh)
try:
monkeypatch.setattr(_geo, "discover_egress_ip", lambda *a, **k: EXIT)
found = _gather(lambda: _launch(proxy=proxy.proxy, binary_path=binary), witness)
finally:
proxy.close()
doh.close()
assert not witness.heard()["udp"], "the witness heard a datagram behind an HTTP proxy: %s" % (witness.heard()["udp"],)
assert not witness.heard()["tcp"], (
"the witness heard a connection behind an HTTP proxy that refuses it (the proxy never connected): %s" % (witness.heard()["tcp"],))
assert not [c for c in found if " typ srflx " in c or " typ relay " in c], "a candidate that nothing allocated: %s" % (found,)
def test_the_control_with_no_proxy_the_witness_hears_the_browser_direct(monkeypatch, witness):
"""Without this the green above proves nothing: the laboratory must SEE a direct datagram and a direct connection."""
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
from invisible_core import _geo
monkeypatch.setattr(_geo, "discover_egress_ip", lambda *a, **k: EXIT) # the world has no network: nothing to wait for
_gather(lambda: _launch(binary_path=binary), witness)
heard = witness.heard()
assert heard["udp"], "the witness heard no datagram of a browser with no proxy: the laboratory does not see a direct send"
assert heard["tcp"], "the witness heard no connection of a browser with no proxy: the laboratory does not see a direct connection"
assert not [h for h in heard["udp"] + heard["tcp"] if h[0] == EXIT_ADDRESS], "a direct send came from the exit of the gateways"
def test_the_control_behind_a_coherent_gateway_the_witness_hears_the_exit_only(monkeypatch, witness):
"""The relay is seen too: the datagrams and the connections of a proxy that carries UDP arrive FROM ITS EXIT, and from nowhere else."""
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
from invisible_core import _geo
gateway = _gateway(udp="relay")
try:
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(gateway))
_gather(lambda: _launch_behind(gateway, binary_path=binary), witness)
assert declared_udp(gateway.proxy, measure_servers(gateway)) == "coherent"
finally:
gateway.close()
heard = witness.heard()
assert heard["udp"], "the witness heard no datagram through a coherent relay"
assert not witness.heard_from_other_than([EXIT_ADDRESS])["udp"], (
"a datagram came from a source that is not the exit of the relay: %s" % (witness.heard_from_other_than([EXIT_ADDRESS])["udp"],))
assert not witness.heard_from_other_than([EXIT_ADDRESS])["tcp"], (
"a connection came from a source that is not the exit of the proxy: %s" % (witness.heard_from_other_than([EXIT_ADDRESS])["tcp"],))
+1 -1
View File
@@ -27,7 +27,7 @@ from invisible_playwright._juggler._marshal import _resource_type
("TYPE_MEDIA", "media"),
("TYPE_WEBSOCKET", "websocket"),
("TYPE_WEB_MANIFEST", "manifest"),
("TYPE_BEACON", "other"),
("TYPE_BEACON", "beacon"),
("TYPE_OTHER", "other"),
])
def test_the_cause_juggler_sends_names_the_resource(cause, expected):
@@ -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()
-47
View File
@@ -1,47 +0,0 @@
"""The drive gate's copy of the first-run declaration must not diverge from the core.
`scripts/ci_drive_gate.py` runs in a job that installs only Playwright, so it
carries FIRST_RUN, a literal copy of what invisible_core declares for the first
run, and writes it into the profile's user.js. Since firefox-55 the engine leaves
Mozilla's first-run lines and the core alone declares that state: without the
copy, run 41388672849 (2026-11-02) showed the terms-of-use modal on Windows
(no mouse event reached the page) and opened Mozilla's privacy page in a second
tab on Linux. This test binds the copy: a first-run pref the core adds, drops or
changes turns it red.
"""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
_GATE = Path(__file__).resolve().parents[1] / "scripts" / "ci_drive_gate.py"
_FIRST_RUN_PREFIXES = ("termsofuse.", "browser.preonboarding.", "datareporting.policy.")
def _first_run_from_gate() -> dict:
"""FIRST_RUN as the gate defines it, without importing Playwright (imported
inside `_drive`)."""
ns: dict = {}
head = _GATE.read_text(encoding="utf-8").split("\nHTML = (")[0]
exec(compile(head, str(_GATE), "exec"), ns) # noqa: S102 - our own file
return ns["FIRST_RUN"]
@pytest.mark.unit
@pytest.mark.parametrize("platform", ["win32", "linux"])
def test_ci_drive_gate_first_run_matches_the_core(monkeypatch, platform):
from invisible_core._fpforge import generate_profile
from invisible_core.prefs import translate_profile_to_prefs
monkeypatch.setattr(sys, "platform", platform)
prefs = translate_profile_to_prefs(generate_profile(970411), timezone="America/New_York")
from_core = {k: v for k, v in prefs.items() if k.startswith(_FIRST_RUN_PREFIXES)}
from_gate = _first_run_from_gate()
assert from_core, "the core declares no first-run state: the engine would show the modal"
assert from_gate == from_core, (
"FIRST_RUN in scripts/ci_drive_gate.py is no longer what invisible_core declares.\n"
" core: %r\n gate: %r" % (from_core, from_gate))
for k, v in from_gate.items():
assert type(v) is type(from_core[k]), k
@@ -0,0 +1,53 @@
"""The drive gate launches the binary through the wrapper and the core, never through bare Playwright.
Since firefox-63 the engine holds every channel that asks the proxy service until the client has said how the session
leaves the host (`Browser.setBrowserProxy`, or `Browser.setNoBrowserProxy` for a session without a proxy). The core's launch
sends that decision first; stock Playwright sends it only when it is given a proxy. A drive gate that launches with
`p.firefox.launch_persistent_context(executable_path=...)` therefore waits for a decision nobody takes: run 43134774602,
`Page.goto: Timeout 30000ms` on every leg, three attempts.
The core also declares the first run (terms of use, pre-onboarding), which the gate used to copy into user.js
(`FIRST_RUN`, tied to the core by a test of its own): with the launch through the core the copy has no reason to exist.
This test reads the script; it launches nothing.
"""
from __future__ import annotations
import ast
from pathlib import Path
import pytest
_GATE = Path(__file__).resolve().parents[1] / "scripts" / "ci_drive_gate.py"
def _tree() -> ast.Module:
return ast.parse(_GATE.read_text(encoding="utf-8"))
@pytest.mark.unit
def test_the_drive_gate_imports_no_playwright_client():
imported = []
for node in ast.walk(_tree()):
if isinstance(node, ast.Import):
imported += [a.name for a in node.names]
elif isinstance(node, ast.ImportFrom):
imported.append(node.module or "")
bare = [m for m in imported if m == "playwright" or m.startswith("playwright.")]
assert not bare, "the drive gate imports %s: a bare Playwright never tells the engine the road of the session" % bare
@pytest.mark.unit
def test_the_drive_gate_launches_with_the_wrapper_on_the_binary_under_test():
calls = [n for n in ast.walk(_tree()) if isinstance(n, ast.Call)
and getattr(n.func, "id", getattr(n.func, "attr", None)) == "InvisiblePlaywright"]
assert len(calls) == 1, "the drive gate must launch with InvisiblePlaywright, once"
keywords = {k.arg: k.value for k in calls[0].keywords}
assert isinstance(keywords.get("binary_path"), ast.Name) and keywords["binary_path"].id == "exe", \
"the binary under test is the gate's argument, handed over as binary_path="
assert isinstance(keywords.get("headless"), ast.Constant) and keywords["headless"].value is True
@pytest.mark.unit
def test_the_drive_gate_keeps_no_copy_of_the_first_run_declaration():
names = {t.id for n in ast.walk(_tree()) if isinstance(n, ast.Assign) for t in n.targets if isinstance(t, ast.Name)}
assert "FIRST_RUN" not in names, "the core declares the first run; a copy in the gate can only drift from it"
+329
View File
@@ -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,113 @@
"""E2E: the rule "a context WITH a proxy resolves by DoH through it, a context WITHOUT one resolves natively and never
uses the DoH", on the case where the two meet: a session with NO launch proxy and a context with a proxy of its own.
The session is launched without a proxy (the DEFAULT context is the browser's own network: it resolves natively), then a
context is made with its own SOCKS5 gateway (`new_context(proxy=..., ignore_https_errors=True)`) and loads
`http://page-a.test:<port>/`. The name `page-a.test` is one that only the FakeDoh can resolve: the machine's resolver
cannot (a `.test` name is on no zone), and the gateway never resolves a name (it refuses a CONNECT that carries one). So
the page loads only if the lookup of that context went to the DoH, through the proxy it was handed, even though no proxy
exists at launch: the choice follows the proxy of the CONTEXT of each lookup, not the proxy of the launch.
The same test is the other half of the rule. While the proxied context loads its page, the default context is busy with
its own background lookups (telemetry, update and extension endpoints...), and those are the machine's own network:
* they must NOT go to the DoH: nothing connects to the bootstrap address or to port 53 by a direct road (the watcher), the
FakeDoh has no query for a name that is not one of the zone names this test asked (a background name of the default
context in `doh.queries` is a lookup of the wrong context sent to the DoH), and the FakeDoh has no failed handshake (a
lookup of a context without `ignore_https_errors` can only fail it, so a failure IS a default-context lookup sent to the
DoH);
* they go to the system resolver. Where the resolver trap runs (Linux, root) the trap sees at least one question that is
no zone name: the background question of the default context. On Windows the native question cannot be observed
without a resolver trap, so there the assertion is the negative one above (nothing of that traffic reaches the DoH).
Red on an engine that picks the road of a lookup by the session instead of by the user context: the background lookups of
the default context go to the DoH by a DIRECT connection (the bootstrap address 192.0.2.53:443 is reached with no proxy;
the giro-2 binary), or, if the proxy resolves remotely, arrive at the gateway as a NAME (refused, listed in `refused`) and
the page does not load. Green when the resolver hook of the engine chooses per lookup by the user context.
Hermetic like the DoH e2e it borrows from (`test_doh_through_the_proxy_e2e.py`: the fixtures, the FakeDoh, the gateway, the
watcher, the trap and the accounting of the end of a test are imported, not copied), with one difference in what is asserted:
with no launch proxy the default context is the machine's own network, so its background traffic is allowed to be direct
and to ask the machine's resolver; every assertion here is about the DoH road, the zone's names and this context.
"""
from __future__ import annotations
import pytest
# The fixtures and the helpers of the DoH e2e (imported, not copied): the hermetic session (autouse), the resolver trap, the
# watcher, the page server, the gateway factory, and the accounting of the connections to the FakeDoh.
from test_doh_through_the_proxy_e2e import ( # noqa: F401 (the hermetic session is autouse and imported by name; the
# other fixtures of the DoH e2e are in conftest.py)
DOH_ADDRESSES, ZONE, _asked_outside, _assert_every_connection_went_through_the_gateway, _direct_to_the_doh,
_hermetic_session, _is_address, _launch, _page_in, _text, _why)
import _doh_servers as ds
from _doh_servers import DOH_BOOTSTRAP, DOH_HOST, DOH_PORT, QTYPE_A
pytestmark = pytest.mark.e2e
#: How long to wait, where the resolver trap runs, for the background question of the default context to reach it.
BACKGROUND_QUESTION_SECONDS = 20
def test_a_context_that_is_the_only_proxy_resolves_its_names_by_doh_through_it(firefox_binary, doh, pages, gateway, trap,
watcher):
"""No proxy at launch; the context has gw. `page-a.test` is asked to the FakeDoh BY gw, the page is reached by ADDRESS
through gw, nothing reaches the DoH directly, the machine's resolver is never asked for the name, and the background
names of the default context neither reach the DoH nor are lost: they go to the system resolver."""
gw = gateway("gw")
background_question = None
with _launch(firefox_binary, None) as browser: # no launch proxy: the session itself is on the host's network
context, page = _page_in(browser, proxy=gw.proxy) # the only proxy there is: the context's own
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
text = _text(page)
if trap is not None:
# The default context asks the system resolver for its own background names while the session lives; the trap
# answers nothing but REFUSED, so the question is all that is left of them. Wait for it here, before teardown.
background_question = ds.wait_until(
lambda: [q for q in trap.queries if q.name not in ZONE], BACKGROUND_QUESTION_SECONDS)
context.close()
watcher.stop()
why = _why(doh, gw)
assert "HOST=page-a.test:%d" % pages.port in text, (
"the page did not load: the name page-a.test, which only the FakeDoh can resolve, was not resolved by DoH through "
"the proxy of the context (the lookup of a context with a proxy did not go to the DoH?): %r" % text + why)
assert doh.vias_of("page-a.test", QTYPE_A) == {"gw"}, "page-a.test (A) was not asked by gw (the proxy of the context) only" + why
assert (DOH_BOOTSTRAP, DOH_PORT) in gw.connects, "no DoH CONNECT to the bootstrap address reached the gateway of the context" + why
assert not [h for h, _p in gw.connects if h == "page-a.test"], (
"the browser sent the NAME page-a.test to the gateway instead of resolving it with the DoH" + why)
assert [h for h, _p in gw.connects if not _is_address(h) and h != DOH_HOST] == [], (
"a CONNECT carried a name: the browser must resolve with the DoH and connect by address" + why)
assert ("127.0.0.1", pages.port) in gw.connects, "the page was not reached by address through the gateway of the context" + why
assert pages.hits and all(host.startswith("page-a.test") for host, _p in pages.hits), pages.hits
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy of the context" + why
_assert_every_connection_went_through_the_gateway(doh, gw)
# The names the DoH was asked for are the names of THIS context and no other: a background name of the default context
# (a mozilla.org or github.com name...) in the log is a lookup of a context without a proxy sent to the DoH.
assert _asked_outside(doh, "page-a.test") == [], (
"the DoH was asked for a name that is not the proxied context's: the default context, which has no proxy, must "
"resolve natively and never use the DoH: %s" % _asked_outside(doh, "page-a.test") + why)
# A lookup of a context without `ignore_https_errors` (the default one) can only fail the handshake with the FakeDoh:
# a failed handshake is a lookup of the wrong context that reached the DoH through this gateway.
assert doh.tls_failures == [], (
"a DoH handshake failed: a context that does not accept the FakeDoh certificate (the default context, which has no "
"proxy) used the DoH: %s" % doh.tls_failures + why)
assert watcher.watched_pids, ("the watcher never saw a browser process (it saw: %s): a watcher that cannot see proves "
"nothing" % watcher.process_names)
assert _direct_to_the_doh(watcher) == [], (
"the browser reached a DoH (%s) or a DNS server (port 53) without the proxy: the background lookups of the default "
"context, which has no proxy, went to the DoH instead of the system resolver: %s"
% (", ".join(DOH_ADDRESSES), watcher.describe()))
if trap is not None:
assert [name for name in ZONE if trap.asked(name)] == [], (
"the browser asked the resolver of the machine for a name of the zone: %s" % trap.describe() + why)
assert background_question, (
"the system resolver was asked nothing but zone names (nothing at all, here): the background names of the "
"default context did not go to it. They went to the DoH, or the default context made no lookup in %d s: %s"
% (BACKGROUND_QUESTION_SECONDS, trap.describe()) + why)
# Where the trap cannot run (Windows, or Linux without root) the native question of the default context cannot be
# observed: the assertion for it is the negative one above (no direct DoH connection, no query outside the zone, no
# failed handshake).
@@ -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))
+8
View File
@@ -982,6 +982,14 @@ _EXPECTED_SIGNATURE = [
# has nothing to arrive through - it is a property of the session, decided
# before the first window is built, so it has to be said at construction.
("show_cursor", inspect.Parameter.KEYWORD_ONLY),
# Added 2026-11-11 on the owner's order, by name: where a SOCKS5 proxy's UDP exit is measured from ("ip:port"
# IPv4 literals; None = the two public defaults). A parameter of the Python launch, kept on the session so the
# launch and every later context proxy use the same list; it is not a browser declaration and reaches neither
# its environment, argv, prefs nor pipe. Both entry points get it.
("udp_stun_servers", inspect.Parameter.KEYWORD_ONLY),
# Added 2026-11-12 on the owner's decision: the New Tab page a retail Firefox keeps preloaded is turned off only on request
# (False); None leaves the engine's default. Passed to the core, a choice of the session; both entry points get it.
("preload_newtab", inspect.Parameter.KEYWORD_ONLY),
]
+240 -196
View File
@@ -1,196 +1,240 @@
"""The host network a page sees is the one the session DECLARES, not the one of the machine (red until it is declared).
Design: ``invisible_WebRTC/notes/declared-interfaces-design.md`` and ``declared-interfaces-proofs.md`` (the private study
repository). Behind a
proxy the engine must not read the host's interfaces: the core declares one adapter in ``STEALTHFOX_WEBRTC_NETWORK``,
``v4=<private address>;v6=<0|1>;p6=<the exit's /64 prefix, empty without IPv6>`` (the IPv6 host is that prefix and a
temporary identifier; v6=1 without a prefix is no IPv6), and the engine answers the reads of the host (the interface list,
the default route, the address and port a bound socket reports) from it (nr_stealth_network.h). A page
then sees what retail Firefox on Windows shows on a machine with that adapter, whatever the machine under the browser has:
* no IPv6: ONE host name (udp + tcp), ranked 127 (the only address);
* IPv6: TWO host names, the IPv6 one ranked 127 above the IPv4 one at 126 (``nrinterfaceprioritizer.cpp:82-85``);
* the host ports are those of a Windows machine, chosen by our code: 49152-65535, a consecutive pair per connection
(IPv4 N, IPv6 N+1), drawn at random by our code for each connection (not by the kernel, not from the seed: two visits
with the same seed must not share ports), the same distribution on every host;
* two connections on one page connect to each other in the time retail takes.
Reference shape (retail 159, measured 2026-11-11, ``captures/retail/firefox-159.0-win/direct-dualstack-stun-candidates``):
host udp 2122252543 (IPv6) and 2122187007 (IPv4), host tcp 2105524479 and 2105458943, one name per address.
Red on an engine without the declared network (before webrtc/declared-interfaces b9bdb3c3ad + 6ca7a8c104): it gathered
every filtered address of the OS and let the kernel hand out the ports, so these failed on every machine with more than
one interface or a port range that is not Windows's, the IPv6 case everywhere, and the loopback test was slower than
retail and died with no usable interface. Hermetic: a local TCP-only SOCKS5 proxy and a local page, no external network.
"""
from __future__ import annotations
import statistics
import pytest
from test_webrtc_realness import (_FAKE_EGRESS, _e2e_binary, _launch, candidates, decode_priority, host_candidates,
is_mdns, local_https_page, socks5_tcp_only) # noqa: F401 (fixtures)
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
NETWORK_ENV = "STEALTHFOX_WEBRTC_NETWORK"
# retail 159 on Windows. The interface rank is the position in the prioritizer's sort, starting at 127
# (nrinterfaceprioritizer.cpp:183-189), so an IPv4-only machine ranks its one host 127, and with IPv6 the IPv6 host
# takes 127 and the IPv4 host 126.
UDP_127, UDP_126, TCP_127, TCP_126 = 2122252543, 2122187007, 2105524479, 2105458943
# The two shapes of the declared adapter: without IPv6, and with the exit's /64 prefix.
V4_ONLY = "v4=192.168.31.7;v6=0;p6="
DUAL = "v4=192.168.31.7;v6=1;p6=2a01:e0a:1f2:3450::/64"
_GATHER_JS = r"""async () => {
const pc = new RTCPeerConnection({iceServers: []});
pc.createDataChannel('');
const cands = [];
pc.addEventListener('icecandidate', e => { if (e.candidate && e.candidate.candidate) cands.push(e.candidate.candidate); });
await pc.setLocalDescription(await pc.createOffer());
await new Promise(r => setTimeout(r, 2500));
try { pc.close(); } catch (e) {}
return cands;
}"""
# Two connections on one page, connected to each other in script (the loopback test many demos use).
_LOOPBACK_JS = r"""async () => {
const t0 = performance.now();
const pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();
pc1.onicecandidate = e => { if (e.candidate) pc2.addIceCandidate(e.candidate).catch(() => {}); };
pc2.onicecandidate = e => { if (e.candidate) pc1.addIceCandidate(e.candidate).catch(() => {}); };
const dc = pc1.createDataChannel('x');
let opened = null, echoed = false;
dc.onopen = () => { opened = Math.round(performance.now() - t0); dc.send('ping'); };
pc2.ondatachannel = ev => { ev.channel.onmessage = m => ev.channel.send('pong:' + m.data); };
dc.onmessage = m => { echoed = (m.data === 'pong:ping'); };
await pc1.setLocalDescription(await pc1.createOffer());
await pc2.setRemoteDescription(pc1.localDescription);
await pc2.setLocalDescription(await pc2.createAnswer());
await pc1.setRemoteDescription(pc2.localDescription);
const deadline = performance.now() + 8000;
while (performance.now() < deadline && !(opened !== null && echoed)) await new Promise(r => setTimeout(r, 5));
pc1.close(); pc2.close();
return {opened, echoed};
}"""
# Retail 159 on Windows, 12 cold launches (``captures/mdns-loopback/retail-159-win-12``): 37-52 ms in ten of twelve, two
# slow ones at about 110, median 41.5. Without mDNS retail takes about 20 ms (``retail-159-win-nomdns``): the other 20 ms are
# the multicast round trip of the responder. The engine makes that round trip too, on the loopback (the responder joins and
# speaks on 127.0.0.1; a name of ours answers with the loopback of its family), so the window is the retail one: 30-55 ms on
# the MEDIAN of five cold launches. It keeps out "dead" (no usable interface), "slower than retail" and "faster than retail"
# (an answer that skips the round trip).
RETAIL_MEDIAN_WINDOW_MS = (30, 55)
def _session(declaration, socks, page_url, monkeypatch, seed, script):
"""One proxied launch with the declaration in the environment; runs ``script`` on the page and returns the result."""
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
monkeypatch.setenv("STEALTHFOX_WEBRTC_PUBLIC_IP", _FAKE_EGRESS)
monkeypatch.delenv("STEALTHFOX_WEBRTC_DISABLE_IPV6", raising=False) # the declaration replaces it
monkeypatch.setenv(NETWORK_ENV, declaration)
prefs = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": ""}
proxy = {"server": "socks5://127.0.0.1:%d" % socks.port}
with _launch(binary_path=binary, proxy=proxy, extra_prefs=prefs, seed=seed) as browser:
page = browser.new_context().new_page()
page.goto(page_url, wait_until="domcontentloaded", timeout=60000)
return script(page)
def _host_shape(declaration, socks, page_url, monkeypatch, seed=42):
return host_candidates(candidates(
_session(declaration, socks, page_url, monkeypatch, seed, lambda page: page.evaluate(_GATHER_JS))))
def _by_protocol(hosts):
return {proto: sorted((c["priority"] for c in hosts if c["proto"] == proto), reverse=True)
for proto in ("UDP", "TCP")}
def _udp_ports_by_rank(hosts):
return {decode_priority(c["priority"])["iface_pref"]: c["port"] for c in hosts if c["proto"] == "UDP"}
def test_without_a_declared_ipv6_the_page_sees_one_host_name(local_https_page, socks5_tcp_only, monkeypatch):
"""One adapter, no IPv6: a udp and a tcp host candidate on ONE mDNS name, ranked 127 as the only address.
The shape is a function of the declaration alone, so this must hold on every machine: run it on a host with three
IPv4 adapters (the engine gathers all three today), in a container with two interfaces (``docker network connect``
before ``docker start``), and in a container with one."""
hosts = _host_shape(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch)
assert all(is_mdns(c["address"]) for c in hosts), [c["address"] for c in hosts]
assert len({c["address"] for c in hosts}) == 1, "host names: %r" % sorted({c["address"] for c in hosts})
assert _by_protocol(hosts) == {"UDP": [UDP_127], "TCP": [TCP_127]}, _by_protocol(hosts)
def test_a_declared_ipv6_gives_two_host_names_ranked_127_and_126(local_https_page, socks5_tcp_only, monkeypatch):
"""One adapter with IPv6: two names; the IPv6 host ranks one above the IPv4 one, as on the retail capture."""
hosts = _host_shape(DUAL, socks5_tcp_only, local_https_page, monkeypatch)
assert all(is_mdns(c["address"]) for c in hosts), [c["address"] for c in hosts]
assert len({c["address"] for c in hosts}) == 2, "host names: %r" % sorted({c["address"] for c in hosts})
assert _by_protocol(hosts) == {"UDP": [UDP_127, UDP_126], "TCP": [TCP_127, TCP_126]}, _by_protocol(hosts)
assert [decode_priority(p)["iface_pref"] for p in _by_protocol(hosts)["UDP"]] == [127, 126]
def test_ipv6_without_the_exit_prefix_is_no_ipv6(local_https_page, socks5_tcp_only, monkeypatch):
"""v6=1 with an empty prefix: the exit gave the core no /64, so the machine has no IPv6 address, and no fallback
invents one. One host name, as without IPv6."""
hosts = _host_shape("v4=192.168.31.7;v6=1;p6=", socks5_tcp_only, local_https_page, monkeypatch)
assert _by_protocol(hosts) == {"UDP": [UDP_127], "TCP": [TCP_127]}, hosts
def test_the_host_ports_are_those_of_a_windows_machine(local_https_page, socks5_tcp_only, monkeypatch):
"""Retail on Windows (6 of 6 runs, ``captures/retail/firefox-159.0-win/direct-dualstack-srflx-ports``): the UDP host
ports are in the dynamic range 49152-65535 and, on one connection, the IPv4 port and the IPv6 port are consecutive
(N, N+1). A page reads them. Linux hands out 32768-60999 at random, so on a Linux host this is red today."""
hosts = _host_shape(DUAL, socks5_tcp_only, local_https_page, monkeypatch)
by_rank = _udp_ports_by_rank(hosts)
assert sorted(by_rank) == [126, 127], by_rank
assert all(49152 <= port <= 65535 for port in by_rank.values()), by_rank
assert by_rank[127] == by_rank[126] + 1, "IPv4 port %d, IPv6 port %d" % (by_rank[126], by_rank[127])
def test_the_host_port_is_in_the_windows_range_without_ipv6_too(local_https_page, socks5_tcp_only, monkeypatch):
"""The one-address case of the range check. On a Linux host it can pass by luck (a kernel port in 49152-60999 falls
in the range); the same-seed test above is the one that cannot."""
hosts = _host_shape(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch)
by_rank = _udp_ports_by_rank(hosts)
assert list(by_rank) == [127] and 49152 <= by_rank[127] <= 65535, by_rank
def _ports_of_two_connections(declaration, socks, page_url, monkeypatch, seed):
def script(page):
first = host_candidates(candidates(page.evaluate(_GATHER_JS)))
second = host_candidates(candidates(page.evaluate(_GATHER_JS)))
return first, second
first, second = _session(declaration, socks, page_url, monkeypatch, seed, script)
return (sorted(c["port"] for c in first if c["proto"] == "UDP"),
sorted(c["port"] for c in second if c["proto"] == "UDP"))
def test_two_connections_on_one_page_get_their_own_port_pair(local_https_page, socks5_tcp_only, monkeypatch):
"""Retail (``captures/retail/firefox-159.0-win/two-pc-port-sequence``, 6 of 6): each connection gets its own pair,
consecutive (N, N+1) in the range, and the second pair is unrelated to the first (not increasing)."""
first, second = _ports_of_two_connections(DUAL, socks5_tcp_only, local_https_page, monkeypatch, 42)
for pair in (first, second):
assert len(pair) == 2 and pair[1] == pair[0] + 1 and 49152 <= pair[0] and pair[1] <= 65535, (first, second)
assert first != second, (first, second)
def test_two_connections_on_one_page_connect_in_the_time_of_retail(local_https_page, socks5_tcp_only, monkeypatch):
"""The names the browser registered for itself must resolve although the declared address is not the host's, and in
the time retail takes: not slower (a responder that cannot hear itself, or an OS list that is empty, kills the test),
not faster (an answer that skips the round trip). Five cold launches, median in the retail window."""
times = []
for n in range(5):
res = _session(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch, 100 + n,
lambda page: page.evaluate(_LOOPBACK_JS))
assert res["echoed"] and res["opened"] is not None, "run %d: the data channel did not open: %r" % (n, res)
times.append(res["opened"])
low, high = RETAIL_MEDIAN_WINDOW_MS
median = statistics.median(times)
assert low <= median <= high, "median %s ms of %r, retail window %d-%d ms" % (median, sorted(times), low, high)
"""The host network a page sees is the one the session DECLARES, not the one of the machine (red until it is declared).
Design: ``invisible_WebRTC/notes/declared-interfaces-design.md`` and ``declared-interfaces-proofs.md`` (the private study
repository). Behind a
proxy the engine must not read the host's interfaces: the core declares one adapter in ``STEALTHFOX_WEBRTC_NETWORK``,
``v4=<private address>;v6=<0|1>;p6=<the exit's /64 prefix, empty without IPv6>`` (the IPv6 host is that prefix and a
temporary identifier; v6=1 without a prefix is no IPv6), and the engine answers the reads of the host (the interface list,
the default route, the address and port a bound socket reports) from it (nr_stealth_network.h). A page
then sees what retail Firefox on Windows shows on a machine with that adapter, whatever the machine under the browser has:
* no IPv6: ONE host name (udp + tcp), ranked 127 (the only address);
* IPv6: TWO host names, the IPv6 one ranked 127 above the IPv4 one at 126 (``nrinterfaceprioritizer.cpp:82-85``);
* the host ports are those of a Windows machine, chosen by our code: 49152-65535, a consecutive pair per connection
(IPv4 N, IPv6 N+1), drawn at random by our code for each connection (not by the kernel, not from the seed: two visits
with the same seed must not share ports), the same distribution on every host;
* two connections on one page connect to each other in the time retail takes.
Reference shape (retail 159, measured 2026-11-11, ``captures/retail/firefox-159.0-win/direct-dualstack-stun-candidates``):
host udp 2122252543 (IPv6) and 2122187007 (IPv4), host tcp 2105524479 and 2105458943, one name per address.
Red on an engine without the declared network (before webrtc/declared-interfaces b9bdb3c3ad + 6ca7a8c104): it gathered
every filtered address of the OS and let the kernel hand out the ports, so these failed on every machine with more than
one interface or a port range that is not Windows's, the IPv6 case everywhere, and the loopback test was slower than
retail and died with no usable interface. Hermetic: a local TCP-only SOCKS5 proxy and a local page, no external network.
"""
from __future__ import annotations
import statistics
import pytest
from test_webrtc_realness import _e2e_binary, _launch, candidates, decode_priority, host_candidates, is_mdns # noqa: F401
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
NETWORK_ENV = "STEALTHFOX_WEBRTC_NETWORK"
# retail 159 on Windows. The interface rank is the position in the prioritizer's sort, starting at 127
# (nrinterfaceprioritizer.cpp:183-189), so an IPv4-only machine ranks its one host 127, and with IPv6 the IPv6 host
# takes 127 and the IPv4 host 126.
UDP_127, UDP_126, TCP_127, TCP_126 = 2122252543, 2122187007, 2105524479, 2105458943
# The two shapes of the declared adapter: without IPv6, and with the exit's /64 prefix.
V4_ONLY = "v4=192.168.31.7;v6=0;p6="
DUAL = "v4=192.168.31.7;v6=1;p6=2a01:e0a:1f2:3450::/64"
_GATHER_JS = r"""async () => {
const pc = new RTCPeerConnection({iceServers: []});
pc.createDataChannel('');
const cands = [];
pc.addEventListener('icecandidate', e => { if (e.candidate && e.candidate.candidate) cands.push(e.candidate.candidate); });
await pc.setLocalDescription(await pc.createOffer());
await new Promise(r => setTimeout(r, 2500));
try { pc.close(); } catch (e) {}
return cands;
}"""
# Two connections on one page, connected to each other in script (the loopback test many demos use).
_LOOPBACK_JS = r"""async () => {
const t0 = performance.now();
const pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();
pc1.onicecandidate = e => { if (e.candidate) pc2.addIceCandidate(e.candidate).catch(() => {}); };
pc2.onicecandidate = e => { if (e.candidate) pc1.addIceCandidate(e.candidate).catch(() => {}); };
const gathered = {pc1: [], pc2: []};
const keep = (name, e) => { if (e.candidate && e.candidate.candidate) gathered[name].push(e.candidate.candidate); };
pc1.addEventListener('icecandidate', e => keep('pc1', e));
pc2.addEventListener('icecandidate', e => keep('pc2', e));
const dc = pc1.createDataChannel('x');
let opened = null, echoed = false;
dc.onopen = () => { opened = Math.round(performance.now() - t0); dc.send('ping'); };
pc2.ondatachannel = ev => { ev.channel.onmessage = m => ev.channel.send('pong:' + m.data); };
dc.onmessage = m => { echoed = (m.data === 'pong:ping'); };
await pc1.setLocalDescription(await pc1.createOffer());
await pc2.setRemoteDescription(pc1.localDescription);
await pc2.setLocalDescription(await pc2.createAnswer());
await pc1.setRemoteDescription(pc2.localDescription);
const deadline = performance.now() + 8000;
while (performance.now() < deadline && !(opened !== null && echoed)) await new Promise(r => setTimeout(r, 5));
// The road the connection took, read from the browser's own statistics: the nominated pair, and the protocol of each end.
let pair = null;
try {
const stats = await pc1.getStats();
const byId = {};
stats.forEach(r => { byId[r.id] = r; });
stats.forEach(r => {
if (r.type === 'candidate-pair' && r.state === 'succeeded' && (r.nominated || !pair)) {
const l = byId[r.localCandidateId] || {}, rm = byId[r.remoteCandidateId] || {};
pair = {local: l.protocol, remote: rm.protocol, localType: l.candidateType, remoteType: rm.candidateType,
remoteAddress: rm.address || null};
}
});
} catch (e) {}
pc1.close(); pc2.close();
return {opened, echoed, pair, gathered};
}"""
# Retail 159 on Windows, 12 cold launches (``captures/mdns-loopback/retail-159-win-12``): 37-52 ms in ten of twelve, two
# slow ones at about 110, median 41.5. Without mDNS retail takes about 20 ms (``retail-159-win-nomdns``): the other 20 ms are
# the multicast round trip of the responder. That is a MEASURE of a fast machine and is printed, never judged: on a
# GitHub runner the same road takes 67 ms (Windows) and 122 ms (Linux), and a verdict on an absolute time is a verdict on
# the machine. What the test judges is the ROAD, which the machine cannot change (see the test), and a ceiling under the
# first retry of the mDNS responder (3 s), which no machine is slow enough to reach by being slow.
RETAIL_MEDIAN_WINDOW_MS = (30, 55) # printed beside the measure, for the reader
MDNS_RETRY_MS = 3000 # the responder asks again after 3 s: a run that opens only then took the slow road
def _session(declaration, socks, page_url, monkeypatch, seed, script):
"""One proxied launch with the declaration in the environment; runs ``script`` on the page and returns the result."""
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
monkeypatch.setenv(NETWORK_ENV, declaration)
prefs = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": ""}
proxy = {"server": "socks5://127.0.0.1:%d" % socks.port}
with _launch(binary_path=binary, proxy=proxy, extra_prefs=prefs, seed=seed) as browser:
page = browser.new_context().new_page()
page.goto(page_url, wait_until="domcontentloaded", timeout=60000)
return script(page)
def _host_shape(declaration, socks, page_url, monkeypatch, seed=42):
return host_candidates(candidates(
_session(declaration, socks, page_url, monkeypatch, seed, lambda page: page.evaluate(_GATHER_JS))))
def _by_protocol(hosts):
return {proto: sorted((c["priority"] for c in hosts if c["proto"] == proto), reverse=True)
for proto in ("UDP", "TCP")}
def _udp_ports_by_rank(hosts):
return {decode_priority(c["priority"])["iface_pref"]: c["port"] for c in hosts if c["proto"] == "UDP"}
def test_without_a_declared_ipv6_the_page_sees_one_host_name(local_https_page, socks5_tcp_only, monkeypatch):
"""One adapter, no IPv6: a udp and a tcp host candidate on ONE mDNS name, ranked 127 as the only address.
The shape is a function of the declaration alone, so this must hold on every machine: run it on a host with three
IPv4 adapters (the engine gathers all three today), in a container with two interfaces (``docker network connect``
before ``docker start``), and in a container with one."""
hosts = _host_shape(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch)
assert all(is_mdns(c["address"]) for c in hosts), [c["address"] for c in hosts]
assert len({c["address"] for c in hosts}) == 1, "host names: %r" % sorted({c["address"] for c in hosts})
assert _by_protocol(hosts) == {"UDP": [UDP_127], "TCP": [TCP_127]}, _by_protocol(hosts)
def test_a_declared_ipv6_gives_two_host_names_ranked_127_and_126(local_https_page, socks5_tcp_only, monkeypatch):
"""One adapter with IPv6: two names; the IPv6 host ranks one above the IPv4 one, as on the retail capture."""
hosts = _host_shape(DUAL, socks5_tcp_only, local_https_page, monkeypatch)
assert all(is_mdns(c["address"]) for c in hosts), [c["address"] for c in hosts]
assert len({c["address"] for c in hosts}) == 2, "host names: %r" % sorted({c["address"] for c in hosts})
assert _by_protocol(hosts) == {"UDP": [UDP_127, UDP_126], "TCP": [TCP_127, TCP_126]}, _by_protocol(hosts)
assert [decode_priority(p)["iface_pref"] for p in _by_protocol(hosts)["UDP"]] == [127, 126]
def test_ipv6_without_the_exit_prefix_is_no_ipv6(local_https_page, socks5_tcp_only, monkeypatch):
"""v6=1 with an empty prefix: the exit gave the core no /64, so the machine has no IPv6 address, and no fallback
invents one. One host name, as without IPv6."""
hosts = _host_shape("v4=192.168.31.7;v6=1;p6=", socks5_tcp_only, local_https_page, monkeypatch)
assert _by_protocol(hosts) == {"UDP": [UDP_127], "TCP": [TCP_127]}, hosts
def test_the_host_ports_are_those_of_a_windows_machine(local_https_page, socks5_tcp_only, monkeypatch):
"""Retail on Windows (6 of 6 runs, ``captures/retail/firefox-159.0-win/direct-dualstack-srflx-ports``): the UDP host
ports are in the dynamic range 49152-65535 and, on one connection, the IPv4 port and the IPv6 port are consecutive
(N, N+1). A page reads them. Linux hands out 32768-60999 at random, so on a Linux host this is red today."""
hosts = _host_shape(DUAL, socks5_tcp_only, local_https_page, monkeypatch)
by_rank = _udp_ports_by_rank(hosts)
assert sorted(by_rank) == [126, 127], by_rank
assert all(49152 <= port <= 65535 for port in by_rank.values()), by_rank
assert by_rank[127] == by_rank[126] + 1, "IPv4 port %d, IPv6 port %d" % (by_rank[126], by_rank[127])
def test_the_host_port_is_in_the_windows_range_without_ipv6_too(local_https_page, socks5_tcp_only, monkeypatch):
"""The one-address case of the range check. On a Linux host it can pass by luck (a kernel port in 49152-60999 falls
in the range); the same-seed test above is the one that cannot."""
hosts = _host_shape(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch)
by_rank = _udp_ports_by_rank(hosts)
assert list(by_rank) == [127] and 49152 <= by_rank[127] <= 65535, by_rank
def _ports_of_two_connections(declaration, socks, page_url, monkeypatch, seed):
def script(page):
first = host_candidates(candidates(page.evaluate(_GATHER_JS)))
second = host_candidates(candidates(page.evaluate(_GATHER_JS)))
return first, second
first, second = _session(declaration, socks, page_url, monkeypatch, seed, script)
return (sorted(c["port"] for c in first if c["proto"] == "UDP"),
sorted(c["port"] for c in second if c["proto"] == "UDP"))
def test_two_connections_on_one_page_get_their_own_port_pair(local_https_page, socks5_tcp_only, monkeypatch):
"""Retail (``captures/retail/firefox-159.0-win/two-pc-port-sequence``, 6 of 6): each connection gets its own pair,
consecutive (N, N+1) in the range, and the second pair is unrelated to the first (not increasing)."""
first, second = _ports_of_two_connections(DUAL, socks5_tcp_only, local_https_page, monkeypatch, 42)
for pair in (first, second):
assert len(pair) == 2 and pair[1] == pair[0] + 1 and 49152 <= pair[0] and pair[1] <= 65535, (first, second)
assert first != second, (first, second)
def test_two_connections_on_one_page_connect_in_the_time_of_retail(local_https_page, socks5_tcp_only, monkeypatch, capsys):
"""The names the browser registered for itself must resolve although the declared address is not the host's, and
the connection must take the road retail takes. Five cold launches; EVERY one is judged on the road, none on the clock:
* the data channel opens and echoes (a responder that cannot hear itself, or an OS list that is empty, kills it);
* each connection gathered a UDP host candidate named by mDNS (a run without UDP is the reserved-port failure: the
socket could not bind and the connection fell back to TCP, about 600 ms on average);
* the nominated pair is direct and local over UDP at both ends: host or peer-reflexive, never relay or server-reflexive, never
TCP (a peer-reflexive end is legitimate: the other connection's mDNS name was not resolved yet and its check came first);
* it opens in less than the responder's first retry (3 s): a name that does not come back opens only at the retry.
The time itself is printed with the retail window beside it: a fast machine shows 30-55 ms, a runner shows more, and
neither is a verdict (an absolute time failed on both GitHub runners with a healthy engine)."""
runs = []
for n in range(5):
res = _session(V4_ONLY, socks5_tcp_only, local_https_page, monkeypatch, 100 + n,
lambda page: page.evaluate(_LOOPBACK_JS))
assert res["echoed"] and res["opened"] is not None, "run %d: the data channel did not open: %r" % (n, res)
runs.append(res)
for side in ("pc1", "pc2"):
hosts = [c for c in res["gathered"][side] if " typ host" in c]
udp = [c for c in hosts if " UDP " in c.upper() or " udp " in c]
assert udp, "run %d: %s gathered no UDP host candidate (the road without UDP): %r" % (n, side, res["gathered"][side])
assert any(c.split()[4].endswith(".local") for c in udp), (
"run %d: %s has no mDNS name among its UDP host candidates: %r" % (n, side, udp))
pair = res["pair"]
assert pair, "run %d: the browser reports no nominated pair: %r" % (n, res)
assert pair["local"] == "udp" and pair["remote"] == "udp", (
"run %d: the connection did not take UDP at both ends (the road through TCP): %r" % (n, pair))
# DIRECT and local: each end is a host candidate, or a peer-reflexive one. The remote end is prflx when the other connection's mDNS
# name was not resolved yet and its connectivity check arrived first: the address the check came from is learned as prflx, and
# that is the same road. What it must never be is a relay or a server-reflexive candidate (a road through the proxy or the
# network), and never TCP (checked above).
assert pair["localType"] in ("host", "prflx") and pair["remoteType"] in ("host", "prflx"), (
"run %d: the pair is not direct and local (a relay or a server-reflexive road): %r" % (n, pair))
assert res["opened"] < MDNS_RETRY_MS, "run %d: opened after %d ms, at the responder's retry" % (n, res["opened"])
times = sorted(r["opened"] for r in runs)
low, high = RETAIL_MEDIAN_WINDOW_MS
with capsys.disabled():
print("\n[measure] two connections on one page open in %r ms, median %s (retail on a fast machine %d-%d ms; not a verdict)"
% (times, statistics.median(times), low, high))
@@ -0,0 +1,37 @@
"""The README and the docs name the MCP server's repository and command as they are now.
After the September renames, `github.com/feder-cr/AIHawk` stopped being the MCP
server: GitHub sends a renamed name to whatever object carries it, and on
2026-11-06 that is an unrelated repository. Thirteen links answered 200 with a
page that was not the one promised, which no link checker reports. Seven places
also said `uvx aihawk`, a command that does not exist; the command is
`invisible-playwright-mcp`.
CHANGELOG.md keeps the old name on purpose (an entry says what was true then),
and so does the fixture in scripts/sync_article_pixels.py, which is the deliberate
wrong case. Neither is read here.
"""
from __future__ import annotations
from pathlib import Path
import pytest
pytestmark = pytest.mark.unit
ROOT = Path(__file__).resolve().parents[1]
OLD = ("github.com/feder-cr/AIHawk", "uvx aihawk")
def pages():
return [ROOT / "README.md", *sorted((ROOT / "docs").rglob("*.md"))]
def test_no_page_links_the_old_repository_or_runs_the_old_command():
found = ["%s:%d: %s" % (p.relative_to(ROOT), n, old)
for p in pages()
for n, line in enumerate(p.read_text(encoding="utf-8").splitlines(), 1)
for old in OLD if old.lower() in line.lower()]
assert not found, ("these name the MCP server by its old name, which now leads elsewhere: use "
"github.com/feder-cr/invisible_playwright_mcp and `uvx invisible-playwright-mcp`:\n"
+ "\n".join(found))
+127 -137
View File
@@ -1,20 +1,37 @@
"""E2E: behind a proxy every name is resolved by Firefox's DoH THROUGH the proxy, and nothing leaves the host.
WRITTEN AGAINST THE CONTRACT, BEFORE THE ENGINE THAT KEEPS IT EXISTS. No binary in this tree has the behaviour yet, so
these tests cannot go green here; what is proven now is that the tools they stand on are right
(`test_the_fake_doh_answers.py`, `test_the_http_proxy_helper_asks_for_credentials.py`,
`test_the_leak_watcher_sees_a_direct_connection.py`) and that the session declares what the contract starts from
(`test_doh_session_prefs_unit.py`). Run against an engine that keeps the contract, they are the proof; run against one
that does not, each of them fails on the thing it names.
Hermetic on a real binary. The tools they stand on are proven by `test_the_fake_doh_answers.py`,
`test_the_http_proxy_helper_asks_for_credentials.py` and `test_the_leak_watcher_sees_a_direct_connection.py`, and the
session declaration they start from by `test_doh_session_prefs_unit.py`. Run against an engine that keeps the contract,
they are the proof; run against one that does not, each of them fails on the thing it names.
The contract (core-19 and motore-18): a PROXIED session declares TRR mode 3 (`network.trr.uri` the DoH of Mozilla,
`network.trr.bootstrapAddr` an address so the DoH host is found with no DNS, `network.proxy.allow_bypass` false).
Every name the browser resolves - page hosts, ICE server names, HTTP/3 hosts - goes to that DoH; a DoH request is a
channel like any other, so it leaves THROUGH the session proxy (a SOCKS5 CONNECT or an HTTP CONNECT to
162.159.61.4:443), by the proxy of the context of the lookup; the browser then connects to the resolved ADDRESS (SOCKS5
by address, never by name). The session proxy is the first command on the pipe, and every proxied channel waits for
it: nothing goes DIRECT. No UDP/53 and no direct TCP leave the browser, and no helper process (crash reporter, default
browser agent, maintenance service, updater, pingsender) is started.
The fake DoH is NOT `mozilla.cloudflare-dns.com`. That host is HSTS-preloaded/pinned, and Firefox refuses any
certificate override for such a host ("HSTS or pinned host - no overrides allowed", MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT),
so a self-signed fake for it is rejected whatever `ignore_https_errors` says. The test declares its own provider through
the core's `extra_prefs` overlay (applied last, documented for this): `network.trr.uri` = `https://doh.gateway.test/
dns-query` (a `.test` name is on no preload list) and `network.trr.bootstrapAddr` = `192.0.2.53` (TEST-NET-1: the
address of the FakeDoh as a gateway knows it, never a real one). The gateways map a CONNECT to that address (or name) to
the FakeDoh. The core's own default provider is checked by `test_doh_session_prefs_unit.py`, not here.
The contract (core-19 and motore-18): the core declares the DoH PROVIDER for every session (`network.trr.uri` the DoH of
Mozilla, `network.trr.bootstrapAddr` an address so the DoH host is found with no DNS) and, with a proxy,
`network.proxy.allow_bypass` false; the ENGINE owns the state, so the core never writes `network.trr.mode`,
`exclude-etc-hosts` or `excluded-domains`. Each browser context is a whole situation, decided per lookup by the user
context of the lookup (the DoH service itself stays in mode 0; Juggler publishes the contexts that have a proxy):
* a context WITH a proxy - its own, or the launch proxy, which is the proxy of every context that has none of its own,
the default one included - resolves its names ONLY by DoH, THROUGH that proxy, fail-closed: a DoH request is a channel
like any other, so it leaves by a SOCKS5 CONNECT or an HTTP CONNECT to the DoH address, by the proxy of the context of
the lookup, and the browser then connects to the resolved ADDRESS (SOCKS5 by address, never by name);
* a context WITHOUT a proxy resolves natively (the system resolver) and NEVER reaches the DoH.
Page hosts, ICE server names and HTTP/3 hosts of a proxied context all follow the first rule. The session proxy is the
first command on the pipe, and every proxied channel waits for it: nothing of a proxied context goes DIRECT. No UDP/53
and no direct TCP to a DoH leave the browser, and no helper process (crash reporter, default browser agent,
maintenance service, updater, pingsender) is started. The tests of a session WITH a launch proxy may therefore assert
that nothing at all goes direct and nothing asks the system resolver (the default context is proxied too); the tests of a
session WITHOUT one assert only about the DoH road, because the default context is then the machine's own network.
`test_context_proxy_only_resolves_by_doh_e2e.py` and `test_resolver_race_e2e.py` test the rule where it is sharpest.
How each test sees it, with nothing but loopback:
@@ -32,8 +49,13 @@ accept the FakeDoh certificate: the pages are opened in contexts made with `igno
implements per user context (`Browser.setIgnoreHTTPSErrors` -> `nsICertOverrideService`, keyed by the origin attributes
of the TLS socket), and a DoH request of a lookup carries the user context of that lookup
(`StealthApplyTRRContextToChannel`). So the lookups of THESE contexts accept the certificate; a lookup of the default
context (user context 0: the browser's own background resolutions) cannot be made to, and mode 3 does not need it. This
is why a test says "a context with no proxy of its own" where the brief says "the default context".
context (user context 0: the browser's own background resolutions, telemetry and the like) cannot be made to. In a session
WITH a launch proxy the default context is proxied too, so its background lookups go to the FakeDoh through the launch
proxy and fail the handshake BY DESIGN: no assertion there counts the FakeDoh's TLS failures or treats a name of the
default context as a result (the accounting helper below counts them against the CONNECTs of the gateway). In a session
WITHOUT a launch proxy the default context resolves natively and never reaches the FakeDoh: there a TLS failure at the
FakeDoh is itself the sign of the defect. Every assertion is about the names and the contexts the test itself creates.
This is why a test says "a context with no proxy of its own" where the brief says "the default context".
Assumptions that could not be verified without the engine, each one the first place to look if a test fails for no
visible reason: (1) the TRR channel of a lookup in a context honours `ignore_https_errors` of that context; (2) the
@@ -58,18 +80,18 @@ from invisible_playwright import InvisiblePlaywright
import _doh_servers as ds
import _trap_policy
from _doh_servers import DOH_BOOTSTRAP, DOH_HOST, DOH_PORT, QTYPE_A, DohGateway, FakeDoh
from _doh_servers import DOH_BOOTSTRAP, DOH_HOST, DOH_PORT, DOH_PROVIDER_PREFS, QTYPE_A, DohGateway, FakeDoh
from _http_proxy import HttpProxy, basic
from _leaks import ResolverTrap, Watcher
from _servers import LocalServer
from _doh_support import ZONE, Pages # noqa: F401 (Pages and ZONE are imported by name by the sibling tests)
from _servers import LocalServer # noqa: F401
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
#: The zone of the FakeDoh: every name a test uses, all pointing at the loopback where the page server is.
ZONE = {"page-a.test": "127.0.0.1", "page-b.test": "127.0.0.1", "page-c.test": "127.0.0.1",
"stun-a.test": "127.0.0.1"}
#: Loopback targets go through the proxy too (as in test_proxy_socks_auth_e2e.py), so the road of a page is observable.
PREFS = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": ""}
#: The two `network.trr.*` entries replace the core's default provider (a preloaded host whose certificate cannot be
#: overridden) with the FakeDoh's: https://doh.gateway.test/dns-query, found at 192.0.2.53 with no DNS.
PREFS = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": "", **DOH_PROVIDER_PREFS}
#: The helper processes of Firefox that a session behind a proxy must never start (match on the executable's stem).
HELPERS = ("crashreporter", "default-browser-agent", "maintenanceservice", "updater", "pingsender")
GEO = SessionGeo("America/New_York", "203.0.113.7", latitude=40.7128, longitude=-74.0060,
@@ -77,6 +99,7 @@ GEO = SessionGeo("America/New_York", "203.0.113.7", latitude=40.7128, longitude=
# ------------------------------------------------------------------------------------------------------- fixtures
# `doh`, `gateway`, `trap`, `watcher` and `pages` are in conftest.py: the sibling files use them without importing them.
@pytest.fixture(autouse=True)
def _hermetic_session(monkeypatch):
"""No egress lookup on the internet, and no egress drift check through the proxy.
@@ -86,110 +109,18 @@ def _hermetic_session(monkeypatch):
BROWSER's roads, so the answer is declared: the same facts (timezone, locale, position, an exit address) the
lookup would have returned.
"""
monkeypatch.setattr("invisible_playwright.launcher.prepare_session_geo", lambda tz, proxy, locale: GEO)
monkeypatch.setattr("invisible_playwright.launcher.prepare_session_geo", lambda tz, proxy, locale, **_kw: GEO)
monkeypatch.setattr(InvisiblePlaywright, "_assert_uscita_invariata", lambda self: None)
@pytest.fixture
def doh():
import h2 # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
server = FakeDoh(ZONE)
yield server
server.close()
@pytest.fixture
def gateway(doh):
made = []
def make(name, **kwargs):
gw = DohGateway(name, doh, **kwargs)
made.append(gw)
return gw
yield make
for gw in made:
gw.close()
@pytest.fixture
def trap():
"""The resolver trap, counting every question the machine's resolver is asked.
None only where it cannot run AND the gate does not require it (a developer's machine). With INVPW_REQUIRE_TRAP=1
(the gate's Linux leg) a trap that is unavailable or whose port 53 cannot be bound is a failure with its reason."""
if not ResolverTrap.available:
why = _trap_policy.failure(None, False, ResolverTrap.reason)
if why:
pytest.fail(why)
yield None
return
resolver = ResolverTrap()
try:
resolver.__enter__()
except OSError as exc: # port 53 taken (another worker holds the trap)
why = _trap_policy.failure(None, True, bind_error=exc)
if why:
pytest.fail(why)
yield None
return
try:
yield resolver
finally:
resolver.__exit__(None, None, None)
@pytest.fixture
def watcher(firefox_binary):
"""Started BEFORE the test body, so before any launch; stopped by the test or here."""
w = Watcher(match=("firefox", Path(firefox_binary).stem.lower())).start()
yield w
w.stop()
class Pages:
"""A local HTTP server: every path answers a page that says which Host it was asked for."""
def __init__(self):
outer = self
self.hits = []
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self): # noqa: N802
host = self.headers.get("Host", "")
outer.hits.append((host, self.path))
body = ("<!doctype html><title>page</title><body>HOST=%s</body>" % host).encode()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
self._server = LocalServer(("127.0.0.1", 0), Handler)
self.port = self._server.server_address[1]
threading.Thread(target=self._server.serve_forever, daemon=True).start()
def url(self, name):
return "http://%s:%d/" % (name, self.port)
def close(self):
self._server.shutdown()
self._server.server_close()
@pytest.fixture
def pages():
server = Pages()
yield server
server.close()
# The core also asks the exit of a SOCKS5 proxy (its UDP measurement, invisible_core._udp_exit): api.ipify.org, icanhazip.com and
# checkip.amazonaws.com BY NAME through the gateway of the context, which the tests below read as "a CONNECT carried a name"
# (run 43164943499, Windows). The answer is declared here too.
monkeypatch.setattr("invisible_core._geo.discover_egress_ip", lambda *_a, **_k: GEO.egress_ip)
# --------------------------------------------------------------------------------------------------------- helpers
def _launch(binary, proxy, **kwargs):
return InvisiblePlaywright(seed=42, binary_path=binary, proxy=proxy, extra_prefs=dict(PREFS), **kwargs)
# headless=True: a headed browser on a virtual display the wrapper starts itself, as in every other e2e (a runner has no screen).
return InvisiblePlaywright(seed=42, binary_path=binary, proxy=proxy, extra_prefs=dict(PREFS), **{"headless": True, **kwargs})
def _page_in(browser, proxy=None):
@@ -209,7 +140,7 @@ def _why(doh, *proxies):
"""What every side saw, for the message of a failed assertion."""
lines = ["FakeDoh queries: %s" % [tuple(q) for q in doh.queries],
"FakeDoh connections (via, protocol): %s" % doh.connections,
"FakeDoh TLS failures: %s" % doh.tls_failures]
"FakeDoh TLS failures (the default context's background lookups fail by design): %s" % doh.tls_failures]
for p in proxies:
lines.append("%s CONNECTs: %s" % (p.name, p.connects))
if getattr(p, "refused", None):
@@ -225,8 +156,61 @@ def _is_address(host):
return False
def _assert_stayed_home(watcher, trap=None):
"""Nothing went past the gateway (no direct connection) and nothing asked the machine's resolver."""
#: The addresses a DoH request could reach by a road other than the proxy of its context: the bootstrap address of the
#: test's provider and the one of the core's default provider.
DOH_ADDRESSES = (DOH_BOOTSTRAP, "162.159.61.4")
def _direct_to_the_doh(watcher):
"""The direct connections the watcher saw to a DoH address or to a DNS port (53)."""
return [c for c in watcher.direct
if c.remote.rsplit(":", 1)[0] in DOH_ADDRESSES or c.remote.endswith(":53")]
def _asked_outside(doh, *zone_names):
"""The FakeDoh queries whose name is none of `zone_names` nor a name under one of them (the question of the HTTPS
record of a name is `_<port>._https.<name>`, which ends with it). Empty when only the names of the test's own
contexts were asked, i.e. when no background name of another context reached the DoH."""
names = tuple(n.lower() for n in zone_names)
return [q for q in doh.queries if not any(q.name == n or q.name.endswith("." + n) for n in names)]
def _assert_every_connection_went_through_the_gateway(doh, *proxies):
"""Every connection the browser made, the test's own and (in a session with a launch proxy) the background traffic
of the default context, is accounted for at a gateway, and none reached the FakeDoh by another road.
The background lookups of a proxied default context (telemetry and the like) have no `ignore_https_errors`, so their
TLS handshake with the FakeDoh fails BY DESIGN. That is an expected outcome, counted here, not ignored:
* the FakeDoh served no connection (successful or failed) by `direct`: each one arrived by a named gateway;
* per gateway, the connections the FakeDoh served (completed + failed handshakes) are all tunnels of a DoH CONNECT
that the gateway itself recorded (it records the CONNECT before it hands the socket over), so none is
unaccounted for: served <= recorded DoH CONNECTs;
* no CONNECT of any gateway carries the name of the test's own zone (the browser resolves those with the DoH and
connects by address); a CONNECT to some other non-loopback target is listed by the gateway in `refused`, i.e. it
was attempted THROUGH the gateway and went no further, which is the point.
"""
why = _why(doh, *proxies)
names = {p.name for p in proxies}
served = list(doh.connections) + [(via, "tls-failed") for via, _error in doh.tls_failures]
by_road = {via for via, _what in served}
assert by_road <= names, "the FakeDoh served a connection by a road that is no gateway of the test: %s" % (
sorted(by_road - names)) + why
for proxy in proxies:
mine = [what for via, what in served if via == proxy.name]
recorded = len(proxy.doh_connects())
assert len(mine) <= recorded, (
"%s: the FakeDoh served %d connection(s) (%d failed handshakes) but the gateway recorded only %d DoH "
"CONNECT(s)" % (proxy.name, len(mine), mine.count("tls-failed"), recorded) + why)
zone_names = [h for h, _p in proxy.connects if h.lower() in ZONE]
assert zone_names == [], "%s was sent the NAME %s instead of an address" % (proxy.name, zone_names) + why
def _assert_stayed_home(watcher, trap=None, doh=None, *proxies):
"""Nothing went past the gateway (no direct connection), nothing asked the machine's resolver, and (when the
FakeDoh and the proxies are given) every connection is accounted for at a gateway."""
if doh is not None:
_assert_every_connection_went_through_the_gateway(doh, *proxies)
assert watcher.watched_pids, ("the watcher never saw a browser process (it saw: %s): a watcher that cannot see "
"proves nothing" % watcher.process_names)
assert watcher.direct == [], "the browser connected past the gateway: %s" % watcher.describe()
@@ -265,7 +249,7 @@ def test_names_resolve_through_doh_by_the_proxy(firefox_binary, doh, pages, gate
"a CONNECT carried a name: the browser must resolve with the DoH and connect by address" + why)
assert ("127.0.0.1", pages.port) in gw1.connects, "the page was not reached by address through gw1" + why
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy" + why
_assert_stayed_home(watcher, trap)
_assert_stayed_home(watcher, trap, doh, gw1)
def test_an_ice_server_name_resolves_the_same_way(firefox_binary, doh, pages, gateway, trap, watcher):
@@ -283,7 +267,7 @@ def test_an_ice_server_name_resolves_the_same_way(firefox_binary, doh, pages, ga
why = _why(doh, gw1)
assert asked, "the browser never asked the DoH for the ICE server name" + why
assert doh.vias_of("stun-a.test") == {"gw1"}, "stun-a.test was not asked by gw1 only" + why
_assert_stayed_home(watcher, trap)
_assert_stayed_home(watcher, trap, doh, gw1)
def test_two_contexts_two_doh_exits(firefox_binary, doh, pages, gateway, trap, watcher):
@@ -312,7 +296,7 @@ def test_two_contexts_two_doh_exits(firefox_binary, doh, pages, gateway, trap, w
"gw1 saw: %s" % gw1.credentials_seen)
assert gw2.credentials_seen and set(gw2.credentials_seen) == {("gw2-user", "gw2-pass")}, (
"gw2 saw: %s" % gw2.credentials_seen)
_assert_stayed_home(watcher, trap)
_assert_stayed_home(watcher, trap, doh, gw1, gw2)
def test_an_authenticated_http_proxy_resolves(firefox_binary, doh, pages, trap, watcher):
@@ -346,7 +330,7 @@ def test_an_authenticated_http_proxy_resolves(firefox_binary, doh, pages, trap,
"every DoH CONNECT must carry the preemptive Basic header %r, saw %r" % (expected, authorizations) + why)
assert [s for s in proxy.refused_for_credentials if (s.host, s.port) in ds.DOH_TARGETS] == [], (
"the DoH CONNECT needed a 407 round trip: the header was not preemptive" + why)
_assert_stayed_home(watcher, trap)
_assert_stayed_home(watcher, trap, doh, proxy)
finally:
proxy.close()
@@ -367,7 +351,7 @@ def test_nothing_leaves_the_host_between_launch_and_the_first_command(firefox_bi
why = _why(doh, gw1)
assert "HOST=page-a.test" in text
assert gw1.accepted_at, "the browser never connected to the gateway" + why
_assert_stayed_home(watcher, trap)
_assert_stayed_home(watcher, trap, doh, gw1)
def test_no_helper_process_starts(firefox_binary, doh, pages, gateway, trap, watcher):
@@ -408,23 +392,26 @@ def test_a_dead_proxy_does_not_fall_back(firefox_binary, doh, pages, gateway, tr
"the dead proxy still served a page: %s" % pages.hits + why)
assert doh.queries_for("page-c.test") == [], "page-c.test was resolved after the proxy died" + why
assert gw1.killed and failed.value is not None
_assert_stayed_home(watcher, trap)
_assert_stayed_home(watcher, trap, doh, gw1)
def test_a_session_without_a_proxy_resolves_with_the_system_resolver(firefox_binary, pages, watcher):
"""The negative control: with no proxy the exit is the machine's own network and retail resolves with the system
resolver (mode 0). No `network.trr.*` pref is declared. Where the resolver trap can run (Linux, root) it also sees the
question; where it cannot (Windows) the page is reached by a name the system resolves by itself, and the trap's
assertion is the only one that is not made."""
"""The negative control: with no proxy anywhere the exit is the machine's own network and retail resolves with the
system resolver. The core declares the DoH provider (uri + bootstrapAddr) in every session, but no engine-owned
state (`network.trr.mode` and the other two), and no context has a proxy, so no lookup is a DoH lookup: the
resolver trap sees the question and no connection goes to a DoH address."""
trapped = ResolverTrap.available
why = _trap_policy.failure(None, trapped, ResolverTrap.reason)
if why:
pytest.fail(why)
name = "page-d.test" if trapped else "localhost"
session = InvisiblePlaywright(seed=42, binary_path=firefox_binary, proxy=None)
session = InvisiblePlaywright(seed=42, binary_path=firefox_binary, proxy=None, headless=True)
session._timezone, session._locale = GEO.timezone, GEO.locale
declared = [k for k in session._build_prefs() if k.startswith("network.trr.")]
assert declared == [], "a session without a proxy declared TRR prefs: %s" % declared
prefs = session._build_prefs()
assert prefs.get("network.trr.mode") != 3, "a session without a proxy turned TRR on: %s" % prefs.get("network.trr.mode")
engine_owned = [k for k in ("network.trr.mode", "network.trr.exclude-etc-hosts", "network.trr.excluded-domains")
if k in prefs]
assert engine_owned == [], "a session without a proxy declared engine-owned TRR prefs: %s" % engine_owned
trap = None
if trapped:
@@ -445,3 +432,6 @@ def test_a_session_without_a_proxy_resolves_with_the_system_resolver(firefox_bin
assert "HOST=%s:%d" % (name, pages.port) in text, "the page did not load through the system resolver: %r" % text
if trap is not None:
assert trap.asked(name), "the system resolver was never asked for %s: %s" % (name, trap.describe())
assert watcher.watched_pids, "the watcher never saw a browser process: %s" % watcher.process_names
assert _direct_to_the_doh(watcher) == [], (
"a session with no proxy reached a DoH (or a DNS server) instead of the system resolver: %s" % watcher.describe())
+216
View File
@@ -0,0 +1,216 @@
"""E2E: the DoH of a proxied context when it is slow, and when it refuses once.
The engine resolves the names of a context with a proxy by the DoH service, which stays in global mode 0, and asks it
with a per-request TRR_ONLY (fail-closed: no native fallback). Mozilla does not exercise that combination: its TRR-only
is the GLOBAL mode 3, and several timeouts and counters of `TRRService` depend on the global mode. These two tests put
the combination under the two stresses a real DoH gives, on the layout of `test_context_proxy_only_resolves_by_doh_e2e.py`
(no launch proxy, one context with its own SOCKS5 gateway; the FakeDoh can be reached only through it, and only it
knows the names used here, so a page loads only if the lookup went to the DoH).
* `test_a_slow_doh_still_resolves_the_name_of_a_proxied_context`: the FakeDoh holds EVERY answer for `slow-a.test` for 2 s
(`delay_names`; each response is held after its query arrived, the A and the AAAA of the lookup together, so the
connection to the DoH is up at once and only the answer is late: this is what the browser's DoH request timeout
measures). In global mode 0 `TRRService::GetRequestTimeout` returns `network.trr.request_timeout_ms` (1.5 s); in global
mode 3 it returns `network.trr.request_timeout_mode_trronly_ms` (30 s). A request made TRR_ONLY per request under a global
mode 0 would keep the 1.5 s one and fail a lookup whose answer is only 2 s away, with nothing to fall back to. The page
must load, within 20 s, and the FakeDoh log must show the queries answered after the delay.
* `test_a_name_the_doh_refused_once_resolves_on_the_next_request`: the FakeDoh refuses the FIRST query of each type for
`flaky-a.test` by ending the exchange with no answer (a reset h2 stream: a failure of the CHANNEL, the kind
`ConfirmationContext::RecordTRRStatus` counts; `_doh_servers.FAILURE_KINDS` has the other two) and serves it afterwards.
The first navigation may fail (NS_ERROR_UNKNOWN_HOST) or load; then a retry loop (up to 5 navigations 2 s apart, each in a
fresh page of the same context, nothing cleared) must load within 15 s AND the FakeDoh must have been asked a second time:
the browser asks again instead of serving the failure from a cache or from a temporary block that a global TRR-only
mode would not have (`IsTemporarilyBlocked` returns false under global mode 3, and its blocklist is fed by failures
counted under the global modes).
Red on an engine with the 1.5 s DoH timeout (the giro-2 and giro-3 binaries before the timeout fix) for the first test:
the lookup of `slow-a.test` fails after 1.5 s, the navigation ends in NS_ERROR_UNKNOWN_HOST and the page never loads. The
second test is red if the failure of the first lookup sticks (negative cache or temporary block) longer than the retry loop.
"""
from __future__ import annotations
import time
import pytest
# The fixtures and the helpers of the DoH e2e (imported, not copied): the hermetic session (autouse), the resolver trap,
# the watcher, the page server, the gateway factory, and the accounting of the connections to the FakeDoh.
from test_doh_through_the_proxy_e2e import ( # noqa: F401 (the hermetic session is autouse and imported by name; the
# other fixtures of the DoH e2e are in conftest.py)
DOH_ADDRESSES, _asked_outside, _assert_every_connection_went_through_the_gateway, _direct_to_the_doh,
_hermetic_session, _is_address, _launch, _page_in, _text, _why)
import _doh_servers as ds
from _doh_servers import DOH_BOOTSTRAP, DOH_HOST, DOH_PORT, QTYPE_A, QTYPE_AAAA
pytestmark = pytest.mark.e2e
#: The latency of the slow DoH, and what a page behind it may take at most.
DOH_LATENCY_S = 2.0
SLOW_LOAD_LIMIT_S = 20.0
#: The retries after a refusal: how many, how far apart, and the time they all have.
RETRIES = 5
RETRY_GAP_S = 2.0
RETRY_WINDOW_S = 15.0
#: Firefox keeps the failure of ANY lookup (a refused DoH query included) in the DNS cache for network.dnsNegativeCacheExpiration
#: = 60 s, plus 60 s of grace (network.dnsNegativeCacheExpirationGracePeriod): retail behaviour, under a global TRR-only mode
#: too, measured by reading nsHostResolver.cpp:1333-1349 (not by a run). To isolate what this test is about (no TEMPORARY BLOCK
#: of the DoH and no stickiness beyond that cache) the session shortens the cache to 1 s and drops the grace period: the
#: refusal is then forgotten within the retry window. This only touches a cache; the code path of the lookup is the same.
SHORT_NEGATIVE_CACHE = {"network.dnsNegativeCacheExpiration": 1, "network.dnsNegativeCacheExpirationGracePeriod": 0}
def _launch_with_a_short_negative_cache(binary):
"""A session without a launch proxy (the proxy is the context's) whose DNS negative cache is 1 s."""
from invisible_playwright import InvisiblePlaywright
from test_doh_through_the_proxy_e2e import PREFS
return InvisiblePlaywright(seed=42, binary_path=binary, proxy=None, extra_prefs={**PREFS, **SHORT_NEGATIVE_CACHE},
headless=True)
def _navigate(context, url, timeout_ms):
"""(text or None, error or None, seconds) of one navigation in a fresh page of `context`, which is closed after."""
page = context.new_page()
started = time.monotonic()
try:
page.goto(url, wait_until="load", timeout=timeout_ms)
return _text(page), None, time.monotonic() - started
except Exception as exc: # noqa: BLE001 - the failure is the result
return None, "%s: %s" % (type(exc).__name__, str(exc).splitlines()[0] if str(exc) else ""), \
time.monotonic() - started
finally:
try:
page.close()
except Exception: # noqa: BLE001 - a page that cannot be closed is not the subject
pass
def _only_the_doh_road_was_used(doh, gw, watcher):
"""The layout assertions of the context-only e2e: the DoH was reached by the gateway of the context, by address,
and nothing went past it."""
why = _why(doh, gw)
assert (DOH_BOOTSTRAP, DOH_PORT) in gw.connects, "no DoH CONNECT to the bootstrap address reached the gateway" + why
assert [h for h, _p in gw.connects if not _is_address(h) and h != DOH_HOST] == [], (
"a CONNECT carried a name: the browser must resolve with the DoH and connect by address" + why)
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy of the context" + why
_assert_every_connection_went_through_the_gateway(doh, gw)
# Context-only layout: the default context resolves natively and never uses the DoH, so a failed handshake (the lookup
# of a context that does not accept the FakeDoh certificate) is a lookup of the wrong context sent to the DoH.
assert doh.tls_failures == [], "a DoH handshake failed: the default context used the DoH: %s" % doh.tls_failures + why
assert watcher.watched_pids, ("the watcher never saw a browser process (it saw: %s): a watcher that cannot see proves "
"nothing" % watcher.process_names)
assert _direct_to_the_doh(watcher) == [], (
"the browser reached a DoH (%s) or a DNS server (port 53) without the proxy: %s"
% (", ".join(DOH_ADDRESSES), watcher.describe()))
def test_a_slow_doh_still_resolves_the_name_of_a_proxied_context(firefox_binary, doh, pages, gateway, watcher,
record_property):
"""`slow-a.test` is known only to the FakeDoh, which answers it 2 s after the query. The page of a context with a
proxy of its own must load within 20 s, reached by address through that proxy."""
doh.names["slow-a.test"] = "127.0.0.1"
doh.delay_names["slow-a.test"] = DOH_LATENCY_S
gw = gateway("gw")
text = error = None
seconds = 0.0
with _launch(firefox_binary, None) as browser: # no launch proxy: only the context has one
context, page = _page_in(browser, proxy=gw.proxy)
started = time.monotonic()
try:
page.goto(pages.url("slow-a.test"), wait_until="load", timeout=int(SLOW_LOAD_LIMIT_S * 1000))
text = _text(page)
except Exception as exc: # noqa: BLE001 - reported below with what the FakeDoh saw
error = "%s: %s" % (type(exc).__name__, str(exc).splitlines()[0] if str(exc) else "")
seconds = time.monotonic() - started
context.close()
watcher.stop()
record_property("goto_seconds", "%.2f" % seconds)
answers = doh.answers_for("slow-a.test")
why = _why(doh, gw) + "\n FakeDoh answers (name, qtype, via, outcome, seconds held): %s\n goto took %.2f s" % (
[tuple(a) for a in doh.answers], seconds)
assert error is None and text is not None, (
"the page behind a DoH that answers in %.0f s did not load (%s): the DoH request of a lookup made TRR_ONLY per "
"request gave up before the answer (the 1.5 s timeout of global mode 0?)" % (DOH_LATENCY_S, error) + why)
assert "HOST=slow-a.test:%d" % pages.port in text, "the page is not the page of the name: %r" % text + why
assert seconds < SLOW_LOAD_LIMIT_S, "the page took %.1f s to load, the limit is %.0f s" % (seconds, SLOW_LOAD_LIMIT_S) + why
assert seconds >= DOH_LATENCY_S - 0.2, (
"the page loaded in %.2f s, before the DoH could have answered (%.0f s): the name was not resolved by it"
% (seconds, DOH_LATENCY_S) + why)
assert [a for a in answers if a.qtype == QTYPE_A], "the DoH was never asked for the A record of the name" + why
assert answers and all(a.outcome == "answered" for a in answers), "the DoH refused something here" + why
assert min(a.delay for a in answers) >= 1.8, (
"a query was answered after only %.2f s: the FakeDoh did not hold it (A and AAAA: %s)"
% (min(a.delay for a in answers), [(a.qtype, round(a.delay, 2)) for a in answers]) + why)
assert doh.vias_of("slow-a.test", QTYPE_A) == {"gw"}, "slow-a.test (A) was not asked by gw (the proxy of the context)" + why
assert not [h for h, _p in gw.connects if h == "slow-a.test"], "the browser sent the NAME to the gateway" + why
assert ("127.0.0.1", pages.port) in gw.connects, "the page was not reached by address through the gateway" + why
assert _asked_outside(doh, "slow-a.test") == [], (
"the DoH was asked for a name that is not the proxied context's: %s" % _asked_outside(doh, "slow-a.test") + why)
_only_the_doh_road_was_used(doh, gw, watcher)
def test_a_name_the_doh_refused_once_resolves_on_the_next_request(firefox_binary, doh, pages, gateway, watcher,
record_property):
"""The FakeDoh ends the exchange of the first A (and the first AAAA) query for `flaky-a.test` with no answer, then
serves the name. The first navigation may fail with NS_ERROR_UNKNOWN_HOST or load; a retry (a fresh page of the same
context, 2 s apart, up to 5 times, within 15 s) must load, and the browser must have asked the DoH again. The
DNS negative cache (60 s + 60 s of grace in a release, the same under a global TRR-only mode) is shortened to 1 s
for this test (SHORT_NEGATIVE_CACHE): without it the retries would be answered from the cache, as in a retail
Firefox, and the test would say nothing about a temporary block of the DoH.
WHAT IT MEASURES: that a lookup the DoH refused once is not blocked by anything of the DoH itself (no temporary
blocklist, no failure counter: under a per-request TRR_ONLY with the service in global mode 0 neither applies, by
reading TRRService.cpp:1025-1066, :1126, :1250-1298 and TRR.cpp:177-217) and that the browser asks the DoH again
(a second A query at the FakeDoh) and resolves the name when it is served. WHAT IT DOES NOT MEASURE: how long Firefox
keeps the failure of a lookup in its DNS cache (60 s + 60 s of grace in a release, retail behaviour, the same in a
global TRR-only mode); that duration is shortened here on purpose and is not tested."""
doh.names["flaky-a.test"] = "127.0.0.1"
doh.fail_first["flaky-a.test"] = "close"
gw = gateway("gw")
url = pages.url("flaky-a.test")
attempts = [] # (text or None, error or None, seconds)
with _launch_with_a_short_negative_cache(firefox_binary) as browser:
context, page = _page_in(browser, proxy=gw.proxy)
page.close()
attempts.append(_navigate(context, url, 20000))
window_starts = time.monotonic()
while attempts[-1][0] is None and len(attempts) <= RETRIES:
remaining = RETRY_WINDOW_S - (time.monotonic() - window_starts)
if remaining <= 0:
break
time.sleep(min(RETRY_GAP_S, remaining))
remaining = RETRY_WINDOW_S - (time.monotonic() - window_starts)
if remaining <= 0:
break
attempts.append(_navigate(context, url, int(min(8.0, remaining) * 1000)))
context.close()
watcher.stop()
record_property("attempts", str([(ok is not None, err, round(s, 2)) for ok, err, s in attempts]))
queries = doh.queries_for("flaky-a.test", QTYPE_A)
why = _why(doh, gw) + "\n FakeDoh answers (name, qtype, via, outcome, seconds held): %s\n navigations (text, error, s): %s" % (
[tuple(a) for a in doh.answers], attempts)
first_text, first_error, _s = attempts[0]
assert first_text is not None or "NS_ERROR_UNKNOWN_HOST" in (first_error or ""), (
"the first navigation failed in a way that is not the refusal of the name: %s" % first_error + why)
refused = [a for a in doh.answers_for("flaky-a.test") if a.outcome == "close"]
assert {a.qtype for a in refused} <= {QTYPE_A, QTYPE_AAAA} and [a for a in refused if a.qtype == QTYPE_A], (
"the FakeDoh never refused the first A query of the name: the test did not exercise a refusal" + why)
loaded = [a for a in attempts if a[0] is not None]
assert loaded, (
"no navigation to a name the DoH refused once loaded in %d attempts / %.0f s: the failure of the first lookup "
"sticks (a cached failure or a temporary block)" % (len(attempts), RETRY_WINDOW_S) + why)
assert "HOST=flaky-a.test:%d" % pages.port in loaded[0][0], "the page is not the page of the name: %r" % loaded[0][0] + why
assert len(queries) >= 2, (
"the DoH was asked for the A record of the name %d time(s): the browser must ask again after a refusal, not serve "
"a cached failure beyond the DoH's own negative TTL" % len(queries) + why)
assert [a for a in doh.answers_for("flaky-a.test", QTYPE_A) if a.outcome == "answered"], (
"the DoH never answered the name after the refusal" + why)
assert doh.vias_of("flaky-a.test", QTYPE_A) == {"gw"}, "flaky-a.test (A) was not asked by gw only" + why
assert not [h for h, _p in gw.connects if h == "flaky-a.test"], "the browser sent the NAME to the gateway" + why
assert _asked_outside(doh, "flaky-a.test") == [], (
"the DoH was asked for a name that is not the proxied context's: %s" % _asked_outside(doh, "flaky-a.test") + why)
_only_the_doh_road_was_used(doh, gw, watcher)
@@ -0,0 +1,307 @@
"""Every order in which the engine's events about a popup can reach the adoption gives the client exactly one `page` event.
NO BROWSER HERE: the real dispatchers over a scripted Juggler connection, and the adoption thread stopped, one step at a time, at SIX
points of its own (before it records itself as building, before it sends the init scripts, before it waits for the main frame, before it
records itself as waiting, before it waits for the ready, before it announces) while the engine's events are delivered between the steps.
The events of a target that is not a page a caller asked for, as the engine sends them: ATTACH (always first), then FRAME (the main frame
and its contexts), COMMIT (the initial about:blank), READY, and DETACH (the tab is closed: a download's empty tab, a popup the site closed)
which can come after ANY prefix of the others and after which the engine answers "cannot find session" to every command about the
session. For each of the prefixes that can occur, EVERY placement of its events among the eight moments of the adoption (parked at
each of the six points, while it waits for the ready, after it) is run: 650 cases, none sampled.
The invariant (`_Adoption`): such a target gives the client exactly ONE `page` event, at its ready or at its disappearance, and when
it disappeared its close right after, never before; no warning of a failed adoption; nothing left in the registry; the adoption thread
ends. A target that gets neither a ready nor a detach gives no event and its wait ends with its context.
Why it exists: the same race was found four times by a run on a loaded machine, each time one step further along (a detach before the
ready, during the build, between the build and the wait, and a command answered "cannot find session"); a fifth was this test's first
find (a detach while the adoption waits for the main frame of a tab the engine never announced).
"""
from __future__ import annotations
import itertools
import threading
import time
import warnings
import pytest
from invisible_core.juggler.connection import ProtocolError
from invisible_playwright._juggler import dispatcher as base
from invisible_playwright._juggler import remote
from invisible_playwright._juggler import server as server_mod
from invisible_playwright._juggler.server import LocalUtilsDispatcher
from test_a_closed_context_leaves_nothing_in_the_registry import ScriptedJuggler
pytestmark = pytest.mark.unit
TARGET = "x1"
SESSION = "xs1"
FRAME = "fx1"
#: where the adoption thread can be stopped, in the order it reaches them
GATES = ["building", "init_scripts", "main_frame", "waiting", "ready_wait", "announce"]
#: the moments an event can be delivered: parked at each gate, while it waits for the ready, parked at `announce`, after it is over
MOMENTS = ["g0", "g1", "g2", "g3", "g4", "during_wait", "g5", "after"]
class Engine(ScriptedJuggler):
"""The scripted engine, which answers 'cannot find session' to a command about a session whose target it took away."""
def __init__(self):
super().__init__()
self.gone_sessions = set()
def send(self, method, params=None, session=None, timeout=30):
if session in self.gone_sessions:
raise ProtocolError('%s: ERROR: cannot find session with id "%s"' % (method, session))
return super().send(method, params, session, timeout)
def attach(self, opener_target, context_id):
self.sessions[TARGET] = SESSION
self.dispatch_event("Browser.attachedToTarget", {
"sessionId": SESSION,
"targetInfo": {"targetId": TARGET, "type": "page", "openerId": opener_target, "browserContextId": context_id}}, None)
def frame(self):
self.dispatch_event("Page.frameAttached", {"frameId": FRAME, "parentFrameId": None}, SESSION)
for world in ("", "utility"):
self.dispatch_event("Runtime.executionContextCreated", {
"executionContextId": "e%s" % world, "auxData": {"frameId": FRAME, "name": world}}, SESSION)
def commit(self):
self.dispatch_event("Page.navigationStarted", {"frameId": FRAME, "navigationId": "n1", "url": "about:blank"}, SESSION)
self.dispatch_event("Page.navigationCommitted", {"frameId": FRAME, "navigationId": "n1", "url": "about:blank", "name": ""}, SESSION)
def ready(self):
self.dispatch_event("Page.ready", {}, SESSION)
def detach(self):
self.gone_sessions.add(SESSION)
self.dispatch_event("Browser.detachedFromTarget", {"targetId": TARGET, "sessionId": SESSION}, None)
class Gates:
"""Stops the adoption thread of the popup at each of the six points, until the test lets it pass."""
def __init__(self):
self.reached = [threading.Event() for _ in GATES]
self.release = [threading.Event() for _ in GATES]
self.passed = set()
def pause(self, index):
if threading.current_thread().name != "invpw-adopt-%s" % TARGET or index in self.passed:
return
self.passed.add(index)
self.reached[index].set()
self.release[index].wait(10)
def open_all(self):
for event in self.release:
event.set()
def _thread():
for t in threading.enumerate():
if t.name == "invpw-adopt-%s" % TARGET:
return t
return None
def _wait(condition, seconds=3.0):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
if condition():
return True
time.sleep(0.002)
return condition()
def _install_gates(monkeypatch, gates):
def gated(index, owner, name):
original = getattr(owner, name)
def wrapper(*args, **kwargs):
gates.pause(index)
return original(*args, **kwargs)
monkeypatch.setattr(owner, name, wrapper)
gated(0, server_mod.BrowserDispatcher, "_enter_building")
gated(1, server_mod.InjectedScript, "install")
gated(2, server_mod.Lifecycle, "wait_for_main_frame")
gated(3, server_mod.BrowserDispatcher, "_enter_waiting")
gated(4, server_mod.PageDispatcher, "wait_until_ready")
gated(5, server_mod.BrowserDispatcher, "_enter_announced")
def _run(events, placement):
"""One case: `events` (a prefix of frame, commit, ready, detach) delivered at the moments in `placement` (one per event)."""
gates = Gates()
trace = []
original_emit = base.Dispatcher.emit
def spy(self, method, params=None):
if method == "page" and getattr(self, "TYPE", "") == "BrowserContext":
trace.append("page")
elif method == "close" and getattr(self, "TYPE", "") == "Page" and getattr(self, "target_id", None) == TARGET:
trace.append("close")
return original_emit(self, method, params)
with pytest.MonkeyPatch.context() as mp:
mp.setattr(base.Dispatcher, "emit", spy)
_install_gates(mp, gates)
server = remote._SharedServer()
browser_type = remote.SharedBrowserType(server)
LocalUtilsDispatcher(server)
conn = Engine()
browser = remote.SharedBrowserDispatcher(server, browser_type, conn, "firefox/1")
try:
context = server.object(server.handle({"guid": browser.guid, "method": "newContext", "params": {}})["context"]["guid"])
# the opener, built with no gate (the gates only stop the popup's own thread)
server.handle({"guid": context.guid, "method": "newPage", "params": {"pageNumber": 1}})
opener_target = next(t for t in conn.sessions if t != TARGET)
del trace[:] # the opener's own page event is not the popup's
todo = list(zip(events, placement))
delivered = set()
def deliver(moment):
for event, where in list(todo):
if where == moment:
getattr(conn, event)()
delivered.add(event)
todo.remove((event, where))
def deliver_next():
"""The adoption is blocked in a wait that only an event of the engine can end: the next one arrives now (that wait IS the
moment it was placed at)."""
if todo:
event, _where = todo.pop(0)
getattr(conn, event)()
delivered.add(event)
return True
return False
def advance_until(condition, what, seconds=3.0):
"""Wait for `condition`; while nothing moves for 0.1 s, deliver the next pending event."""
end = time.monotonic() + seconds
idle_since = time.monotonic()
while time.monotonic() < end:
if condition():
return True
if time.monotonic() - idle_since > 0.1:
if deliver_next():
idle_since = time.monotonic()
else:
idle_since = time.monotonic() + 1e9 # nothing left to deliver: just wait
time.sleep(0.002)
assert condition(), what
return True
def parked(i):
return gates.reached[i].is_set() or _thread() is None
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
conn.attach(opener_target, context.context_id)
assert gates.reached[0].wait(3), "the adoption thread never started"
for i in range(5): # parked at gate i
if i > 0:
advance_until(lambda: parked(i) or any(gates.reached[j].is_set() for j in range(i + 1, 6)),
"the adoption thread never reached %s" % GATES[i])
deliver("g%d" % i)
gates.release[i].set()
# gate 4 is released: the thread is in (or about to be in) its wait for the ready
deliver("during_wait")
final_unblocked = "ready" in delivered or "detach" in delivered or any(e in ("ready", "detach") for e, _ in todo)
if final_unblocked:
advance_until(lambda: gates.reached[5].is_set() or _thread() is None, "the wait for the ready never ended")
deliver("g5") # parked at the announcement (if it got there)
gates.release[5].set()
advance_until(lambda: _thread() is None, "the adoption thread never ended")
deliver("after")
while deliver_next(): # anything left arrives after it all
pass
else:
while deliver_next():
pass
time.sleep(0.05)
assert _thread() is not None or not trace, "a target with neither ready nor detach was announced"
time.sleep(0.01)
bad = [str(w.message) for w in caught if "adoption" in str(w.message)]
return trace, bad, dict(server_state=len(browser._adoptions)), (browser, context, gates, conn)
finally:
gates.open_all()
def _check(events, placement):
trace, bad, state, (browser, context, gates, conn) = _run(events, placement)
try:
label = "events %s at %s" % (events, placement)
problems = []
disappears = "detach" in events
if bad:
problems.append("a warning of a failed adoption: %s" % bad)
if "ready" in events or disappears:
if trace.count("page") != 1:
problems.append("%d page events" % trace.count("page"))
if disappears:
if trace.count("close") != 1:
problems.append("%d close events" % trace.count("close"))
elif "page" in trace and trace.index("page") > trace.index("close"):
problems.append("the close came before the page")
elif trace.count("close"):
problems.append("a close for a page that did not disappear")
if state["server_state"] != 0:
problems.append("%d adoptions left in the registry" % state["server_state"])
else:
if trace:
problems.append("events %r for a target with neither ready nor detach" % (trace,))
# its context closes: the wait ends, still nothing announced
browser.server.handle({"guid": context.guid, "method": "close", "params": {}})
if not _wait(lambda: _thread() is None):
problems.append("the wait did not end with its context")
if trace.count("page"):
problems.append("announced after its context closed")
return label, problems
finally:
gates.open_all()
try:
browser.server.shutdown()
except Exception:
pass
def _placements(n, moments):
"""Every way of putting n events, in order, on the given moments (the same moment allowed, the order kept)."""
return itertools.combinations_with_replacement(range(len(moments)), n)
SEQUENCES = {
"frame_commit_ready": (["frame", "commit", "ready"], MOMENTS),
"frame_commit_ready_detach": (["frame", "commit", "ready", "detach"], MOMENTS),
"frame_commit_detach": (["frame", "commit", "detach"], MOMENTS),
"frame_detach": (["frame", "detach"], MOMENTS),
"detach": (["detach"], MOMENTS),
# neither ready nor detach: nothing is announced; the events can only arrive while the adoption is alive
"frame_commit": (["frame", "commit"], MOMENTS[:6]),
}
@pytest.mark.parametrize("name", sorted(SEQUENCES))
def test_every_order_of_the_events_of_a_popup_gives_one_page_event(name):
events, moments = SEQUENCES[name]
failures = []
count = 0
for combo in _placements(len(events), moments):
placement = [moments[i] for i in combo]
count += 1
try:
label, problems = _check(events, placement)
except AssertionError as e:
label, problems = "events %s at %s" % (events, placement), [str(e)]
if problems:
failures.append("%s: %s" % (label, "; ".join(problems)))
assert count > 0
assert not failures, "%d of %d orders broke the invariant, e.g.:\n %s" % (len(failures), count, "\n ".join(failures[:12]))
@@ -54,18 +54,42 @@ def test_every_op_of_a_route_goes_through__send_and_nothing_else_talks_to_the_pa
assert not _sends_network_command(fn), "%s sends a Network command by itself" % name
def test__send_swallows_a_request_the_browser_already_closed_and_nothing_else():
def test__send_answers_every_protocol_error_of_a_route_command_as_may_fail():
"""Stock's `sendMayFail`: whatever the engine says about a request the page already closed ("Cannot find request",
"NS_BINDING_ABORTED [nsIInterceptedChannel.resetInterceptionWithURI]", the next wording) is not the client's error."""
send = _methods(_route_dispatcher())["_send"]
handlers = [n for n in ast.walk(send) if isinstance(n, ast.ExceptHandler)]
caught = {ast.unparse(h.type) for h in handlers if h.type is not None}
assert caught == {"juggler.ProtocolError", "juggler.TargetClosedError"}, caught
assert not any(isinstance(n, ast.Raise) for h in handlers for n in ast.walk(h)), \
"an error of a route command must never reach the client: it would be raised on its NEXT route command"
source = ast.get_source_segment(SERVER.read_text(encoding="utf-8"), send)
assert '"Cannot find request" not in str(exc)' in source and "raise" in source, \
"a ProtocolError other than 'Cannot find request' must still reach the client"
assert source.index("self.dispose()") > source.index("except juggler.TargetClosedError"), \
"the route is disposed after a swallowed error too"
@pytest.mark.parametrize("message", [
'Network.resumeInterceptedRequest: Cannot find request "123"',
"Network.resumeInterceptedRequest: Component returned failure code: 0x804b0002 (NS_BINDING_ABORTED) "
"[nsIInterceptedChannel.resetInterceptionWithURI]",
"Network.abortInterceptedRequest: Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)",
])
def test_a_protocol_error_from_the_engine_is_not_the_clients_error(message):
from invisible_playwright._juggler import server as srv
class Page:
def send(self, command, params):
raise srv.juggler.ProtocolError(message)
class Request:
page = Page()
request_id = "r1"
route = object.__new__(srv.RouteDispatcher)
route.request, route.answered, route.dispose = Request(), False, lambda: None
assert route._send("Network.resumeInterceptedRequest", {}) is None
def test_the_stock_client_the_networkidle_e2e_drives_the_server_with_is_a_pinned_dev_dependency():
"""That e2e fails (not skips) without the stock Playwright client, so CI must install it: the `dev` extra pins it to the
version of scripts/playwright_pin.txt."""
+10 -3
View File
@@ -354,10 +354,17 @@ def test_webgl_getParameter_deterministic(page):
res = _ev(page, """() => {
const norm = v => (ArrayBuffer.isView(v) ? Array.from(v) : v);
const c = document.createElement('canvas');
// The browser's own reason for a context it could not create (the event carries it; the page only
// sees null otherwise). A null seen once in 31 runs of the e2e on a loaded runner said 'gl null' and
// nothing else, which cannot be told from a missing GL, a refused library, an allocation that failed.
const errors = [];
c.addEventListener('webglcontextcreationerror', e => errors.push(e.statusMessage || ''), false);
const gl = c.getContext('webgl');
if (!gl) {
return {ok: false, reason: 'gl null',
webgl2: !!c.getContext('webgl2')};
const c2 = document.createElement('canvas');
c2.addEventListener('webglcontextcreationerror', e => errors.push('webgl2: ' + (e.statusMessage || '')), false);
return {ok: false, reason: 'gl null', errors,
webgl2: !!c2.getContext('webgl2')};
}
if (gl.isContextLost()) {
return {ok: false, reason: 'context lost'};
@@ -385,7 +392,7 @@ def test_webgl_getParameter_deterministic(page):
}""")
assert res["ok"], (
f"WebGL getParameter check failed: reason={res.get('reason')!r} "
f"webgl2={res.get('webgl2')!r} round={res.get('round')!r} "
f"webgl2={res.get('webgl2')!r} errors={res.get('errors')!r} round={res.get('round')!r} "
f"param={res.get('param')!r} first={res.get('first')!r} "
f"ref={res.get('ref')!r}"
)
+53 -42
View File
@@ -21,9 +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 engine's own processes below the test (`-contentproc ... tab`): a
cross-site frame adds at least one, a same-site one adds none. The count is read after the browser is quiet
(the engine pre-allocates a content process and replaces it when it is used).
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
@@ -37,13 +42,18 @@ from urllib.parse import parse_qs, urlsplit
import pytest
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)
}
@@ -125,35 +135,9 @@ def engine_dir(firefox_binary):
return str(Path(firefox_binary).resolve().parent)
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`."""
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 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
@@ -211,25 +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 content process: 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, cross_site_loop, engine_dir):
"""Green today, the control: a frame of the page's own site adds no content process."""
"""Green today, the control: a frame of the page's own site gets no process, and none for another site.
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). 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)
page.goto(cross_site_loop["same_site"], wait_until="load")
assert wait_for(page, lambda: any(r["path"] == "/report/loaded" for r in cross_site_loop["reports"]))
after = quiet(engine_dir)
assert not (after - before), "a same-site frame started a process: %s" % sorted(after - 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 = 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 ──────────────────────────────────
+185 -52
View File
@@ -1,23 +1,69 @@
"""HTTP/3 behind a SOCKS5 proxy: the page reads `nextHopProtocol`, and a retail Firefox with no proxy uses h3.
"""HTTP/3 behind a proxy: visits of one page read the protocols a retail Firefox reads, road by road.
⛔ THE KNOWN-BAD INPUT: the engine refuses HTTP/3 whenever a proxy is in use (AltSvcCache::UpdateAltServiceMapping, the
attempt of DnsAndConnectSocket, HttpBaseChannel), so a page behind a SOCKS5 gateway that relays UDP read `h2` where the
same Firefox with no proxy reads `h3`. With a gateway that relays UDP the QUIC connection goes through the ASSOCIATE of the
proxy (the server sees the relay, never this host); with one that does not, the QUIC handshake never completes and Firefox
falls back to h2 by itself, and nothing UDP leaves this host direct.
⛔ THE KNOWN-BAD INPUT: an engine that refuses HTTP/3 whenever a proxy is in use reads `h2` on every visit behind a SOCKS5 gateway
that relays UDP where the same Firefox reads `h3` after the first visits; one that reads `h3` at the FIRST visit of THIS
fixture (see below: it is not a retail fact, it is a property of the fixture); and one that tries h3 over a UDP that goes nowhere
makes the page wait for a timeout before it falls back to h2.
The server is local, reached by its address (an address of this host that is not loopback: a loopback destination goes
direct whatever the proxy), with a self-signed certificate (the context ignores certificate errors).
THE REFERENCE is a retail Firefox 159 on Windows, measured with DoH forced like our core (15 sessions per condition, one
profile per session). With UDP free the first runs read h2/h2/h3 in 9 sessions, h2/h2/h2 in 4 and h2/h3/h3 in 2, and h3 does
not have to come at the second visit. THE THIRD RUN (Windows, DoH and UDP free) READ h3 AT THE FIRST VISIT IN 3 SESSIONS OF 15
(h3, h2, h2): behind a proxy "visit 1 is always h2" is NOT a retail fact. With UDP blocked it is h2/h2/h2 in 15 of 15, with no
delay of the load: the only outcome of the retail that repeats every time. With no
proxy and the native DNS (measured in loopback) it is h2, h3, h3. The method is the retail's: one context, the same page again
and again (``?v=N`` keeps each visit off the HTTP cache), a pause of two seconds after each load so that the Alt-Svc it carries
settles, and the ``nextHopProtocol`` of the navigation entry of the document,
``performance.getEntriesByType('navigation')[0].nextHopProtocol``. What each road reads is in ``_udp_line.expected_protocols``
and is judged by ``_udp_line.judge_visits``.
WHY VISIT 1 IS h2 HERE. The retail reads h3 at the first visit when the DNS answer carries the HTTPS record (type 65, with
``alpn=h3``): the browser then knows before it connects. The server of these tests is reached by its ADDRESS, so no name is
looked up and no HTTPS record exists; and the FakeDoh of the tests (tests/_doh_servers.py) never serves a type 65 with data
(``FakeDoh.https_served`` stays empty; each test below asserts it, or that the page was reached by an address). That is what
makes the first visit h2 in a hermetic test, and only that: a FakeDoh that learns to serve type 65 changes the expectation
for the name it serves, and this test says so before it goes red on a protocol.
THE VISITS. No proxy: three, exactly h2, h3, h3. Behind a proxy: FIVE, on every road (the same number for all, for symmetry), and
all five are done (no early stop: the judge is a pure function of the list, so it is deterministic). On the road with UDP free
the first visit must be h2 (the fixture has no HTTPS record), at least one visit must be h3 within the five, and once a visit is
h3 the next ones are h3 too; the second visit is not required to be h3. On the roads without usable UDP every one of the five is h2 and visits 2 to 5 load no more
than ``LOAD_MARGIN_MS`` slower than the first. Time: about 3 s a visit (load plus the pause), so about 15 s of browsing per
proxy test and 9 s for the one with no proxy.
THE ROADS. A proxy whose UDP the core MEASURED ``coherent`` (a STUN Binding through its ASSOCIATE came back from the address of
its TCP exit) carries QUIC through the relay, the server sees the relay and never this host, and the page ends up on h3 as the
retail does with UDP free. Every other proxy is "a router that drops UDP", and the engine acts on it: the SOCKS5 proxy
that refuses UDP (``no``), whose UDP leaves from another address (``no``) or that never answers (``unmeasured``), and an HTTP
proxy (which has no UDP at all): h2 on every visit, nothing QUIC reaches the server, no datagram of the page goes to a relay, and
no visit waits for a timeout. The core's measurement is not replaced: it asks the relay of each gateway for a Binding for real,
at the server the launch names (``udp_stun_servers``), and the test says what the launch declared.
The server is local, reached by its address (an address of this host that is not loopback: a loopback destination goes direct
whatever the proxy), with a self-signed certificate (the context ignores certificate errors); its TCP side speaks HTTP/2 and
carries ``Alt-Svc: h3`` (tests/_h3_server.py).
"""
from __future__ import annotations
import os
import socket
import time
import pytest
from _host_address import this_host_address
from _udp_line import (declared_udp, egress_by_proxy, expected_protocols, judge_visits, measure_servers, no_https_record,
visits_for)
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
#: What the product's own probe of the egress is told when there is no proxy: RFC 5737 TEST-NET-3.
EXIT_DIRECT = "203.0.113.7"
#: What the core is expected to have measured, by road.
_DECLARED = {"socks5_coherent": "coherent", "socks5_no_udp": "no", "socks5_mismatched": "no", "socks5_unmeasured": "unmeasured"}
#: The pause after each load (the retail method), and the nextHopProtocol of the document.
PAUSE_MS = 2000
_NAV_JS = "() => performance.getEntriesByType('navigation')[0].nextHopProtocol"
def _binary():
cand = os.environ.get("STEALTHFOX_E2E_BINARY") or os.environ.get("INVPW_BINARY_PATH")
@@ -26,65 +72,152 @@ def _binary():
return cand
def _address_of_this_host() -> str:
probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
probe.connect(("192.0.2.1", 9))
return probe.getsockname()[0]
finally:
probe.close()
def _gateway(road: str, host: str):
from _socks_servers import coherent, mismatched, silent_udp, tcp_only
make = {"socks5_coherent": coherent, "socks5_no_udp": tcp_only, "socks5_mismatched": mismatched,
"socks5_unmeasured": silent_udp}[road]
# The relay sits on the address of this host, as a real gateway's does: the engine's UDP sockets are bound to an interface.
# Its datagrams leave from that address too, on every system: Windows cannot send from 127.0.0.1 to an address of its own host
# (WinError 10051, which this test once read as "the server saw QUIC from []"). The relay is told from a client that came direct
# by the PORT it sends from (``gateway.exit_ports``), and it forwards only to this host: the browser's own QUIC to the Internet
# stays in the lab.
gateway = make(user="alice", password="s3cret", relay_host=host, exit_host=host)
gateway.forward_only_to = {host}
return gateway
_FETCH = """async (url) => {
const seen = [];
for (let i = 0; i < 12; i++) {
const r = await fetch(url + '?n=' + i, {cache: 'no-store', mode: 'no-cors'});
await r.arrayBuffer();
const entry = performance.getEntriesByType('resource').filter(e => e.name.includes('?n=' + i)).pop();
seen.push(entry ? entry.nextHopProtocol : '?');
await new Promise(resolve => setTimeout(resolve, 500));
}
return seen;
}"""
def _protocols_behind(gateway, server, monkeypatch):
def _visits(road, server, monkeypatch, discover, **launch):
"""Visit the page of ``server`` ``visits_for(road)`` times in one context; the nextHopProtocol of the document of each visit
and the time ``page.goto`` took to the load event, in milliseconds."""
from invisible_core import _geo
from invisible_playwright import InvisiblePlaywright
monkeypatch.setattr(_geo, "discover_egress_ip", lambda *_a, **_k: gateway.tcp_exit)
with InvisiblePlaywright(headless=True, binary_path=_binary(), timezone="America/New_York",
proxy=gateway.proxy) as browser:
monkeypatch.setattr(_geo, "discover_egress_ip", discover)
protocols, walls = [], []
# Firefox turns HTTP/3 off when the certificate chain ends in a root that is not one of its own (a self-signed test
# server always does): measured, the Alt-Svc is learned, the QUIC handshake of validation succeeds with the override and
# Firefox then closes it itself (hasThirdPartyRoots), so the visits stay h2. A test with a certificate of its own turns
# that check off; the product does not (it would change what Firefox does with a root it does not know).
prefs = {"network.http.http3.disable_when_third_party_roots_found": False, **launch.pop("extra_prefs", {})}
with InvisiblePlaywright(headless=True, binary_path=_binary(), timezone="America/New_York", locale="en-US",
extra_prefs=prefs, **launch) as browser:
context = browser.new_context(ignore_https_errors=True)
page = context.new_page()
page.goto(server.url, wait_until="load", timeout=60000) # the answer that carries Alt-Svc: h3
page.wait_for_timeout(1500)
return page.evaluate(_FETCH, server.url)
for visit in range(1, visits_for(road) + 1):
url = server.url if visit == 1 else "%s?v=%d" % (server.url, visit)
started = time.monotonic()
page.goto(url, wait_until="load", timeout=60000)
walls.append(round((time.monotonic() - started) * 1000))
page.wait_for_timeout(PAUSE_MS) # let the later resources and the Alt-Svc settle
protocols.append(page.evaluate(_NAV_JS))
return protocols, walls
def test_a_page_behind_a_gateway_that_relays_udp_reads_h3_and_the_quic_goes_by_the_relay(monkeypatch):
def _report(road, protocols, walls, server, gateway=None):
said = ("the %d visits of road %s read %s (a retail Firefox reads %s), loaded in %s ms; the server answered TCP with "
"ALPN %s and saw QUIC from %s" % (len(protocols), road, protocols, expected_protocols(road), walls,
server.tcp_alpn, server.quic_peers))
if gateway is not None:
said += "; datagrams the relay carried: %s" % sorted({(h, p) for h, p, _data in gateway.datagrams})
if gateway.send_errors:
said += "; sends of the relay that failed: %s" % sorted(set(gateway.send_errors))
return said
def test_a_page_with_no_proxy_reads_h2_then_h3_then_h3(monkeypatch):
import aioquic # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
from _h3_server import H3Server
from _socks_servers import coherent
host = _address_of_this_host()
with H3Server(host) as server, coherent(user="alice", password="s3cret", relay_host=host) as gateway:
protocols = _protocols_behind(gateway, server, monkeypatch)
with H3Server(this_host_address()) as server:
assert not no_https_record(server.address), no_https_record(server.address)
protocols, walls = _visits("direct", server, monkeypatch, egress_by_proxy(direct=EXIT_DIRECT))
problems = judge_visits("direct", protocols, walls)
assert not problems, "; ".join(problems) + ". " + _report("direct", protocols, walls, server)
assert server.quic_peers, "the h3 visits did not reach the server by QUIC"
def test_a_page_behind_a_gateway_that_relays_udp_starts_on_h2_reaches_h3_within_five_visits_and_the_quic_goes_by_the_relay(monkeypatch):
import aioquic # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
from _h3_server import H3Server
host = this_host_address()
with H3Server(host) as server, _gateway("socks5_coherent", host) as gateway:
assert not no_https_record(host), no_https_record(host)
protocols, walls = _visits("socks5_coherent", server, monkeypatch, egress_by_proxy(gateway), proxy=gateway.proxy,
udp_stun_servers=measure_servers(gateway))
carried = [(h, p) for h, p, _data in gateway.datagrams if (h, p) == (host, server.port)]
assert "h3" in protocols, f"nextHopProtocol of 12 fetches behind a gateway that relays UDP: {protocols}"
assert carried, "the QUIC datagrams did not go by the relay of the gateway"
assert server.quic_peers and set(server.quic_peers) == {"127.0.0.1"}, (
f"the QUIC server saw {server.quic_peers}: only the relay of the gateway (127.0.0.1) may reach it")
declared = declared_udp(gateway.proxy, measure_servers(gateway))
said = _report("socks5_coherent", protocols, walls, server, gateway)
assert declared == "coherent", "the core measured the gateway %s, not coherent: the engine would not use its relay. %s" % (declared, said)
problems = judge_visits("socks5_coherent", protocols, walls)
assert not problems, "; ".join(problems) + ". " + said
assert carried, "the QUIC datagrams did not go by the relay of the gateway. " + said
assert not gateway.send_errors, "the relay of the gateway could not send. " + said
assert server.quic_peer_addrs and {a for a, _p in server.quic_peer_addrs} == {host} and {p for _a, p in server.quic_peer_addrs} <= set(gateway.exit_ports), (
"the QUIC server saw %s: only the relay of the gateway (%s, from the ports %s) may reach it. %s" % (
server.quic_peer_addrs, host, gateway.exit_ports, said))
def test_a_page_behind_a_gateway_without_udp_falls_back_to_h2_and_nothing_goes_direct(monkeypatch):
@pytest.mark.parametrize("road", ["socks5_no_udp", "socks5_mismatched", "socks5_unmeasured"])
def test_a_page_behind_a_socks5_proxy_that_is_not_coherent_reads_h2_on_every_visit_and_loads_without_delay(monkeypatch, road):
"""A relay that is refused, that leaves from another address or that never answers is a router that drops UDP: every
visit (five) is h2, nothing QUIC reaches the server, nothing of the page goes to the relay, and visits 2 to 5 load as fast as 1."""
import aioquic # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
from _h3_server import H3Server
from _socks_servers import tcp_only
host = _address_of_this_host()
with H3Server(host) as server, tcp_only(user="alice", password="s3cret") as gateway:
protocols = _protocols_behind(gateway, server, monkeypatch)
assert "?" not in protocols and "h3" not in protocols, (
f"behind a gateway that carries no UDP every fetch is h2 (or http/1.1), never h3: {protocols}")
assert not server.quic_peers, f"a QUIC connection reached the server direct, around the proxy: {server.quic_peers}"
host = this_host_address()
with H3Server(host) as server, _gateway(road, host) as gateway:
assert not no_https_record(host), no_https_record(host)
protocols, walls = _visits(road, server, monkeypatch, egress_by_proxy(gateway), proxy=gateway.proxy,
udp_stun_servers=measure_servers(gateway))
to_the_server = [(h, p) for h, p, _data in gateway.datagrams if (h, p) == (host, server.port)]
declared = declared_udp(gateway.proxy, measure_servers(gateway))
said = _report(road, protocols, walls, server, gateway)
assert declared == _DECLARED[road], "the core declared udp=%s, the road is %s. %s" % (declared, _DECLARED[road], said)
problems = judge_visits(road, protocols, walls)
assert not problems, "; ".join(problems) + ". " + said
assert not server.quic_peers, "a QUIC connection reached the server: %s. %s" % (server.quic_peers, said)
assert not to_the_server, "the page's UDP went to a relay that was not measured coherent. " + said
def test_a_page_behind_an_http_proxy_reads_h2_on_every_visit_and_loads_without_delay(monkeypatch):
"""An HTTP proxy has no UDP at all: the engine refuses HTTP/3 behind it and the page falls to h2 by itself."""
import aioquic # noqa: F401 - the dev extra installs it: a missing one is a failure, never a skip
from _doh_servers import FakeDoh, relay
from _h3_server import H3Server
from _http_proxy import HttpProxy
class ProxyToTheServer(HttpProxy):
"""The HTTP proxy of the tests relays a CONNECT to a loopback address only; this one also relays the one to the server."""
target = None
def _connect(self, conn, host, port, authorization):
if (host, port) != self.target:
return super()._connect(conn, host, port, authorization)
upstream = socket.create_connection((host, port), timeout=10)
self._record("CONNECT", host, port, authorization, 200)
self._answer(conn, 200)
try:
relay(conn, upstream)
finally:
upstream.close()
host = this_host_address()
doh = FakeDoh({})
try:
with H3Server(host) as server:
proxy = ProxyToTheServer("http1", doh)
proxy.target = (host, server.port)
try:
protocols, walls = _visits("http_proxy", server, monkeypatch, lambda *_a, **_k: EXIT_DIRECT, proxy=proxy.proxy)
connects = [c for c in proxy.connects if c == (host, server.port)]
finally:
proxy.close()
said = _report("http_proxy", protocols, walls, server) + "; CONNECTs to the server: %d" % len(connects)
problems = judge_visits("http_proxy", protocols, walls)
assert not problems, "; ".join(problems) + ". " + said
assert not no_https_record(host, doh), no_https_record(host, doh)
assert connects, "the page did not go through the proxy. " + said
assert not server.quic_peers, "a QUIC connection reached the server direct, around the proxy: %s. %s" % (server.quic_peers, said)
finally:
doh.close()
@@ -0,0 +1,176 @@
"""E2E: the name of an ICE server is resolved in the USER CONTEXT of the page, so it goes by the proxy of that context.
The defect these tests hold: the ICE resolver of a PeerConnection (NrIceResolver) resolved the NAME in `iceServers`
with default OriginAttributes, so the DoH request of that lookup left in the default user context (user context 0) and
not in the context of the page. In the log of the engine the page's own lookups read `Resolving host
[page-a.test]<^userContextId=6...>` and the ICE one reads `Resolving host [stun-a.test]<>`. Two consequences a page
(or the other side of the wire) can see:
* the DoH request of the ICE name went by the proxy of the SESSION and not by the one of the context of the page, and
with `ignore_https_errors` a property of the context, the lookup of the default context cannot accept the DoH
certificate: it fails at once (TRR error, no DNS answer) and the STUN server is marked FAILED a millisecond later;
* so the gather of a page behind a gateway that does not relay UDP ended at once, without the ~11 s of nICEr's own
timer that a retail Firefox on a network that drops UDP shows (the 701 at 11.1-11.3 s, see
`test_a_proxy_that_does_not_relay_udp_gives_no_srflx_at_all` in test_webrtc_realness.py).
How each test sees it, with nothing but loopback (the tools are the ones of test_doh_through_the_proxy_e2e.py,
`_doh_servers.py`, `_http_proxy.py` and `_socks_servers.py`):
* the FakeDoh maps the ICE names to 198.51.100.5 (`STUN_NUMBER`, TEST-NET-2), NOT to loopback: the ICE code skips a
loopback STUN server, so a loopback answer would end the gather at once for a reason that has nothing to do with
the context;
* the gateway is a SOCKS5 one that is TCP only: `DohGateway` is a `Gateway` built with `udp="refuse"` (the option of
`_socks_servers.py`; `tcp_only()` is the same thing for the plain gateway), so UDP ASSOCIATE is answered with reply
code 7 and the page gets no srflx; or an HTTP proxy with credentials, which has no UDP at all;
* the FakeDoh cannot read the user context of a DoH request (the request does not carry it), so a test attributes a
question to a context by the GATEWAY it arrived by: the default context goes through the session proxy, each
context under test through a proxy of its own. A question for an ICE name that arrives by the session proxy would
be a question of the default context.
Every test is RED on an engine that resolves the ICE name with default OriginAttributes (the FakeDoh is never asked
the name: the lookup of the default context fails its TLS handshake with the FakeDoh BY DESIGN) and GREEN on one that
carries the attributes of the PeerConnection into the resolver. Two tests of test_doh_through_the_proxy_e2e.py turn
green with the same fix without change: `test_an_ice_server_name_resolves_the_same_way` and
`test_an_authenticated_http_proxy_resolves`.
"""
from __future__ import annotations
import pytest
# The fixtures and the helpers of the DoH e2e (imported, not copied): the hermetic session (autouse), the resolver
# trap, the watcher, the page server, the gateway factory, and the checks of the end-of-test accounting.
from test_doh_through_the_proxy_e2e import ( # noqa: F401 (the hermetic session is autouse and imported by name; the
# other fixtures of the DoH e2e are in conftest.py)
PREFS, ZONE, _assert_stayed_home, _create_a_peer_connection_for, _hermetic_session, _page_in, _why)
# The page-side probe of the realness test: one STUN server, the candidates, the ICE errors, the timeline in ms
# (`at_ms`: host/srflx/error/complete from the offer) and the end of the gather. Imported, not edited.
from test_webrtc_realness import _RELAY_PROBE_JS, candidates
import _doh_servers as ds
from _doh_servers import QTYPE_A, FakeDoh
from _http_proxy import HttpProxy, basic
from _socks_servers import STUN_NUMBER
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
#: The ICE names of the tests. Both resolve to a routable documentation address that only a relay could reach.
ICE_ZONE = {**ZONE, "stun-a.test": STUN_NUMBER, "stun-b.test": STUN_NUMBER}
STUN_A = "stun:stun-a.test:3478"
@pytest.fixture
def doh():
"""The FakeDoh with the ICE names pointing at STUN_NUMBER (overrides the one of the DoH e2e)."""
pytest.importorskip("h2", reason="Firefox's TRR speaks h2: the FakeDoh serves it with the h2 package")
server = FakeDoh(ICE_ZONE)
yield server
server.close()
@pytest.fixture
def tcp_only_proxy(doh, gateway, request):
"""A proxy without UDP, by kind: a SOCKS5 gateway whose UDP ASSOCIATE is refused, or an HTTP proxy with credentials."""
if request.param == "socks5":
# DohGateway is built with udp="refuse": the TCP-only option of _socks_servers.Gateway (reply code 7).
gw = gateway("gw1")
assert gw.udp == "refuse"
yield gw
return
proxy = HttpProxy("http1", doh, user="ferd_http_user", password="pw-é42")
try:
yield proxy
finally:
proxy.close()
def _launch(binary, proxy):
"""Like the DoH e2e's `_launch`, with the baseline's mDNS host candidates declared as the realness test does."""
from invisible_playwright import InvisiblePlaywright
return InvisiblePlaywright(seed=42, binary_path=binary, proxy=proxy, headless=True,
extra_prefs={**PREFS, "media.peerconnection.ice.obfuscate_host_addresses": True})
# ============================================================================================================ tests
@pytest.mark.parametrize("tcp_only_proxy", ["socks5", "http_with_credentials"], indirect=True,
ids=["socks5_tcp_only", "http_with_credentials"])
def test_a_gateway_without_udp_resolves_the_ice_name_then_ends_in_701(firefox_binary, doh, pages, tcp_only_proxy,
trap, watcher):
"""A page in a context with no proxy of its own (the proxy of the session is its proxy) gives `iceServers` a NAME.
The name is asked to the DoH THROUGH that proxy, in the context of the page (whose certificate override accepts the
FakeDoh), the answer is 198.51.100.5, the STUN request has no road (the proxy has no UDP) and the gather ends the
way a retail Firefox on a network that drops UDP ends: host UDP and TCP candidates, no srflx, ONE ICE error 701 at
nICEr's own time (10-13 s) together with the end of the gather. On an engine that resolves the name in the default
context the FakeDoh is never asked and the gather ends at once (the name is unresolved)."""
proxy = tcp_only_proxy
with _launch(firefox_binary, proxy.proxy) as browser:
context, page = _page_in(browser)
page.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
res = page.evaluate(_RELAY_PROBE_JS, STUN_A)
context.close()
watcher.stop()
why = _why(doh, proxy) + "\n page: candidates %s, ICE errors %s, timeline (ms from the offer) %s" % (
res["candidates"], res["errors"], res["at_ms"])
# 1. The name was asked, by the proxy of the context and by no other road.
ds.wait_until(lambda: doh.queries_for("stun-a.test", QTYPE_A), 3)
assert doh.queries_for("stun-a.test", QTYPE_A), (
"the DoH was never asked stun-a.test (A): the ICE resolver looked the name up in the default user context, whose "
"DoH request cannot accept the FakeDoh certificate" + why)
assert doh.vias_of("stun-a.test", QTYPE_A) == {proxy.name}, (
"stun-a.test (A) was not asked by the proxy of the context only" + why)
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy" + why
assert proxy.doh_connects(), "the proxy carried no DoH CONNECT" + why
if isinstance(proxy, HttpProxy):
expected = basic("ferd_http_user", "pw-é42")
assert set(proxy.doh_authorizations()) == {expected}, (
"every DoH CONNECT must carry the preemptive Basic header" + why)
assert [s for s in proxy.refused_for_credentials if (s.host, s.port) in ds.DOH_TARGETS] == [], (
"the DoH CONNECT needed a 407 round trip: the header was not preemptive" + why)
# 2. The end of the gather, as a retail Firefox with UDP blocked.
cands = candidates(res["candidates"])
typ = [c["typ"] for c in cands]
assert "srflx" not in typ and "relay" not in typ, "a candidate that nothing allocated" + why
assert [e["code"] for e in res["errors"]] == [701], "the STUN request must end in ONE ICE error 701" + why
protocols = sorted({c["proto"].upper() for c in cands if c["typ"] == "host"})
assert protocols == ["TCP", "UDP"], "host candidates of a retail with UDP blocked: UDP and TCP" + why
assert 10_000 <= res["at_ms"]["error"] <= 13_000, (
"the 701 came at %s ms; nICEr's time on a network that drops UDP is 11.1-11.3 s (an immediate error means the "
"name was never resolved)" % res["at_ms"]["error"] + why)
assert "complete" in res["at_ms"], "the gather did not end by itself" + why
_assert_stayed_home(watcher, trap, doh, proxy)
def test_the_ice_name_of_a_context_goes_by_the_proxy_of_that_context(firefox_binary, doh, pages, gateway, trap,
watcher):
"""The session proxy is gw0; the context 1 has gw1, the context 2 has gw2. The page of each context asks for the
name of its own (stun-a.test, stun-b.test) and each name is asked at the gateway of ITS context only. No question
for an ICE name leaves in the default context: the FakeDoh cannot read the user context of a request, so the
default context is told by its road, the session proxy gw0, which must have carried no question for either name."""
gw0, gw1, gw2 = gateway("gw0"), gateway("gw1"), gateway("gw2")
with _launch(firefox_binary, gw0.proxy) as browser:
context_1, page_1 = _page_in(browser, proxy=gw1.proxy)
context_2, page_2 = _page_in(browser, proxy=gw2.proxy)
page_1.goto(pages.url("page-a.test"), wait_until="load", timeout=30000)
page_2.goto(pages.url("page-b.test"), wait_until="load", timeout=30000)
_create_a_peer_connection_for(page_1, "stun-a.test")
_create_a_peer_connection_for(page_2, "stun-b.test")
asked_a = ds.wait_until(lambda: doh.queries_for("stun-a.test", QTYPE_A), 30)
asked_b = ds.wait_until(lambda: doh.queries_for("stun-b.test", QTYPE_A), 30)
for page in (page_1, page_2):
page.evaluate("() => window.__pc.close()")
context_1.close()
context_2.close()
watcher.stop()
why = _why(doh, gw0, gw1, gw2)
assert asked_a, "the DoH was never asked stun-a.test (the lookup left in the default context)" + why
assert asked_b, "the DoH was never asked stun-b.test (the lookup left in the default context)" + why
assert doh.vias_of("stun-a.test", QTYPE_A) == {"gw1"}, "stun-a.test must be asked by gw1 (context 1) only" + why
assert doh.vias_of("stun-b.test", QTYPE_A) == {"gw2"}, "stun-b.test must be asked by gw2 (context 2) only" + why
on_the_session_proxy = [q for q in doh.queries if q.via == "gw0" and q.name in ("stun-a.test", "stun-b.test")]
assert on_the_session_proxy == [], (
"a question for an ICE name left in the default context (by the session proxy gw0): %s" % on_the_session_proxy
+ why)
assert gw1.doh_connects() and gw2.doh_connects(), "each context's proxy must have carried a DoH CONNECT" + why
_assert_stayed_home(watcher, trap, doh, gw0, gw1, gw2)
+49 -15
View File
@@ -113,23 +113,57 @@ def test_the_posix_pipe_carries_messages_both_ways(firefox_binary, served, first
pass
# A parent whose descriptor table has nothing on 3 and 4 and whose pipes land far from them launches a program that reads fd 3 and
# answers on fd 4, the contract of the engine (`nsRemoteDebuggingPipe.cpp` hard-wires the two numbers), and says what else it holds.
_SPAWN_PARENT = """
import fcntl, os, sys
from invisible_core.juggler import connection
for fd in range(3, 64):
try:
os.close(fd)
except OSError:
pass
real_pipe = os.pipe
def far_pipe():
r, w = real_pipe()
r2, w2 = fcntl.fcntl(r, fcntl.F_DUPFD, 20), fcntl.fcntl(w, fcntl.F_DUPFD, 20)
os.close(r)
os.close(w)
return r2, w2
os.pipe = far_pipe
engine = ("import os; d = os.read(3, 16); "
"extra = [fd for fd in range(5, 40) if os.path.exists('/proc/self/fd/%d' % fd) or os.path.exists('/dev/fd/%d' % fd)]; "
"os.write(4, b'pong:' + d + b':' + str(len(extra)).encode())")
our_write, our_read, process = connection._spawn_posix(sys.executable, ["-c", engine], dict(os.environ))
os.write(our_write, b"ping")
sys.stdout.write(os.read(our_read, 64).decode())
process.wait(timeout=10)
"""
@pytest.mark.unit
def test_the_spawn_keeps_the_two_hardwired_descriptors():
"""The keep list must name 3 and 4, and this is a check on the CODE.
"""What the launch must do, executed: the child it starts finds the pipe on descriptors 3 (it reads) and 4 (it writes), and no
descriptor of the parent above them.
⛔ Written as a source assertion on purpose. The behavioural test above
needs a Linux Firefox; this one needs nothing, so the day somebody
"simplifies" the keep list back to the two pipe ends the failure arrives on
every POSIX machine in the unit suite rather than on the one person who has
a Linux build.
⛔ THIS ASSERTED THE TEXT OF THE CORE'S SOURCE and broke the day the core launched with `posix_spawn` and file actions instead of
`pass_fds=(its_read, its_write, 3, 4)`: the behaviour did not change, the words did. It needs no Linux Firefox: the "engine" is a
program that reads fd 3 and answers on fd 4, exactly the contract of `nsRemoteDebuggingPipe.cpp`. The day somebody changes the
launch so that the browser starts with nothing on 4 (a live process whose first write gets EPIPE), this fails on every POSIX
machine of the unit suite rather than on the one person who has a Linux build.
"""
import inspect
import subprocess
import sys
from invisible_core.juggler import connection as conn
source = inspect.getsource(conn._spawn_posix)
assert "pass_fds=(its_read, its_write, 3, 4)" in source, (
"the spawn no longer keeps descriptors 3 and 4. CPython's close sweep "
"runs AFTER preexec_fn, so the dup2'd descriptors are closed again "
"before exec and the browser starts with nothing on 4 - a live process "
"whose first write gets EPIPE.")
done = subprocess.run([sys.executable, "-c", _SPAWN_PARENT], capture_output=True, text=True, timeout=60)
assert done.returncode == 0, ("the launch failed: %s" % (done.stderr.strip().splitlines()[-1:],))
assert done.stdout.startswith("pong:ping:"), (
"the child did not find the pipe on descriptors 3 and 4: it read nothing on 3 or its answer on 4 never came (%r)"
% done.stdout)
assert done.stdout.rsplit(":", 1)[-1] == "0", (
"the child holds descriptors above 4 that the parent opened: " + done.stdout)
+1 -1
View File
@@ -168,7 +168,7 @@ def no_geo_lookup(monkeypatch):
# Before, `resolve_session_locale` was a separate network call imported
# inside __enter__, and stubbing only the geo left these tests at 34 s.
monkeypatch.setattr("invisible_playwright.launcher.prepare_session_geo",
lambda tz, proxy, locale: SessionGeo(
lambda tz, proxy, locale, **_kw: SessionGeo(
"America/New_York", "198.51.100.4",
locale=decide_session_locale("en-US")))
# And the lifetime guard. `bind` waits for the browser tree to APPEAR -
@@ -18,7 +18,8 @@ import pytest
from _servers import LocalServer
pytestmark = pytest.mark.e2e
# Bound to the engine that carries the UDP line: red on firefox-61/62 (the engine fix is in the 63): skips on the published engine; runs on the candidate.
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
def _stock_client(module):
+12 -1
View File
@@ -230,13 +230,24 @@ class _Page:
"""The `PageDispatcher` seen from the numbering: what it was given."""
def __init__(self, server, context, session, target_id, number,
opener=None):
opener=None, is_gone=None):
self.target_id = target_id
self.number = number
self.opener = opener
self.popups_opened = 0
self.channel = {"guid": "page-" + target_id}
gone_while_building = False
def wait_until_ready(self, timeout=20.0):
pass # the engine of this test says Page.ready at once
def settle_events(self):
pass
def announce(self, context, replay):
context.emit("page", {"page": self.channel})
def announce_closed(self):
pass
+171
View File
@@ -0,0 +1,171 @@
"""What a popup does depends on what its destination answers; the client must see what stock Firefox makes it see.
Reference: Playwright 1.62 with its own Firefox, measured (a `window.open(url)` from a click, and a clicked
`<a target=_blank>`, destination on the opener's site, two repetitions each, 30 s observed unless said; the destination on
another site gave the same):
* 204 No Content: NO `page` event at all (observed for 30 s). The popup is never announced.
* a destination that never answers: NO `page` event (observed for 30 s).
* a destination that answers a normal HTML page after N seconds: the `page` event arrives when the answer comes, N s after
the click, with the destination as its url, and the load follows at once. There is no ceiling: with N = 25 the event
came at about 25 s (checked by hand, the 25 s case is not run here; this file uses 4 s).
* `Content-Disposition: attachment`: the `page` event arrives at once (url empty), a `download` event arrives on the
OPENER (not on the popup) and the popup closes within about 10 ms.
Why it matters here: the page dispatcher announces a popup when the engine says it is ready (`Page.ready`), and gives up on
one that never does after 20 s. A destination that answers late must still be announced when it answers, one that never
becomes a page must not be announced, and a download started by a popup must reach the client on the opener like on stock.
The waits for "no event" are bounded to 8 s here (stock was observed for 30 s).
Transports: the client of this wheel in the same process, and the stock Playwright client over `launch_server`.
"""
from __future__ import annotations
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
pytestmark = pytest.mark.e2e
SLOW_SECONDS = 4
NO_EVENT_SECONDS = 8
class _Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *args):
pass
def _send(self, code, ctype, body=b"", extra=()):
self.send_response(code)
if ctype:
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
for key, value in extra:
self.send_header(key, value)
self.end_headers()
self.wfile.write(body)
def do_GET(self):
port = self.server.server_address[1]
try:
if self.path.startswith("/main"):
body = ""
for d in "1234":
url = "http://127.0.0.1:%d/d%s" % (port, d)
body += ("<a id=link%s target=_blank href='%s'>a</a> "
"<button id=open%s onclick=\"window.open('%s')\">w</button><br>") % (d, url, d, url)
self._send(200, "text/html", ("<!doctype html><title>opener</title>" + body).encode())
elif self.path.startswith("/d1"):
self.send_response(204)
self.send_header("Content-Length", "0")
self.end_headers()
elif self.path.startswith("/d2"):
time.sleep(SLOW_SECONDS)
self._send(200, "text/html", b"<!doctype html><title>slow</title><p>slow page</p>")
elif self.path.startswith("/d3"):
time.sleep(NO_EVENT_SECONDS + 6) # longer than any wait of a test: it never answers in time
self._send(200, "text/html", b"<!doctype html><title>late</title>")
elif self.path.startswith("/d4"):
self._send(200, "text/plain", b"hello attachment\n",
[("Content-Disposition", 'attachment; filename="a.txt"')])
else:
self._send(404, "text/plain", b"not found")
except (ConnectionError, TimeoutError, OSError):
self.close_connection = True
class _Server(ThreadingHTTPServer):
daemon_threads = True
@pytest.fixture(scope="module")
def site():
srv = _Server(("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()
class _Run:
"""One popup attempt: the opener page, what the context announced, what the opener downloaded."""
def __init__(self, launched, port, how, dest):
self.context = launched.new_context(accept_downloads=True)
self.opener = self.context.new_page()
self.popups, self.downloads, self.arrived_at = [], [], None
self.context.on("page", self._on_page)
self.opener.on("download", lambda download: self.downloads.append(download))
self.opener.goto("http://127.0.0.1:%d/main" % port)
self.clicked = time.time()
self.opener.click("#%s%s" % (how, dest))
def _on_page(self, page):
self.popups.append(page)
self.arrived_at = time.time() - self.clicked
def wait_until(self, predicate, seconds):
end = time.time() + seconds
while time.time() < end and not predicate():
self.opener.wait_for_timeout(100) # the sync client reads the engine's events inside its calls
return predicate()
def close(self):
try:
self.context.close()
except Exception:
pass
@pytest.mark.parametrize("how", ["open", "link"])
def test_a_popup_to_a_204_is_never_announced(browser, site, how):
run = _Run(browser, site, how, "1")
try:
assert not run.wait_until(lambda: run.popups, NO_EVENT_SECONDS), \
"a 204 destination was announced as a page after %.1fs (stock gives no page event)" % run.arrived_at
assert len(run.context.pages) == 1
finally:
run.close()
@pytest.mark.parametrize("how", ["open", "link"])
def test_a_popup_to_a_server_that_never_answers_is_never_announced(browser, site, how):
run = _Run(browser, site, how, "3")
try:
assert not run.wait_until(lambda: run.popups, NO_EVENT_SECONDS), \
"an unanswered destination was announced as a page after %.1fs (stock gives no page event)" % run.arrived_at
assert len(run.context.pages) == 1
finally:
run.close()
@pytest.mark.parametrize("how", ["open", "link"])
def test_a_popup_to_a_slow_page_is_announced_when_it_answers(browser, site, how):
run = _Run(browser, site, how, "2")
try:
assert run.wait_until(lambda: run.popups, SLOW_SECONDS + 6), "the slow popup never arrived"
assert run.arrived_at >= SLOW_SECONDS - 0.5, "announced after %.1fs, before the page answered" % run.arrived_at
popup = run.popups[0]
popup.wait_for_load_state("load", timeout=10000)
assert popup.url == "http://127.0.0.1:%d/d2" % site
assert popup.evaluate("document.title") == "slow"
assert len(run.context.pages) == 2
finally:
run.close()
@pytest.mark.parametrize("how", ["open", "link"])
def test_a_popup_to_an_attachment_reports_the_download_on_the_opener_and_closes(browser, site, how):
run = _Run(browser, site, how, "4")
try:
assert run.wait_until(lambda: run.downloads, 10), "no `download` event on the opener (stock gives one)"
assert run.downloads[0].suggested_filename == "a.txt"
assert run.popups, "stock announces the popup (its url is empty) before it closes"
assert run.wait_until(lambda: run.popups[0].is_closed(), 10), "the popup of a download stays open"
assert len(run.context.pages) == 1
finally:
run.close()
+239
View File
@@ -0,0 +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. 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)))
@@ -0,0 +1,56 @@
"""``preload_newtab`` of InvisiblePlaywright: the option travels to the core only when the caller asked.
A wrapper that always handed the kwarg to the core would raise TypeError on a pairing with a core that does not know it, for a caller who
never used it. ``None`` (default) hands over nothing; ``False`` / ``True`` arrive as given; the async class and ``launch_server`` carry it too.
"""
import inspect
import pytest
from invisible_playwright import InvisiblePlaywright
pytestmark = pytest.mark.unit
KEY = "browser.newtab.preload"
def _built(**kw):
from invisible_core import decide_session_locale
session = InvisiblePlaywright(seed=7, binary_path="firefox", **kw)
session._timezone, session._locale = "Asia/Tokyo", decide_session_locale("en-US")
return session._build_prefs()
def test_by_default_the_wrapper_asks_the_core_nothing_about_it(monkeypatch):
from invisible_playwright import _session
seen = {}
real = _session.compose_session_prefs
def spy(profile, **kw):
seen.update(kw)
kw.pop("preload_newtab", None) # a core that does not know the option
return real(profile, **kw)
monkeypatch.setattr(_session, "compose_session_prefs", spy)
prefs = _built()
assert "preload_newtab" not in seen
assert KEY not in prefs
def test_asked_to_turn_it_off_the_pref_is_false():
pytest.importorskip("invisible_core")
from invisible_core import prefs as core_prefs
if "preload_newtab" not in inspect.signature(core_prefs.compose_session_prefs).parameters:
pytest.skip("this core does not know preload_newtab yet")
assert _built(preload_newtab=False)[KEY] is False
assert _built(preload_newtab=True)[KEY] is True
def test_the_option_is_a_parameter_of_every_entry_point():
from invisible_playwright import async_api
from invisible_playwright._juggler import remote
for fn in (InvisiblePlaywright.__init__, async_api.InvisiblePlaywright.__init__, remote.launch_server):
assert "preload_newtab" in inspect.signature(fn).parameters, fn
@@ -0,0 +1,54 @@
"""``preload_newtab=False`` leaves no privileged-about process; without the option the preloaded New Tab page has one.
A retail Firefox keeps a New Tab page preloaded in a process of its own (remote type ``privilegedabout``, about 200 MB). The core writes nothing
by default, so the session has it; ``preload_newtab=False`` declares ``browser.newtab.preload`` false and the process is not born (measured on the
candidate engine, three runs of three). The processes are read from the engine's own log, which names the type of every process it creates
(``Setting remoteType of process <pid> to <type>``): it needs ``MOZ_LOG=Process:5,timestamp,sync`` and a file base before the launch, and it holds
on every platform. The assertion is on ``privilegedabout`` only: a Mozilla site's process beside it depends on the country of the machine.
"""
import inspect
import re
import time
import pytest
TYPE = re.compile(r"Setting remoteType of process (\d+) to (\S+)")
def _remote_types(tmp_path, binary, **option):
from invisible_playwright import InvisiblePlaywright
mp = pytest.MonkeyPatch()
base = tmp_path / ("proc-%s" % ("-".join("%s-%s" % kv for kv in sorted(option.items())) or "default"))
mp.setenv("MOZ_LOG", "Process:5,timestamp,sync")
mp.setenv("MOZ_LOG_FILE", str(base))
try:
with InvisiblePlaywright(seed=7, binary_path=binary, headless=True, humanize=False, locale="en-US",
timezone="America/New_York", **option) as browser:
page = browser.new_context().new_page()
page.goto("about:blank")
time.sleep(10)
finally:
mp.undo()
types = []
for path in sorted(tmp_path.glob(base.name + "*")):
types += [m.group(2) for m in TYPE.finditer(path.read_text(encoding="utf-8", errors="replace"))]
return types
@pytest.mark.e2e
def test_without_the_option_the_new_tab_page_is_preloaded_in_its_own_process(firefox_binary, tmp_path):
types = _remote_types(tmp_path, firefox_binary)
assert types, "the engine wrote no line about its processes: the control cannot judge"
assert "privilegedabout" in types, "the retail keeps the New Tab page preloaded: %s" % sorted(set(types))
@pytest.mark.e2e
def test_asked_to_turn_the_preload_off_there_is_no_privileged_about_process(firefox_binary, tmp_path):
from invisible_core import prefs as core_prefs
if "preload_newtab" not in inspect.signature(core_prefs.compose_session_prefs).parameters:
pytest.skip("this core does not know preload_newtab yet")
types = _remote_types(tmp_path, firefox_binary, preload_newtab=False)
assert types, "the engine wrote no line about its processes: the control cannot judge"
assert "privilegedabout" not in types, "a process of the preloaded New Tab page was born: %s" % sorted(set(types))
@@ -0,0 +1,274 @@
"""E2E: behind a gateway that DECLARES its exit, every value a page can read says that exit and nothing says this machine.
This replaces a check that was made by hand through a paid proxy against pages on the internet. No test here needs a real proxy
or a site on the internet: the proxy is a local SOCKS5 gateway (``ExitGateway``, a ``coherent`` UDP road) that answers "what is my
address" with the exit it declares, the names of the pages are resolved by a FakeDoh through that gateway, and the pages are a
local site that reads the same values a page on the internet reads. The truth for the zone and the country of an exit is the
core's own offline geo database (``ip_to_timezone`` and ``ip_to_country``, asked at test time), not a second service: the tests
ask whether the pages say what the path ``prepare_session_geo`` takes says, for six exits in six countries. The session geo is
NOT stubbed: the only replaced step is the HTTPS question "what is my address" (``egress_by_proxy``), which no local gateway can
answer as itself; the zone, the language and the srflx are decided by the core from that answer.
One launch per exit (``observed``, six of them) is read by the tests below; each test judges one thing:
* the address a site sees, and that nothing reached the site, or the network, past the gateway;
* WebRTC: the candidates and the SDP carry nothing of this machine;
* DNS: the names of the pages reach the gateway (as DoH) and are not asked of the system resolver;
* the time zone of the page, of its offsets read two ways, and of a worker;
* the language of the page, of a worker and of the Accept-Language the site receives, and that it fits the exit's country;
* a vendored detection page, served locally and loaded behind the gateway.
The four states of the gateway (coherent, TCP only, mismatched, silent) are tested by ``test_webrtc_realness.py``; here only the
"nothing of the host" part of a coherent gather is added.
Hermetic on a real binary; the resolver trap runs where it can (Linux, root; ``INVPW_REQUIRE_TRAP=1`` makes a trap that cannot
run a failure, as in the DoH suite), and the other assertions do not depend on it. On Windows the trap does not exist, and the
Watcher still sees a connection to a DNS port.
"""
from __future__ import annotations
import ipaddress
from pathlib import Path
import pytest
from invisible_playwright import InvisiblePlaywright
import _realness_support as rs
import _trap_policy
from _doh_servers import DOH_PROVIDER_PREFS, QTYPE_A, FakeDoh
from _host_address import this_host_address
from _leaks import ResolverTrap, Watcher
from _socks_servers import STUN_NUMBER, STUN_PORT
from _udp_line import egress_by_proxy, measure_servers
from test_detectors_e2e import _DetectorSite
from test_webrtc_realness import _RELAY_PROBE_JS
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
#: Loopback goes through the gateway too (the site is on loopback), and the DoH provider is the FakeDoh's (a preloaded host's
#: certificate cannot be overridden): the same two things the DoH suite declares.
PREFS = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": "", **DOH_PROVIDER_PREFS,
"media.peerconnection.ice.obfuscate_host_addresses": True}
STUN = "stun:%s:%d" % (STUN_NUMBER, STUN_PORT)
def _start_trap():
"""The resolver trap, or None where it cannot run and the gate does not require it (see the ``trap`` fixture)."""
if not ResolverTrap.available:
why = _trap_policy.failure(None, False, ResolverTrap.reason)
if why:
pytest.fail(why)
return None
trap = ResolverTrap()
try:
trap.__enter__()
except OSError as exc:
why = _trap_policy.failure(None, True, bind_error=exc)
if why:
pytest.fail(why)
return None
return trap
def _truth_of(exit_ip):
"""The zone and the country the core's geo database gives the exit: the truth of these tests."""
from invisible_core._geo import ip_to_country, ip_to_timezone
from invisible_core.download import ensure_geoip_mmdb
database = ensure_geoip_mmdb()
return ip_to_timezone(exit_ip, database), ip_to_country(exit_ip, database)
def _launch(binary, gateway, **extra):
return InvisiblePlaywright(seed=42, headless=True, binary_path=binary, proxy=gateway.proxy,
udp_stun_servers=measure_servers(gateway), extra_prefs=dict(PREFS), **extra)
@pytest.fixture(scope="module", params=list(rs.EXITS), ids=list(rs.EXITS))
def observed(request, firefox_binary):
"""One launch behind the exit ``request.param``, read once: the plain data of everything it showed (the browser and the
servers are closed before this returns)."""
from invisible_core import _geo
label = request.param
exit_ip = rs.EXITS[label]
zone, country = _truth_of(exit_ip)
relay_host = this_host_address() # before any server: a host with no route skips with nothing left listening
seen = rs.Observation(label=label, exit_ip=exit_ip, zone=zone, country=country, host=rs.host_addresses() | {relay_host})
patch = pytest.MonkeyPatch()
doh = FakeDoh(rs.ZONE_NAMES)
gateway = rs.ExitGateway("exit", doh, udp="relay", tcp_exit=exit_ip, udp_exit=exit_ip, relay_host=relay_host)
site = rs.Site(gateway)
trap = None
watcher = Watcher(match=("firefox", Path(firefox_binary).stem.lower()))
try:
patch.setattr(_geo, "discover_egress_ip", egress_by_proxy(gateway))
trap = _start_trap()
watcher.start()
with _launch(firefox_binary, gateway) as browser:
context = browser.new_context(ignore_https_errors=True)
page = context.new_page()
page.goto(site.url(), wait_until="load", timeout=60000)
result = page.evaluate(rs.PAGE_JS)
seen.probe = page.evaluate(_RELAY_PROBE_JS, STUN)
context.close()
watcher.stop()
seen.ip_seen, seen.reads = result["ip"], {"page": result["page"], "worker": result["worker"]}
seen.arrivals = list(site.arrivals)
seen.headers = site.headers_of("/", "/fetch", "/worker-fetch")
seen.connects, seen.site_port = list(gateway.connects), site.port
# The relay of the gateway is on this host's address (the ICE sockets cannot send to loopback on Windows): the UDP
# that goes to it is the road, not a leak.
seen.direct = [c.remote for c in watcher.direct if not (c.protocol == "udp" and c.remote.rsplit(":", 1)[0] == relay_host)]
seen.watched = len(watcher.watched_pids)
seen.doh_vias = {name: set(doh.vias_of(name, QTYPE_A)) for name in rs.ZONE_NAMES}
seen.doh_connects = list(gateway.doh_connects())
seen.gateway_name = gateway.name
seen.trap_ran = trap is not None
seen.trap_queries = [q.name for q in trap.queries] if trap is not None else []
seen.datagrams = [(h, p) for h, p, _payload in gateway.datagrams]
finally:
watcher.stop()
if trap is not None:
trap.__exit__(None, None, None)
patch.undo()
site.close()
gateway.close()
doh.close()
return seen
# ============================================================================================================ the tests
def test_a_site_sees_the_declared_exit_and_nothing_reaches_it_past_the_gateway(observed):
"""1. A page asks a local "what is my address" endpoint, through the gateway, and is told the exit the gateway declares.
The site tells a connection the gateway opened from one it did not (``ExitGateway.upstream_ports``): any request on the
second kind is a direct connection. The watcher, which samples the connections of every browser process from before the
launch, sees none to a non-loopback address either (other than the gateway's own UDP relay)."""
assert observed.watched, "the watcher never saw a browser process: it proves nothing"
problems = rs.ip_problems(observed.ip_seen, observed.arrivals, observed.direct, observed.exit_ip, observed.connects,
observed.site_port)
assert problems == [], "exit %s (%s): %s" % (observed.exit_ip, observed.label, problems)
def test_a_coherent_gather_shows_nothing_of_this_machine(observed):
"""2. The candidates and the SDP of a gather behind a coherent gateway: host candidates are mDNS names, there is no IPv6
candidate behind an IPv4 exit, the server-reflexive candidate (if one is born) is the exit, and neither the SDP nor the
candidates write a private address, a loopback one, or any address of this machine's interfaces."""
problems = rs.webrtc_problems(observed.probe, observed.exit_ip, observed.host)
assert problems == [], "exit %s (%s): %s; candidates: %s; sdp: %r" % (
observed.exit_ip, observed.label, problems, observed.probe.get("candidates"), observed.probe.get("sdp"))
def test_the_names_of_the_pages_reach_the_gateway_and_not_the_system_resolver(observed):
"""3. The page was reached by a NAME. The browser asked the FakeDoh for it, through the gateway (a DoH CONNECT), connected
to the answer by ADDRESS (no CONNECT carries the name), and asked the resolver of the machine nothing: the trap, where it
can run, counted no question; where it cannot, no connection to port 53 was seen by the watcher."""
assert observed.doh_vias[rs.SITE_NAME] == {observed.gateway_name}, (
"%s was asked of the DoH by %s, not by the gateway only" % (rs.SITE_NAME, observed.doh_vias[rs.SITE_NAME]))
assert observed.doh_connects, "no DoH CONNECT reached the gateway"
assert [h for h, _p in observed.connects if h.lower() in rs.ZONE_NAMES] == [], (
"a CONNECT carried the NAME of a page instead of its address: %s" % observed.connects)
assert [c for c in observed.direct if c.endswith(":53")] == [], "a connection to a DNS port: %s" % observed.direct
assert [q for q in observed.trap_queries if q.endswith(".test")] == [], (
"the browser asked the resolver of the machine for %s" % observed.trap_queries)
if observed.trap_ran:
assert observed.trap_queries == [], "the browser asked the resolver of the machine: %s" % observed.trap_queries
def test_the_timezone_of_the_page_its_offsets_and_its_worker_are_the_exits(observed):
"""4. ``Intl.DateTimeFormat().resolvedOptions().timeZone``, the UTC offset computed two ways in the page (the clock of the
page, ``getTimezoneOffset``, and the wall clock ``Intl`` prints for the zone the page names) at a northern-winter and a
northern-summer instant, and the same reads inside a dedicated Worker, all equal the zone of the exit. The zone expected is
what the core's own geo database gives the declared exit (``ip_to_timezone``): the truth here is the core's database, not a
second service. The offsets expected come from the system tz database (``zoneinfo``)."""
problems = rs.timezone_problems(observed.reads, observed.zone)
assert problems == [], "exit %s (%s, %s): %s" % (observed.exit_ip, observed.label, observed.zone, problems)
def test_the_language_of_the_page_its_worker_and_the_header_agree_and_fit_the_country(observed):
"""5. ``navigator.language``, ``navigator.languages``, the ``Intl`` locale, the same inside a Worker, and the
``Accept-Language`` the site receives (of the navigation, of a fetch and of the fetch of a worker) agree with each other,
and the primary language is plausible for the country of the exit (a table of this suite, ``PLAUSIBLE_PRIMARY``; a country
that is not in it is checked for agreement only)."""
problems = rs.language_problems(observed.reads, observed.headers, observed.country)
assert problems == [], "exit %s (%s, %s): %s" % (observed.exit_ip, observed.label, observed.country, problems)
# ------------------------------------------------------------------------------------- the vendored detection page
#: What the vendored detection page reads, in the page itself: the outcome fields only (the lies, the flags of a headless
#: browser, and the three "lied" fields of the zone, the Intl and the worker).
_DETECTION_JS = """() => {
const f = window.Fingerprint;
if (!f || !f.headless) return {ready: false};
const on = (o) => Object.entries(o || {}).filter(([, v]) => v === true).map(([k]) => k).sort();
return {
ready: true,
lies: (f.lies && f.lies.totalLies) || 0,
headless: on(f.headless.headless),
zone: f.timezone ? {location: f.timezone.location, lied: !!f.timezone.lied} : null,
intl: f.intl ? {lied: !!f.intl.lied} : null,
worker: f.workerScope ? {lied: !!f.workerScope.lied} : null,
};
}"""
def _detection_page_of(site):
"""The URL of the vendored detection page of the local site of ``test_detectors_e2e.py``: the one of its URL properties that
is not the root (the root serves three other libraries; this page is the one that reports lies and headless flags)."""
own = [name for name, value in vars(type(site)).items() if isinstance(value, property) and name.endswith("_url")]
assert len(own) == 1, own
return getattr(site, own[0])
def test_the_vendored_detection_page_finds_nothing_behind_the_gateway(firefox_binary, monkeypatch):
"""6. The vendored detection page, served locally, loaded behind the gateway: no lies, no flag of a headless browser, and
none of the zone, the Intl or the worker reads marked as lied; and the zone the page reads is the exit's.
Stock Playwright Firefox 1.62 (its own Firefox, no proxy, the same page, observed once on the machine this was written on)
shows ZERO lies and ZERO lied fields, and ONE headless flag: ``webDriverIsOn``, because stock runs with ``navigator.webdriver``
true. That flag is the automation itself and not a reading the browser should share, so the assertion here stays zero for
the headless flags; for the lies and the lied fields stock's outcome is zero too, so they are asserted zero. The page's
worker-scope key was absent from stock's fingerprint, so it is asserted only when the page produces it."""
from invisible_core import _geo
exit_ip = rs.EXITS["germany"]
expected_zone, _country = _truth_of(exit_ip)
doh = FakeDoh(rs.ZONE_NAMES)
site = _DetectorSite()
gateway = rs.ExitGateway("exit", doh, udp="relay", tcp_exit=exit_ip, udp_exit=exit_ip, relay_host=this_host_address())
try:
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(gateway))
with _launch(firefox_binary, gateway) as browser:
context = browser.new_context(ignore_https_errors=True)
page = context.new_page()
page.goto(_detection_page_of(site), wait_until="domcontentloaded", timeout=60000)
page.wait_for_function("() => !!(window.Fingerprint && window.Fingerprint.headless)", timeout=90000)
outcome = page.evaluate(_DETECTION_JS)
context.close()
reached = ("127.0.0.1", site.port) in gateway.connects
finally:
site.close()
gateway.close()
doh.close()
print("[detection page behind %s] %r" % (exit_ip, outcome))
assert outcome["ready"], "the detection page never produced its fingerprint: %r" % outcome
assert reached, "the detection page was not loaded through the gateway: %s" % gateway.connects
assert outcome["lies"] == 0, "the detection page found %d lie(s): %r" % (outcome["lies"], outcome)
assert outcome["headless"] == [], "the detection page raised headless flags: %r" % outcome
lied = {k: v for k, v in (("zone", outcome["zone"]), ("intl", outcome["intl"]), ("worker", outcome["worker"]))
if v and v.get("lied")}
assert not lied, "the detection page marked as lied: %r" % lied
assert outcome["zone"] is not None, "the detection page read no zone: %r" % outcome
read = outcome["zone"]["location"].replace(", ", "/").replace(" ", "_")
assert read in rs.acceptable_zones(expected_zone) or read == expected_zone, (
"the detection page reads the zone %r, the exit's is %s" % (outcome["zone"]["location"], expected_zone))
def test_the_exits_are_distinct_places():
"""The six exits are six different zones (a test of the table, with no browser: it asks the database only), so a page that
ignored the exit and kept one zone could not pass them all."""
zones = {label: _truth_of(ip)[0] for label, ip in rs.EXITS.items()}
assert len(set(zones.values())) == len(zones), zones
for ip in rs.EXITS.values():
assert ipaddress.ip_address(ip).is_global, ip
+202
View File
@@ -0,0 +1,202 @@
"""E2E: the first navigation of a fresh context never asks the system resolver, whatever the situation of the context.
The rule (owner decision B): each browser context is a whole situation. A context WITH a proxy (its own, or the launch
proxy that every context without a proxy of its own inherits) resolves its names ONLY by DoH, through that proxy,
fail-closed; a context WITHOUT a proxy resolves natively and never uses the DoH. The resolver hook of the engine chooses
per lookup by the user context of the lookup, from the contexts that Juggler publishes as proxied in a pref.
The race this file is about: the proxy of a context is declared by the wrapper AFTER `Browser.createBrowserContext` and the
first lookup of its first page can be made at once. If the engine does not know yet that the context is proxied, the first
lookup takes the native road: the system resolver is asked for a name of a proxied context (a leak of the name, and on a
real network the page does not even load). Every case here therefore creates the context and navigates IMMEDIATELY: no
wait, no warm-up, no earlier page in the same context. The names are known only to the FakeDoh (`race-<n>.test` are on no
zone of the machine and the gateway never resolves a name), so a native lookup ends in NS_ERROR_UNKNOWN_HOST and a page
that loads proves that the DoH, through the gateway of its context, resolved the name.
Three situations (the parameter):
* `context_proxy`: no launch proxy; 8 contexts created back-to-back, each with a gateway of its own and a distinct name,
each navigated at once and closed. Every page loads, every name is asked only by the gateway of its context, none is
ever asked `direct`, nothing reaches the DoH by a direct connection, and no DoH query or failed handshake belongs to the
default context (which has no proxy and resolves natively);
* `browser_proxy`: a launch proxy and contexts WITHOUT a proxy of their own, navigated at once: they use the launch proxy
(the DoH through it), as does the default context, so here nothing at all may go direct or ask the system resolver;
* `context_without_proxy_beside_a_proxied_one`: no launch proxy, a proxied context A and a context B without a proxy.
A name is not hermetic for B (the names the system resolver knows are the host's), so B navigates by ADDRESS
(`http://127.0.0.1:<port>/`, which needs no name) before and after A has used the DoH, and the test shows that B never
borrowed the proxy of A (its server is not in A's gateway log) and never shows up at the FakeDoh (the only queries are
A's names, by A's gateway).
Where the resolver trap runs (Linux, root) it adds the direct proof: it is never asked for a name of the proxied contexts.
On Windows the native question cannot be observed without a resolver trap, so there the proof is the one above: the page of
a name known only to the DoH loads, and the DoH log and the gateways account for every name.
Fixtures, FakeDoh, gateway, watcher, trap and the accounting of the end of a test are those of
`test_doh_through_the_proxy_e2e.py` (imported, not copied).
"""
from __future__ import annotations
import pytest
from test_doh_through_the_proxy_e2e import ( # noqa: F401 (the hermetic session is autouse and imported by name; the
# other fixtures of the DoH e2e are in conftest.py)
DOH_ADDRESSES, Pages, _asked_outside, _assert_every_connection_went_through_the_gateway, _assert_stayed_home,
_direct_to_the_doh, _hermetic_session, _is_address, _launch, _page_in, _text, _why)
from _doh_servers import DOH_HOST, QTYPE_A
pytestmark = pytest.mark.e2e
#: Contexts created back-to-back in one session.
ROUNDS = 8
#: A navigation that cannot resolve its name must fail fast (NS_ERROR_UNKNOWN_HOST), not wait the default 30 s per round.
GOTO_MS = 20000
def _race_names(prefix):
return ["%s-%d.test" % (prefix, i) for i in range(ROUNDS)]
def _navigate_at_once(browser, pages, name, proxy):
"""Create a context (with `proxy` when given), open its first page and navigate at once, with nothing in between.
Returns (text of the page or None, error text or None). The context is closed either way."""
context, page = _page_in(browser, proxy=proxy)
try:
page.goto(pages.url(name), wait_until="load", timeout=GOTO_MS)
return _text(page), None
except Exception as exc: # noqa: BLE001 - the failure is the result: it is reported with the other rounds
return None, "%s: %s" % (type(exc).__name__, str(exc).splitlines()[0] if str(exc) else "")
finally:
context.close()
def _names_asked_to_the_system_resolver(trap, names):
"""The trap's questions about one of `names` or a name under one (None when there is no trap)."""
if trap is None:
return None
return [q for q in trap.queries if any(q.name == n or q.name.endswith("." + n) for n in names)]
@pytest.mark.parametrize("mode", ["context_proxy", "browser_proxy", "context_without_proxy_beside_a_proxied_one"])
def test_the_first_navigation_of_a_fresh_context_never_asks_the_system_resolver(
mode, firefox_binary, doh, pages, gateway, trap, watcher):
if mode == "context_without_proxy_beside_a_proxied_one":
_beside_a_proxied_context(firefox_binary, doh, pages, gateway, trap, watcher)
else:
_back_to_back_contexts(mode, firefox_binary, doh, pages, gateway, trap, watcher)
def _back_to_back_contexts(mode, firefox_binary, doh, pages, gateway, trap, watcher):
names = _race_names("race-" + mode.split("_")[0])
doh.names.update({n: "127.0.0.1" for n in names})
if mode == "context_proxy":
# no launch proxy; one gateway per context, so "asked only by the gateway of its own context" is checkable
launch_gateway, roads = None, {n: gateway("gw-%d" % i) for i, n in enumerate(names)}
else:
# a launch proxy; the contexts have none of their own and inherit it
launch_gateway = gateway("launch")
roads = {n: launch_gateway for n in names}
gateways = list(dict.fromkeys(roads.values()))
outcomes = {}
with _launch(firefox_binary, launch_gateway.proxy if launch_gateway else None) as browser:
for name in names:
own_proxy = roads[name].proxy if launch_gateway is None else None
outcomes[name] = _navigate_at_once(browser, pages, name, own_proxy)
watcher.stop()
why = _why(doh, *gateways)
failed = {n: err for n, (text, err) in outcomes.items() if text is None}
assert failed == {}, (
"%d of %d first navigations failed: the name, known only to the DoH, was not resolved by it through the proxy of "
"its context (a native lookup would end in NS_ERROR_UNKNOWN_HOST): %s" % (len(failed), ROUNDS, failed) + why)
wrong = {n: text for n, (text, _e) in outcomes.items() if "HOST=%s:%d" % (n, pages.port) not in text}
assert wrong == {}, "a page loaded but is not the page of its name: %s" % wrong + why
for name in names:
road = roads[name]
assert doh.vias_of(name, QTYPE_A) == {road.name}, (
"%s (A) was not asked by %s (the proxy of its context) only: %s" % (name, road.name, doh.vias_of(name)) + why)
assert not [h for h, _p in road.connects if h == name], (
"the browser sent the NAME %s to the gateway instead of resolving it with the DoH" % name + why)
assert ("127.0.0.1", pages.port) in road.connects, "%s was not reached by address through %s" % (name, road.name) + why
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without the proxy of its context" + why
for gw in gateways:
assert gw.doh_connects(), "%s carried no DoH CONNECT" % gw.name + why
assert [h for h, _p in gw.connects if not _is_address(h) and h != DOH_HOST] == [], (
"a CONNECT of %s carried a name: the browser must resolve with the DoH and connect by address" % gw.name + why)
assert pages.hits and {host.split(":")[0] for host, _p in pages.hits} == set(names), (
"the page server saw hosts other than the names of the rounds: %s" % pages.hits)
_assert_every_connection_went_through_the_gateway(doh, *gateways)
assert watcher.watched_pids, ("the watcher never saw a browser process (it saw: %s): a watcher that cannot see proves "
"nothing" % watcher.process_names)
assert _direct_to_the_doh(watcher) == [], (
"the browser reached a DoH (%s) or a DNS server without the proxy of its context: %s"
% (", ".join(DOH_ADDRESSES), watcher.describe()) + why)
asked_natively = _names_asked_to_the_system_resolver(trap, names)
if asked_natively is not None:
assert asked_natively == [], (
"the system resolver was asked for a name of a proxied context: %s" % trap.describe() + why)
if launch_gateway is None:
# No launch proxy: the default context is the machine's own network. It resolves natively and never uses the DoH:
# no name but the rounds' in the DoH log, and no failed handshake (only the default context lacks the certificate
# exception, so a failed handshake is a lookup of the default context that reached the DoH).
assert _asked_outside(doh, *names) == [], (
"the DoH was asked for a name that is not one of the proxied contexts' (the default context has no proxy and "
"must resolve natively): %s" % _asked_outside(doh, *names) + why)
assert doh.tls_failures == [], "a context without the FakeDoh certificate exception used the DoH: %s" % doh.tls_failures + why
else:
# The launch proxy is the proxy of the default context too: its background names go to the DoH through the launch
# proxy (their handshakes fail BY DESIGN and are counted by the accounting above), so here nothing may go direct or
# ask the system resolver at all.
_assert_stayed_home(watcher, trap, doh, launch_gateway)
def _beside_a_proxied_context(firefox_binary, doh, pages, gateway, trap, watcher):
name_a = "race-beside-a.test"
doh.names[name_a] = "127.0.0.1"
gw_a = gateway("gw-a")
home_b = Pages() # B's own server: whose gateway log it is in says which road B took
try:
with _launch(firefox_binary, None) as browser:
context_b, page_b = _page_in(browser) # no proxy of its own, no launch proxy
context_a, page_a = _page_in(browser, proxy=gw_a.proxy) # created while B lives
page_b.goto(home_b.url("127.0.0.1"), wait_until="load", timeout=GOTO_MS)
first_b = _text(page_b)
page_a.goto(pages.url(name_a), wait_until="load", timeout=GOTO_MS)
text_a = _text(page_a)
page_b.goto(home_b.url("127.0.0.1") + "again", wait_until="load", timeout=GOTO_MS) # after A has used the DoH
second_b = _text(page_b)
context_a.close()
context_b.close()
watcher.stop()
why = _why(doh, gw_a)
assert "HOST=%s:%d" % (name_a, pages.port) in text_a, (
"A's page did not load: the name, known only to the DoH, was not resolved by it through A's proxy: %r" % text_a + why)
assert "HOST=127.0.0.1:%d" % home_b.port in first_b and "HOST=127.0.0.1:%d" % home_b.port in second_b, (
"B's pages did not load by address: %r %r" % (first_b, second_b) + why)
assert [path for _h, path in home_b.hits if path != "/favicon.ico"] == ["/", "/again"], "B's server saw: %s" % home_b.hits
assert doh.vias_of(name_a, QTYPE_A) == {"gw-a"}, "%s (A) was not asked by A's gateway only" % name_a + why
assert ("127.0.0.1", pages.port) in gw_a.connects, "A's page was not reached by address through A's gateway" + why
assert ("127.0.0.1", home_b.port) not in gw_a.connects, (
"B's page went through A's gateway: B, which has no proxy, borrowed the proxy of A" + why)
# B's lookups are the machine's own and never show up at the FakeDoh: only A's name was asked, by A's gateway.
assert _asked_outside(doh, name_a) == [], (
"the FakeDoh was asked for a name that is not A's (B and the default context have no proxy and must not use the "
"DoH): %s" % _asked_outside(doh, name_a) + why)
assert "direct" not in {q.via for q in doh.queries}, "something reached the DoH without A's proxy" + why
assert doh.tls_failures == [], "a context without the FakeDoh certificate exception used the DoH: %s" % doh.tls_failures + why
_assert_every_connection_went_through_the_gateway(doh, gw_a)
assert watcher.watched_pids, ("the watcher never saw a browser process (it saw: %s): a watcher that cannot see "
"proves nothing" % watcher.process_names)
assert _direct_to_the_doh(watcher) == [], (
"the browser reached a DoH or a DNS server without the proxy: %s" % watcher.describe() + why)
asked_natively = _names_asked_to_the_system_resolver(trap, [name_a])
if asked_natively is not None:
assert asked_natively == [], "the system resolver was asked for A's name: %s" % trap.describe() + why
finally:
home_b.close()
@@ -0,0 +1,45 @@
"""`request.resource_type` agrees with the pinned Playwright driver for every cause the engine reports.
The table that turns a Juggler `cause` (the name of an nsIContentPolicy constant) into a Playwright resource type was a copy of the
driver's, and it went stale: the pinned driver (the `playwright==` of the dev extra, scripts/playwright_pin.txt) says `beacon` for
TYPE_BEACON and `cspreport` for TYPE_CSP_REPORT, ours said `other` for both, so a beacon was an `other` request to a client and to a
route filter, where stock Firefox shows `beacon` (measured on cnbc.com and scmp.com: the same POSTs, 2 and 8 per page, `other`
here and `beacon` on stock). The test reads the driver's own table from the installed package (no import of it), so the next driver
version that changes it fails here, and nothing else needs updating by hand.
"""
from __future__ import annotations
import importlib.util
import pathlib
import re
import pytest
from invisible_playwright._juggler import _marshal
pytestmark = pytest.mark.unit
def _driver_table():
spec = importlib.util.find_spec("playwright")
if spec is None or not spec.submodule_search_locations:
pytest.fail("the pinned Playwright driver is not installed: the dev extra pins it", pytrace=False)
bundle = pathlib.Path(list(spec.submodule_search_locations)[0]) / "driver" / "package" / "lib" / "coreBundle.js"
if not bundle.exists():
pytest.fail("the pinned driver has no coreBundle.js at %s" % bundle, pytrace=False)
text = bundle.read_text(encoding="utf-8", errors="replace")
start = text.index("TYPE_INVALID:")
block = text[text.rindex("{", 0, start): text.index("};", start)]
return dict(re.findall(r'(TYPE_[A-Z_]+):\s*"([a-z]+)"', block))
def test_every_cause_the_driver_knows_has_the_same_resource_type_here():
driver = _driver_table()
assert len(driver) >= 20, driver
ours = {cause: _marshal._resource_type({"cause": cause}) for cause in driver}
assert ours == driver, {c: (ours[c], driver[c]) for c in driver if ours[c] != driver[c]}
def test_a_beacon_is_a_beacon_and_a_csp_report_a_cspreport():
assert _marshal._resource_type({"cause": "TYPE_BEACON"}) == "beacon"
assert _marshal._resource_type({"cause": "TYPE_CSP_REPORT"}) == "cspreport"
+120
View File
@@ -0,0 +1,120 @@
"""A route whose request the page has already abandoned is answered quietly.
Found and first fixed by richardpowellus (invisible_playwright #351); the test is his, adapted to the fix that swallows only
"Cannot find request" and a closed target (the same `RouteDispatcher._send`).
The known-bad input, measured on 2026-10-14 with
`page.route("**/*", lambda r: r.continue_())` and sixty sequential
`page.goto(url, wait_until="load")` calls on a loopback page: 4-12 of them
failed. Every failing `continue_` was the previous document's `/favicon.ico`,
whose channel the next navigation had aborted while the route sat with the
handler. The engine answered `Network.resumeInterceptedRequest` with
NS_BINDING_ABORTED, the server raised it, and it came out of the caller's NEXT
call (`Page.goto: Route.continue_: ...`, `Page.evaluate: Route.continue_: ...`)
or left that goto waiting for a load that never came.
Playwright's own Firefox server sends all three interception answers with
`sendMayFail`: a request that is gone has nothing left to answer.
"""
from __future__ import annotations
import http.server
import socket
import threading
import pytest
PAGE = b"<!doctype html><html><body><form><textarea></textarea></form></body></html>"
HELD = b"<!doctype html><html><body><img src='/held.png'></body></html>"
def _serve():
class H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
body = HELD if self.path.startswith("/held") and \
not self.path.endswith(".png") else PAGE
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *a):
pass
s = socket.socket()
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
s.close()
srv = http.server.ThreadingHTTPServer(("127.0.0.1", port), H)
srv.daemon_threads = True
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv, "http://127.0.0.1:%d" % port
@pytest.mark.e2e
@pytest.mark.parametrize("answer", ["continue_", "fulfill", "abort"])
def test_answering_a_route_the_next_navigation_aborted_does_not_raise(
firefox_binary, answer):
"""The image of a page the caller has navigated away from is still held
by the handler; answering it afterwards neither raises nor poisons the
caller's next call."""
from invisible_playwright import InvisiblePlaywright
srv, base = _serve()
held = []
def handler(route):
if route.request.url.endswith("/held.png"):
held.append(route)
else:
route.continue_()
try:
with InvisiblePlaywright(seed=4243, binary_path=firefox_binary,
headless=True) as b:
page = b.new_context().new_page()
page.route("**/*", handler)
page.goto(base + "/held", wait_until="commit", timeout=15000)
for _ in range(100):
if held:
break
page.wait_for_timeout(50)
assert held, "the page's image never reached the handler"
page.goto(base + "/next", wait_until="load", timeout=15000)
route = held[0]
if answer == "fulfill":
route.fulfill(status=200, body="")
else:
getattr(route, answer)()
assert page.evaluate("1 + 1") == 2
assert page.url == base + "/next"
finally:
srv.shutdown()
@pytest.mark.e2e
def test_sequential_routed_gotos_neither_hang_nor_raise(firefox_binary):
"""The measured case: every routed goto's favicon is still being
continued when the next goto aborts it."""
from invisible_playwright import InvisiblePlaywright
srv, base = _serve()
failures = []
try:
with InvisiblePlaywright(seed=4243, binary_path=firefox_binary,
headless=True) as b:
page = b.new_context().new_page()
page.route("**/*", lambda r: r.continue_())
for i in range(40):
try:
page.goto(f"{base}/p?{i % 2}", wait_until="load",
timeout=8000)
page.evaluate("1")
except Exception as e: # noqa: BLE001 - the failure is the finding
failures.append((i, type(e).__name__, str(e)[:200]))
finally:
srv.shutdown()
assert not failures, failures
@@ -0,0 +1,84 @@
"""The UDP association of the proxy is ready BEFORE the PeerConnection is born: its first datagram does not wait for a handshake.
⛔ THE KNOWN-BAD INPUT. The sockets of a PeerConnection are made in the SOCKET process; the pool of UDP associations was warmed only
where Necko opens a SOCKS5 connection (the parent, where HTTP lives). So the first ICE socket found the pool empty and made its
association from scratch: TCP, greeting, auth, ASSOCIATE, four round trips before the first STUN datagram left (605 ms of 1083 on a
real proxy 150 ms away; measured in the logs of the giro 2 binary: "layer pushed" at +34 ms from the birth of the PeerConnection,
"ASSOCIATE OK" at +639 ms). A retail Firefox at home has no such wait.
What is asserted, with a gateway that answers every step of the handshake after a round trip (130 ms):
1. an association the gateway granted was completed before the PeerConnection was created (the page loaded through the same
proxy first, which is when Firefox learns the proxy); alone this does not tell the processes apart (the parent's pool is
warmed by the page load), the second line does;
2. the first STUN datagram of the PeerConnection reaches the relay within a fraction of a handshake of its birth (a cold
association needs three answered steps, 3 x 130 ms, before it can send).
Hermetic: a local SOCKS5 gateway with a relay and a fake STUN server, a local page reached through the proxy, no external network.
Red on an engine that warms the pool only in the process of the HTTP connections: measured on the giro 2 binary, the first datagram left
396 ms after the birth of the PeerConnection (3 x 130 ms) instead of at once.
"""
from __future__ import annotations
import time
import pytest
from _socks_servers import STUN_NUMBER, STUN_PORT, coherent
from _udp_line import egress_by_proxy
from test_webrtc_realness import _e2e_binary, _launch # noqa: F401
# Bound to the engine that carries the UDP line: red before the UDP line (firefox-63): skips on the published engine; runs on the candidate.
pytestmark = [pytest.mark.e2e, pytest.mark.usefixtures("the_udp_line")]
RTT_MS = 130
_PC_JS = """async (stun) => {
const t_pc = Date.now();
const pc = new RTCPeerConnection({iceServers: [{urls: ['stun:' + stun]}]});
pc.createDataChannel('x');
let t_srflx = null;
pc.onicecandidate = e => { if (e.candidate && e.candidate.type === 'srflx' && t_srflx === null) t_srflx = Date.now(); };
await pc.setLocalDescription(await pc.createOffer());
const deadline = Date.now() + 8000;
while (t_srflx === null && Date.now() < deadline) await new Promise(r => setTimeout(r, 5));
pc.close();
return {t_pc, t_srflx};
}"""
def test_the_first_datagram_does_not_wait_for_a_handshake(local_https_page, monkeypatch):
binary = _e2e_binary()
if not binary:
pytest.skip("no patched binary (set STEALTHFOX_E2E_BINARY)")
from invisible_core import _geo
with coherent(user="alice", password="s3cret", rtt_ms=RTT_MS) as gateway:
# ⛔ THE SESSION'S UDP HAS TO BE DECLARED COHERENT, or the engine treats the proxy as a router that drops UDP (no association is
# asked, no datagram leaves) - the red of the giro 3 gate. The core declares `coherent` when the UDP probe's mapped address IS
# the TCP exit it discovered; a hermetic test gives it the gateway's TCP exit as every e2e of the line does (the probe that
# follows still runs through the relay, for real). The hermetic world has no network but the gateway, so the core's own discovery of the
# exit (third-party echo services) fails and the verdict would be `unmeasured`.
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(gateway))
prefs = {"network.proxy.allow_hijacking_localhost": True, "network.proxy.no_proxies_on": ""}
with _launch(binary_path=binary, proxy=gateway.proxy, extra_prefs=prefs, seed=7) as browser:
page = browser.new_context().new_page()
page.goto(local_https_page, wait_until="load", timeout=60000) # through the proxy: Firefox learns it here
page.wait_for_timeout(2500) # the pool has time to make its associations
result = page.evaluate(_PC_JS, "%s:%d" % (STUN_NUMBER, STUN_PORT))
t_pc = result["t_pc"] / 1000.0
granted = [a for a in gateway.associations if a[1] is not None]
first = next((t for host, port, _atyp, t in gateway.datagram_log if host == STUN_NUMBER), None)
assert granted, "the proxy was never asked for an association"
# the first association of the gateway is the core's own UDP probe, made before the browser exists: it is no pool
# association of the engine, and counting it made this test pass with an engine that asked for none
granted = granted[1:]
assert granted, "the engine never asked the proxy for an association (only the core's probe did): the session's UDP was not declared coherent"
ready_before = [a for a in granted if gateway.wall0 + a[1] < t_pc]
assert ready_before, (
"no association was completed before the PeerConnection was born (granted at %s s from the gateway's start, the "
"PeerConnection at %.3f s): the first ICE socket made its own, from scratch"
% ([round(a[1], 3) for a in granted], t_pc - gateway.wall0))
assert first is not None, "no STUN datagram of the PeerConnection reached the relay"
wait = gateway.wall0 + first - t_pc
assert wait < 0.25, (
"the first STUN datagram left %.0f ms after the PeerConnection was born; a ready association sends at once, a cold one "
"needs three answered steps of %d ms" % (wait * 1000, RTT_MS))
assert result["t_srflx"] is not None, "no srflx candidate came back through the relay"
@@ -0,0 +1,61 @@
"""The DoH e2e launch their browser on a virtual display, whatever machine they run on (run 43176569993: 19 of 19 of
wrapper.e2e.doh on Linux died at the launch with "no DISPLAY environment variable specified": the files launched a
headed browser with a window on a runner that has no screen).
``headless=True`` is a headed browser on a display the wrapper starts itself, as in the UDP and realness e2e. A test
does not behave differently by the display of the machine it runs on, so the launchers do not look at ``DISPLAY``.
Nothing is launched here: the session object holds the answer."""
from __future__ import annotations
import ast
import json
import pathlib
import sys
import pytest
import test_doh_through_the_proxy_e2e as through_the_proxy
import test_doh_under_stress_e2e as under_stress
import test_ice_names_by_the_context_proxy_e2e as ice_names
pytestmark = pytest.mark.unit
LAUNCHERS = {
"the DoH e2e": lambda: through_the_proxy._launch("/nowhere/firefox", None),
"the stress e2e": lambda: under_stress._launch_with_a_short_negative_cache("/nowhere/firefox"),
"the ICE names e2e": lambda: ice_names._launch("/nowhere/firefox", None),
}
@pytest.mark.parametrize("host", ["linux without a display", "linux with a display", "windows"])
@pytest.mark.parametrize("which", sorted(LAUNCHERS))
def test_every_launcher_asks_for_a_virtual_display_on_every_host(monkeypatch, which, host):
monkeypatch.setattr(sys, "platform", "win32" if host == "windows" else "linux")
if host == "linux with a display":
monkeypatch.setenv("DISPLAY", ":0")
else:
monkeypatch.delenv("DISPLAY", raising=False)
assert LAUNCHERS[which]()._headless is True
def test_what_the_caller_asks_for_wins():
assert through_the_proxy._launch("/nowhere/firefox", None, headless=False)._headless is False
def test_no_session_of_a_suite_that_launches_on_a_runner_is_made_without_a_display():
"""Run 43188313516: the one test of the DoH suite that built its session by hand
(``InvisiblePlaywright(...)`` and then ``with session``) died with "no DISPLAY environment variable specified".
Every direct construction in the files of the suites that run on a Linux runner says ``headless``."""
tests = pathlib.Path(__file__).resolve().parent
required = json.loads((tests.parent / "ci" / "required-suites.json").read_text(encoding="utf-8"))
files = sorted({name.split("::")[0] for row in required if row["id"] in ("wrapper.e2e.doh", "wrapper.e2e.realness")
for name in row["tests"]})
assert files, "no file for the DoH and realness suites"
bare = []
for name in files:
path = tests.parent / name
for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
if isinstance(node, ast.Call) and getattr(node.func, "id", None) == "InvisiblePlaywright":
if not any(k.arg == "headless" or k.arg is None for k in node.keywords):
bare.append("%s:%d" % (name, node.lineno))
assert bare == [], "InvisiblePlaywright(...) without headless= (a runner has no screen): %s" % bare
@@ -0,0 +1,38 @@
"""The core discovers the exit of a context's proxy by asking the PROXY, by NAME, and nothing else leaves.
When a context is given a SOCKS5 proxy, the core measures what it needs before it sends ``Browser.setContextProxy``
(``invisible_core._udp_exit.measure_proxy_udp``): the TCP exit through that proxy, with the services of the core
(``_geo._IP_ECHO_ENDPOINTS``), and the UDP exit beside it. The names are resolved by the PROXY (remote DNS: the host's own resolver is
never asked), through the gateway of THAT context and no other. The DoH e2e declare this discovery away (their subject is the roads
of the BROWSER, and the asserts on the CONNECTs of a gateway would otherwise see the core's three names), so this test keeps what
the declaration hides: the discovery goes through the gateway of the context, by name, only to the services of the core, and a
gateway that refuses them never makes the measurement say ``coherent``.
"""
import pytest
from invisible_core import _geo, _udp_exit
pytestmark = pytest.mark.unit
#: The services of the core, in the order it asks them (https, so port 443).
ECHO = [(url.split("//", 1)[1], 443) for url in _geo._IP_ECHO_ENDPOINTS]
SERVICES = {url.split("//", 1)[1] for url in _geo._IP_ECHO_ENDPOINTS + _geo._IPV6_ECHO_ENDPOINTS}
def test_the_exit_of_a_context_is_asked_to_its_own_gateway_by_name(gateway):
mine = gateway("gw-mine")
other = gateway("gw-other")
command = _udp_exit.context_proxy_command(mine.proxy)
assert command is not None
assert mine.connects[:len(ECHO)] == ECHO, "the discovery goes through the gateway of the context, by name, in the core's order"
assert {host for host, _port in mine.connects} <= SERVICES, (
"only the services of the core are asked through it: %s" % (mine.connects,))
assert other.connects == [], "the gateway of another context never sees it: %s" % (other.connects,)
def test_a_gateway_that_refuses_the_services_never_gives_a_coherent_udp(gateway):
gw = gateway("gw-refusing")
command = _udp_exit.context_proxy_command(gw.proxy)
assert command["type"] == "socks"
assert gw.refused[:len(ECHO)] == ECHO, "the gateway refused the services: %s" % (gw.refused,)
assert command["udp"] != "coherent", "a measurement that could not run is never coherent: %s" % (command,)
@@ -0,0 +1,233 @@
"""The two knobs of the FakeDoh used by `test_doh_under_stress_e2e.py`: a latency on every answer and a first query that
is refused. Tested with plain Python clients, on HTTP/1.1 and on h2, like `test_the_fake_doh_answers.py`.
* `delay_s` / `delay_names`: each answer is held that long after its QUERY arrived (not only the connection set-up), and
over h2 the answers of one connection are held independently, so the A and the AAAA of one lookup both come back after
the delay, not one after the other (the second after twice the delay would turn a 2 s latency into a 4 s one);
* `fail_first`: the first query of each type for a name is refused as `close` (no answer: an h2 stream reset or a closed
HTTP/1.1 connection), `http503` or `servfail`; every later one is served; the other names are untouched.
"""
from __future__ import annotations
import ssl
import time
import pytest
import _doh_servers as ds
from _doh_servers import DOH_HOST, DOH_PATH, FakeDoh, QTYPE_A, QTYPE_AAAA, encode_query
from test_the_fake_doh_answers import NAMES, _h1_request, _tls, read_response
pytestmark = pytest.mark.unit
DELAY = 0.6
#: Slack for a loaded machine: the answer must not come EARLIER than the delay, and not much later.
LATE = 1.5
# ------------------------------------------------------------------------------------------------- clients
def _h1_post(tls, name, qtype=QTYPE_A):
started = time.monotonic()
status, _headers, body = _h1_request(tls, "POST", DOH_PATH, encode_query(name, qtype), "application/dns-message")
return status, body, time.monotonic() - started
def _h2_exchange(doh, messages):
"""Send every message as its own POST stream at once on one h2 connection. Returns one entry per message, in order:
``("reset", seconds)`` or ``(status, body, seconds)``, seconds counted from the moment all streams were sent."""
h2_config = pytest.importorskip("h2.config")
h2_connection = pytest.importorskip("h2.connection")
h2_events = pytest.importorskip("h2.events")
tls = _tls(("127.0.0.1", doh.port), alpn=["h2", "http/1.1"])
assert tls.selected_alpn_protocol() == "h2"
conn = h2_connection.H2Connection(config=h2_config.H2Configuration(client_side=True, header_encoding="utf-8"))
conn.initiate_connection()
ids = []
for message in messages:
stream_id = conn.get_next_available_stream_id()
conn.send_headers(stream_id, [(":method", "POST"), (":scheme", "https"), (":authority", DOH_HOST),
(":path", DOH_PATH), ("accept", "application/dns-message"),
("content-type", "application/dns-message"),
("content-length", str(len(message)))])
conn.send_data(stream_id, message, end_stream=True)
ids.append(stream_id)
tls.sendall(conn.data_to_send())
started = time.monotonic()
status, body, done = {}, {i: b"" for i in ids}, {}
tls.settimeout(10)
try:
while len(done) < len(ids):
data = tls.recv(65536)
assert data, "the server closed the connection"
for event in conn.receive_data(data):
if isinstance(event, h2_events.ResponseReceived):
status[event.stream_id] = dict(event.headers)[":status"]
elif isinstance(event, h2_events.DataReceived):
body[event.stream_id] += event.data
conn.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
elif isinstance(event, h2_events.StreamEnded):
done[event.stream_id] = ("answer", time.monotonic() - started)
elif isinstance(event, h2_events.StreamReset):
done[event.stream_id] = ("reset", time.monotonic() - started)
tls.sendall(conn.data_to_send())
finally:
tls.close()
out = []
for i in ids:
kind, seconds = done[i]
out.append(("reset", seconds) if kind == "reset" else (status[i], body[i], seconds))
return out
# ----------------------------------------------------------------------------------------------- the defaults
def test_the_defaults_change_nothing():
with FakeDoh(NAMES, h2=False) as doh:
assert (doh.delay_s, doh.delay_names, doh.fail_first) == (0.0, {}, {})
tls = _tls(("127.0.0.1", doh.port), alpn=["http/1.1"])
try:
status, body, took = _h1_post(tls, "page-a.test")
finally:
tls.close()
assert status == 200 and read_response(body)[4] and took < DELAY
(answer,) = doh.answers
assert (answer.name, answer.qtype, answer.via, answer.outcome) == ("page-a.test", QTYPE_A, "direct", "answered")
assert answer.delay < DELAY
# ----------------------------------------------------------------------------------------------------- latency
def test_every_answer_over_http1_is_held_for_the_delay():
with FakeDoh(NAMES, h2=False, delay_s=DELAY) as doh:
tls = _tls(("127.0.0.1", doh.port), alpn=["http/1.1"])
try:
first = _h1_post(tls, "page-a.test")
second = _h1_post(tls, "other.test", QTYPE_AAAA)
finally:
tls.close()
for status, body, took in (first, second):
assert status == 200 and DELAY - 0.05 <= took < DELAY + LATE, took
assert read_response(first[1])[4], "the answer is the normal one, only late"
assert [round(a.delay, 1) for a in doh.answers] == [round(DELAY, 1)] * 2
assert all(a.delay >= DELAY - 0.05 for a in doh.answers)
def test_every_answer_over_h2_is_held_for_the_delay_and_the_a_and_the_aaaa_wait_together():
with FakeDoh(NAMES, delay_s=DELAY) as doh:
a, aaaa = _h2_exchange(doh, [encode_query("page-a.test", QTYPE_A), encode_query("page-a.test", QTYPE_AAAA)])
for status, _body, took in (a, aaaa):
assert status == "200" and DELAY - 0.05 <= took < 2 * DELAY + 0.3, (
"both answers are held in parallel: %.2f s, not %.2f s" % (took, 2 * DELAY))
assert read_response(a[1])[4] and not read_response(aaaa[1])[4]
assert {x.qtype for x in doh.answers_for("page-a.test")} == {QTYPE_A, QTYPE_AAAA}
assert all(x.delay >= DELAY - 0.05 for x in doh.answers)
def test_the_delay_of_a_name_only_holds_that_name_and_the_names_under_it():
with FakeDoh(NAMES, delay_names={"page-a.test": DELAY}) as doh:
slow, fast, below = _h2_exchange(doh, [encode_query("page-a.test"), encode_query("other.test"),
encode_query("_80._https.page-a.test", QTYPE_A)])
assert slow[2] >= DELAY - 0.05 and below[2] >= DELAY - 0.05
assert fast[0] == "200" and fast[2] < DELAY, "an unrelated name is not held: %.2f s" % fast[2]
def test_the_delay_can_be_changed_while_the_server_runs():
with FakeDoh(NAMES, h2=False) as doh:
tls = _tls(("127.0.0.1", doh.port), alpn=["http/1.1"])
try:
assert _h1_post(tls, "page-a.test")[2] < DELAY
doh.delay_s = DELAY
assert _h1_post(tls, "page-a.test")[2] >= DELAY - 0.05
finally:
tls.close()
# ------------------------------------------------------------------------------------------------ first refused
def test_an_unknown_failure_kind_is_refused_at_construction():
with pytest.raises(ValueError):
FakeDoh(NAMES, fail_first={"page-a.test": "explode"})
def test_http503_once_over_http1_then_the_name_is_served_and_other_names_never_fail():
with FakeDoh(NAMES, h2=False, fail_first={"page-a.test": "http503"}) as doh:
tls = _tls(("127.0.0.1", doh.port), alpn=["http/1.1"])
try:
assert _h1_post(tls, "other.test")[0] == 200
assert _h1_post(tls, "page-a.test")[0] == 503, "the first query of the name is refused"
assert _h1_post(tls, "page-a.test")[0] == 200, "the second one is served"
assert _h1_post(tls, "page-a.test")[0] == 200
finally:
tls.close()
assert [a.outcome for a in doh.answers_for("page-a.test")] == ["http503", "answered", "answered"]
assert len(doh.queries_for("page-a.test")) == 3, "a refused query is still a query"
def test_servfail_once_is_a_dns_answer_with_rcode_2():
with FakeDoh(NAMES, h2=False, fail_first={"page-a.test": "servfail"}) as doh:
tls = _tls(("127.0.0.1", doh.port), alpn=["http/1.1"])
try:
status, body, _took = _h1_post(tls, "page-a.test")
_i, _f, rcode, name, answers = read_response(body)
assert (status, rcode, name, answers) == (200, ds.RCODE_SERVFAIL, "page-a.test", [])
assert read_response(_h1_post(tls, "page-a.test")[1])[4], "the second one has its address"
finally:
tls.close()
def test_close_once_over_http1_ends_the_connection_without_an_answer():
with FakeDoh(NAMES, h2=False, fail_first={"page-a.test": "close"}) as doh:
tls = _tls(("127.0.0.1", doh.port), alpn=["http/1.1"])
try:
with pytest.raises((AssertionError, OSError, ssl.SSLError)):
_h1_post(tls, "page-a.test")
finally:
tls.close()
tls = _tls(("127.0.0.1", doh.port), alpn=["http/1.1"])
try:
assert _h1_post(tls, "page-a.test")[0] == 200
finally:
tls.close()
assert [a.outcome for a in doh.answers_for("page-a.test")] == ["close", "answered"]
def test_close_once_over_h2_resets_the_stream_and_keeps_the_connection():
with FakeDoh(NAMES, fail_first={"page-a.test": "close"}) as doh:
first, = _h2_exchange(doh, [encode_query("page-a.test")])
second, = _h2_exchange(doh, [encode_query("page-a.test")])
assert first[0] == "reset" and second[0] == "200"
assert [a.outcome for a in doh.answers_for("page-a.test")] == ["close", "answered"]
def test_the_first_query_of_each_type_is_refused_so_a_whole_first_lookup_fails():
"""A and AAAA of the first lookup both fail, whichever arrives first; the second lookup is served in full."""
with FakeDoh(NAMES, fail_first={"page-a.test": "http503"}) as doh:
first = _h2_exchange(doh, [encode_query("page-a.test", QTYPE_A), encode_query("page-a.test", QTYPE_AAAA)])
second = _h2_exchange(doh, [encode_query("page-a.test", QTYPE_A), encode_query("page-a.test", QTYPE_AAAA)])
assert [r[0] for r in first] == ["503", "503"]
assert [r[0] for r in second] == ["200", "200"]
def test_a_refusal_can_be_slow_too():
with FakeDoh(NAMES, delay_s=DELAY, fail_first={"page-a.test": "http503"}) as doh:
(refused,) = _h2_exchange(doh, [encode_query("page-a.test")])
assert refused[0] == "503" and refused[2] >= DELAY - 0.05
assert doh.answers_for("page-a.test")[0].delay >= DELAY - 0.05
def test_a_gateway_hands_the_knobs_over_with_the_connection():
"""Through a DohGateway the FakeDoh is the same object: the delay holds on the tunnelled road too."""
from _doh_servers import DohGateway
from test_the_fake_doh_answers import _socks_connect
with FakeDoh(NAMES, h2=False, delay_s=DELAY) as doh, DohGateway("gw1", doh) as gw:
s, code = _socks_connect(gw.port, ds.DOH_BOOTSTRAP, 443)
assert code == 0
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
context.set_alpn_protocols(["http/1.1"])
tls = context.wrap_socket(s, server_hostname=DOH_HOST)
try:
status, _body, took = _h1_post(tls, "page-a.test")
finally:
tls.close()
assert status == 200 and took >= DELAY - 0.05
assert doh.answers[0].via == "gw1"
+434
View File
@@ -0,0 +1,434 @@
"""The server and the judge of the HTTP/3 e2e work, without a browser (hermetic, loopback).
A retail Firefox (Windows 159, DoH forced like our core, 15 sessions per condition) never reads h3 at the first visit
behind a proxy: with UDP free h2/h2/h3 in 9, h2/h2/h2 in 4, h2/h3/h3 in 2; with UDP blocked h2/h2/h2 in 15 of 15 with no delay of
the load; with no proxy and the native DNS (loopback) h2, h3, h3. The e2e visits the page 3 times with no proxy and 5 times
behind any proxy and asserts that. These tests hold what it stands on: the local server really speaks HTTP/2 on its TCP port (if it
spoke HTTP/1.1 the first visit could never read ``h2``), says ``Alt-Svc: h3`` there, and answers the same document over HTTP/3;
and the function that judges the visits names what is wrong.
"""
from __future__ import annotations
import asyncio
import socket
import ssl
import time
import pytest
import _udp_line as line
from _h3_server import PAGE, H3Server
pytestmark = pytest.mark.unit
# -- the server ---------------------------------------------------------------------------------------------------------
def _tls_client(server, alpn):
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
context.set_alpn_protocols(alpn)
raw = socket.create_connection((server.address, server.port), timeout=10)
return context.wrap_socket(raw, server_hostname=server.address)
def _h2_get(server, path):
import h2.config
import h2.connection
import h2.events
tls = _tls_client(server, ["h2", "http/1.1"])
try:
assert tls.selected_alpn_protocol() == "h2", "the TCP side did not negotiate h2"
conn = h2.connection.H2Connection(config=h2.config.H2Configuration(client_side=True, header_encoding="utf-8"))
conn.initiate_connection()
conn.send_headers(1, [(":method", "GET"), (":authority", server.address), (":scheme", "https"), (":path", path)],
end_stream=True)
tls.sendall(conn.data_to_send())
headers, body, ended = {}, b"", False
while not ended:
data = tls.recv(65536)
assert data, "the server closed the connection before the end of the stream"
for event in conn.receive_data(data):
if isinstance(event, h2.events.ResponseReceived):
headers = dict(event.headers)
elif isinstance(event, h2.events.DataReceived):
body += event.data
conn.acknowledge_received_data(event.flow_controlled_length, event.stream_id)
elif isinstance(event, h2.events.StreamEnded):
ended = True
out = conn.data_to_send()
if out:
tls.sendall(out)
return headers, body
finally:
tls.close()
def test_the_tcp_side_speaks_http2_and_says_where_h3_is():
with H3Server("127.0.0.1") as server:
headers, body = _h2_get(server, "/?v=1")
assert headers[":status"] == "200"
assert headers["alt-svc"] == 'h3=":%d"; ma=3600' % server.port
assert headers["content-type"].startswith("text/html")
assert body == PAGE
assert server.tcp_alpn == ["h2"] and server.tcp_requests == ["/?v=1"]
def test_a_second_request_on_the_same_connection_is_answered_too():
with H3Server("127.0.0.1") as server:
for path in ("/?v=1", "/?v=2"):
assert _h2_get(server, path)[1] == PAGE
assert server.tcp_requests == ["/?v=1", "/?v=2"]
def test_a_client_that_offers_only_http1_is_answered_with_the_alt_svc_too():
with H3Server("127.0.0.1") as server:
tls = _tls_client(server, ["http/1.1"])
try:
tls.sendall(b"GET /?v=1 HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n")
data = b""
while True:
chunk = tls.recv(65536)
if not chunk:
break
data += chunk
finally:
tls.close()
assert data.startswith(b"HTTP/1.1 200 OK") and data.endswith(PAGE)
assert ('Alt-Svc: h3=":%d"; ma=3600' % server.port).encode() in data
assert server.tcp_alpn == ["http/1.1"]
def test_the_same_document_is_answered_over_http3_and_the_peer_is_recorded():
from aioquic.asyncio.client import connect
from aioquic.asyncio.protocol import QuicConnectionProtocol
from aioquic.h3.connection import H3_ALPN, H3Connection
from aioquic.h3.events import DataReceived, HeadersReceived
from aioquic.quic.configuration import QuicConfiguration
class Client(QuicConnectionProtocol):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.http = None
self.status, self.body = None, b""
self.finished = asyncio.Event()
def quic_event_received(self, event):
if self.http is None:
return
for http_event in self.http.handle_event(event):
if isinstance(http_event, HeadersReceived):
self.status = dict(http_event.headers).get(b":status")
elif isinstance(http_event, DataReceived):
self.body += http_event.data
if http_event.stream_ended:
self.finished.set()
async def get(self, authority, path):
self.http = H3Connection(self._quic)
stream = self._quic.get_next_available_stream_id()
self.http.send_headers(stream, [(b":method", b"GET"), (b":scheme", b"https"),
(b":authority", authority.encode()), (b":path", path.encode())], end_stream=True)
self.transmit()
await asyncio.wait_for(self.finished.wait(), 10)
async def fetch(server):
configuration = QuicConfiguration(is_client=True, alpn_protocols=H3_ALPN, verify_mode=ssl.CERT_NONE)
async with connect(server.address, server.port, configuration=configuration, create_protocol=Client) as client:
await client.get("%s:%d" % (server.address, server.port), "/?v=2")
return client.status, client.body
with H3Server("127.0.0.1") as server:
status, body = asyncio.run(fetch(server))
assert status == b"200" and body == PAGE
assert server.quic_peers == ["127.0.0.1"] and server.h3_requests == ["/?v=2"]
# -- the sequence a retail Firefox reads, and the judge -------------------------------------------------------------------
H2 = ["h2"] * 5
FAST = [900, 300, 310, 305, 290]
PROXY_ROADS = ("socks5_coherent", "socks5_no_udp", "socks5_mismatched", "socks5_unmeasured", "http_proxy")
H2_ROADS = ("socks5_no_udp", "socks5_mismatched", "socks5_unmeasured", "http_proxy")
def test_the_number_of_visits_of_each_road():
assert line.visits_for("direct") == 3
for road in PROXY_ROADS:
assert line.visits_for(road) == 5, road
def test_with_no_proxy_the_sequence_is_h2_h3_h3_and_nothing_else():
assert line.judge_visits("direct", ["h2", "h3", "h3"], [900, 300, 310]) == []
for wrong in (["h2", "h2", "h3"], ["h2", "h2", "h2"], ["h3", "h3", "h3"], ["h2", "h3", "h2"]):
assert line.judge_visits("direct", wrong, [900, 300, 310]), wrong
@pytest.mark.parametrize("sequence", [
["h2", "h2", "h3", "h3", "h3"], # the commonest retail sequence (9 of 15)
["h2", "h3", "h3", "h3", "h3"], # retail, 2 of 15
["h2", "h2", "h2", "h2", "h3"], # h3 as late as the fifth visit
["h2", "h2", "h2", "h3", "h3"],
])
def test_behind_a_gateway_with_udp_free_h3_may_come_at_any_visit_after_the_first(sequence):
assert line.judge_visits("socks5_coherent", sequence, FAST) == []
@pytest.mark.parametrize("sequence", [
["h3", "h3", "h3", "h3", "h3"], # h3 at visit 1
["h3", "h2", "h3", "h3", "h3"],
["h2", "h2", "h2", "h2", "h2"], # never h3 in five visits: the engine refuses h3 behind the proxy
["h2", "h3", "h2", "h3", "h3"], # h3 goes back to h2
["h2", "h2", "h3", "h3", "h2"],
])
def test_behind_a_gateway_with_udp_free_these_sequences_are_errors(sequence):
assert line.judge_visits("socks5_coherent", sequence, FAST), sequence
def test_h3_on_the_first_visit_is_an_error_and_says_so_on_every_road():
assert any("visit 1 read h3" in p for p in line.judge_visits("direct", ["h3", "h3", "h3"], [900, 300, 310]))
for road in PROXY_ROADS:
problems = line.judge_visits(road, ["h3", "h3", "h3", "h3", "h3"], FAST)
assert any("visit 1 read h3" in p for p in problems), (road, problems)
def test_the_judge_names_what_the_retail_reads():
problems = line.judge_visits("socks5_coherent", H2, FAST)
assert len(problems) == 1 and "none of the 5 visits read h3" in problems[0] and "9 of 15" in problems[0], problems
problems = line.judge_visits("socks5_no_udp", ["h2", "h2", "h3", "h3", "h3"], FAST)
assert any("15 of 15" in p for p in problems), problems
def test_h3_where_udp_is_dropped_is_an_error():
for road in H2_ROADS:
for sequence in (["h2", "h2", "h3", "h3", "h3"], ["h2", "h2", "h2", "h2", "h3"], ["h2", "h3", "h3", "h3", "h3"]):
assert line.judge_visits(road, sequence, FAST), (road, sequence)
assert line.judge_visits(road, H2, FAST) == [], road
def test_an_unknown_road_is_refused():
for call in (line.expected_protocols, line.visits_for):
with pytest.raises(KeyError):
call("socks5_maybe")
def test_a_later_load_that_waits_for_a_fallback_is_an_error_where_udp_is_dropped_and_only_there():
slow = [900, 900 + line.LOAD_MARGIN_MS + 1, 310, 305, 290]
problems = line.judge_visits("socks5_no_udp", H2, slow)
assert len(problems) == 1 and "visit 2 loaded" in problems[0], problems
assert line.judge_visits("socks5_no_udp", H2, [900, 900 + line.LOAD_MARGIN_MS, 310, 305, 290]) == []
for number in (3, 4, 5): # every later visit is judged, not only the second
walls = list(FAST)
walls[number - 1] = 900 + line.LOAD_MARGIN_MS + 1
problems = line.judge_visits("http_proxy", H2, walls)
assert len(problems) == 1 and "visit %d loaded" % number in problems[0], (number, problems)
# where UDP is free the loads are not judged (an h3 handshake has its own cost)
assert line.judge_visits("socks5_coherent", ["h2", "h2", "h3", "h3", "h3"], slow) == []
assert line.judge_visits("direct", ["h2", "h3", "h3"], [900, 900 + line.LOAD_MARGIN_MS + 1, 310]) == []
def test_a_series_of_the_wrong_length_is_an_error():
assert line.judge_visits("direct", ["h2", "h3"], [900, 300])
assert line.judge_visits("direct", ["h2", "h3", "h3"], [900, 300])
assert line.judge_visits("socks5_coherent", ["h2", "h2", "h3"], [900, 300, 310])
assert line.judge_visits("socks5_coherent", ["h2", "h2", "h3", "h3", "h3"], [900, 300, 310])
assert line.judge_visits("socks5_no_udp", ["h2", "h2", "h2"], [900, 300, 310])
# ------------------------------------------------------------------------------------------ the first visit is h2 by fixture
# The retail reads h3 at the first visit when the DNS answer carries the HTTPS record (type 65): the third retail run did in 3
# sessions of 15. The e2e expects h2 first only because the fixture has no such record.
def test_a_page_reached_by_an_address_has_no_https_record_to_wait_for():
assert line.no_https_record("192.0.2.1") == []
assert line.no_https_record("[2001:db8::1]") == []
def test_a_page_reached_by_a_name_may_have_one_and_the_check_says_so():
problems = line.no_https_record("site.test")
assert problems and "HTTPS record" in problems[0]
def test_the_fake_doh_never_serves_a_type_65_with_data_and_the_check_reads_what_it_served():
import _doh_servers as doh_servers
server = doh_servers.FakeDoh({"site.test": "192.0.2.1"})
try:
query = doh_servers.parse_query(doh_servers.encode_query("site.test", doh_servers.QTYPE_HTTPS))
message = doh_servers.answer_for({"site.test": "192.0.2.1"}, query)
assert int.from_bytes(message[6:8], "big") == 0, "a type 65 answer with data: the h2-first expectation no longer holds"
assert server.https_served == []
assert line.no_https_record("192.0.2.1", server) == []
server.https_served.append("site.test") # a FakeDoh that learned to serve the record
problems = line.no_https_record("192.0.2.1", server)
assert problems and "site.test" in problems[0]
finally:
server.close()
# -- the relay of the gateway: a send that fails is said, and a relay that leaves from the host's address works ----------------
# The e2e once read "the server saw QUIC from []" on Windows: the relay sent from 127.0.0.1 to an address of its own host (WinError 10051),
# the send ran in a timer that ignored every OSError, and the relay had still logged the datagram as carried.
def _associate(gateway):
"""A SOCKS5 UDP ASSOCIATE on ``gateway`` with no credentials: the control connection (kept open) and the relay's address."""
control = socket.create_connection(("127.0.0.1", gateway.port), timeout=5)
control.sendall(b"\x05\x01\x00")
assert control.recv(2) == b"\x05\x00"
control.sendall(b"\x05\x03\x00\x01\x00\x00\x00\x00\x00\x00")
reply = b""
while len(reply) < 10:
reply += control.recv(10 - len(reply))
assert reply[1] == 0, "the association was refused: %r" % reply
return control, (socket.inet_ntoa(reply[4:8]), int.from_bytes(reply[8:10], "big"))
def _wrapped(host, port, payload):
return b"\x00\x00\x00\x01" + socket.inet_aton(host) + port.to_bytes(2, "big") + payload
def test_a_send_the_relay_cannot_make_is_recorded_and_the_report_of_the_e2e_says_it():
import test_http3_through_the_proxy_e2e as e2e
from _socks_servers import coherent
with coherent() as gateway:
assert gateway.send_errors == []
def refused():
raise OSError(10051, "A socket operation was attempted to an unreachable network")
gateway._later(refused, "the datagram to 203.0.113.9:443")
assert len(gateway.send_errors) == 1 and gateway.send_errors[0].startswith("the datagram to 203.0.113.9:443: OSError")
class Server:
tcp_alpn, quic_peers = ["h2"], []
said = e2e._report("socks5_coherent", ["h2"], [1], Server, gateway)
assert "sends of the relay that failed" in said and "10051" in said
def test_a_relay_that_leaves_from_the_address_of_the_host_reaches_a_server_on_it_and_is_told_by_its_port():
from _host_address import this_host_address
from _socks_servers import coherent
host = this_host_address()
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind((host, 0))
server.settimeout(5)
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.bind((host, 0)) # an engine's UDP sockets are bound to an interface
with coherent(relay_host=host, exit_host=host) as gateway:
gateway.forward_only_to = {host}
control, relay = _associate(gateway)
try:
client.sendto(_wrapped(host, server.getsockname()[1], b"quic" * 300), relay)
data, peer = server.recvfrom(4096)
assert data == b"quic" * 300
assert peer[0] == host and peer[1] in gateway.exit_ports, "the relay's port is not in exit_ports: %s" % (gateway.exit_ports,)
direct = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
direct.bind((host, 0))
direct.sendto(b"direct", server.getsockname())
data, peer = server.recvfrom(4096)
assert data == b"direct" and peer[1] not in gateway.exit_ports, "a client that came direct looks like the relay"
direct.close()
# the browser's own QUIC to a public address is recorded as carried and goes nowhere: the lab stays closed
client.sendto(_wrapped("203.0.113.9", 443, b"background"), relay)
time.sleep(0.3)
assert ("203.0.113.9", 443) in {(h, p) for h, p, _d in gateway.datagrams}
assert gateway.send_errors == [], gateway.send_errors
finally:
control.close()
client.close()
server.close()
def test_the_fake_stun_of_a_relay_that_leaves_from_the_address_of_the_host_answers_through_the_relay():
from _host_address import this_host_address
from _socks_servers import MEASURE_NUMBER, STUN_PORT, coherent
host = this_host_address()
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.bind((host, 0))
client.settimeout(5)
with coherent(relay_host=host, exit_host=host) as gateway:
control, relay = _associate(gateway)
try:
request = b"\x00\x01\x00\x00\x21\x12\xa4\x42" + b"txid-of-12by"
client.sendto(_wrapped(MEASURE_NUMBER, STUN_PORT, request), relay)
answer, _peer = client.recvfrom(4096)
assert answer[3] == 1 and socket.inet_ntoa(answer[4:8]) == MEASURE_NUMBER and int.from_bytes(answer[8:10], "big") == STUN_PORT
assert answer[10:12] == b"\x01\x01", "not a STUN Binding success: %r" % answer[10:20]
assert gateway.send_errors == [], gateway.send_errors
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)
+81
View File
@@ -0,0 +1,81 @@
"""The address of this host that the relay of an e2e test binds to is computed by ONE helper, and a host with no default
route (a container or a CI runner without a network, a laptop offline) SKIPS the test instead of erroring, before any
server of the test has started (it used to raise OSError in the middle of the construction of the chain, after the TURN
server, the resolver and the page were listening)."""
import types
import pytest
import _host_address
import _turn_chain
pytestmark = pytest.mark.unit
class _Probe:
"""A UDP socket of a host whose routing table is ``address`` (a string), or empty (None)."""
def __init__(self, address):
self.address, self.closed = address, False
def connect(self, _target):
if self.address is None:
raise OSError(10051, "Network is unreachable")
def getsockname(self):
return (self.address, 40000)
def close(self):
self.closed = True
def _host_with(monkeypatch, address):
probes = []
def make(*_args):
probes.append(_Probe(address))
return probes[-1]
monkeypatch.setattr(_host_address, "socket", types.SimpleNamespace(socket=make, AF_INET=2, SOCK_DGRAM=2))
return probes
def test_a_host_with_a_default_route_gives_the_address_it_sends_from(monkeypatch):
probes = _host_with(monkeypatch, "192.168.7.20")
assert _host_address.this_host_address() == "192.168.7.20"
assert all(p.closed for p in probes)
def test_a_host_with_no_default_route_skips_the_test(monkeypatch):
probes = _host_with(monkeypatch, None)
with pytest.raises(pytest.skip.Exception, match="no default route"):
_host_address.this_host_address()
assert all(p.closed for p in probes)
def test_the_chain_asks_the_address_before_it_starts_any_server(monkeypatch):
started = []
for name in ("TurnServer", "FakeDoh", "Page"):
monkeypatch.setattr(_turn_chain, name, lambda *a, _n=name, **k: started.append(_n))
_host_with(monkeypatch, None)
monkeypatch.setattr(_turn_chain, "this_host_address", _host_address.this_host_address)
with pytest.raises(pytest.skip.Exception, match="no default route"):
_turn_chain.Chain()
assert started == [], "a server was started before the address of this host was known: %s" % started
def test_the_chain_with_a_relay_host_of_its_own_does_not_ask_for_the_address(monkeypatch):
def boom():
raise AssertionError("asked")
monkeypatch.setattr(_turn_chain, "this_host_address", boom)
chain = _turn_chain.Chain(relay_host="127.0.0.1")
try:
assert chain.relay_host == "127.0.0.1"
finally:
chain.close()
def test_there_is_one_copy_of_the_helper():
import pathlib
here = pathlib.Path(__file__).parent
for name in ("_turn_chain.py", "test_http3_through_the_proxy_e2e.py", "test_webrtc_realness.py"):
text = (here / name).read_text(encoding="utf-8")
assert '"192.0.2.1"' not in text, "%s has its own copy of the probe of the default route" % name
@@ -0,0 +1,76 @@
"""E2E: the engine never reads the host's hosts file (drivers\\etc\\hosts, /etc/hosts), with a proxy or without.
WHY. Firefox reads that file once, in the first moments of the parent process, to keep the names it holds out of the DoH
(`network.trr.exclude-etc-hosts`, default true in Mozilla's build). A name found there is then answered by the host: with a
proxy that is a name leaving by the machine's resolver, and with or without a proxy it is a value taken from the host
(the file is the host's, not the persona's). The engine declares `network.trr.exclude-etc-hosts` false by default, so the read
(DNSServiceBase::DoReadEtcHostsFile, which returns before building the path when the pref is false) never happens.
HOW IT IS SEEN. A late attach of a debugger cannot prove it (the read is at start-up, before any attach), so the browser is
launched with MOZ_LOG=sync,nsHostResolver:5 and MOZ_LOG_FILE=<dir>/moz-%PID.log (one file per process): the line the engine
writes when it reads the file is "Reading hosts file at <path>" (DNSServiceBase.cpp:121). The test asserts that no log of any
process of the browser contains it, and, as a control that the logging worked, that the parent process logged the start of
its resolver ("nsHostResolver::Init"). The environment of the test process reaches the browser through the product's launch
(the diagnostic runs of the owner pass MOZ_LOG the same way).
Red on an engine whose default is true (the round-2 binary reads it twice per parent process); green on one with the
default false (commit fd21b34813 of the engine).
"""
from __future__ import annotations
import glob
import os
import time
import pytest
from test_doh_through_the_proxy_e2e import ( # noqa: F401 (the hermetic session is autouse and imported by name; the
# other fixtures of the DoH e2e are in conftest.py)
_hermetic_session, _launch, _page_in, _text)
pytestmark = pytest.mark.e2e
_READ = b"Reading hosts file at"
_STARTED = b"nsHostResolver::Init"
#: Start-up tasks are in the first seconds; the page load and this pause let them all happen before the browser is closed.
SETTLE_S = 4.0
def _logs_of(directory):
return sorted(glob.glob(os.path.join(str(directory), "moz-*.log*")))
def _count(path, needle):
with open(path, "rb") as f:
return sum(1 for line in f if needle in line)
def _report(directory):
rows = []
for path in _logs_of(directory):
rows.append("%s: started=%d reads=%d" % (os.path.basename(path), _count(path, _STARTED), _count(path, _READ)))
return "\n ".join(rows) or "(no log file was written)"
@pytest.mark.parametrize("with_a_proxy", [True, False], ids=["launch_proxy", "no_proxy"])
def test_the_hosts_file_of_the_host_is_never_read(with_a_proxy, firefox_binary, doh, pages, gateway, watcher, tmp_path,
monkeypatch):
logs = tmp_path / "moz"
logs.mkdir()
monkeypatch.setenv("MOZ_LOG", "sync,nsHostResolver:5")
monkeypatch.setenv("MOZ_LOG_FILE", str(logs / "moz-%PID.log"))
gw = gateway("gw") if with_a_proxy else None
with _launch(firefox_binary, gw.proxy if gw else None) as browser:
context, page = _page_in(browser)
page.goto("about:blank")
time.sleep(SETTLE_S)
context.close()
watcher.stop()
report = _report(logs)
started = [p for p in _logs_of(logs) if _count(p, _STARTED)]
assert started, ("the control failed: no process logged the start of its resolver, so the logging did not work and an "
"empty result would prove nothing\n " + report)
reading = [p for p in _logs_of(logs) if _count(p, _READ)]
assert reading == [], ("the browser read the host's hosts file ('Reading hosts file at ...'): the default of "
"network.trr.exclude-etc-hosts must be false\n " + report)
@@ -35,17 +35,47 @@ def _connect_raw(proxy, target, authorization=None):
if authorization:
head += "Proxy-Authorization: %s\r\n" % authorization
s.sendall((head + "\r\n").encode())
# One byte at a time, so that not a byte of what follows the head is taken from the tunnel: a relay that sends the
# 200 and the first bytes of the far side together (a server that writes and closes at once) would otherwise lose them here.
data = b""
while b"\r\n\r\n" not in data:
chunk = s.recv(4096)
chunk = s.recv(1)
if not chunk:
break
data += chunk
lines = data.split(b"\r\n\r\n")[0].decode().split("\r\n")
lines = data.decode().split("\r\n\r\n")[0].split("\r\n")
headers = {k.strip().lower(): v.strip() for k, _, v in (l.partition(":") for l in lines[1:])}
return s, lines[0], headers
def test_what_follows_the_head_of_a_connect_answer_is_left_for_the_caller():
"""The answer and the first bytes of the tunnel can reach the socket in one segment (the far side writes and
closes at once): the caller reads them after the head, none was swallowed with it."""
listener = socket.socket()
listener.bind(("127.0.0.1", 0))
listener.listen(1)
def serve():
c, _ = listener.accept()
while b"\r\n\r\n" not in c.recv(4096):
pass
c.sendall(b"HTTP/1.1 200 Connection established\r\n\r\nhello")
c.close()
threading.Thread(target=serve, daemon=True).start()
class Stub:
port = listener.getsockname()[1]
s, status, _h = _connect_raw(Stub, "198.51.100.1:443")
try:
assert status.split()[1] == "200"
assert s.recv(10) == b"hello"
finally:
s.close()
listener.close()
def test_basic_is_base64_of_utf8_user_colon_password():
assert basic(USER, PASSWORD) == "Basic " + base64.b64encode("ferd:user:pässword".encode("utf-8")).decode()
@@ -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")
@@ -12,7 +12,6 @@ import errno
import socket
import subprocess
import sys
import threading
import time
import pytest
@@ -135,8 +134,20 @@ def _tcp_ask(port, name):
return data
def _udp_ask_at(address: str, port: int, name: str) -> bytes:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(3)
try:
s.sendto(ds.encode_query(name, ds.QTYPE_A, 0x004D), (address, port))
return s.recvfrom(4096)[0]
finally:
s.close()
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
@@ -147,6 +158,31 @@ def test_the_trap_counts_a_query_it_is_sent_and_refuses_what_it_cannot_answer():
assert trap.asked("LEAK.test.") and trap.names() == ["leak-tcp.test", "leak.test"]
def test_the_trap_goes_to_the_next_loopback_address_when_the_first_has_its_port_taken():
"""On a hosted runner something can hold 127.0.0.1:53 (or a wildcard of it): the trap takes the first loopback address
of TRAP_ADDRESSES it can bind, says which, and that is the address a resolv.conf is written with (run 43146661635: the
trap could not bind and eight tests ended in error at setup)."""
import _leaks
holder_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
holder_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
holder_tcp.bind(("127.0.0.1", 0))
port = holder_tcp.getsockname()[1]
try:
holder_udp.bind(("127.0.0.1", port))
except OSError:
raise
holder_tcp.listen(1)
# port != 0 is the case of port 53: the addresses are tried in order
with ResolverTrap(port=port, rewrite_resolv_conf=False) as trap:
assert trap.address != "127.0.0.1" and trap.address in _leaks.TRAP_ADDRESSES, trap.address
assert _udp_ask_at(trap.address, port, "leak.test")[3] & 0xF == ds.RCODE_REFUSED
finally:
holder_tcp.close()
holder_udp.close()
def test_the_trap_answers_the_names_it_is_given_over_udp_and_tcp():
with ResolverTrap({"page-d.test": "127.0.0.1"}, port=0, rewrite_resolv_conf=False) as trap:
for data in (_udp_ask(trap.port, "page-d.test"), _tcp_ask(trap.port, "page-d.test")):
@@ -162,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")
@@ -25,8 +25,12 @@ def test_build_env_carries_the_seed_declaration(seed):
@pytest.mark.unit
@pytest.mark.parametrize("proxy", [None, {"server": "socks5://127.0.0.1:1"}])
def test_a_session_declares_its_seed_network_with_or_without_a_proxy(proxy):
def test_a_session_declares_its_seed_network_with_or_without_a_proxy(monkeypatch, proxy):
from invisible_playwright import _session
from invisible_playwright.launcher import InvisiblePlaywright
# Nothing here launches a browser, and the engine is not what is asked about: under a local seal (the gate's, for a
# candidate) there is no engine to download, and resolving one is not this test's business.
monkeypatch.setattr(_session, "resolve_executable", lambda path: pathlib.Path("firefox"))
ip = InvisiblePlaywright(seed=42, proxy=proxy)
assert ip._build_env({})[NETWORK] == network_to_declare(42)
@@ -49,7 +53,7 @@ def test_the_server_default_session_declares_the_network_of_its_seed(monkeypatch
seeds.append(self.seed)
monkeypatch.setattr(InvisiblePlaywright, "__init__", spy)
monkeypatch.setattr(_session, "session_geo", lambda tz, px, loc: SessionGeo(
monkeypatch.setattr(_session, "session_geo", lambda tz, px, loc, **_kw: SessionGeo(
"America/New_York", None, locale=decide_session_locale("en-US")))
_prefs, env = _session.default_session(None, proxy)
assert env[NETWORK] == network_to_declare(seeds[0])
+193
View File
@@ -0,0 +1,193 @@
"""The judges and the gateway of the realness suite (``test_realness_behind_a_declared_exit_e2e.py``), held to what they say.
No browser: golden reads for the judges (each red case is one the e2e must catch), and the gateway and the site with a plain
socket client, so that "a connection the gateway did not open is a leak" is shown to work before a browser is trusted with it.
"""
from __future__ import annotations
import ipaddress
import socket
import struct
import pytest
import _realness_support as rs
pytestmark = pytest.mark.unit
EXIT = rs.EXITS["germany"]
HOST_LAN = "192.168.1.20"
GOOD_SDP = "v=0\r\no=- 1 0 IN IP4 0.0.0.0\r\nc=IN IP4 0.0.0.0\r\n"
MDNS_HOST = "candidate:0 1 UDP 2122252543 1460e928-16b3-4c66-80ad-04abcdef0000.local 54551 typ host"
SRFLX = "candidate:1 1 UDP 1686052863 %s 58555 typ srflx raddr 0.0.0.0 rport 0"
def _probe(*lines, sdp=GOOD_SDP):
return {"candidates": list(lines), "sdp": sdp + "".join("a=%s\r\n" % line for line in lines), "errors": []}
# ---------------------------------------------------------------------------------------------------------- the table
def test_every_declared_exit_is_a_public_ipv4_address_of_its_own():
addresses = list(rs.EXITS.values())
assert len(set(addresses)) == len(addresses) >= 6
for address in addresses:
parsed = ipaddress.ip_address(address)
assert parsed.version == 4 and parsed.is_global, address
# ---------------------------------------------------------------------------------------------------------- webrtc
def test_a_coherent_gather_with_mdns_hosts_and_the_exit_as_srflx_is_clean():
assert rs.webrtc_problems(_probe(MDNS_HOST, SRFLX % EXIT), EXIT, {HOST_LAN, "127.0.0.1"}) == []
@pytest.mark.parametrize("probe, fragment", [
(_probe("candidate:0 1 UDP 2122252543 %s 54551 typ host" % HOST_LAN), "not mDNS"),
(_probe(MDNS_HOST, SRFLX % rs.EXITS["japan"]), "server-reflexive"),
(_probe(MDNS_HOST, "candidate:2 1 UDP 2122252542 2001:db8::7 54552 typ host"), "IPv6"),
(_probe(MDNS_HOST, sdp="v=0\r\nc=IN IP4 0.0.0.0\r\na=ice-ufrag:x\r\na=candidate:9 1 UDP 1 10.0.0.8 5 typ host raddr "
"10.0.0.8 rport 5\r\n"), "private"),
({"candidates": [], "sdp": GOOD_SDP, "errors": [{"code": 701}]}, "no candidate"),
], ids=["raw_lan_host", "srflx_is_not_the_exit", "ipv6_behind_ipv4", "private_address_in_the_sdp", "no_candidate"])
def test_a_gather_that_shows_the_host_or_disagrees_with_the_exit_is_named(probe, fragment):
problems = rs.webrtc_problems(probe, EXIT, {HOST_LAN})
assert problems and any(fragment in p for p in problems), problems
def test_an_address_of_this_machines_interfaces_in_the_sdp_is_named_even_when_it_is_not_private():
public_own = rs.EXITS["japan"] # an interface can carry a public address: the exit of this test is another one
problems = rs.webrtc_problems(_probe(MDNS_HOST, sdp=GOOD_SDP + "a=x-note:%s\r\n" % public_own), EXIT, {public_own})
assert any("interfaces" in p for p in problems), problems
# --------------------------------------------------------------------------------------------------------------- zone
def test_the_offsets_of_a_zone_at_the_two_instants_follow_its_daylight_saving():
assert rs.expected_offsets("Asia/Kolkata") == [330, 330]
assert rs.expected_offsets("America/Los_Angeles") == [-480, -420]
assert rs.expected_offsets("Australia/Melbourne") == [660, 600] # the southern hemisphere runs the other way
assert rs.expected_offsets("Asia/Tokyo") == [540, 540]
def _read(zone, **override):
read = {"zone": zone, "offsets_by_date": rs.expected_offsets(zone), "offsets_by_intl": rs.expected_offsets(zone),
"language": "de", "languages": ["de", "en-US", "en"], "intl": "de"}
read.update(override)
return read
def test_a_page_and_a_worker_that_say_the_zone_of_the_exit_are_clean():
assert rs.timezone_problems({"page": _read("Europe/Berlin"), "worker": _read("Europe/Berlin")}, "Europe/Berlin") == []
@pytest.mark.parametrize("worker, fragment", [
(_read("Europe/London"), "worker: Intl says"),
(_read("Europe/Berlin", offsets_by_date=[0, 0]), "worker: offsets_by_date"),
(_read("Europe/Berlin", offsets_by_intl=[120, 60]), "worker: offsets_by_intl"),
], ids=["worker_zone", "clock_offset", "intl_offset"])
def test_a_worker_that_keeps_another_zone_or_offset_is_named(worker, fragment):
problems = rs.timezone_problems({"page": _read("Europe/Berlin"), "worker": worker}, "Europe/Berlin")
assert any(fragment in p for p in problems), problems
def test_the_older_canonical_name_of_a_zone_is_the_zone():
both = {"page": _read("Asia/Calcutta"), "worker": _read("Asia/Kolkata")}
assert rs.timezone_problems(both, "Asia/Kolkata") == []
# ---------------------------------------------------------------------------------------------------------- language
HEADER = "de,en-US;q=0.7,en;q=0.3"
HEADERS = {"/": HEADER, "/fetch": HEADER, "/worker-fetch": HEADER}
def test_a_language_everything_agrees_on_and_the_country_speaks_is_clean():
reads = {"page": _read("Europe/Berlin"), "worker": _read("Europe/Berlin")}
assert rs.language_problems(reads, HEADERS, "DE") == []
def test_a_country_that_is_not_in_the_table_is_checked_for_agreement_only():
reads = {"page": _read("Europe/Berlin"), "worker": _read("Europe/Berlin")}
assert rs.language_problems(reads, HEADERS, "ZZ") == []
assert rs.language_problems(reads, HEADERS, None) == []
@pytest.mark.parametrize("change, fragment", [
(lambda reads, headers: reads["worker"].update(languages=["en-US", "en"]), "worker: languages"),
(lambda reads, headers: reads["worker"].update(intl="en-US"), "worker: the Intl locale"),
(lambda reads, headers: reads["page"].update(language="en-US"), "navigator.language"),
(lambda reads, headers: headers.update({"/worker-fetch": "en-US,en;q=0.5"}), "/worker-fetch: Accept-Language"),
(lambda reads, headers: headers.update({"/fetch": None}), "carried no Accept-Language"),
], ids=["worker_languages", "worker_intl", "navigator_language", "worker_header", "no_header"])
def test_a_read_that_disagrees_with_the_others_is_named(change, fragment):
reads = {"page": _read("Europe/Berlin"), "worker": _read("Europe/Berlin")}
headers = dict(HEADERS)
change(reads, headers)
problems = rs.language_problems(reads, headers, "DE")
assert any(fragment in p for p in problems), problems
def test_a_language_the_country_does_not_speak_is_named():
reads = {"page": _read("Asia/Tokyo", language="ru", languages=["ru", "en"], intl="ru"),
"worker": _read("Asia/Tokyo", language="ru", languages=["ru", "en"], intl="ru")}
headers = {path: "ru,en;q=0.5" for path in HEADERS}
problems = rs.language_problems(reads, headers, "JP")
assert any("not plausible for JP" in p for p in problems), problems
# ------------------------------------------------------------------------------------------ the gateway and the site
def _ask(s):
s.sendall(b"GET /ip HTTP/1.0\r\nHost: x\r\nAccept-Language: de\r\n\r\n")
data = b""
while True:
chunk = s.recv(4096)
if not chunk:
break
data += chunk
return data.split(b"\r\n\r\n", 1)[1].decode()
def _get_ip_through(gateway_port, site_port):
s = socket.create_connection(("127.0.0.1", gateway_port), timeout=10)
try:
s.sendall(b"\x05\x01\x00")
assert s.recv(2) == b"\x05\x00"
s.sendall(b"\x05\x01\x00\x01" + socket.inet_aton("127.0.0.1") + struct.pack("!H", site_port))
reply = b""
while len(reply) < 10:
reply += s.recv(10 - len(reply))
assert reply[1] == 0, reply
return _ask(s)
finally:
s.close()
def test_the_site_tells_a_connection_of_the_gateway_from_a_direct_one(doh):
gateway = rs.ExitGateway("exit", doh, tcp_exit=EXIT, udp_exit=EXIT)
site = rs.Site(gateway)
try:
assert _get_ip_through(gateway.port, site.port) == EXIT
direct = socket.create_connection(("127.0.0.1", site.port), timeout=10)
try:
assert _ask(direct).startswith("DIRECT 127.0.0.1")
finally:
direct.close()
verdicts = [a.via_gateway for a in site.arrivals]
assert verdicts == [True, False], site.arrivals
problems = rs.ip_problems(EXIT, site.arrivals, [], EXIT, gateway.connects, site.port)
assert any("did not open" in p for p in problems), problems
assert site.headers_of("/ip") == {"/ip": "de"}
finally:
site.close()
gateway.close()
def test_a_run_through_the_gateway_only_is_clean_and_a_wrong_address_is_named(doh):
gateway = rs.ExitGateway("exit", doh, tcp_exit=EXIT, udp_exit=EXIT)
site = rs.Site(gateway)
try:
seen = _get_ip_through(gateway.port, site.port)
assert rs.ip_problems(seen, site.arrivals, [], EXIT, gateway.connects, site.port) == []
assert any("declared exit" in p for p in rs.ip_problems("192.0.2.1", site.arrivals, [], EXIT, gateway.connects, site.port))
assert any("past the gateway" in p for p in rs.ip_problems(seen, site.arrivals, ["192.0.2.9:443"], EXIT,
gateway.connects, site.port))
finally:
site.close()
gateway.close()
@@ -0,0 +1,192 @@
"""The resolver trap counts the questions of the user that runs the test, and only those (no browser, no root, no network).
Run 43188313516: /etc/resolv.conf is the machine's, and on a CI runner the agent of the runner asks for github.com,
api.github.com and its own orchestrator through it while the trap is up: 6 tests of the realness suite and 1 of the DoH
suite failed with "the browser asked the resolver of the machine: github.com ...". The trap now reads, for each question,
the user that owns the socket it came from (/proc/net on Linux) and counts only the user the test runs as. No list of names.
"""
from __future__ import annotations
import socket
import pytest
from _doh_servers import QTYPE_A, encode_query
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
#: The head and two rows of /proc/net/udp as the kernel writes them (uid is the 8th column).
UDP_TABLE = """ sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode ref pointer drops
120: 0100007F:0035 00000000:0000 07 00000000:00000000 00:00000000 00000000 0 0 12345 2 0000000000000000 0
305: 00000000:C350 00000000:0000 07 00000000:00000000 00:00000000 00000000 1001 0 67890 2 0000000000000000 0
"""
def _ask(trap: ResolverTrap, name: str):
"""One UDP question from this process to the trap; the answer, or None."""
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client:
client.settimeout(5)
client.sendto(encode_query(name, QTYPE_A), ("127.0.0.1", trap.port))
try:
return client.recvfrom(4096)[0]
except socket.timeout:
return None
def test_the_owner_of_a_socket_is_read_from_the_row_of_its_local_port():
assert uid_from_proc_net(UDP_TABLE, 0xC350) == 1001
assert uid_from_proc_net(UDP_TABLE, 0x35) == 0
def test_a_port_with_no_row_has_no_owner_and_a_garbled_row_is_skipped():
assert uid_from_proc_net(UDP_TABLE, 4242) is None
assert uid_from_proc_net("head\nnot a row\n 1: nonsense x y z a b c d\n", 80) is None
def test_the_owner_of_a_peer_is_none_off_linux_and_for_a_socket_that_is_gone(monkeypatch):
monkeypatch.setattr("_leaks.sys.platform", "win32")
assert owner_of_the_peer("udp", ("127.0.0.1", 40000)) is None
monkeypatch.setattr("_leaks.sys.platform", "linux")
def no_proc(*args, **kwargs):
raise OSError("no /proc here")
monkeypatch.setattr("_leaks.open", no_proc, raising=False)
assert owner_of_the_peer("udp", ("127.0.0.1", 40000)) is None
def test_a_question_of_the_user_of_the_test_is_counted():
with ResolverTrap({"page-d.test": "127.0.0.1"}, port=0, rewrite_resolv_conf=False, only_uid=1000,
owner_of=lambda protocol, peer: 1000) as trap:
assert _ask(trap, "page-d.test")
assert trap.names() == ["page-d.test"] and trap.foreign == []
def test_a_question_of_another_user_is_answered_and_listed_not_counted():
"""The agent of the runner (another user) asks for github.com: the browser is not blamed for it."""
with ResolverTrap({"github.com": "127.0.0.1"}, port=0, rewrite_resolv_conf=False, only_uid=0,
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, a.uid) for q, a in trap.foreign] == [("github.com", 1001)]
assert "github.com" in trap.describe() and "not counted" in trap.describe()
def test_a_question_whose_socket_is_gone_counts_as_the_browsers():
with ResolverTrap(port=0, rewrite_resolv_conf=False, only_uid=0, owner_of=lambda protocol, peer: None) as trap:
_ask(trap, "page-x.test")
assert trap.names() == ["page-x.test"] and trap.foreign == []
def test_the_kernel_names_this_process_as_the_owner_of_its_own_socket():
"""On Linux the row of /proc/net says the uid of this process for a socket this process holds; elsewhere there is
no such table and the answer is None (the question then counts as the browser's)."""
import os
import sys
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as mine:
mine.bind(("127.0.0.1", 0))
owner = owner_of_the_peer("udp", mine.getsockname())
assert owner == (os.geteuid() if sys.platform.startswith("linux") else None)
def test_the_owner_of_a_question_that_waits_for_its_answer_is_always_found():
"""Measured: a client that waits for the answer (every resolver of a browser and of a runner does) has its socket open
when the trap reads the table, which it does on receipt, before answering: 200 questions, 0 unreadable. A client that
sends and closes at once (nothing resolves like that) loses its row; its question then counts as the browser's, the
side a leak would be seen from (measured on Linux: 739 of 3000 such datagrams arrived, all unreadable)."""
import os
import sys
unreadable = []
def reading(protocol, peer):
uid = owner_of_the_peer(protocol, peer)
if uid is None:
unreadable.append(peer)
return uid
with ResolverTrap({"page-w.test": "127.0.0.1"}, port=0, rewrite_resolv_conf=False,
only_uid=os.geteuid() if hasattr(os, "geteuid") else 0, owner_of=reading) as trap:
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
@@ -9,6 +9,7 @@ from pathlib import Path
import pytest
import _trap_policy
from _leaks import ResolverTrap
pytestmark = pytest.mark.unit
@@ -20,8 +21,16 @@ def _e2e():
return importlib.import_module("test_doh_through_the_proxy_e2e")
def _conftest():
# the shared fixtures live in tests/conftest.py (the lint of F811: no file re-declares an imported fixture)
here = str(Path(__file__).resolve().parent)
if here not in sys.path:
sys.path.insert(0, here)
return importlib.import_module("conftest")
def _fixture_body(module):
fixture = module.trap
fixture = _conftest().trap
return getattr(fixture, "_get_wrapped_function", lambda: getattr(fixture, "__wrapped__"))()
@@ -41,8 +50,8 @@ def test_the_policy_names_the_reason_when_the_gate_requires_the_trap():
def test_the_trap_fixture_fails_when_the_gate_requires_it_and_it_cannot_run(monkeypatch):
module = _e2e()
monkeypatch.setenv("INVPW_REQUIRE_TRAP", "1")
monkeypatch.setattr(module.ResolverTrap, "available", False)
monkeypatch.setattr(module.ResolverTrap, "reason", "no root here")
monkeypatch.setattr(ResolverTrap, "available", False)
monkeypatch.setattr(ResolverTrap, "reason", "no root here")
with pytest.raises(pytest.fail.Exception, match="no root here"):
next(_fixture_body(module)())
@@ -50,12 +59,12 @@ def test_the_trap_fixture_fails_when_the_gate_requires_it_and_it_cannot_run(monk
def test_the_trap_fixture_fails_when_the_gate_requires_it_and_port_53_is_taken(monkeypatch):
module = _e2e()
monkeypatch.setenv("INVPW_REQUIRE_TRAP", "1")
monkeypatch.setattr(module.ResolverTrap, "available", True)
monkeypatch.setattr(ResolverTrap, "available", True)
def busy(self):
raise OSError("Address already in use")
monkeypatch.setattr(module.ResolverTrap, "__enter__", busy)
monkeypatch.setattr(ResolverTrap, "__enter__", busy)
with pytest.raises(pytest.fail.Exception, match="Address already in use"):
next(_fixture_body(module)())
@@ -63,15 +72,34 @@ def test_the_trap_fixture_fails_when_the_gate_requires_it_and_port_53_is_taken(m
def test_the_trap_fixture_yields_none_without_the_variable(monkeypatch):
module = _e2e()
monkeypatch.delenv("INVPW_REQUIRE_TRAP", raising=False)
monkeypatch.setattr(module.ResolverTrap, "available", False)
monkeypatch.setattr(ResolverTrap, "available", False)
assert next(_fixture_body(module)()) is None
def test_the_no_proxy_test_fails_when_the_gate_requires_the_trap_and_it_cannot_run(monkeypatch):
module = _e2e()
monkeypatch.setenv("INVPW_REQUIRE_TRAP", "1")
monkeypatch.setattr(module.ResolverTrap, "available", False)
monkeypatch.setattr(module.ResolverTrap, "reason", "no root here")
monkeypatch.setattr(ResolverTrap, "available", False)
monkeypatch.setattr(ResolverTrap, "reason", "no root here")
test = module.test_a_session_without_a_proxy_resolves_with_the_system_resolver
with pytest.raises(pytest.fail.Exception, match="no root here"):
test("unused-binary", None, None)
def test_a_closed_trap_gives_its_port_back_at_once():
"""The threads that answer on the trap's sockets end BEFORE the sockets are closed. On Linux a close() from another thread
does not wake a thread blocked in accept()/recvfrom(): the kernel kept the socket, still bound, so the port stayed taken after
the test and the next trap went to 127.0.0.2, then 127.0.0.3 ... until none of the eight was left ("Address already in use" on
all of them, run 43164943499). The old code fails here on Linux; no root is needed (a free port, no resolv.conf)."""
first = ResolverTrap(port=0, rewrite_resolv_conf=False)
first.__enter__()
port = first.port
assert port and first.address == "127.0.0.1"
first.__exit__(None, None, None)
again = ResolverTrap(port=port, rewrite_resolv_conf=False)
try:
again.__enter__()
assert again.address == "127.0.0.1", (
"the port %d of the closed trap was still taken: the second trap had to go to %s" % (port, again.address))
finally:
again.__exit__(None, None, None)
@@ -0,0 +1,277 @@
"""The position the core declares for a session reaches the engine for EVERY context, and the user's own wins.
The core computes the position (``SessionGeo.geolocation_override()``: latitude, longitude, accuracy) from the exit
and the seed. This package carries it as the standard ``geolocation`` context option, in the session's context defaults,
so ``Browser.setGeolocationOverride`` is sent for the default context, for each ``new_context``/``new_page`` and for each
context a remote client opens; a ``geolocation=`` given by the caller replaces it; and the permission is never granted
here (the engine answers only a page that was granted).
Hermetic: the engine is a recording connection, the geo step answers a made-up exit at 45.0 / 9.0.
"""
from __future__ import annotations
import ast
import pathlib
import pytest
from invisible_core import SessionGeo, decide_session_locale
from invisible_core._geoposition import declared_position
from invisible_core.juggler.connection import EventListeners
from invisible_playwright import InvisiblePlaywright, _session
from invisible_playwright._juggler import remote
from invisible_playwright._juggler.server import BrowserDispatcher, Server
from invisible_playwright.async_api import InvisiblePlaywright as AsyncInvisiblePlaywright
_PKG = pathlib.Path(__file__).resolve().parent.parent / "src" / "invisible_playwright"
EXIT = (45.0, 9.0)
def _geo_of(seed):
p = declared_position(seed, *EXIT)
return SessionGeo("Europe/Rome", "203.0.113.7", p.latitude, p.longitude,
decide_session_locale("it-IT"), p.accuracy)
def _past_geo(cls, seed=42, geo=None):
"""A session past the geo step of __enter__, without the network."""
obj = cls(seed=seed, timezone="Europe/Rome", locale="it-IT")
geo = geo if geo is not None else _geo_of(seed)
obj._timezone, obj._locale = geo.timezone, geo.locale
obj._geolocation = geo.geolocation_override()
return obj
class _Connection(EventListeners):
def __init__(self):
super().__init__()
self.sent = []
def startup_send(self, method, params=None):
return self.send(method, params, timeout=None)
def send(self, method, params=None, session=None, timeout=30):
self.sent.append((method, params))
return {"browserContextId": "CTX-%d" % len(self.sent)}
def _dispatcher():
conn = _Connection()
return conn, BrowserDispatcher(Server(), None, conn, "151.0")
def _overrides(conn):
return [p for m, p in conn.sent if m == "Browser.setGeolocationOverride"]
def _protocol_params(kwargs):
"""The session's defaults in the protocol's spelling, as the remote server and the Playwright client both give them."""
return {("timezoneId" if k == "timezone_id" else k): v for k, v in kwargs.items()}
# -- the defaults carry the declaration --------------------------------------------------------------------------
@pytest.mark.unit
@pytest.mark.parametrize("cls", [InvisiblePlaywright, AsyncInvisiblePlaywright])
def test_the_context_defaults_carry_the_declared_position(cls):
session = _past_geo(cls)
want = declared_position(42, *EXIT).as_override()
assert session._default_context_kwargs()["geolocation"] == want
@pytest.mark.unit
@pytest.mark.parametrize("cls", [InvisiblePlaywright, AsyncInvisiblePlaywright])
def test_when_the_coordinates_are_unavailable_the_defaults_carry_nothing(cls):
no_point = SessionGeo("Europe/Rome", "203.0.113.7", locale=decide_session_locale("it-IT"))
session = _past_geo(cls, geo=no_point)
assert "geolocation" not in session._default_context_kwargs()
@pytest.mark.unit
def test_a_session_that_has_not_decided_yet_declares_nothing():
assert "geolocation" not in InvisiblePlaywright(seed=42)._default_context_kwargs()
@pytest.mark.unit
def test_two_seeds_get_different_positions_and_one_seed_the_same():
a1 = _past_geo(InvisiblePlaywright, 1)._default_context_kwargs()["geolocation"]
a2 = _past_geo(InvisiblePlaywright, 1)._default_context_kwargs()["geolocation"]
b = _past_geo(InvisiblePlaywright, 2)._default_context_kwargs()["geolocation"]
assert a1 == a2 and a1 != b
# -- the command: the default context and every new context ----------------------------------------------------
@pytest.mark.unit
def test_the_default_context_gets_the_override_with_exactly_three_keys():
"""`launch_persistent_context` takes the defaults as context options and addresses the default context by absence."""
conn, browser = _dispatcher()
session = _past_geo(InvisiblePlaywright)
browser._apply_context_options(None, _protocol_params(session._default_context_kwargs()))
(params,) = _overrides(conn)
assert "browserContextId" not in params, "the default context is addressed by absence"
assert set(params) == {"geolocation"}
assert set(params["geolocation"]) == {"latitude", "longitude", "accuracy"}
assert params["geolocation"] == declared_position(42, *EXIT).as_override()
@pytest.mark.unit
def test_a_new_context_gets_the_override_for_its_own_id():
conn, browser = _dispatcher()
session = _past_geo(InvisiblePlaywright)
browser.op_new_context(_protocol_params(session._default_context_kwargs()))
(params,) = _overrides(conn)
assert params["browserContextId"].startswith("CTX-")
assert params["geolocation"] == declared_position(42, *EXIT).as_override()
@pytest.mark.unit
def test_the_permission_is_not_granted_by_us():
conn, browser = _dispatcher()
session = _past_geo(InvisiblePlaywright)
browser.op_new_context(_protocol_params(session._default_context_kwargs()))
assert not [m for m, _ in conn.sent if m in ("Browser.grantPermissions", "Browser.setPermissions")]
assert "permissions" not in session._default_context_kwargs()
# -- the sync and the async wrappers: new_context and new_page ---------------------------------------------------
class _StubContext:
def new_page(self, **kw):
return object()
def add_cookies(self, cookies):
pass
class _StubBrowser:
def __init__(self):
self.context_kwargs, self.page_kwargs = [], []
def new_context(self, **kw):
self.context_kwargs.append(kw)
return _StubContext()
def new_page(self, **kw):
self.page_kwargs.append(kw)
page = type("_Page", (), {})()
page.context = _StubContext()
return page
@pytest.mark.unit
def test_new_context_and_new_page_get_the_declared_position():
session = _past_geo(InvisiblePlaywright)
browser = _StubBrowser()
session._patch_new_context_defaults(browser)
browser.new_context()
browser.new_page()
want = declared_position(42, *EXIT).as_override()
assert browser.context_kwargs[0]["geolocation"] == want
assert browser.page_kwargs[0]["geolocation"] == want
@pytest.mark.unit
def test_a_geolocation_given_by_the_user_wins():
session = _past_geo(InvisiblePlaywright)
browser = _StubBrowser()
session._patch_new_context_defaults(browser)
mine = {"latitude": 10.0, "longitude": 20.0}
browser.new_context(geolocation=mine)
browser.new_page(geolocation=mine)
assert browser.context_kwargs[0]["geolocation"] == mine
assert browser.page_kwargs[0]["geolocation"] == mine
# ... and the next context, which names none, is back on the declared one: nothing leaks from the previous.
browser.new_context()
assert browser.context_kwargs[1]["geolocation"] == declared_position(42, *EXIT).as_override()
@pytest.mark.unit
def test_a_user_geolocation_reaches_the_engine_instead_of_the_declared_one():
conn, browser = _dispatcher()
session = _past_geo(InvisiblePlaywright)
params = _protocol_params(session._default_context_kwargs())
params["geolocation"] = {"latitude": 10.0, "longitude": 20.0, "accuracy": 5}
browser.op_new_context(params)
(sent,) = _overrides(conn)
assert sent["geolocation"] == {"latitude": 10.0, "longitude": 20.0, "accuracy": 5}
@pytest.mark.unit
def test_a_context_that_closes_leaves_no_override_for_the_next():
"""Each context carries its own id: the first (user's) and the second (declared) never share a command."""
conn, browser = _dispatcher()
session = _past_geo(InvisiblePlaywright)
mine = {"latitude": 10.0, "longitude": 20.0, "accuracy": 5}
first = _protocol_params(session._default_context_kwargs())
first["geolocation"] = mine
browser.op_new_context(first)
browser.op_new_context(_protocol_params(session._default_context_kwargs()))
one, two = _overrides(conn)
assert one["browserContextId"] != two["browserContextId"]
assert one["geolocation"] == mine
assert two["geolocation"] == declared_position(42, *EXIT).as_override()
# -- the served browser: a remote client's context gets the session defaults ------------------------------------------
@pytest.mark.unit
def test_a_remote_clients_context_gets_the_declared_position_and_its_own_wins():
session = _past_geo(InvisiblePlaywright)
defaults = remote._context_defaults(session, None)
assert defaults["geolocation"] == declared_position(42, *EXIT).as_override()
class _Browser:
guid = "browser"
endpoint = remote.RemoteEndpoint.__new__(remote.RemoteEndpoint)
endpoint.context_defaults = dict(defaults)
endpoint.context_options_override = False
endpoint.browser = _Browser()
endpoint._pages = iter(range(10))
plain = endpoint._prepared({"guid": "browser", "method": "newContext", "params": {}})
assert plain["params"]["geolocation"] == defaults["geolocation"]
mine = {"latitude": 10.0, "longitude": 20.0}
own = endpoint._prepared({"guid": "browser", "method": "newContext", "params": {"geolocation": mine}})
assert own["params"]["geolocation"] == mine
page = endpoint._prepared({"guid": "browser", "method": "newPage", "params": {}})
assert page["params"]["geolocation"] == defaults["geolocation"]
# -- the geo step is asked WITH the seed, in every entry --------------------------------------------------------
@pytest.mark.unit
def test_every_call_to_the_geo_step_hands_it_the_session_seed():
"""Without the seed the core declares nothing, so a call site that forgets it is a session with no position."""
sites = []
for path in _PKG.rglob("*.py"):
if "_pw" in path.relative_to(_PKG).parts:
continue
tree = ast.parse(path.read_text(encoding="utf-8"))
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
name = getattr(node.func, "id", getattr(node.func, "attr", ""))
if name in ("prepare_session_geo", "session_geo"):
sites.append((path.name, node.lineno, any(k.arg == "seed" for k in node.keywords)))
# asyncio.to_thread(prepare_session_geo, ...): the function is an argument
if name == "to_thread" and node.args and getattr(node.args[0], "id", "") == "prepare_session_geo":
sites.append((path.name, node.lineno, any(k.arg == "seed" for k in node.keywords)))
assert len(sites) >= 4, sites
assert [s for s in sites if not s[2]] == [], sites
@pytest.mark.unit
def test_the_session_geo_step_passes_the_seed_to_the_core(monkeypatch):
import invisible_core
seen = {}
def fake(timezone, proxy, locale, *, seed=None):
seen["seed"] = seed
return _geo_of(7)
# conftest's autouse patch replaced `_session.session_geo` with a fixed answer: undo it, the real one is under test.
monkeypatch.undo()
monkeypatch.setattr(invisible_core, "prepare_session_geo", fake)
_session.session_geo("auto", None, "auto", seed=7)
assert seen["seed"] == 7
@@ -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))
+6 -4
View File
@@ -83,8 +83,10 @@ def _resolve_through_doh(chain, name, qtype=QTYPE_A, target=DOH_BOOTSTRAP):
return payload
def test_a_client_walks_the_whole_road_and_the_turn_server_sees_the_gateways_exit():
with c.Chain(rtt_ms=20, relay_host="127.0.0.1") as chain:
@pytest.mark.parametrize("exit_host", [c.EXIT_HOST, "127.0.0.3"])
def test_a_client_walks_the_whole_road_and_the_turn_server_sees_the_gateways_exit(exit_host):
"""Whatever address the gateway's exit is (``exit_host``: the e2e of the chain by name gives it a documentation address held on lo)."""
with c.Chain(rtt_ms=20, relay_host="127.0.0.1", exit_host=exit_host) as chain:
# the name of the TURN server is asked of the DoH, through a CONNECT: the answer is an address
answer = _resolve_through_doh(chain, c.TURN_NAME)
assert socket.inet_ntoa(answer[-4:]) == c.TURN_IP
@@ -117,8 +119,8 @@ def test_a_client_walks_the_whole_road_and_the_turn_server_sees_the_gateways_exi
port = struct.unpack("!H", mapped[2:4])[0] ^ (c.MAGIC >> 16)
ip = socket.inet_ntoa(struct.pack("!I", struct.unpack("!I", mapped[4:8])[0] ^ c.MAGIC))
# the XOR-MAPPED-ADDRESS is the source the TURN server saw: the gateway's exit, not this client
assert ip == c.EXIT_HOST and (ip, port) in [(a[0], a[1]) for a in chain.turn.allocations]
assert {s[0] for s in chain.turn.seen} == {c.EXIT_HOST}
assert ip == exit_host and (ip, port) in [(a[0], a[1]) for a in chain.turn.allocations]
assert {s[0] for s in chain.turn.seen} == {exit_host}
# nothing was carried by name or to port 53: the only datagrams are the two Allocates, by address
assert [(h, p, a) for h, p, a, _t in chain.datagram_log] == [(c.TURN_IP, c.TURN_PORT, 1)] * 2
assert chain.refused == []
+113
View File
@@ -0,0 +1,113 @@
"""The helpers the e2e tests of the UDP line share work, without a browser (hermetic, loopback).
The core measures the UDP exit of a SOCKS5 proxy before it declares it (``invisible_core._udp_exit``), from the servers of the
launch parameter ``udp_stun_servers``. An e2e that expects the engine to use a relay is only as good as the measurement that
precedes it: if the gateway of the test did not answer the Binding the way the core asks it (a STUN request wrapped in the
SOCKS5 UDP header, to an IPv4 literal, through the ASSOCIATE), the road would be declared ``no`` and the engine would never
send the page's UDP there, and the e2e would fail for a reason that is not the product's. These tests hold the gateways of
``_socks_servers`` and the chain of ``_turn_chain`` to the real measurement of the core, and the helper that builds the list
to its form.
"""
from __future__ import annotations
import ipaddress
import pytest
import _turn_chain as chain_mod
from _socks_servers import EXIT, MEASURE_NUMBER, STUN_NUMBER, STUN_PORT, coherent, mismatched, silent_udp, tcp_only
from _udp_line import declared_udp, egress_by_proxy, measure_servers
from invisible_core import _geo, _udp_exit
pytestmark = pytest.mark.unit
@pytest.fixture(autouse=True)
def _fresh(monkeypatch):
monkeypatch.setattr(_udp_exit, "_cache", {})
def test_the_measure_servers_are_ip_port_ipv4_literals_that_the_core_takes():
for gateway in (coherent(), tcp_only(), mismatched(), silent_udp()):
with gateway:
servers = measure_servers(gateway)
assert servers and all(isinstance(entry, str) for entry in servers)
for entry in servers:
host, _, port = entry.rpartition(":")
assert ipaddress.ip_address(host).version == 4, entry
assert 1 <= int(port) <= 65535, entry
assert _udp_exit.stun_servers(servers), "the core refused the list the helper builds"
def test_the_measure_server_is_not_the_one_the_page_asks():
"""So that what the measurement sent through the relay is never mistaken for what the page sent."""
with coherent() as gateway:
assert measure_servers(gateway) == ["%s:%d" % (MEASURE_NUMBER, STUN_PORT)]
assert MEASURE_NUMBER != STUN_NUMBER
def test_the_helper_refuses_a_name_or_a_bad_port():
class Named:
measure_servers = ["stun.example.test:3478"]
class Ported:
measure_servers = ["198.51.100.6:0"]
for gateway in (Named(), Ported()):
with pytest.raises(ValueError):
measure_servers(gateway)
@pytest.mark.parametrize("make, verdict", [
(lambda: coherent(), "coherent"),
(lambda: coherent(user="alice", password="s3cret"), "coherent"),
(lambda: mismatched(), "no"),
(lambda: tcp_only(), "no"),
(lambda: silent_udp(), "unmeasured"),
], ids=["coherent", "coherent_with_credentials", "mismatched", "tcp_only", "silent_udp"])
def test_the_gateway_answers_the_core_measurement_the_way_its_name_says(make, verdict):
"""The real measurement of the core, against the gateway, asked at the server the helper hands out."""
with make() as gateway:
got = _udp_exit.measure_udp_exit(gateway.proxy, gateway.tcp_exit, udp_stun_servers=measure_servers(gateway),
budget=1.5)
assert got == verdict
if gateway.udp == "relay":
asked = {host for host, _port, _payload in gateway.datagrams}
assert asked == {MEASURE_NUMBER}, "the measurement asked %s; the page's server is not its business" % asked
def test_the_chain_answers_the_core_measurement_coherent():
"""The road of the whole-chain e2e (TURN by name, DoH, page): its relay answers a Binding to the helper's server with the
address its datagrams leave from, which is its TCP exit."""
with chain_mod.Chain(rtt_ms=0, relay_host="127.0.0.1") as chain:
assert chain.tcp_exit == chain_mod.EXIT_HOST
got = _udp_exit.measure_udp_exit(chain.proxy, chain.tcp_exit, udp_stun_servers=measure_servers(chain), budget=1.5)
assert got == "coherent"
# And the TCP exit the e2e hands the core is the chain's own: with any other address it would read ``no``.
other = _udp_exit.measure_udp_exit(chain.proxy, EXIT, udp_stun_servers=measure_servers(chain), budget=1.5)
assert other == "no"
def test_each_proxy_has_the_tcp_exit_of_its_own_gateway():
with coherent(exit_ip="203.0.113.7") as first, coherent(exit_ip="198.51.100.77") as second:
discover = egress_by_proxy(first, second)
assert discover(first.proxy) == "203.0.113.7"
assert discover(dict(second.proxy, username="x")) == "198.51.100.77"
assert discover(first.proxy, timeout=3) == "203.0.113.7"
with pytest.raises(AssertionError):
discover({"server": "socks5://127.0.0.1:1"})
with pytest.raises(AssertionError):
discover(None)
assert egress_by_proxy(first, direct="192.0.2.9")(None) == "192.0.2.9"
def test_what_the_launch_declared_is_what_the_core_measured_and_an_absent_measurement_is_not_unmeasured(monkeypatch):
with silent_udp() as mute, coherent(exit_ip="198.51.100.77") as good:
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(mute, good))
with pytest.raises(AssertionError):
declared_udp(mute.proxy, measure_servers(mute)) # nothing measured yet
assert _udp_exit.measure_proxy_udp(good.proxy, measure_servers(good)) == "coherent"
assert declared_udp(good.proxy, measure_servers(good)) == "coherent"
# a measurement the launch made with ANOTHER list is not this one
with pytest.raises(AssertionError):
declared_udp(good.proxy, ["198.51.100.8:3478"])
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more