Compare commits
90
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc6d861f62 | ||
|
|
8f8a191e9b | ||
|
|
eca6652f56 | ||
|
|
fbae6d54a4 | ||
|
|
836e16724e | ||
|
|
2ca4fa8084 | ||
|
|
8dc5c3745a | ||
|
|
ce65951227 | ||
|
|
766961dcdb | ||
|
|
eb203fc58c | ||
|
|
3f4ee5c61e | ||
|
|
5d0be75316 | ||
|
|
dbd2022e34 | ||
|
|
ac5a519244 | ||
|
|
f5d2ec81f9 | ||
|
|
6d1bd1047b | ||
|
|
ac75085d10 | ||
|
|
8ab1d3d68a | ||
|
|
b58edbf367 | ||
|
|
aad5ac38da | ||
|
|
ac62151198 | ||
|
|
94fd5740c8 | ||
|
|
174c6b8b88 | ||
|
|
4bf9b5e009 | ||
|
|
0af776766a | ||
|
|
f5234742e6 | ||
|
|
07018c00b7 | ||
|
|
b37287094e | ||
|
|
4d97eae291 | ||
|
|
a4e6c8f56d | ||
|
|
435d261ce4 | ||
|
|
8a42ed3676 | ||
|
|
2c6a93900f | ||
|
|
756f722d40 | ||
|
|
215f552a10 | ||
|
|
98da306330 | ||
|
|
b14f479e09 | ||
|
|
af48556777 | ||
|
|
5776836ab6 | ||
|
|
da0720364a | ||
|
|
c3295c5b12 | ||
|
|
a7b1acf732 | ||
|
|
8d6d6ae208 | ||
|
|
194ae6f042 | ||
|
|
dee362ea02 | ||
|
|
f8e5ff8700 | ||
|
|
e8b3efa8c9 | ||
|
|
b02f74ed58 | ||
|
|
b48592587f | ||
|
|
66e5b75cb6 | ||
|
|
8e4be5b67d | ||
|
|
69a9c60328 | ||
|
|
bd71ac2026 | ||
|
|
cba46aa042 | ||
|
|
55ce95a1ad | ||
|
|
a837e63a08 | ||
|
|
70f81bbb3a | ||
|
|
3a67051a92 | ||
|
|
112607291a | ||
|
|
38fb8b6877 | ||
|
|
2703b5fc97 | ||
|
|
323d272a32 | ||
|
|
b7f974788a | ||
|
|
3f372e4675 | ||
|
|
c3dad8b9e9 | ||
|
|
50f2e53c9c | ||
|
|
0a0a2f4efd | ||
|
|
8add8e4a42 | ||
|
|
89c7d3be3b | ||
|
|
241d156f1f | ||
|
|
d6dc3bf0ba | ||
|
|
74deb6a060 | ||
|
|
fa735a74e7 | ||
|
|
d6498e527b | ||
|
|
92712b1658 | ||
|
|
ab3247d359 | ||
|
|
4bf642a58a | ||
|
|
360a22887f | ||
|
|
2d31ecdfff | ||
|
|
6b67a514e5 | ||
|
|
f42d5ecd26 | ||
|
|
1f06722137 | ||
|
|
9f91d752e4 | ||
|
|
c820dd50f9 | ||
|
|
c6d3ded241 | ||
|
|
11db0d50b5 | ||
|
|
194035dec5 | ||
|
|
79b46cc0a2 | ||
|
|
8c926d9551 | ||
|
|
c65828d809 |
No files matched your search
+26
-20
@@ -113,6 +113,12 @@ jobs:
|
||||
sudo apt-get install -y xvfb
|
||||
# the fontconfig e2e trace the opens of the browser: strace is not in the runner image (setsid is, util-linux)
|
||||
sudo apt-get install -y strace
|
||||
# tests/test_security_state_engine_e2e.py, on a crash of the engine: a core file where kernel.core_pattern says, and gdb to read it (the test deletes the core and
|
||||
# uploads the backtrace with the evidence). Only a process that lifts its own core limit leaves a core, the runner's default limit is 0.
|
||||
sudo apt-get install -y gdb
|
||||
mkdir -p "$RUNNER_TEMP/invpw-cores"
|
||||
sudo sysctl -w kernel.core_pattern="$RUNNER_TEMP/invpw-cores/core.%e.%p"
|
||||
echo "INVPW_CORE_DIR=$RUNNER_TEMP/invpw-cores" >> "$GITHUB_ENV"
|
||||
sudo "$(which python)" -m playwright install-deps firefox
|
||||
# The security state is a ready directory of the repository (ci/security-state/, a result with no data, the sha256 in ci/security-state.pin.json): with
|
||||
# STEALTHFOX_SECURITY_STATE set the core neither downloads nor generates one. BEFORE `fetch`, which makes the state present (it would download and generate it).
|
||||
@@ -318,6 +324,11 @@ jobs:
|
||||
if: needs.core-on-index.outputs.available == 'true'
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 20
|
||||
# TEMP and TMP on D:\a\_temp (the runner's temp folder): the Firefox profiles land in TEMP and on C: they saturate the disk (queue up to 144,
|
||||
# latencies up to 4 s, parent main thread still 40-60 s). On the job, not in a step: `runner.temp` is not readable in a job's `env`.
|
||||
env:
|
||||
TEMP: 'D:\a\_temp'
|
||||
TMP: 'D:\a\_temp'
|
||||
# `run:` blocks are PowerShell on Windows unless said otherwise (e2e-hunt.yml had a ParserError on its first launch there).
|
||||
defaults:
|
||||
run:
|
||||
@@ -345,15 +356,22 @@ jobs:
|
||||
|
||||
# THE SAME e2e ON WINDOWS (Federico, 12/11: every test of the product runs on Linux AND Windows; where Windows behaves
|
||||
# differently the test adapts to the system). Before this, 562 of the 808 e2e had never run on Windows in any round. The census
|
||||
# of 12/11 (run 43307193708) took ~50 minutes in one job, so the files are split in four parts (the sorted list, every fourth
|
||||
# file: a split that does not move when a file is added elsewhere). Left out, by name, are the suites ci/required-suites.json
|
||||
# declares `linux_only` (the reason is on the row); tests/test_every_suite_runs_on_linux_and_windows.py holds both together.
|
||||
# of 12/11 (run 43307193708) took ~50 minutes in one job, so the files are split in four parts: the rows `wrapper.e2e.suite.windows.1`
|
||||
# to `.4` of ci/required-suites.json, balanced on the test times measured on Windows (a split that does not move when a file is added
|
||||
# elsewhere: a new file is added by hand to a row). Left out of the rows, by name, are the suites ci/required-suites.json declares
|
||||
# `linux_only` (the reason is on the row) and the tests that skip on Windows; tests/test_the_e2e_suite_is_accounted_for.py holds the
|
||||
# partition whole and tests/test_every_suite_runs_on_linux_and_windows.py holds both systems together.
|
||||
e2e-windows:
|
||||
name: e2e (windows, part ${{ matrix.part }})
|
||||
needs: core-on-index
|
||||
if: needs.core-on-index.outputs.available == 'true' && inputs.only != 'windows-control-a'
|
||||
runs-on: windows-2022
|
||||
timeout-minutes: 40
|
||||
# TEMP and TMP on D:\a\_temp (the runner's temp folder): the Firefox profiles land in TEMP and on C: they saturate the disk (queue up to 144,
|
||||
# latencies up to 4 s, parent main thread still 40-60 s). On the job, not in a step: `runner.temp` is not readable in a job's `env`.
|
||||
env:
|
||||
TEMP: 'D:\a\_temp'
|
||||
TMP: 'D:\a\_temp'
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -381,23 +399,11 @@ jobs:
|
||||
# The GeoIP database made by the repository, as on the Linux run (no download, the same bytes every run).
|
||||
- name: The GeoIP database (made by the repository, same bytes every run)
|
||||
run: python scripts/ci_lab_geoip.py build
|
||||
- name: The files of this part, without the linux_only suites
|
||||
run: |
|
||||
set -e
|
||||
python -m pytest --collect-only -q -m e2e -o addopts= -p no:cacheprovider 2>/dev/null | grep "::" | cut -d: -f1 | sort -u > "$RUNNER_TEMP/e2e_files.txt"
|
||||
python - "${{ matrix.part }}" "$RUNNER_TEMP" <<'PY'
|
||||
import json, os, sys
|
||||
part, tmp = int(sys.argv[1]), sys.argv[2]
|
||||
rows = json.load(open("ci/required-suites.json", encoding="utf-8"))
|
||||
left_out = [t for r in rows if r.get("linux_only") for t in r["tests"]]
|
||||
files = [l.strip() for l in open(os.path.join(tmp, "e2e_files.txt")) if l.strip()]
|
||||
files = [f for f in files if f not in left_out]
|
||||
mine = [f for i, f in enumerate(files) if i % 4 == part - 1]
|
||||
nodes = [t for t in left_out if "::" in t and t.split("::")[0] in mine]
|
||||
open(os.path.join(tmp, "e2e_args.txt"), "w").write("\n".join(mine + ["--deselect=" + n for n in nodes]) + "\n")
|
||||
print("%d e2e files, %d left out as linux_only, %d in part %d, %d node(s) deselected"
|
||||
% (len(files) + len([t for t in left_out if "::" not in t]), len(left_out), len(mine), part, len(nodes)))
|
||||
PY
|
||||
# The files of the part are the rows `wrapper.e2e.suite.windows.N` of ci/required-suites.json (files, and node ids where a file has tests that skip on
|
||||
# Windows or run in another suite): the same list the gate of the candidate runs on the engine under test, so what is measured here and there is one
|
||||
# partition. tests/test_the_e2e_suite_is_accounted_for.py holds it whole, and the suites declared `linux_only` are left out of it by name.
|
||||
- name: The files of this part (the row of the suite, in ci/required-suites.json)
|
||||
run: python scripts/ci_verdict.py args --required ci/required-suites.json --suite "wrapper.e2e.suite.windows.${{ matrix.part }}" --os windows > "$RUNNER_TEMP/e2e_args.txt"
|
||||
- name: Run this part of the e2e
|
||||
env:
|
||||
PYTHONUNBUFFERED: "1"
|
||||
|
||||
+11
-3
@@ -14,7 +14,15 @@
|
||||
{"id": "wrapper.e2e.fakeweb", "giro": "G2", "os": ["linux", "windows"], "min_tests": 4, "exact": true, "tests": ["tests/test_fakeweb_p2_e2e.py", "tests/test_fakeweb_p4_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The fake web, offline: our browser on the hard pages (profile P2: a reused routed page reaches networkidle every time, also under a load of three other browsers; the other site is another process) and on the 17-step journey of a person (profile P4), each judged against what stock Firefox does, as tests/fakeweb/pages.json declares it. 4 = 3 + 1. Stock itself is held to that declaration, and compared with ours step by step, by scripts/run_fakeweb.py in .github/workflows/fakeweb.yml. Needs the candidate binary (STEALTHFOX_E2E_BINARY)."},
|
||||
{"id": "wrapper.e2e.fontconfig", "giro": "G2", "os": ["linux"], "min_tests": 2, "exact": true, "tests": ["tests/test_the_parent_reads_the_bundle_from_fontconfig_s_cache_linux_e2e.py"], "marker": "e2e", "needs_root": false, "linux_only": "Fontconfig exists only on Linux: the parent of the engine shows <GRE>/fonts to it (FcConfigAppFontAddDir) to rebuild a font from a path and a face index. On Windows DirectWrite opens the file from its path, with no folder to scan and no cache to read, so this test has no Windows counterpart.", "note": "2 = (1) the stand-in that runs the engine under strace stays in the engine's place, as the core launches it (the leader of a process group of its own): a fake engine with a child, no browser; the process the launcher holds lives as long as the fake engine, and the group killed holds strace and the child (the stand-in that exec'd setsid forked and exited 0 at once: candidate 44161687675); (2) the warm launch of the parent reads the bundle from fontconfig's cache and does not scan it again (from firefox-66, engine_at_least). Two launches under strace with the same XDG_CACHE_HOME of the test, the first cold and the second warm: the cold parent opens every font file of <GRE>/fonts (the folder as the disk lists it) before any page and fontconfig writes its cache; the warm parent does not open every one of them, and it opens a *.cache-* file of fontconfig (a few files are opened to be used, so the verdict asks about the whole folder, as a scan does). Scan and drawing are told apart by position: only what the parent opens before the first page counts (the opens that draw are written as after_startup). Evidence in RUNNER_TEMP/invpw-evidence/fontconfig-cache: the interval and the number of opens of the bundle, the names of the files of the bundle each launch opened before the first page, the size of the cache file, the VmRSS of the parent after about:blank and after a page with every family, and a third launch with gfx.bundled-fonts.activate=0 (the behaviour before), which is evidence only. Needs strace on the runner: without it both are red, not skipped. No threshold."},
|
||||
{"id": "wrapper.unit.compositing", "giro": "G1", "os": ["linux", "windows"], "min_tests": 30, "exact": true, "tests": ["tests/test_the_page_bytes_reference_compares_decoded_pixels.py"], "marker": "unit", "needs_root": false, "note": "The helpers of wrapper.e2e.compositing on known inputs, no browser: the PNG compared on decoded pixels (another deBG chunk and compression are the same, one pixel is not, every scanline filter), the comparison with a reference (changed, missing and extra keys named, the entry to record), the type of an engine process, an engine process known by its executable and not by the name it gives itself (Linux), and the CPU of a window, and the shape of the committed Windows reference, and the box cut out of a screenshot (its pixels, a box outside the picture refused, written as a PNG and read back, two boxes told apart by a pixel that is named, the pixels that are not grey)."},
|
||||
{"id": "wrapper.unit.all.linux", "giro": "G1", "os": ["linux"], "min_tests": 2178, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_goto_follows_the_base_url.py", "tests/test_hook_wiring.py", "tests/test_imports.py", "tests/test_integration.py", "tests/test_juggler_event_buffer.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py", "tests/test_juggler_lives_in_the_core.py", "tests/test_juggler_posix_pipe.py", "tests/test_juggler_transport.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_launch_counters_run_on_github.py", "tests/test_launcher_config.py", "tests/test_launcher_helpers.py", "tests/test_motion_never_hides_a_programming_error.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_no_legacy_in_the_wrapper.py", "tests/test_no_override_leaves_the_persona_scheme.py", "tests/test_no_thread_is_started_on_the_reader.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pin.py", "tests/test_pin_dicts_are_valid.py", "tests/test_pinning_doc.py", "tests/test_pointer_server.py", "tests/test_popup_adoption_unit.py", "tests/test_prefs_composition_arm.py", "tests/test_preload_newtabLine truncated
|
||||
{"id": "wrapper.unit.all.windows", "giro": "G1", "os": ["windows"], "min_tests": 2179, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_goto_follows_the_base_url.py", "tests/test_hook_wiring.py", "tests/test_imports.py", "tests/test_integration.py", "tests/test_juggler_event_buffer.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py", "tests/test_juggler_lives_in_the_core.py", "tests/test_juggler_transport.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_launch_counters_run_on_github.py", "tests/test_launcher_config.py", "tests/test_launcher_helpers.py", "tests/test_motion_never_hides_a_programming_error.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_no_legacy_in_the_wrapper.py", "tests/test_no_override_leaves_the_persona_scheme.py", "tests/test_no_thread_is_started_on_the_reader.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pin.py", "tests/test_pin_dicts_are_valid.py", "tests/test_pinning_doc.py", "tests/test_pointer_server.py", "tests/test_popup_adoption_unit.py", "tests/test_prefs_composition_arm.py", "tests/test_prefs_composition_arm_on_windows.py", "tests/tLine truncated
|
||||
{"id": "wrapper.e2e.securitystate", "giro": "G2", "os": ["linux", "windows"], "min_tests": 4, "exact": true, "tests": ["tests/test_security_state_engine_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The security state the core declares, against the engine: the engine launched directly in its generate mode makes what it is given (the contract's result, security_state/ with the bytes of the full filter and of the delta, the core's own validation of it); a normal launch declares no pref of the mode and re-imports nothing; a certificate that Mozilla's CRLite test data say is revoked in a delta is refused at the first navigation (SEC_ERROR_REVOKED_CERTIFICATE) while a valid one loads, and the revoked one loads when the ready directory has no data; a ready directory with no or an empty security_state/ starts. Certificates made on the run (a fresh root trusted in cert9.db by the engine's own xpcshell, Mozilla's default test key as the key of CN=int), servers on loopback, no network. Red on firefox-67 (no generate mode)."}
|
||||
{"id": "wrapper.unit.all.linux", "giro": "G1", "os": ["linux"], "min_tests": 2260, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_suite_run.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_goto_follows_the_base_url.py", "tests/test_hook_wiring.py", "tests/test_imports.py", "tests/test_integration.py", "tests/test_juggler_event_buffer.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py", "tests/test_juggler_lives_in_the_core.py", "tests/test_juggler_posix_pipe.py", "tests/test_juggler_transport.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_launch_counters_run_on_github.py", "tests/test_launcher_config.py", "tests/test_launcher_helpers.py", "tests/test_motion_never_hides_a_programming_error.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_no_legacy_in_the_wrapper.py", "tests/test_no_override_leaves_the_persona_scheme.py", "tests/test_no_thread_is_started_on_the_reader.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pin.py", "tests/test_pin_dicts_are_valid.py", "tests/test_pinning_doc.py", "tests/test_pointer_server.py", "tests/test_popup_adoption_unit.py", "tests/test_prefs_composition_arm.pLine truncated
|
||||
{"id": "wrapper.unit.all.windows", "giro": "G1", "os": ["windows"], "min_tests": 2261, "exact": true, "tests": ["tests/test_a_162_message_is_read_like_a_161_one.py", "tests/test_a_click_makes_one_mousemove_at_its_point.py", "tests/test_a_closed_context_leaves_nothing_in_the_registry.py", "tests/test_a_closed_page_says_nothing.py", "tests/test_a_closed_pipe_is_a_closed_target.py", "tests/test_a_commit_at_any_point_of_the_hand_over_reaches_the_client_once.py", "tests/test_a_context_proxy_carries_its_measured_udp_exit.py", "tests/test_a_context_route_disables_the_cache.py", "tests/test_a_detached_frame_answers_detached.py", "tests/test_a_dialog_is_a_protocol_object.py", "tests/test_a_dialog_is_answered_after_a_pause.py", "tests/test_a_download_finished_before_it_was_announced_is_finished.py", "tests/test_a_failed_expect_carries_its_call_log.py", "tests/test_a_failed_launch_stops_the_display.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py", "tests/test_a_launch_gives_the_core_its_engine_for_the_security_state.py", "tests/test_a_launch_has_one_deadline.py", "tests/test_a_launch_without_a_session_gets_one.py", "tests/test_a_live_event_does_not_overtake_the_replay_of_a_new_page.py", "tests/test_a_module_that_leaves_a_browser_open_fails.py", "tests/test_a_new_page_waits_for_the_engine.py", "tests/test_a_non_finite_number_crosses_the_wire_as_a_tag.py", "tests/test_a_page_closed_before_its_announcement_is_not_announced.py", "tests/test_a_page_is_handed_over_only_when_the_engine_says_it_is_ready.py", "tests/test_a_path_leaves_as_one_stroke.py", "tests/test_a_port_number_is_held_until_it_is_used.py", "tests/test_a_request_and_a_response_are_light.py", "tests/test_a_request_says_what_it_is.py", "tests/test_a_session_ends_before_the_next_test_starts.py", "tests/test_a_stroke_is_judged_by_its_shape_not_its_length.py", "tests/test_a_unit_test_does_not_read_the_seal_of_the_job.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_expect_reads_its_value_once.py", "tests/test_async_api.py", "tests/test_browser_output_is_drained.py", "tests/test_ci_downloads_are_authenticated.py", "tests/test_ci_drive_gate_goes_through_the_core.py", "tests/test_ci_host_gate.py", "tests/test_ci_lab_geoip.py", "tests/test_ci_lab_geoip_verify.py", "tests/test_ci_lab_intermediates.py", "tests/test_ci_lab_security_state.py", "tests/test_ci_real_geoip_check.py", "tests/test_ci_real_geoip_exit_code.py", "tests/test_ci_runs_once_per_commit.py", "tests/test_ci_suite_run.py", "tests/test_ci_verdict.py", "tests/test_ci_workflows_build_the_geoip_database.py", "tests/test_ci_workflows_set_the_intermediates_list.py", "tests/test_ci_workflows_set_the_security_state.py", "tests/test_cli.py", "tests/test_click_rhythm.py", "tests/test_connect_does_not_start_threads_on_the_loop.py", "tests/test_context_locale_is_a_list.py", "tests/test_core_pin.py", "tests/test_cpu_by_type_window.py", "tests/test_cross_origin_iframe.py", "tests/test_cursor_dispatch.py", "tests/test_cursor_wiring.py", "tests/test_docs_name_the_mcp_repo_as_it_is.py", "tests/test_doh_session_prefs_unit.py", "tests/test_drag_motion.py", "tests/test_e2e_hermetic.py", "tests/test_element_handle_actions.py", "tests/test_every_order_of_the_events_of_a_popup_gives_one_page_event.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_refusal_is_declared.py", "tests/test_every_route_command_is_answered_may_fail.py", "tests/test_every_suite_runs_on_linux_and_windows.py", "tests/test_expose_binding_refusal.py", "tests/test_fakeweb_p4_report.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fixtures_name_why_the_package_is_missing.py", "tests/test_fork.py", "tests/test_frame_dispatch.py", "tests/test_geoip_used.py", "tests/test_goto_follows_the_base_url.py", "tests/test_hook_wiring.py", "tests/test_imports.py", "tests/test_integration.py", "tests/test_juggler_event_buffer.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py", "tests/test_juggler_lives_in_the_core.py", "tests/test_juggler_transport.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_launch_counters_run_on_github.py", "tests/test_launcher_config.py", "tests/test_launcher_helpers.py", "tests/test_motion_never_hides_a_programming_error.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_no_event_of_any_family_is_lost_by_the_hand_over.py", "tests/test_no_legacy_in_the_wrapper.py", "tests/test_no_override_leaves_the_persona_scheme.py", "tests/test_no_thread_is_started_on_the_reader.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pin.py", "tests/test_pin_dicts_are_valid.py", "tests/test_pinning_doc.py", "tests/test_pointer_server.py", "tests/test_popup_adoption_unit.py", "tests/test_prefs_composition_arm.py", "tests/test_prefs_compositioLine truncated
|
||||
{"id": "wrapper.e2e.securitystate", "giro": "G2", "os": ["linux", "windows"], "min_tests": 4, "exact": true, "tests": ["tests/test_security_state_engine_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The security state the core declares, against the engine: the engine launched directly in its generate mode makes what it is given (the contract's result, security_state/ with the bytes of the full filter and of the delta, the core's own validation of it); a normal launch declares no pref of the mode and re-imports nothing; a certificate that Mozilla's CRLite test data say is revoked in a delta is refused at the first navigation (SEC_ERROR_REVOKED_CERTIFICATE) while a valid one loads, and the revoked one loads when the ready directory has no data; a ready directory with no or an empty security_state/ starts. Certificates made on the run (a fresh root trusted in cert9.db by the engine's own xpcshell, Mozilla's default test key as the key of CN=int), servers on loopback, no network. Red on firefox-67 (no generate mode)."},
|
||||
{"id": "wrapper.e2e.suite.linux.1", "giro": "G2", "os": ["linux"], "min_tests": 376, "exact": true, "tests": ["tests/test_a_closed_browser_leaves_the_others_alone_e2e.py", "tests/test_a_context_that_ends_leaves_no_process_e2e.py", "tests/test_a_cors_preflight_is_not_a_request_of_the_page_e2e.py", "tests/test_a_declared_webgl_extension_survives_its_use_e2e.py", "tests/test_a_granted_permission_is_the_one_the_page_asks_for_e2e.py", "tests/test_a_launch_without_a_session_gets_one_e2e.py", "tests/test_a_left_documents_body_is_evicted_e2e.py", "tests/test_a_mouse_click_makes_one_mousemove_on_its_point_e2e.py", "tests/test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_e2e.py", "tests/test_a_popup_is_reported_when_the_engine_says_it_is_ready_as_playwright_does_e2e.py", "tests/test_a_screenshot_draws_the_text_of_the_bundled_fonts_as_the_content_does_e2e.py", "tests/test_a_served_browser_answers_a_plain_client_e2e.py", "tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_turn_name_over_tcp_goes_through_the_proxy_of_the_context_e2e.py", "tests/test_accept_language_on_the_wire_e2e.py", "tests/test_browser_output_is_drained.py", "tests/test_click_rhythm.py", "tests/test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py", "tests/test_control_a_selects_all_in_a_field_e2e.py", "tests/test_cross_origin_iframe.py", "tests/test_declared_host_network_e2e.py", "tests/test_detectors_e2e.py", "tests/test_e2e.py", "tests/test_element_handle_actions.py", "tests/test_element_screenshot_e2e.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_file_chooser.py", "tests/test_fingerprint_surface.py", "tests/test_fission_frames_history_and_processes_e2e.py", "tests/test_fission_frames_workers_storage_and_special_frames_e2e.py", "tests/test_frames_outlive_the_back_forward_cache_e2e.py", "tests/test_goto_networkidle_after_spa_e2e.py", "tests/test_goto_script_redirect_e2e.py", "tests/test_hidden_display_linux.py", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_the_ice_name_of_a_context_goes_by_the_proxy_of_that_context", "tests/test_ignore_https_errors_e2e.py", "tests/test_injected_node_surface.py", "tests/test_juggler_connection.py", "tests/test_juggler_posix_pipe.py", "tests/test_juggler_transport.py", "tests/test_navigation_across_processes_e2e.py", "tests/test_navigation_response.py", "tests/test_networkidle_reaches_the_client_e2e.py", "tests/test_oop_frame_element.py", "tests/test_oop_frame_geometry.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pointer_position.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_preload_newtab_turns_the_privileged_about_process_off_e2e.py", "tests/test_realness_behind_a_declared_exit_e2e.py", "tests/test_resolver_race_e2e.py", "tests/test_route_header_order_e2e.py", "tests/test_same_document_goto_e2e.py", "tests/test_screencast.py", "tests/test_screencast_stop_e2e.py", "tests/test_screenshot_looks_where_you_are.py", "tests/test_security_state_engine_e2e.py", "tests/test_service_worker.py", "tests/test_service_worker_controller_e2e.py", "tests/test_set_offline_e2e.py", "tests/test_shadow_trusted_input.py", "tests/test_strict_and_force.py", "tests/test_the_callers_code_is_not_counted_e2e.py", "tests/test_the_device_enumeration_takes_the_declared_time_e2e.py", "tests/test_the_engine_is_born_in_the_job_e2e.py::test_a_launch_scans_no_process_of_the_machine", "tests/test_the_engine_is_born_in_the_job_e2e.py::test_after_close_no_process_of_the_session_is_left", "tests/test_the_hosts_file_of_the_host_is_never_read_e2e.py", "tests/test_trial_does_not_act.py", "tests/test_turn_over_tcp_is_tried_for_real_e2e.py", "tests/test_ua_widget_not_selectable.py", "tests/test_voices_e2e.py", "tests/test_wait_for_function.py", "tests/test_webgl_draws_on_the_engine_s_own_gl_e2e.py", "tests/test_webgl_noise_active.py", "tests/test_webrtc_realness.py::test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_its_relay", "tests/test_webrtc_realness.py::test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server", "tests/test_webrtc_realness.py::test_a_host_with_ipv6_addresses_gathers_through_an_ipv4_relay", "tests/test_webrtc_realness.py::test_a_proxy_that_does_not_relay_udp_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_relay_never_answers_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_udp_leaves_from_another_address_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_not_blocked_behind_tcp_only_socks", "tests/test_webrtc_realness.py::test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far_away", "tests/test_webrtc_realness.py::test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context", "tests/test_webrtc_realness.py::test_two_contexts_with_two_proxies_each_gets_the_srflx_of_its_own"], "marker": "e2e", "needs_root": false, "windows_twin"Line truncated
|
||||
{"id": "wrapper.e2e.suite.linux.2", "giro": "G2", "os": ["linux"], "min_tests": 411, "exact": true, "tests": ["tests/test_a_click_waits_for_the_navigation_it_plans_e2e.py", "tests/test_a_context_init_script_runs_once_e2e.py", "tests/test_a_drag_keeps_its_buttons_pressed_e2e.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_goto_to_a_response_with_no_document_ends_e2e.py", "tests/test_a_keepalive_request_reaches_the_client_e2e.py", "tests/test_a_latin_letter_on_a_cyrillic_persona_e2e.py", "tests/test_a_page_cannot_probe_the_juggler_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_pointer_event_is_handled_before_the_call_returns_e2e.py", "tests/test_a_request_says_what_it_is_e2e.py", "tests/test_a_worker_comes_back_with_its_page_from_the_cache_e2e.py", "tests/test_actions_without_a_point.py", "tests/test_add_script_tag.py", "tests/test_an_isolated_page_and_the_next_e2e.py", "tests/test_bypass_csp_e2e.py", "tests/test_caller_world_handles_e2e.py", "tests/test_canvas_reads_as_drawn.py", "tests/test_canvas_render_stealth.py", "tests/test_context_locale_e2e.py", "tests/test_context_proxy_only_resolves_by_doh_e2e.py", "tests/test_doh_through_the_proxy_e2e.py", "tests/test_doh_under_stress_e2e.py", "tests/test_download_is_intercepted_e2e.py", "tests/test_drag_motion.py", "tests/test_expose_binding_e2e.py", "tests/test_fakeweb_p4_e2e.py", "tests/test_fingerprint_consistency.py", "tests/test_fission_frames_dialogs_downloads_popups_e2e.py", "tests/test_fission_frames_route_and_bindings_e2e.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fission_iframe_crash_e2e.py", "tests/test_fission_strategy1_bench.py", "tests/test_goto_to_the_same_url_e2e.py", "tests/test_http3_through_the_proxy_e2e.py", "tests/test_input_is_born_before_the_page_sees_it_e2e.py", "tests/test_juggler_actions.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py::test_a_javascript_that_THROWS_arrives_as_an_error_not_as_None", "tests/test_juggler_injected.py::test_actionability_DISTINGUISHES_instead_of_always_saying_yes", "tests/test_juggler_injected.py::test_reads_that_make_no_sense_are_REJECTED", "tests/test_juggler_injected.py::test_states_DISCRIMINATE_instead_of_always_saying_true", "tests/test_juggler_injected.py::test_the_DOM_READING_group", "tests/test_juggler_injected.py::test_the_selector_engines_respond", "tests/test_juggler_injected.py::test_the_text_reads", "tests/test_juggler_lifecycle_e2e.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_keyboard_rhythm.py", "tests/test_long_session_e2e.py", "tests/test_mouse.py", "tests/test_mouse_events_keep_their_values_e2e.py", "tests/test_new_page_defaults.py", "tests/test_popup_destinations_e2e.py", "tests/test_popup_pages.py", "tests/test_proxy_http_auth_e2e.py", "tests/test_proxy_reaches_the_browser.py", "tests/test_proxy_socks_auth_e2e.py", "tests/test_requestless_navigation.py", "tests/test_route_abort_code.py", "tests/test_route_e2e.py", "tests/test_route_post_data_e2e.py", "tests/test_route_sends_a_navigation_elsewhere_e2e.py", "tests/test_route_superseded_e2e.py", "tests/test_same_document_navigation.py", "tests/test_screenshot_of_text_returns_linux_e2e.py", "tests/test_scroll_into_view.py", "tests/test_scroll_only_if_needed_e2e.py", "tests/test_service_workers_blocked.py", "tests/test_set_input_files_payloads.py", "tests/test_software_compositing_is_declared_e2e.py", "tests/test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py", "tests/test_the_callers_code_runs_once_e2e.py", "tests/test_the_close_returns_when_the_browser_has_exited_e2e.py", "tests/test_the_favicon_stays_out_of_sight_e2e.py", "tests/test_the_font_list_is_the_bundle_e2e.py", "tests/test_the_parent_reads_the_bundle_from_fontconfig_s_cache_linux_e2e.py", "tests/test_the_scheme_is_the_personas_e2e.py", "tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_when_the_exit_of_the_lab_is_loopback", "tests/test_typing_a_character_without_a_key_e2e.py", "tests/test_wait_for_timeout.py", "tests/test_web_fonts_of_closed_contexts_e2e.py"], "marker": "e2e", "needs_root": false, "windows_twin": "wrapper.e2e.suite.windows.2", "note": "Part 2 of the whole e2e suite of the wrapper (every test that opens the browser: what e2e.yml runs on the published engine), on the engine under test, as two passes through scripts/ci_suite_run.py (4 browsers at once, then the wall_clock tests alone; no rerun). The files of the 2 rows of linux are the files of tests/ that tests/test_the_e2e_suite_is_accounted_for.py holds one by one: a file whole when every test of it is here, else its tests by name. Partition from the junits of runs 44942540063 and 44985244053, test time balanced (about 564 s of estimated wall time, 4 browsers). A new file is added by hand to a row of each system and the minimum of the row goes up by hand. Left out of every row, with the reason in the accounting test: the files and tests of wrapLine truncated
|
||||
{"id": "wrapper.e2e.suite.linux.3", "giro": "G2", "os": ["linux"], "min_tests": 239, "exact": true, "tests": ["tests/test_a_click_in_an_iframe_lands_at_the_frames_own_screen_origin_e2e.py", "tests/test_a_context_language_is_the_accept_language_of_every_request_e2e.py", "tests/test_a_goto_to_a_refused_port_ends_with_its_reason_e2e.py", "tests/test_a_launch_and_a_context_timezone_reach_the_page_e2e.py", "tests/test_a_popup_of_a_link_reaches_the_client_e2e.py", "tests/test_a_regional_indicator_pair_measures_the_same_first_and_after_other_families_e2e.py", "tests/test_audio_context_values_are_declared_e2e.py", "tests/test_audio_noise_e2e.py", "tests/test_audio_sample_rate_is_declared_e2e.py", "tests/test_bundle_font_names_e2e.py", "tests/test_canvas_create_pattern_projection_e2e.py", "tests/test_canvas_measure_text_metrics_e2e.py", "tests/test_css_media_reads_the_declared_screen_and_pointer_e2e.py", "tests/test_dom_iterables_from_evaluate_e2e.py", "tests/test_every_reader_of_a_webgl_canvas_agrees_e2e.py", "tests/test_fakeweb_p2_e2e.py", "tests/test_fission_frames_tree_input_and_pixels_e2e.py", "tests/test_focus_survives_os_deactivation_e2e.py", "tests/test_fullscreen_without_wm_e2e.py", "tests/test_geolocation_reads_nothing_of_the_host_windows_e2e.py", "tests/test_goto_and_every_way_it_is_stopped_e2e.py", "tests/test_hardware_values_are_declared_e2e.py", "tests/test_ipv6_literal_connect_e2e.py", "tests/test_moz_element_paints_a_webgl_canvas_as_drawn_e2e.py", "tests/test_native_line_endings_are_windows_e2e.py", "tests/test_nested_frame_actions.py", "tests/test_networkidle_through_a_served_browser_with_routes_e2e.py", "tests/test_nothing_leaves_but_the_proxy_e2e.py", "tests/test_nothing_of_a_context_leaves_but_through_its_proxy_e2e.py", "tests/test_page_element_atoms_run_in_a_sandbox_e2e.py", "tests/test_popup_geometry_is_the_declared_frame_e2e.py", "tests/test_script_cache_written_is_adopted_e2e.py", "tests/test_the_branding_a_page_loads_is_the_declared_archive_e2e.py", "tests/test_the_evaluated_code_has_no_debugger_name_e2e.py", "tests/test_the_launch_counter_is_one_plain_get_before_any_page_e2e.py", "tests/test_the_shutdown_ping_leaves_by_the_background_task_e2e.py", "tests/test_webgl_declared_parameters_e2e.py", "tests/test_webgl_shader_language_e2e.py", "tests/test_webgpu_adapter_is_declared_e2e.py", "tests/test_webgpu_canvas_readback_is_noised_e2e.py", "tests/test_webgpu_external_texture_e2e.py", "tests/test_window_occlusion_e2e.py"], "marker": "e2e", "needs_root": false, "windows_twin": "wrapper.e2e.suite.windows.3", "note": "Part 2 of the whole e2e suite of the wrapper (every test that opens the browser: what e2e.yml runs on the published engine), on the engine under test, as two passes through scripts/ci_suite_run.py (4 browsers at once, then the wall_clock tests alone; no rerun). The files of the 2 rows of linux are the files of tests/ that tests/test_the_e2e_suite_is_accounted_for.py holds one by one: a file whole when every test of it is here, else its tests by name. Partition from the junits of runs 44942540063 and 44985244053, test time balanced (about 565 s of estimated wall time, 4 browsers). A new file is added by hand to a row of each system and the minimum of the row goes up by hand. Left out of every row, with the reason in the accounting test: the files and tests of wrapper.e2e.udp.exit and wrapper.e2e.udp.sandbox (root and user namespaces, their own rows), the files of the round after the publication (tests/_post_publication.py), and the tests that skip on linux (a skip is red in the verdict)."},
|
||||
{"id": "wrapper.e2e.suite.windows.1", "giro": "G2", "os": ["windows"], "min_tests": 260, "exact": true, "tests": ["tests/test_a_click_waits_for_the_navigation_it_plans_e2e.py", "tests/test_a_closed_browser_leaves_the_others_alone_e2e.py", "tests/test_a_context_init_script_runs_once_e2e.py", "tests/test_a_goto_to_a_refused_port_ends_with_its_reason_e2e.py", "tests/test_a_granted_permission_is_the_one_the_page_asks_for_e2e.py", "tests/test_a_left_documents_body_is_evicted_e2e.py", "tests/test_a_page_cannot_probe_the_juggler_e2e.py", "tests/test_a_tiny_download_on_a_served_browser_is_saved_e2e.py", "tests/test_a_worker_comes_back_with_its_page_from_the_cache_e2e.py", "tests/test_browser_output_is_drained.py", "tests/test_canvas_create_pattern_projection_e2e.py", "tests/test_click_rhythm.py", "tests/test_closing_one_of_four_browsers_does_not_hold_the_loop_e2e.py", "tests/test_context_locale_e2e.py", "tests/test_context_proxy_only_resolves_by_doh_e2e.py", "tests/test_detectors_e2e.py", "tests/test_download_is_intercepted_e2e.py", "tests/test_e2e.py", "tests/test_element_handle_actions.py", "tests/test_every_page_draws_its_own_acts.py", "tests/test_every_reader_of_a_webgl_canvas_agrees_e2e.py", "tests/test_fission_identity_parity_e2e.py", "tests/test_fission_iframe_crash_e2e.py", "tests/test_focus_survives_os_deactivation_e2e.py", "tests/test_geolocation_reads_nothing_of_the_host_windows_e2e.py", "tests/test_goto_to_the_same_url_e2e.py", "tests/test_ignore_https_errors_e2e.py", "tests/test_juggler_actions.py", "tests/test_juggler_transport.py", "tests/test_keyboard_rhythm.py", "tests/test_moz_element_paints_a_webgl_canvas_as_drawn_e2e.py", "tests/test_nested_frame_actions.py", "tests/test_popups_reach_the_client_e2e.py", "tests/test_preload_newtab_turns_the_privileged_about_process_off_e2e.py", "tests/test_route_superseded_e2e.py", "tests/test_scroll_only_if_needed_e2e.py", "tests/test_security_state_engine_e2e.py", "tests/test_service_worker.py", "tests/test_service_workers_blocked.py", "tests/test_strict_and_force.py", "tests/test_the_engine_is_born_in_the_job_e2e.py", "tests/test_the_hosts_file_of_the_host_is_never_read_e2e.py", "tests/test_the_shutdown_ping_leaves_by_the_background_task_e2e.py", "tests/test_trial_does_not_act.py", "tests/test_ua_widget_not_selectable.py", "tests/test_webgpu_canvas_readback_is_noised_e2e.py"], "marker": "e2e", "needs_root": false, "linux_twin": "wrapper.e2e.suite.linux.1", "note": "Part 1 of the whole e2e suite of the wrapper (every test that opens the browser: what e2e.yml runs on the published engine), on the engine under test, as two passes through scripts/ci_suite_run.py (4 browsers at once, then the wall_clock tests alone; no rerun). The files of the 4 rows of windows are the files of tests/ that tests/test_the_e2e_suite_is_accounted_for.py holds one by one: a file whole when every test of it is here, else its tests by name. Partition from the junits of runs 44942540063 and 44985244053, test time balanced (about 609 s of estimated wall time, 4 browsers). A new file is added by hand to a row of each system and the minimum of the row goes up by hand. Left out of every row, with the reason in the accounting test: the files and tests of wrapper.e2e.udp.exit and wrapper.e2e.udp.sandbox (root and user namespaces, their own rows), the files of the round after the publication (tests/_post_publication.py), and the tests that skip on windows (a skip is red in the verdict)."},
|
||||
{"id": "wrapper.e2e.suite.windows.2", "giro": "G2", "os": ["windows"], "min_tests": 218, "exact": true, "tests": ["tests/test_a_goto_to_a_response_with_no_document_ends_e2e.py", "tests/test_a_latin_letter_on_a_cyrillic_persona_e2e.py", "tests/test_a_regional_indicator_pair_measures_the_same_first_and_after_other_families_e2e.py", "tests/test_a_turn_name_over_tcp_goes_through_the_proxy_of_the_context_e2e.py", "tests/test_add_script_tag.py", "tests/test_an_isolated_page_and_the_next_e2e.py", "tests/test_audio_context_values_are_declared_e2e.py", "tests/test_bundle_font_names_e2e.py", "tests/test_caller_world_handles_e2e.py", "tests/test_canvas_reads_as_drawn.py", "tests/test_canvas_render_stealth.py", "tests/test_css_media_reads_the_declared_screen_and_pointer_e2e.py", "tests/test_declared_host_network_e2e.py", "tests/test_expose_binding_e2e.py", "tests/test_fission_frames_dialogs_downloads_popups_e2e.py", "tests/test_fullscreen_without_wm_e2e.py", "tests/test_goto_networkidle_after_spa_e2e.py", "tests/test_goto_script_redirect_e2e.py", "tests/test_hidden_desktop.py", "tests/test_ice_names_by_the_context_proxy_e2e.py::test_the_ice_name_of_a_context_goes_by_the_proxy_of_that_context", "tests/test_juggler_lifecycle_e2e.py", "tests/test_key_delay_reaches_the_keyboard.py", "tests/test_long_session_e2e.py", "tests/test_mouse.py", "tests/test_native_line_endings_are_windows_e2e.py", "tests/test_navigation_across_processes_e2e.py", "tests/test_networkidle_reaches_the_client_e2e.py", "tests/test_nothing_leaves_but_the_proxy_e2e.py", "tests/test_nothing_of_a_context_leaves_but_through_its_proxy_e2e.py", "tests/test_oop_frame_geometry.py", "tests/test_proxy_socks_auth_e2e.py", "tests/test_resolver_race_e2e.py", "tests/test_route_e2e.py", "tests/test_screencast_stop_e2e.py", "tests/test_the_branding_a_page_loads_is_the_declared_archive_e2e.py", "tests/test_the_device_enumeration_takes_the_declared_time_e2e.py", "tests/test_the_evaluated_code_has_no_debugger_name_e2e.py", "tests/test_the_favicon_stays_out_of_sight_e2e.py", "tests/test_the_font_list_is_the_bundle_e2e.py", "tests/test_the_scheme_is_the_personas_e2e.py", "tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_when_the_exit_of_the_lab_is_loopback", "tests/test_turn_over_tcp_is_tried_for_real_e2e.py", "tests/test_voices_e2e.py", "tests/test_wait_for_function.py", "tests/test_wait_for_timeout.py", "tests/test_web_fonts_of_closed_contexts_e2e.py", "tests/test_webrtc_realness.py::test_a_gateway_that_is_far_away_still_gives_the_page_a_srflx_born_through_its_relay", "tests/test_webrtc_realness.py::test_a_gather_after_the_page_loaded_through_the_gateway_costs_only_the_road_to_the_server", "tests/test_webrtc_realness.py::test_a_host_with_ipv6_addresses_gathers_through_an_ipv4_relay", "tests/test_webrtc_realness.py::test_a_proxy_that_does_not_relay_udp_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_relay_never_answers_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_a_proxy_whose_udp_leaves_from_another_address_gives_no_srflx_at_all", "tests/test_webrtc_realness.py::test_not_blocked_behind_tcp_only_socks", "tests/test_webrtc_realness.py::test_the_first_candidate_of_a_gather_does_not_wait_for_a_gateway_that_is_far_away", "tests/test_webrtc_realness.py::test_the_turn_over_tcp_of_a_context_goes_through_the_proxy_of_that_context", "tests/test_webrtc_realness.py::test_two_contexts_with_two_proxies_each_gets_the_srflx_of_its_own"], "marker": "e2e", "needs_root": false, "linux_twin": "wrapper.e2e.suite.linux.2", "note": "Part 2 of the whole e2e suite of the wrapper (every test that opens the browser: what e2e.yml runs on the published engine), on the engine under test, as two passes through scripts/ci_suite_run.py (4 browsers at once, then the wall_clock tests alone; no rerun). The files of the 4 rows of windows are the files of tests/ that tests/test_the_e2e_suite_is_accounted_for.py holds one by one: a file whole when every test of it is here, else its tests by name. Partition from the junits of runs 44942540063 and 44985244053, test time balanced (about 610 s of estimated wall time, 4 browsers). A new file is added by hand to a row of each system and the minimum of the row goes up by hand. Left out of every row, with the reason in the accounting test: the files and tests of wrapper.e2e.udp.exit and wrapper.e2e.udp.sandbox (root and user namespaces, their own rows), the files of the round after the publication (tests/_post_publication.py), and the tests that skip on windows (a skip is red in the verdict)."},
|
||||
{"id": "wrapper.e2e.suite.windows.3", "giro": "G2", "os": ["windows"], "min_tests": 273, "exact": true, "tests": ["tests/test_a_click_in_an_iframe_lands_at_the_frames_own_screen_origin_e2e.py", "tests/test_a_context_that_ends_leaves_no_process_e2e.py", "tests/test_a_cors_preflight_is_not_a_request_of_the_page_e2e.py", "tests/test_a_launch_without_a_session_gets_one_e2e.py", "tests/test_a_mouse_click_makes_one_mousemove_on_its_point_e2e.py", "tests/test_a_page_over_ipv6_gathers_on_a_machine_declared_without_it_e2e.py", "tests/test_a_served_browser_answers_a_plain_client_e2e.py", "tests/test_actions_without_a_point.py", "tests/test_audio_noise_e2e.py", "tests/test_audio_sample_rate_is_declared_e2e.py", "tests/test_bypass_csp_e2e.py", "tests/test_control_a_selects_all_in_a_field_e2e.py", "tests/test_cross_origin_iframe.py", "tests/test_dom_iterables_from_evaluate_e2e.py", "tests/test_drag_motion.py", "tests/test_element_screenshot_e2e.py", "tests/test_fakeweb_p4_e2e.py", "tests/test_fingerprint_consistency.py", "tests/test_first_launch_from_a_new_path.py", "tests/test_fission_frames_history_and_processes_e2e.py", "tests/test_fission_frames_workers_storage_and_special_frames_e2e.py", "tests/test_fission_strategy1_bench.py", "tests/test_goto_and_every_way_it_is_stopped_e2e.py", "tests/test_http3_through_the_proxy_e2e.py", "tests/test_input_is_born_before_the_page_sees_it_e2e.py", "tests/test_ipv6_literal_connect_e2e.py", "tests/test_networkidle_through_a_served_browser_with_routes_e2e.py", "tests/test_page_number_follows_the_call.py", "tests/test_persistent_profile_keeps_state.py", "tests/test_pointer_position.py", "tests/test_popup_destinations_e2e.py", "tests/test_popup_pages.py", "tests/test_proxy_http_auth_e2e.py", "tests/test_requestless_navigation.py", "tests/test_route_abort_code.py", "tests/test_route_post_data_e2e.py", "tests/test_same_document_navigation.py", "tests/test_screencast.py", "tests/test_screenshot_looks_where_you_are.py", "tests/test_service_worker_controller_e2e.py", "tests/test_set_input_files_payloads.py", "tests/test_set_offline_e2e.py", "tests/test_the_callers_code_is_not_counted_e2e.py", "tests/test_the_callers_code_runs_once_e2e.py", "tests/test_the_close_returns_when_the_browser_has_exited_e2e.py", "tests/test_the_launch_counter_is_one_plain_get_before_any_page_e2e.py", "tests/test_webgl_declared_parameters_e2e.py", "tests/test_webgl_shader_language_e2e.py", "tests/test_webgpu_adapter_is_declared_e2e.py", "tests/test_webgpu_external_texture_e2e.py"], "marker": "e2e", "needs_root": false, "linux_twin": "wrapper.e2e.suite.linux.1", "note": "Part 3 of the whole e2e suite of the wrapper (every test that opens the browser: what e2e.yml runs on the published engine), on the engine under test, as two passes through scripts/ci_suite_run.py (4 browsers at once, then the wall_clock tests alone; no rerun). The files of the 4 rows of windows are the files of tests/ that tests/test_the_e2e_suite_is_accounted_for.py holds one by one: a file whole when every test of it is here, else its tests by name. Partition from the junits of runs 44942540063 and 44985244053, test time balanced (about 610 s of estimated wall time, 4 browsers). A new file is added by hand to a row of each system and the minimum of the row goes up by hand. Left out of every row, with the reason in the accounting test: the files and tests of wrapper.e2e.udp.exit and wrapper.e2e.udp.sandbox (root and user namespaces, their own rows), the files of the round after the publication (tests/_post_publication.py), and the tests that skip on windows (a skip is red in the verdict)."},
|
||||
{"id": "wrapper.e2e.suite.windows.4", "giro": "G2", "os": ["windows"], "min_tests": 270, "exact": true, "tests": ["tests/test_a_context_language_is_the_accept_language_of_every_request_e2e.py", "tests/test_a_declared_webgl_extension_survives_its_use_e2e.py", "tests/test_a_drag_keeps_its_buttons_pressed_e2e.py", "tests/test_a_field_is_typed_after_a_pause.py", "tests/test_a_keepalive_request_reaches_the_client_e2e.py", "tests/test_a_launch_and_a_context_timezone_reach_the_page_e2e.py", "tests/test_a_page_that_moves_on_e2e.py", "tests/test_a_pointer_event_is_handled_before_the_call_returns_e2e.py", "tests/test_a_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_a_request_says_what_it_is_e2e.py", "tests/test_a_screenshot_draws_the_text_of_the_bundled_fonts_as_the_content_does_e2e.py", "tests/test_accept_language_on_the_wire_e2e.py", "tests/test_canvas_measure_text_metrics_e2e.py", "tests/test_doh_through_the_proxy_e2e.py", "tests/test_doh_under_stress_e2e.py", "tests/test_fakeweb_p2_e2e.py", "tests/test_file_chooser.py", "tests/test_fingerprint_surface.py", "tests/test_fission_frames_route_and_bindings_e2e.py", "tests/test_fission_frames_tree_input_and_pixels_e2e.py", "tests/test_frames_outlive_the_back_forward_cache_e2e.py", "tests/test_hardware_values_are_declared_e2e.py", "tests/test_injected_node_surface.py", "tests/test_juggler_connection.py", "tests/test_juggler_event_listeners.py", "tests/test_juggler_injected.py::test_a_javascript_that_THROWS_arrives_as_an_error_not_as_None", "tests/test_juggler_injected.py::test_actionability_DISTINGUISHES_instead_of_always_saying_yes", "tests/test_juggler_injected.py::test_reads_that_make_no_sense_are_REJECTED", "tests/test_juggler_injected.py::test_states_DISCRIMINATE_instead_of_always_saying_true", "tests/test_juggler_injected.py::test_the_DOM_READING_group", "tests/test_juggler_injected.py::test_the_selector_engines_respond", "tests/test_juggler_injected.py::test_the_text_reads", "tests/test_mouse_events_keep_their_values_e2e.py", "tests/test_navigation_response.py", "tests/test_new_page_defaults.py", "tests/test_oop_frame_element.py", "tests/test_page_element_atoms_run_in_a_sandbox_e2e.py", "tests/test_popup_geometry_is_the_declared_frame_e2e.py", "tests/test_proxy_reaches_the_browser.py", "tests/test_realness_behind_a_declared_exit_e2e.py", "tests/test_route_header_order_e2e.py", "tests/test_route_sends_a_navigation_elsewhere_e2e.py", "tests/test_same_document_goto_e2e.py", "tests/test_script_cache_written_is_adopted_e2e.py", "tests/test_scroll_into_view.py", "tests/test_shadow_trusted_input.py", "tests/test_software_compositing_is_declared_e2e.py", "tests/test_the_association_is_ready_when_the_peerconnection_is_born_e2e.py", "tests/test_typing_a_character_without_a_key_e2e.py", "tests/test_webgl_noise_active.py", "tests/test_window_occlusion_e2e.py"], "marker": "e2e", "needs_root": false, "linux_twin": "wrapper.e2e.suite.linux.2", "note": "Part 4 of the whole e2e suite of the wrapper (every test that opens the browser: what e2e.yml runs on the published engine), on the engine under test, as two passes through scripts/ci_suite_run.py (4 browsers at once, then the wall_clock tests alone; no rerun). The files of the 4 rows of windows are the files of tests/ that tests/test_the_e2e_suite_is_accounted_for.py holds one by one: a file whole when every test of it is here, else its tests by name. Partition from the junits of runs 44942540063 and 44985244053, test time balanced (about 609 s of estimated wall time, 4 browsers). A new file is added by hand to a row of each system and the minimum of the row goes up by hand. Left out of every row, with the reason in the accounting test: the files and tests of wrapper.e2e.udp.exit and wrapper.e2e.udp.sandbox (root and user namespaces, their own rows), the files of the round after the publication (tests/_post_publication.py), and the tests that skip on windows (a skip is red in the verdict)."},
|
||||
{"id": "wrapper.e2e.suite.windows.control_a", "giro": "G2", "os": ["windows"], "min_tests": 20, "exact": true, "tests": ["tests/test_control_a_selects_all_in_a_field_e2e.py"], "marker": "e2e", "needs_root": false, "linux_twin": "wrapper.e2e.suite.linux.1", "note": "The keyboard shortcut Control+A selects all in a field (5 ways to press it x an input and a textarea, in-process and served to the stock client), alone on its own Windows runner (windows-latest), as e2e.yml runs it on the published engine: the Windows keyboard of a real user is what it needs. The same file is in one of wrapper.e2e.suite.windows.1..4 and in wrapper.e2e.suite.linux.1."}
|
||||
]
|
||||
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run ONE row of the whole-e2e suite against a binary, for the candidate's gate, and write ONE junit for the judge.
|
||||
|
||||
ci_suite_run.py --required ci/required-suites.json --suite wrapper.e2e.suite.linux.1 --os linux --binary FF --junit result/x.xml
|
||||
|
||||
The run is the run of ``scripts/run_e2e.py`` (``invisible_core.testing.e2e``: the two passes, ``-m "e2e and not wall_clock"`` with 4 browsers at once and then
|
||||
``-m "e2e and wall_clock"`` alone, ``--dist loadfile``, the deadline per test, no rerun) on the files and node ids of the row; this script does not copy it, it calls it.
|
||||
What it adds is the end: that run writes one junit per pass, and the judge (``scripts/ci_verdict.py judge``) reads one. The two are merged into ONE xunit2 file, every
|
||||
testcase as pytest wrote it (``classname`` kept, no ``file``/``line``).
|
||||
|
||||
The exit code is 0 when the passes reached their end, red tests included: the verdict is the judge's, and a failed test is a line of its list, not a reason to lose the
|
||||
junit. It is not 0 when a pass did not run to its end (interrupted, an internal error, a usage error: the code of that pass) or when no junit was written at all.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import copy
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
from typing import Callable, Optional, Sequence
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import ci_verdict # noqa: E402 (the judge: the row is read the way it reads it)
|
||||
|
||||
#: pytest's exit codes that mean "the pass reached its end": all passed, some failed, nothing collected (a client with no `wall_clock` test has an empty pass).
|
||||
_REACHED_THE_END = (0, 1, 5)
|
||||
|
||||
|
||||
def row_arguments(required: str, suite: str, os_name: str) -> list:
|
||||
"""The files and node ids of the row, in its order (what ``ci_verdict.py args`` prints, without the marker: the passes bring their own)."""
|
||||
return list(ci_verdict.find_suite(ci_verdict.load_required(required), suite, os_name)["tests"])
|
||||
|
||||
|
||||
def pass_junits(directory: Path, procs: str = "4") -> list:
|
||||
"""The junit file of each pass of the run, in the order of the passes (``invisible_core.testing.e2e`` names them)."""
|
||||
from invisible_core.testing import e2e
|
||||
|
||||
return [e2e.junit_file(Path(directory), selection) for _width, selection in e2e.passes(procs)]
|
||||
|
||||
|
||||
def merge_junits(paths: Sequence, out: Path) -> int:
|
||||
"""Write ONE xunit2 junit with every testcase of the junit files that exist, in the order given. -> the number of testcases.
|
||||
|
||||
The counts of the testsuite are those of the testcases written, not the sum of the headers read: a header that disagrees with its own cases is not copied.
|
||||
A path that does not exist is a pass that wrote nothing (it is not an error here: the judge counts what is in the file)."""
|
||||
cases = []
|
||||
for path in paths:
|
||||
if not Path(path).is_file():
|
||||
continue
|
||||
cases += [copy.deepcopy(c) for c in ET.parse(path).getroot().iter("testcase")]
|
||||
tags = [{child.tag for child in c} for c in cases]
|
||||
failures = sum(1 for t in tags if "failure" in t and "error" not in t)
|
||||
errors = sum(1 for t in tags if "error" in t)
|
||||
skipped = sum(1 for t in tags if "skipped" in t and not ({"failure", "error"} & t))
|
||||
seconds = sum(float(c.get("time") or 0) for c in cases)
|
||||
suite = ET.Element("testsuite", {"name": "pytest", "errors": str(errors), "failures": str(failures), "skipped": str(skipped),
|
||||
"tests": str(len(cases)), "time": "%.3f" % seconds})
|
||||
suite.extend(cases)
|
||||
root = ET.Element("testsuites", {"name": "pytest tests"})
|
||||
root.append(suite)
|
||||
out = Path(out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
ET.ElementTree(root).write(out, encoding="utf-8", xml_declaration=True)
|
||||
return len(cases)
|
||||
|
||||
|
||||
def run(required: str, suite: str, os_name: str, binary: str, junit: str, *, repo: Path, procs: Optional[str] = None,
|
||||
run_e2e: Optional[Callable] = None, junit_directory: Optional[Path] = None) -> int:
|
||||
"""Run the row and write the merged junit. ``run_e2e`` is ``invisible_core.testing.e2e.main`` (a fake in the unit tests)."""
|
||||
from invisible_core.testing import e2e
|
||||
|
||||
run_e2e = run_e2e or e2e.main
|
||||
arguments = row_arguments(required, suite, os_name)
|
||||
directory = Path(junit_directory or tempfile.mkdtemp(prefix="invpw-suite-junit-"))
|
||||
# the core reads the directory of the junit from the environment (its own order: this variable, the watchdog's folder, the checkout): one name, set for this run
|
||||
before = os.environ.get(e2e.JUNIT_DIR_ENV)
|
||||
os.environ[e2e.JUNIT_DIR_ENV] = str(directory)
|
||||
try:
|
||||
code = run_e2e([binary] + (["-n", procs] if procs else []) + arguments, repo)
|
||||
finally:
|
||||
if before is None:
|
||||
os.environ.pop(e2e.JUNIT_DIR_ENV, None)
|
||||
else:
|
||||
os.environ[e2e.JUNIT_DIR_ENV] = before
|
||||
written = merge_junits(pass_junits(directory, procs or "4"), Path(junit))
|
||||
print("[ci_suite_run] %s on %s: %d test(s) in %s" % (suite, os_name, written, junit), flush=True)
|
||||
if code not in _REACHED_THE_END:
|
||||
print("[ci_suite_run] a pass did not run to its end (exit %s)" % code, file=sys.stderr)
|
||||
return code
|
||||
if not written:
|
||||
print("[ci_suite_run] no pass wrote a junit", file=sys.stderr)
|
||||
return 3
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv: Optional[Sequence[str]] = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--required", required=True, help="ci/required-suites.json")
|
||||
parser.add_argument("--suite", required=True, help="the id of the row")
|
||||
parser.add_argument("--os", required=True, choices=ci_verdict.OSES)
|
||||
parser.add_argument("--binary", required=True, help="the engine under test")
|
||||
parser.add_argument("--junit", required=True, help="the one junit written for the judge")
|
||||
parser.add_argument("--procs", default=None, help="browsers at once, for the first pass (default: the run's own, 4)")
|
||||
ns = parser.parse_args(argv)
|
||||
try:
|
||||
return run(ns.required, ns.suite, ns.os, ns.binary, ns.junit, repo=Path(__file__).resolve().parent.parent, procs=ns.procs)
|
||||
except ci_verdict.Usage as exc:
|
||||
print("ci_suite_run.py: %s" % exc, file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,274 @@
|
||||
"""What the canvas-reader e2e tests share: one scene, the readers of a canvas, the page that serves them, and the comparison of bytes.
|
||||
|
||||
The engine applies its canvas noise (``gfx::StealthProjectPixels``) to a WebGL or WebGPU canvas when a PAGE reads it, and only then. These
|
||||
tests ask whether every road by which a page reads such a canvas gives the same bytes, so they need one scene that the noise touches, the same
|
||||
scene drawn through every API, and the same list of readers for every kind of canvas.
|
||||
|
||||
THE SCENE. Ten triangles with random vertex colours (a fixed generator, the same numbers in every launch and in every API: ``starVertices``)
|
||||
over a white clear. The noise touches only an edge pixel whose 3x3 neighbourhood holds a THIRD colour besides a blend of two, so a flat clear
|
||||
is never touched; ten overlapping triangles make hundreds of such junctions, and the chance that two reads of a noised and an un-noised canvas
|
||||
differ nowhere is nil. The 2D twin (``draw2D``) draws the same triangles with translucent fills and a shadow: a canvas that WOULD be noised if
|
||||
the 2D road were projected, and is not (a 2D canvas reads as drawn).
|
||||
|
||||
THE CONTROL. ``noised=False`` declares ``zoom.stealth.canvas.substitute_pixels`` false: the canvas noise is declared off and NOTHING else changes
|
||||
(same declared GPU, same antialiasing, same raster), so the difference between the two launches is the noise and nothing else, which is why
|
||||
the tests may ask that it touches only the low bit of R, G and B. (A launch with ``hw_seed`` 0 would also change the declared GPU.)
|
||||
|
||||
THE READERS (``readersOf``): the canvas's own read (``readPixels`` / ``getImageData``), ``drawImage`` onto a 2D canvas, ``createImageBitmap``, the
|
||||
PNG of ``toDataURL`` / ``toBlob`` / ``convertToBlob`` (decoded here, never by the browser, so the browser's image decoding is not a variable)
|
||||
and, for an OffscreenCanvas, ``transferToImageBitmap``. Every entry is the base64 of RGBA bytes, top row first; a name that ends in ``.png`` is a
|
||||
PNG file.
|
||||
|
||||
Nothing here waits on a clock: the page's async functions end on events, and the one wait that needs polling (``wait_until``) ends on a condition.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import contextlib
|
||||
import json
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from typing import Dict, List
|
||||
|
||||
import _page_bytes as pb
|
||||
from _servers import LocalServer
|
||||
|
||||
#: The side of every canvas of the scene.
|
||||
SIZE = 128
|
||||
#: A noise seed that no runner has.
|
||||
HW_SEED = 12345
|
||||
#: The persona (identity) seed of every launch: not the noise seed.
|
||||
SEED = 7
|
||||
|
||||
#: The JS of the scene and of the readers. Plain script: it runs in the page and, as the head of a worker's source, in a worker (no ``document`` in it).
|
||||
SHARED_JS = r"""
|
||||
const W = 128, H = 128;
|
||||
|
||||
// ten triangles, 30 vertices of (x, y, r, g, b), x and y in clip space: a fixed generator, so every launch and every API draws the same scene
|
||||
function starVertices() {
|
||||
const v = []; let s = 12345;
|
||||
const rnd = () => (s = (s * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
|
||||
for (let i = 0; i < 30; i++) v.push(rnd() * 1.8 - 0.9, rnd() * 1.8 - 0.9, rnd(), rnd(), rnd());
|
||||
return v;
|
||||
}
|
||||
|
||||
function drawGL(canvas, kind) {
|
||||
const gl = canvas.getContext(kind || 'webgl', {preserveDrawingBuffer: true, antialias: true});
|
||||
if (!gl) throw new Error('no ' + (kind || 'webgl') + ' context');
|
||||
const shader = (type, src) => {
|
||||
const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);
|
||||
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));
|
||||
return s;
|
||||
};
|
||||
const pr = gl.createProgram();
|
||||
gl.attachShader(pr, shader(gl.VERTEX_SHADER, 'attribute vec2 p; attribute vec3 c; varying vec3 v; void main(){v=c;gl_Position=vec4(p,0.,1.);}'));
|
||||
gl.attachShader(pr, shader(gl.FRAGMENT_SHADER, 'precision mediump float; varying vec3 v; void main(){gl_FragColor=vec4(v,1.);}'));
|
||||
gl.linkProgram(pr);
|
||||
if (!gl.getProgramParameter(pr, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(pr));
|
||||
gl.useProgram(pr);
|
||||
const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(starVertices()), gl.STATIC_DRAW);
|
||||
const pl = gl.getAttribLocation(pr, 'p'), cl = gl.getAttribLocation(pr, 'c');
|
||||
gl.enableVertexAttribArray(pl); gl.vertexAttribPointer(pl, 2, gl.FLOAT, false, 20, 0);
|
||||
gl.enableVertexAttribArray(cl); gl.vertexAttribPointer(cl, 3, gl.FLOAT, false, 20, 8);
|
||||
gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT);
|
||||
gl.drawArrays(gl.TRIANGLES, 0, 30);
|
||||
gl.finish();
|
||||
return gl;
|
||||
}
|
||||
|
||||
// the same ten triangles on a 2D canvas, with translucent fills and a shadow
|
||||
function draw2D(x) {
|
||||
x.fillStyle = '#fff'; x.fillRect(0, 0, W, H);
|
||||
const v = starVertices();
|
||||
for (let t = 0; t < 10; t++) {
|
||||
const q = v.slice(t * 15, t * 15 + 15);
|
||||
x.fillStyle = 'rgba(' + Math.round(q[2] * 255) + ',' + Math.round(q[3] * 255) + ',' + Math.round(q[4] * 255) + ',' + (t % 2 ? 0.7 : 1) + ')';
|
||||
x.beginPath();
|
||||
for (let k = 0; k < 3; k++) {
|
||||
const px = (q[k * 5] + 1) / 2 * W, py = (1 - q[k * 5 + 1]) / 2 * H;
|
||||
if (k) x.lineTo(px, py); else x.moveTo(px, py);
|
||||
}
|
||||
x.closePath(); x.fill();
|
||||
}
|
||||
x.shadowColor = 'rgba(0, 0, 0, 0.6)'; x.shadowBlur = 4; x.shadowOffsetX = 3; x.shadowOffsetY = 2;
|
||||
x.fillStyle = 'rgb(200, 120, 20)'; x.fillRect(40, 40, 30, 30);
|
||||
}
|
||||
|
||||
// readPixels, top row first (readPixels gives the bottom row first)
|
||||
function readGL(gl) {
|
||||
const buf = new Uint8Array(W * H * 4);
|
||||
gl.readPixels(0, 0, W, H, gl.RGBA, gl.UNSIGNED_BYTE, buf);
|
||||
const out = new Uint8Array(W * H * 4);
|
||||
for (let y = 0; y < H; y++) out.set(buf.subarray((H - 1 - y) * W * 4, (H - y) * W * 4), y * W * 4);
|
||||
return out;
|
||||
}
|
||||
|
||||
function readCtx(x) { return new Uint8Array(x.getImageData(0, 0, W, H).data); }
|
||||
|
||||
function b64(u8) {
|
||||
let s = '';
|
||||
for (let i = 0; i < u8.length; i += 8192) s += String.fromCharCode.apply(null, u8.subarray(i, i + 8192));
|
||||
return btoa(s);
|
||||
}
|
||||
|
||||
function blobB64(blob) {
|
||||
return new Promise((ok, bad) => {
|
||||
const r = new FileReader();
|
||||
r.onload = () => ok(String(r.result).split(',')[1]);
|
||||
r.onerror = () => bad(new Error('FileReader failed'));
|
||||
r.readAsDataURL(blob);
|
||||
});
|
||||
}
|
||||
|
||||
// what a fresh 2D canvas (made by `make`) holds after `draw(context)`
|
||||
function pixelsOf(make, draw) {
|
||||
const c = make(); c.width = W; c.height = H;
|
||||
const x = c.getContext('2d'); draw(x);
|
||||
return readCtx(x);
|
||||
}
|
||||
|
||||
// every road by which a page turns `src` into bytes: {name: base64 of RGBA, top row first}; a name ending in .png is a PNG file
|
||||
async function readersOf(src, direct, make, withTransfer) {
|
||||
const out = {direct: b64(direct())};
|
||||
out.drawImage = b64(pixelsOf(make, x => x.drawImage(src, 0, 0)));
|
||||
const bm = await createImageBitmap(src);
|
||||
out.createImageBitmap = b64(pixelsOf(make, x => x.drawImage(bm, 0, 0)));
|
||||
bm.close();
|
||||
if (src.toDataURL) {
|
||||
out['toDataURL.png'] = src.toDataURL('image/png').split(',')[1];
|
||||
out['toBlob.png'] = await blobB64(await new Promise(r => src.toBlob(r, 'image/png')));
|
||||
} else {
|
||||
out['convertToBlob.png'] = await blobB64(await src.convertToBlob({type: 'image/png'}));
|
||||
}
|
||||
if (withTransfer && src.transferToImageBitmap) { // last: it empties the canvas
|
||||
const tb = src.transferToImageBitmap();
|
||||
out.transferToImageBitmap = b64(pixelsOf(make, x => x.drawImage(tb, 0, 0)));
|
||||
tb.close();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const makeElement = () => document.createElement('canvas');
|
||||
const makeOffscreen = () => new OffscreenCanvas(W, H);
|
||||
"""
|
||||
|
||||
|
||||
def page_html(page_js: str) -> str:
|
||||
"""A page whose script holds SHARED_JS, ``WORKER_LIB`` (the same text, for the source of a worker) and the page's own functions."""
|
||||
return ("<!doctype html><meta charset=utf-8><title>canvas readers</title><body><script>\n" + SHARED_JS
|
||||
+ "\nconst WORKER_LIB = " + json.dumps(SHARED_JS) + ";\n" + page_js + "\n</script></body>")
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def serve(html: str):
|
||||
"""The page on a local http origin (a secure context, and a site a canvas has a principal on); port 0, the one the system gave."""
|
||||
body = html.encode("utf-8")
|
||||
|
||||
class Page(BaseHTTPRequestHandler):
|
||||
timeout = 5
|
||||
|
||||
def do_GET(self):
|
||||
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)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
httpd = LocalServer(("127.0.0.1", 0), Page)
|
||||
threading.Thread(target=httpd.serve_forever, daemon=True).start()
|
||||
try:
|
||||
yield "http://127.0.0.1:%d/" % httpd.server_address[1]
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def launched(firefox_binary, html: str, noised: bool = True, pin=None, viewport=None):
|
||||
"""The page open in a browser of the product: the engine on (a declared noise seed no runner has), and, when ``noised`` is false, the
|
||||
canvas noise declared off and nothing else. One browser, closed on leaving."""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
prefs = {"zoom.stealth.fpp.hw_seed": HW_SEED}
|
||||
if not noised:
|
||||
prefs["zoom.stealth.canvas.substitute_pixels"] = False
|
||||
with serve(html) as url:
|
||||
with InvisiblePlaywright(seed=SEED, binary_path=firefox_binary, headless=True, extra_prefs=prefs, pin=pin) as browser:
|
||||
context = browser.new_context(viewport=viewport) if viewport else browser.new_context()
|
||||
page = context.new_page()
|
||||
page.goto(url, wait_until="load", timeout=60_000)
|
||||
yield page
|
||||
|
||||
|
||||
def run(page, call: str, deadline_s: int = 120):
|
||||
"""Runs the page's async function ``call`` (a JS expression that gives a promise) to its end and returns what it resolved to. The end is
|
||||
the promise's own: the deadline is only how long a lost event is allowed before the test says so."""
|
||||
page.evaluate("() => { window.DONE = false; window.ERR = null; window.R = null;"
|
||||
" Promise.resolve().then(() => %s).then(r => { window.R = r; window.DONE = true; },"
|
||||
" e => { window.ERR = String((e && e.stack) || e); window.DONE = true; }); }" % call)
|
||||
page.wait_for_function("window.DONE === true", timeout=deadline_s * 1000)
|
||||
err = page.evaluate("window.ERR")
|
||||
assert err is None, "the page could not run %s: %s" % (call, err)
|
||||
return page.evaluate("window.R")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------------------ bytes
|
||||
|
||||
def rgba_of_image(image) -> bytes:
|
||||
"""RGBA bytes of an ``_page_bytes.unfiltered`` image (RGB gets an opaque alpha)."""
|
||||
data, channels = image["data"], image["channels"]
|
||||
if channels == 4:
|
||||
return data
|
||||
assert channels == 3, "a PNG of %d channels is not read here" % channels
|
||||
out = bytearray()
|
||||
for i in range(0, len(data), 3):
|
||||
out += data[i:i + 3] + b"\xff"
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def rgba(name: str, value: str) -> bytes:
|
||||
"""The RGBA bytes of a reader's entry: its base64, or, for a PNG, the pixels it decodes to."""
|
||||
raw = base64.b64decode(value)
|
||||
if name.endswith(".png"):
|
||||
image = pb.unfiltered(raw)
|
||||
assert (image["w"], image["h"]) == (SIZE, SIZE), "%s is a %dx%d image, not %dx%d" % (name, image["w"], image["h"], SIZE, SIZE)
|
||||
return rgba_of_image(image)
|
||||
assert len(raw) == SIZE * SIZE * 4, "%s holds %d bytes, not %d" % (name, len(raw), SIZE * SIZE * 4)
|
||||
return raw
|
||||
|
||||
|
||||
def decode(readers: Dict[str, str], prefix: str = "") -> Dict[str, bytes]:
|
||||
return {prefix + name: rgba(name, value) for name, value in readers.items()}
|
||||
|
||||
|
||||
def differing_pixels(a: bytes, b: bytes) -> int:
|
||||
assert len(a) == len(b), "two images of %d and %d bytes" % (len(a), len(b))
|
||||
return sum(1 for i in range(0, len(a), 4) if a[i:i + 4] != b[i:i + 4])
|
||||
|
||||
|
||||
def only_the_low_bit_of_rgb(a: bytes, b: bytes) -> List[int]:
|
||||
"""The pixels where ``a`` and ``b`` differ by more than the low bit of R, G and B (or in alpha): the noise writes nothing else."""
|
||||
return [i // 4 for i in range(0, len(a), 4)
|
||||
if (a[i] | 1, a[i + 1] | 1, a[i + 2] | 1, a[i + 3]) != (b[i] | 1, b[i + 1] | 1, b[i + 2] | 1, b[i + 3])]
|
||||
|
||||
|
||||
def distinct_colours(a: bytes) -> int:
|
||||
return len({a[i:i + 4] for i in range(0, len(a), 4)})
|
||||
|
||||
|
||||
def disagreements(readers: Dict[str, bytes], reference: str) -> List[str]:
|
||||
"""The readers whose bytes are not those of ``reference``, each with how many pixels differ."""
|
||||
want = readers[reference]
|
||||
return ["%s (%d pixels differ)" % (name, differing_pixels(want, got)) for name, got in readers.items() if got != want]
|
||||
|
||||
|
||||
def assert_agree(what: str, readers: Dict[str, bytes], reference: str = "direct") -> None:
|
||||
bad = disagreements(readers, reference)
|
||||
assert not bad, (
|
||||
"%s: the readers %s do not read what %s reads (readers: %s). Every road by which a page reads a canvas gives the same bytes "
|
||||
"when it is the same canvas" % (what, "; ".join(bad), reference, ", ".join(sorted(readers))))
|
||||
@@ -602,7 +602,8 @@ class DohGateway(Gateway):
|
||||
* CONNECT to a loopback address is relayed for real (the pages and the echo servers of a test);
|
||||
* the egress endpoints of the base class (``api.ipify.org:80``) keep working;
|
||||
* any other CONNECT is refused (reply 2 "not allowed", for an address; 4 "host unreachable", for a name) and
|
||||
listed in :attr:`refused`: the gateway never resolves a name and never reaches past the loopback.
|
||||
listed in :attr:`refused` (and in ``guard``, the record every gateway of ``_socks_servers`` writes under ``$RUNNER_TEMP/invpw-evidence/``):
|
||||
the gateway never resolves a name and never reaches past the loopback. Its UDP relay is the base one: only the lab's, the rest dropped and recorded.
|
||||
|
||||
:attr:`connects` (inherited) lists EVERY CONNECT target in order, so ``("page-a.test", 80)`` in it means the
|
||||
browser sent a name where it should have sent an address. :attr:`credentials_seen` lists every
|
||||
@@ -696,6 +697,7 @@ class DohGateway(Gateway):
|
||||
if not is_loopback(host):
|
||||
self.connects.append((host, port))
|
||||
self.refused.append((host, port))
|
||||
self.guard.refuse(host, port, getattr(self._local, "atyp", 3), "tcp")
|
||||
self._send(c, self._reply(2 if _is_address(host) else 4))
|
||||
return
|
||||
self.connects.append((host, port))
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
"""What an e2e test that fails leaves for a reader, and nothing when it passes.
|
||||
|
||||
``with FailureEvidence("name") as evidence:`` around the body of a test: while the body runs, the helper collects, in a temporary folder,
|
||||
the sources the test points it at (the fake web's own record, the Juggler wire of the served browser, the engine's own Juggler trace,
|
||||
the client's view of every request); when the body raises (an assertion included), it copies what it holds to
|
||||
``$RUNNER_TEMP/invpw-evidence/<name>/<pid>-<ms>/``, the folder the e2e jobs upload (``invpw-evidence-*``), with a ``meta.json``; when the
|
||||
body passes, it deletes it all. Off a runner (no ``RUNNER_TEMP``) nothing is copied. It changes no assertion, wait or deadline of the
|
||||
test: it only listens.
|
||||
|
||||
A test that passed slowly may keep the evidence too: ``evidence.keep(why)`` saves what the helper holds at that moment (the same folder, a
|
||||
``meta.json`` whose ``kept`` says why, judged after the fact and never a verdict). ``arm(moz_log=...)`` also starts the engine's own log
|
||||
(``MOZ_LOG``, its file in the evidence), and ``note_records(name, state)`` adds a record the test keeps itself (``state.lock``,
|
||||
``state.records``) as ``<name>.jsonl``.
|
||||
|
||||
The times written: ``t``, wall-clock seconds since the epoch (``time.time()``; the engine's own trace writes milliseconds in ``t``, its
|
||||
``performance.timeOrigin + now``, also since the epoch), and ``m``, ``time.perf_counter()`` of the test process, finer on Windows (whose wall
|
||||
clock ticks every 15 ms) and shared by the fake web's record, the client's log and the Juggler wire.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import platform
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
#: The folder under ``$RUNNER_TEMP`` the e2e workflows upload (``invpw-evidence-*``).
|
||||
EVIDENCE_FOLDER = "invpw-evidence"
|
||||
#: The most characters of one Juggler message kept in the wire log: a message longer than this is cut and says so.
|
||||
WIRE_LIMIT = 4000
|
||||
#: The engine's trace: the variable `Trace.js` of the engine reads in the parent process (off without it).
|
||||
TRACE_ENV = "INVISIBLE_JUGGLER_TRACE_DIR"
|
||||
#: The base name of the engine's log file in the evidence (``MOZ_LOG_FILE``; the engine adds a suffix per process).
|
||||
MOZ_LOG_BASE = "engine"
|
||||
|
||||
|
||||
class FailureEvidence:
|
||||
def __init__(self, name: str):
|
||||
self.name = name
|
||||
self.work = pathlib.Path(tempfile.mkdtemp(prefix="invpw-failure-evidence-"))
|
||||
self.trace_dir = self.work / "juggler-engine-trace"
|
||||
self.wire_path = self.work / "juggler-wire.jsonl"
|
||||
self.moz_log_dir = self.work / "moz-log"
|
||||
#: The records the test keeps itself, by name (``note_records``).
|
||||
self.records = {}
|
||||
#: What the client heard of each request (a list ``profile_p2.drive(client_log=...)`` fills).
|
||||
self.client_log = []
|
||||
#: The cells of the run, once it has returned (``note_cells``).
|
||||
self.cells = None
|
||||
self._stop = None
|
||||
self._patch = None
|
||||
self._wire = None
|
||||
self._wire_lock = threading.Lock()
|
||||
self.saved_to = None
|
||||
|
||||
# ---- what the test points the helper at ---------------------------------------------------------------------------
|
||||
def watch_server(self, stop) -> None:
|
||||
"""The ``stop`` function ``tests/fakeweb/sites.start`` returned: it carries the server's own record (``stop.state``)."""
|
||||
self._stop = stop
|
||||
|
||||
def note_cells(self, cells) -> None:
|
||||
self.cells = cells
|
||||
|
||||
def note_records(self, name: str, state) -> None:
|
||||
"""A record the test keeps itself (``state.lock``, ``state.records``: a list of dicts), saved as ``<name>.jsonl``."""
|
||||
self.records[name] = state
|
||||
|
||||
def arm(self, moz_log: str = "") -> None:
|
||||
"""Before the browser under test is launched: the engine writes its trace, and the Juggler wire of this process is logged.
|
||||
Armed after the other processes of the test were started, so that they do not inherit the variable. ``moz_log``, a value of
|
||||
``MOZ_LOG`` (modules and levels), also starts the engine's own log into the evidence (a diagnostic no page reads: the core passes it)."""
|
||||
self.trace_dir.mkdir(parents=True, exist_ok=True)
|
||||
self._patch = pytest.MonkeyPatch()
|
||||
self._patch.setenv(TRACE_ENV, str(self.trace_dir))
|
||||
if moz_log:
|
||||
self.moz_log_dir.mkdir(parents=True, exist_ok=True)
|
||||
self._patch.setenv("MOZ_LOG", moz_log)
|
||||
self._patch.setenv("MOZ_LOG_FILE", str(self.moz_log_dir / MOZ_LOG_BASE))
|
||||
self._wire = open(self.wire_path, "w", encoding="utf-8")
|
||||
try:
|
||||
from invisible_core.juggler import connection
|
||||
except Exception as exc: # the trace of the engine is still written; say that the wire is not
|
||||
self._write_wire({"dir": "note", "what": "the Juggler wire is not logged: %r" % (exc,)})
|
||||
return
|
||||
owner = self
|
||||
original_deliver, original_write = connection.Connection._deliver, connection.Connection._write
|
||||
|
||||
def deliver(connection_self, raw):
|
||||
owner._log_wire("in", raw)
|
||||
return original_deliver(connection_self, raw)
|
||||
|
||||
def write(connection_self, msg):
|
||||
owner._log_wire("out", msg)
|
||||
return original_write(connection_self, msg)
|
||||
|
||||
self._patch.setattr(connection.Connection, "_deliver", deliver)
|
||||
self._patch.setattr(connection.Connection, "_write", write)
|
||||
|
||||
# ---- the wire ------------------------------------------------------------------------------------------------------
|
||||
def _write_wire(self, record: dict) -> None:
|
||||
try:
|
||||
with self._wire_lock:
|
||||
if self._wire is not None:
|
||||
self._wire.write(json.dumps(record, default=str) + "\n")
|
||||
self._wire.flush()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _log_wire(self, direction: str, message) -> None:
|
||||
try:
|
||||
if isinstance(message, (bytes, bytearray)):
|
||||
text = bytes(message).decode("utf-8", "replace")
|
||||
else:
|
||||
text = json.dumps(message, default=str)
|
||||
cut = len(text) > WIRE_LIMIT
|
||||
self._write_wire({"t": round(time.time(), 4), "m": round(time.perf_counter(), 6), "dir": direction, "len": len(text), "cut": cut,
|
||||
"msg": text[:WIRE_LIMIT]})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ---- the end ---------------------------------------------------------------------------------------------------------
|
||||
def keep(self, why: str) -> None:
|
||||
"""Saves what the helper holds now, though the test has not failed: a run judged after the fact as one to read (a step slower
|
||||
than any healthy run). Not a verdict: nothing is raised and the test goes on. Never raises."""
|
||||
try:
|
||||
self._save(None, None, kept=why)
|
||||
except Exception as problem:
|
||||
sys.stderr.write("evidence: could not be kept: %r\n" % (problem,))
|
||||
|
||||
def __enter__(self) -> "FailureEvidence":
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb) -> bool:
|
||||
try:
|
||||
if self._patch is not None:
|
||||
self._patch.undo()
|
||||
with self._wire_lock:
|
||||
if self._wire is not None:
|
||||
self._wire.close()
|
||||
self._wire = None
|
||||
if exc_type is not None:
|
||||
self._save(exc_type, exc)
|
||||
except Exception as problem: # the evidence never hides the failure it is about
|
||||
sys.stderr.write("failure evidence: could not be saved: %r\n" % (problem,))
|
||||
finally:
|
||||
shutil.rmtree(self.work, ignore_errors=True)
|
||||
return False
|
||||
|
||||
def _save(self, exc_type, exc, kept: str = "") -> None:
|
||||
base = os.environ.get("RUNNER_TEMP")
|
||||
if not base:
|
||||
return
|
||||
target = pathlib.Path(base) / EVIDENCE_FOLDER / self.name / ("%d-%d" % (os.getpid(), int(time.time() * 1000)))
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
if self._stop is not None and getattr(self._stop, "state", None) is not None:
|
||||
state = self._stop.state
|
||||
with state.lock:
|
||||
records = list(state.records)
|
||||
self._jsonl(target / "fakeweb-server-record.jsonl", records)
|
||||
for name, state in self.records.items():
|
||||
with state.lock:
|
||||
records = list(state.records)
|
||||
self._jsonl(target / ("%s.jsonl" % name), records)
|
||||
self._jsonl(target / "client-request-log.jsonl", list(self.client_log))
|
||||
if self.cells is not None:
|
||||
(target / "cells.json").write_text(json.dumps(self.cells, indent=1, default=str), encoding="utf-8")
|
||||
if self.wire_path.exists():
|
||||
shutil.copyfile(self.wire_path, target / "juggler-wire.jsonl")
|
||||
if self.trace_dir.exists():
|
||||
shutil.copytree(self.trace_dir, target / "juggler-engine-trace", dirs_exist_ok=True)
|
||||
if self.moz_log_dir.exists():
|
||||
shutil.copytree(self.moz_log_dir, target / "moz-log", dirs_exist_ok=True)
|
||||
meta = {"test": self.name, "platform": sys.platform,
|
||||
"machine": platform.machine(), "python": platform.python_version(), "saved_at": round(time.time(), 4),
|
||||
"times": "t: wall-clock seconds since the epoch (the engine's trace: milliseconds, in t); m: time.perf_counter() of the test process, the scale shared by the server record, the client log and the wire",
|
||||
"files": sorted(p.name for p in target.iterdir())}
|
||||
if exc_type is not None:
|
||||
meta["failure"] = "%s: %s" % (exc_type.__name__, str(exc)[:1500])
|
||||
if kept:
|
||||
meta["kept"] = kept
|
||||
(target / "meta.json").write_text(json.dumps(meta, indent=1), encoding="utf-8")
|
||||
self.saved_to = target
|
||||
|
||||
@staticmethod
|
||||
def _jsonl(path: pathlib.Path, records) -> None:
|
||||
with open(path, "w", encoding="utf-8") as out:
|
||||
for record in records:
|
||||
out.write(json.dumps(record, default=str) + "\n")
|
||||
@@ -0,0 +1,244 @@
|
||||
"""What the e2e tests of the font list need to know about the bundle and about the host, read from files and never typed.
|
||||
|
||||
Two sources, both plain data:
|
||||
|
||||
* the bundle manifest the core hands to the engine (``invisible_core._fpforge.profile.FONT_MANIFEST``, the text of
|
||||
``bundle-fonts.list``: ``F|<family>`` opens a family, ``f|<file>|<index>|...|<psname>|<upem>|<ascent>|<descent>|...`` is one of its faces,
|
||||
``A|<alias>|<target>`` is a Windows font-substitute). The engine prefers this text to the copy in its own directory, so it is the list of
|
||||
the families the engine answers to;
|
||||
* the font files of the machine that runs the test (the host): the folders a system installs fonts in. Each file's ``name`` table gives the
|
||||
family, PostScript and full names of each of its faces. A host font whose names are not in the bundle is a "host-only" face: the engine
|
||||
must not know it, and a test that asks the page for it has a name that exists on this machine and in no bundle.
|
||||
|
||||
Only the header and the ``name`` table of a file are read (a font collection is several faces; ``simsun.ttc`` is 15 MB).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Dict, Iterable, List, Optional, Set
|
||||
|
||||
#: What an sfnt file starts with: TrueType 1.0, OpenType with CFF outlines, the Apple TrueType tag, a collection.
|
||||
_SFNT = (b"\x00\x01\x00\x00", b"OTTO", b"true")
|
||||
_COLLECTION = b"ttcf"
|
||||
_EXTENSIONS = {".ttf", ".otf", ".ttc", ".otc"}
|
||||
|
||||
#: name ids of the strings that name a face.
|
||||
FAMILY, FULL, POSTSCRIPT, TYPOGRAPHIC_FAMILY = 1, 4, 6, 16
|
||||
|
||||
|
||||
class Manifest:
|
||||
"""The bundle manifest, parsed: families in order, the faces of each (file, index, PostScript name, metrics) and the aliases."""
|
||||
|
||||
def __init__(self, text: str):
|
||||
self.families: List[str] = []
|
||||
self.faces: Dict[str, List[dict]] = {}
|
||||
self.aliases: Dict[str, str] = {}
|
||||
current: Optional[str] = None
|
||||
for line in text.splitlines():
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
fields = line.split("|")
|
||||
if fields[0] == "F" and len(fields) >= 2:
|
||||
current = fields[1]
|
||||
self.families.append(current)
|
||||
self.faces[current] = []
|
||||
elif fields[0] == "A" and len(fields) >= 3:
|
||||
self.aliases[fields[1]] = fields[2]
|
||||
elif fields[0] == "f" and current is not None and len(fields) >= 19:
|
||||
self.faces[current].append({
|
||||
"file": fields[1], "index": int(fields[2]), "psname": fields[8],
|
||||
"upem": int(fields[9]), "ascent": int(fields[10]), "descent": int(fields[11]),
|
||||
})
|
||||
|
||||
def family_of_psname(self, psname: str) -> Optional[str]:
|
||||
for family, faces in self.faces.items():
|
||||
if any(face["psname"] == psname for face in faces):
|
||||
return family
|
||||
return None
|
||||
|
||||
def face_with_psname(self, psname: str) -> dict:
|
||||
for faces in self.faces.values():
|
||||
for face in faces:
|
||||
if face["psname"] == psname:
|
||||
return face
|
||||
raise AssertionError("the bundle manifest has no face with the PostScript name %r" % psname)
|
||||
|
||||
def known_names(self) -> Set[str]:
|
||||
"""Every name the bundle answers to, lower case: its families, its aliases and the PostScript names of its faces."""
|
||||
names = {family.lower() for family in self.families}
|
||||
names |= {alias.lower() for alias in self.aliases}
|
||||
names |= {face["psname"].lower() for faces in self.faces.values() for face in faces}
|
||||
return names
|
||||
|
||||
|
||||
def bundle_manifest() -> Manifest:
|
||||
"""The manifest of the core installed with the wrapper under test, the one the engine is handed as ``zoom.stealth.fonts.manifest``."""
|
||||
from invisible_core._fpforge.profile import FONT_MANIFEST
|
||||
|
||||
manifest = Manifest(FONT_MANIFEST)
|
||||
assert manifest.families, "the manifest of the core has no family: the parser read nothing"
|
||||
return manifest
|
||||
|
||||
|
||||
def _decode(platform: int, encoding: int, raw: bytes) -> Optional[str]:
|
||||
try:
|
||||
if platform in (0, 3):
|
||||
return raw.decode("utf-16-be")
|
||||
if platform == 1 and encoding == 0:
|
||||
return raw.decode("mac_roman")
|
||||
except UnicodeDecodeError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _name_strings(table: bytes) -> Dict[int, List[tuple]]:
|
||||
"""name id -> [(is english windows name, text)] of one ``name`` table."""
|
||||
out: Dict[int, List[tuple]] = {}
|
||||
if len(table) < 6:
|
||||
return out
|
||||
_format, count, string_offset = struct.unpack(">HHH", table[:6])
|
||||
for i in range(count):
|
||||
record = table[6 + 12 * i: 18 + 12 * i]
|
||||
if len(record) < 12:
|
||||
break
|
||||
platform, encoding, language, name_id, length, offset = struct.unpack(">6H", record)
|
||||
text = _decode(platform, encoding, table[string_offset + offset: string_offset + offset + length])
|
||||
if text:
|
||||
out.setdefault(name_id, []).append((platform == 3 and language == 0x409, text))
|
||||
return out
|
||||
|
||||
|
||||
def face_names(path: Path) -> List[dict]:
|
||||
"""For each face of a font file: ``family`` (every family string, any language), ``psname`` and ``full`` (the English ones, or None).
|
||||
|
||||
An unreadable file, or a file that is not an sfnt, has no faces: a host folder holds other things than fonts."""
|
||||
faces: List[dict] = []
|
||||
try:
|
||||
with open(path, "rb") as handle:
|
||||
head = handle.read(12)
|
||||
if len(head) < 12:
|
||||
return faces
|
||||
if head[:4] == _COLLECTION:
|
||||
count = struct.unpack(">I", head[8:12])[0]
|
||||
if count > 64:
|
||||
return faces
|
||||
offsets = struct.unpack(">%dI" % count, handle.read(4 * count))
|
||||
elif head[:4] in _SFNT:
|
||||
offsets = (0,)
|
||||
else:
|
||||
return faces
|
||||
for base in offsets:
|
||||
handle.seek(base + 4)
|
||||
tables = struct.unpack(">H", handle.read(2))[0]
|
||||
handle.seek(base + 12)
|
||||
directory = handle.read(16 * tables)
|
||||
name_table = None
|
||||
for i in range(tables):
|
||||
tag, _checksum, offset, length = struct.unpack(">4sIII", directory[16 * i: 16 * i + 16])
|
||||
if tag == b"name" and 0 < length <= 1 << 20:
|
||||
handle.seek(offset)
|
||||
name_table = handle.read(length)
|
||||
break
|
||||
if name_table is None:
|
||||
continue
|
||||
strings = _name_strings(name_table)
|
||||
|
||||
def english(name_id: int) -> Optional[str]:
|
||||
for is_english, text in strings.get(name_id, []):
|
||||
if is_english:
|
||||
return text
|
||||
return None
|
||||
|
||||
families = []
|
||||
for name_id in (FAMILY, TYPOGRAPHIC_FAMILY):
|
||||
for _english, text in strings.get(name_id, []):
|
||||
if text not in families:
|
||||
families.append(text)
|
||||
faces.append({"file": str(path), "families": families, "psname": english(POSTSCRIPT), "full": english(FULL)})
|
||||
except (OSError, struct.error):
|
||||
return []
|
||||
return faces
|
||||
|
||||
|
||||
def host_font_files() -> List[Path]:
|
||||
"""The font files the host has installed, in a stable order."""
|
||||
if sys.platform == "win32":
|
||||
roots = [Path(os.environ.get("WINDIR", r"C:\Windows")) / "Fonts"]
|
||||
local = os.environ.get("LOCALAPPDATA")
|
||||
if local:
|
||||
roots.append(Path(local) / "Microsoft" / "Windows" / "Fonts")
|
||||
else:
|
||||
roots = [Path("/usr/share/fonts"), Path("/usr/local/share/fonts"), Path.home() / ".fonts",
|
||||
Path.home() / ".local" / "share" / "fonts"]
|
||||
files: List[Path] = []
|
||||
for root in roots:
|
||||
if root.is_dir():
|
||||
files += [p for p in root.rglob("*") if p.suffix.lower() in _EXTENSIONS and p.is_file()]
|
||||
return sorted(files, key=lambda p: str(p).lower())
|
||||
|
||||
|
||||
def _plain(name: Optional[str]) -> bool:
|
||||
"""A name that goes into a CSS string between double quotes without an escape: printable ASCII, no quote, no backslash."""
|
||||
return bool(name) and all(32 <= ord(ch) < 127 and ch not in "\"\\" for ch in name)
|
||||
|
||||
|
||||
def bundle_file_names(manifest: Manifest, binary: str) -> Set[str]:
|
||||
"""Every name (families of any language, PostScript, full), lower case, that the files of the bundle carry in their own ``name`` tables.
|
||||
|
||||
The engine answers to the other-language family names of a bundled face as it does to its family (a localized name is an alias of the
|
||||
face it names), so a host font that carries such a name is not host-only. The folder is ``<engine>/fonts``; when the build has no such
|
||||
folder the set is empty and the manifest alone decides."""
|
||||
folder = Path(binary).resolve().parent / "fonts"
|
||||
names: Set[str] = set()
|
||||
if not folder.is_dir():
|
||||
return names
|
||||
for name in sorted({face["file"] for faces in manifest.faces.values() for face in faces}):
|
||||
for face in face_names(folder / name):
|
||||
names |= {family.lower() for family in face["families"]}
|
||||
names |= {value.lower() for value in (face["psname"], face["full"]) if value}
|
||||
return names
|
||||
|
||||
|
||||
def host_only_faces(manifest: Manifest, extra_known: Iterable[str] = ()) -> List[dict]:
|
||||
"""The faces of the host whose names the bundle does not know: no family, no alias and no PostScript name of the bundle."""
|
||||
known = manifest.known_names() | set(extra_known)
|
||||
out: List[dict] = []
|
||||
for path in host_font_files():
|
||||
for face in face_names(path):
|
||||
names = [name.lower() for name in face["families"]]
|
||||
if face["psname"]:
|
||||
names.append(face["psname"].lower())
|
||||
if names and not any(name in known for name in names):
|
||||
out.append(face)
|
||||
return out
|
||||
|
||||
|
||||
def host_only_families(manifest: Manifest, extra_known: Iterable[str] = ()) -> List[str]:
|
||||
"""The family names (every language) of the host-only faces, once each, in the order of the files."""
|
||||
extra_known = set(extra_known)
|
||||
known = manifest.known_names() | extra_known
|
||||
seen: Set[str] = set()
|
||||
out: List[str] = []
|
||||
for face in host_only_faces(manifest, extra_known):
|
||||
for family in face["families"]:
|
||||
key = family.lower()
|
||||
if key not in seen and key not in known and _plain(family):
|
||||
seen.add(key)
|
||||
out.append(family)
|
||||
return out
|
||||
|
||||
|
||||
def a_host_only_face(manifest: Manifest, prefer: Iterable[str] = (), extra_known: Iterable[str] = ()) -> dict:
|
||||
"""One host-only face with a PostScript name and a full name a page can write: the first of the ``prefer`` families the host has, else the first.
|
||||
|
||||
The face is what a ``src: local()`` is given: its names exist on this machine (the file is on its disk) and in no bundle."""
|
||||
faces = [f for f in host_only_faces(manifest, extra_known) if _plain(f["psname"]) and _plain(f["full"])]
|
||||
assert faces, "the host has no font whose names are not the bundle's: there is nothing to ask the engine for that only the host knows"
|
||||
for wanted in prefer:
|
||||
for face in faces:
|
||||
if wanted.lower() in (family.lower() for family in face["families"]):
|
||||
return face
|
||||
return faces[0]
|
||||
@@ -0,0 +1,213 @@
|
||||
"""The pieces the e2e tests of the language and the zone a context declares share.
|
||||
|
||||
* ``serve(routes)``: a local HTTP server on a port the OS gives, answering a table of paths (the query is ignored), each with its bytes, its type
|
||||
and, if the test needs them, extra headers. Nothing leaves the machine.
|
||||
* ``open_chrome(port)`` / ``chrome(...)`` / ``set_pref(...)``: the engine's own chrome scope through Marionette, for what no protocol command of
|
||||
the wrapper does: writing ``intl.accept_languages`` while a session runs, and ``content_process_prefs(...)``: what a pref holds in the
|
||||
content process of each tab asked for (the proof that a process has taken a change, read from the process itself).
|
||||
* ``read_in_page_realm(page, body)``: runs ``body`` as an inline ``<script>`` of the page, so in the page's own realm, and returns what it
|
||||
wrote into the DOM. ``page.evaluate`` is not the page's realm on this engine; an inline script is what a site runs.
|
||||
* the measuring scripts of the canvas tests (``MEASURE_JS``): the width of a few strings as a canvas of one language group draws them.
|
||||
|
||||
No clock, no port written as a number, no environment written here.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import json
|
||||
import threading
|
||||
from typing import Any, Dict, Tuple, Union
|
||||
|
||||
import webfont_probe
|
||||
|
||||
#: What the launch of a browser whose chrome scope is read through Marionette is given (the env var MOZ_REMOTE_ALLOW_SYSTEM_ACCESS
|
||||
#: is set by the test with ``monkeypatch``).
|
||||
MARIONETTE_ARGS = ["-marionette", "-remote-allow-system-access"]
|
||||
|
||||
Route = Union[bytes, Tuple[bytes, str], Tuple[bytes, str, Dict[str, str]]]
|
||||
|
||||
|
||||
def serve(routes: Dict[str, Route]):
|
||||
"""A server for ``routes``; returns ``(server, base_url)``. Stop it with :func:`stop`."""
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
path = self.path.split("?", 1)[0]
|
||||
route = routes.get(path)
|
||||
if route is None:
|
||||
self.send_response(404)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
if isinstance(route, bytes):
|
||||
route = (route, "text/html; charset=utf-8")
|
||||
body, kind = route[0], route[1]
|
||||
extra = route[2] if len(route) > 2 else {}
|
||||
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")
|
||||
for name, value in extra.items():
|
||||
self.send_header(name, value)
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
server.daemon_threads = True
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server, "http://127.0.0.1:%d" % server.server_address[1]
|
||||
|
||||
|
||||
def stop(server) -> None:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
PAGE = b"<!doctype html><html><head><meta charset=utf-8><title>t</title></head><body><p id=p>t</p></body></html>"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------- the chrome scope
|
||||
|
||||
def open_chrome(port: int):
|
||||
"""A Marionette session in chrome scope on the engine that listens on ``port``."""
|
||||
marionette = webfont_probe._Marionette(port)
|
||||
marionette.call("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {}}})
|
||||
marionette.call("WebDriver:SetTimeouts", {"script": 240000})
|
||||
marionette.call("Marionette:SetContext", {"value": "chrome"})
|
||||
return marionette
|
||||
|
||||
|
||||
def chrome(marionette, script: str, *args: Any) -> Any:
|
||||
"""Run ``script`` (the body of a function that returns ``JSON.stringify(...)``) in chrome scope; its answer, decoded."""
|
||||
return json.loads(marionette.call("WebDriver:ExecuteScript", {"script": script, "args": list(args)})["value"])
|
||||
|
||||
|
||||
SET_STRING_PREF_JS = """
|
||||
const [name, value] = arguments;
|
||||
Services.prefs.setStringPref(name, value);
|
||||
return JSON.stringify(Services.prefs.getStringPref(name));
|
||||
"""
|
||||
|
||||
|
||||
def set_pref(marionette, name: str, value: str) -> str:
|
||||
return chrome(marionette, SET_STRING_PREF_JS, name, value)
|
||||
|
||||
|
||||
#: What the content process of each tab holds for a pref, read in that process. ``arguments``: the pref's name and the labels of the tabs; a tab is
|
||||
#: found by its address ending in ``?<label>``. A process script (``Services.ppmm.loadProcessScript``, a data: URL, only the processes that exist)
|
||||
#: runs in every process and sends back its pid and the value ``Services.prefs`` of THAT process gives; the answer comes when each tab's process
|
||||
#: has answered. The parent sends a pref change to a content process before this message on the same channel, and the process applies it
|
||||
#: (and runs its observers) before it runs the script, so a process that answers has handled the change.
|
||||
PROCESS_PREFS_JS = """
|
||||
const [name, labels] = arguments;
|
||||
const done = arguments[arguments.length - 1];
|
||||
const wanted = {};
|
||||
for (const win of Services.wm.getEnumerator('navigator:browser')) {
|
||||
for (const tab of win.gBrowser.tabs) {
|
||||
const spec = tab.linkedBrowser.currentURI.spec;
|
||||
const wg = tab.linkedBrowser.browsingContext && tab.linkedBrowser.browsingContext.currentWindowGlobal;
|
||||
for (const label of labels) {
|
||||
if (spec.endsWith('?' + label) && wg && wg.domProcess) { wanted[label] = wg.domProcess.osPid; }
|
||||
}
|
||||
}
|
||||
}
|
||||
const missing = labels.filter((label) => !(label in wanted));
|
||||
if (missing.length) { done(JSON.stringify({missing})); return; }
|
||||
const KEY = 'invisible-probe:pref';
|
||||
const answers = {};
|
||||
const listener = {
|
||||
receiveMessage(message) {
|
||||
answers[message.data.pid] = message.data.value;
|
||||
if (Object.values(wanted).every((pid) => pid in answers)) {
|
||||
Services.ppmm.removeMessageListener(KEY, listener);
|
||||
const prefs = {};
|
||||
for (const [label, pid] of Object.entries(wanted)) { prefs[label] = answers[pid]; }
|
||||
done(JSON.stringify({pids: wanted, prefs}));
|
||||
}
|
||||
},
|
||||
};
|
||||
Services.ppmm.addMessageListener(KEY, listener);
|
||||
const body = 'sendAsyncMessage(' + JSON.stringify(KEY) + ', {pid: Services.appinfo.processID, value: Services.prefs.getStringPref(' + JSON.stringify(name) + ', "")});';
|
||||
Services.ppmm.loadProcessScript('data:,' + encodeURIComponent(body), false);
|
||||
"""
|
||||
|
||||
|
||||
def content_process_prefs(marionette, name: str, labels) -> Dict[str, Any]:
|
||||
"""``{"pids": {label: pid}, "prefs": {label: value}}``: what pref ``name`` holds in the content process of each tab whose address ends with
|
||||
``?<label>`` (or ``{"missing": [labels]}`` when a tab is not there)."""
|
||||
answer = marionette.call("WebDriver:ExecuteAsyncScript", {"script": PROCESS_PREFS_JS, "args": [name, list(labels)]})
|
||||
return json.loads(answer["value"])
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------------------------------------------------- the page realm
|
||||
|
||||
def read_in_page_realm(page, body: str, name: str = "read") -> Any:
|
||||
"""What ``body`` (the body of a function that returns a JSON-able value) gives when an inline script of the page runs it."""
|
||||
page.add_script_tag(content=("document.documentElement.setAttribute('data-%s', JSON.stringify((() => {%s})()));" % (name, body)))
|
||||
return json.loads(page.evaluate("n => document.documentElement.getAttribute('data-' + n)", name))
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------------------------------ the workers
|
||||
|
||||
#: A dedicated worker that answers every message with the language its realm and its navigator speak.
|
||||
LANG_WORKER = b"""
|
||||
onmessage = () => postMessage({languages: [...navigator.languages],
|
||||
intl: Intl.DateTimeFormat().resolvedOptions().locale});
|
||||
"""
|
||||
|
||||
#: Starts that worker in the page and leaves ``window.__ask()`` to ask it again; the worker lives as long as the page.
|
||||
START_LANG_WORKER_JS = """() => {
|
||||
window.__worker = new Worker('/lang-worker.js');
|
||||
window.__ask = () => new Promise((ok) => {
|
||||
window.__worker.onmessage = (e) => ok(e.data);
|
||||
window.__worker.postMessage(0);
|
||||
});
|
||||
}"""
|
||||
|
||||
ASK_LANG_WORKER_JS = "() => window.__ask()"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------------- the canvases
|
||||
|
||||
#: The width of a few strings, in two generic families, as a canvas of ONE language group draws them: Latin text (the generic serif of each
|
||||
#: group is another font), full-width Han, kana, half-width kana. ``widths(canvas)`` takes the 2D context's canvas, a main-thread or a
|
||||
#: worker's OffscreenCanvas, or an element: the font is resolved the way each of them resolves it, which is what the tests compare.
|
||||
MEASURE_JS = """
|
||||
const STRINGS = ['Hamburgefonstiv', '\\u6f22\\u5b57', '\\u3042\\u3044\\u3046', '\\uff71\\uff72\\uff73', '\\u76f4\\u9aa8'];
|
||||
function widths(context) {
|
||||
const out = {};
|
||||
for (const font of ['20px serif', '20px sans-serif']) {
|
||||
context.font = font;
|
||||
out[font] = STRINGS.map((s) => context.measureText(s).width);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
"""
|
||||
|
||||
#: A dedicated worker that measures on its own OffscreenCanvas and answers with the widths.
|
||||
MEASURE_WORKER = (MEASURE_JS + """
|
||||
onmessage = () => postMessage(widths(new OffscreenCanvas(300, 60).getContext('2d')));
|
||||
""").encode()
|
||||
|
||||
#: In the page: the worker's widths, the widths of an OffscreenCanvas of the main thread (no element, no ``lang``), and the widths of a canvas
|
||||
#: ELEMENT whose ``lang`` is each of the two languages asked for.
|
||||
MEASURE_PAGE_JS = """async (languages) => {
|
||||
%s
|
||||
const worker = await new Promise((ok) => {
|
||||
const w = new Worker('/measure-worker.js');
|
||||
w.onmessage = (e) => { ok(e.data); w.terminate(); };
|
||||
w.postMessage(0);
|
||||
});
|
||||
const offscreen = widths(new OffscreenCanvas(300, 60).getContext('2d'));
|
||||
const element = {};
|
||||
for (const lang of languages) {
|
||||
const c = document.createElement('canvas');
|
||||
c.setAttribute('lang', lang);
|
||||
document.body.appendChild(c);
|
||||
element[lang] = widths(c.getContext('2d'));
|
||||
}
|
||||
return {worker, offscreen, element};
|
||||
}""" % MEASURE_JS
|
||||
@@ -0,0 +1,126 @@
|
||||
"""What the window e2e tests ask the operating system itself: which window holds the input focus, on a display of the test's own.
|
||||
|
||||
A page's ``document.hasFocus()`` is what the engine reports. A test that judges "the first session kept the focus when another one took the display" must
|
||||
first know that the OS did give the focus to the second session's window; otherwise a green means only that nothing happened (the second window never took
|
||||
it, or took it later than the read). The OS answers that without the engine:
|
||||
|
||||
* Linux: the X input focus (``XGetInputFocus`` on the display the sessions share); the display is a private Xvfb started for the test (``a_display_of_its_own``),
|
||||
so no other test's headed window moves the focus in it;
|
||||
* Windows: the foreground window (``GetForegroundWindow``), the window of the session found by the title its page gave it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import ctypes
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
from typing import Iterator, Optional
|
||||
|
||||
#: ``None`` and ``PointerRoot``: what the X input focus is when no client holds it.
|
||||
_X_NO_WINDOW = (0, 1)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def a_display_of_its_own(monkeypatch) -> Iterator[str]:
|
||||
"""Linux: a private Xvfb (the number chosen by the server, ``-displayfd``), set as ``DISPLAY`` for the test and stopped at its end.
|
||||
|
||||
Two headed sessions started inside it see each other and nothing else; the Xvfb of ``xvfb-run`` that the parallel workers share is never touched."""
|
||||
process = subprocess.Popen(["Xvfb", "-displayfd", "1", "-screen", "0", "1920x1080x24", "-nolisten", "tcp"],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
||||
answer = {}
|
||||
reader = threading.Thread(target=lambda: answer.setdefault("line", process.stdout.readline()), daemon=True)
|
||||
reader.start()
|
||||
try:
|
||||
reader.join(60)
|
||||
number = answer.get("line", "").strip()
|
||||
assert number.isdigit(), "the private Xvfb did not give a display number (it said %r, exit %r)" % (number, process.poll())
|
||||
monkeypatch.setenv("DISPLAY", ":" + number)
|
||||
for name in ("WAYLAND_DISPLAY", "XAUTHORITY"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
yield ":" + number
|
||||
finally:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(30)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(30)
|
||||
process.stdout.close()
|
||||
|
||||
|
||||
class XFocus:
|
||||
"""The X input focus of a display, read through a connection of its own (libX11, as the engine's own client library)."""
|
||||
|
||||
def __init__(self, display: str) -> None:
|
||||
self.x11 = ctypes.CDLL("libX11.so.6")
|
||||
self.x11.XOpenDisplay.restype, self.x11.XOpenDisplay.argtypes = ctypes.c_void_p, (ctypes.c_char_p,)
|
||||
self.x11.XGetInputFocus.argtypes = (ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_int))
|
||||
self.x11.XCloseDisplay.argtypes = (ctypes.c_void_p,)
|
||||
self.connection = self.x11.XOpenDisplay(display.encode())
|
||||
assert self.connection, "no connection to the display %r" % display
|
||||
|
||||
def holder(self) -> int:
|
||||
window, revert = ctypes.c_ulong(), ctypes.c_int()
|
||||
self.x11.XGetInputFocus(self.connection, ctypes.byref(window), ctypes.byref(revert))
|
||||
return int(window.value)
|
||||
|
||||
def is_a_window(self, holder: int) -> bool:
|
||||
return holder not in _X_NO_WINDOW
|
||||
|
||||
def close(self) -> None:
|
||||
self.x11.XCloseDisplay(self.connection)
|
||||
self.connection = None
|
||||
|
||||
|
||||
class ForegroundWindow:
|
||||
"""Windows: the foreground window of the desktop the sessions run on, and the Firefox window a title names."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
from ctypes import wintypes
|
||||
|
||||
self.user32 = ctypes.WinDLL("user32", use_last_error=True)
|
||||
self.user32.GetForegroundWindow.restype = wintypes.HWND
|
||||
self.user32.SetForegroundWindow.argtypes = (wintypes.HWND,)
|
||||
self.enum = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
|
||||
|
||||
def holder(self) -> int:
|
||||
return self.user32.GetForegroundWindow() or 0
|
||||
|
||||
def is_a_window(self, holder: int) -> bool:
|
||||
return bool(holder)
|
||||
|
||||
def window_titled(self, title: str) -> Optional[int]:
|
||||
"""The one visible top-level Firefox window whose title starts with ``title``, or None (none, or more than one)."""
|
||||
found = []
|
||||
|
||||
def each(hwnd, _):
|
||||
name, text = ctypes.create_unicode_buffer(256), ctypes.create_unicode_buffer(512)
|
||||
self.user32.GetClassNameW(hwnd, name, 256)
|
||||
self.user32.GetWindowTextW(hwnd, text, 512)
|
||||
if name.value.startswith("MozillaWindowClass") and text.value.startswith(title) and self.user32.IsWindowVisible(hwnd):
|
||||
found.append(hwnd)
|
||||
return True
|
||||
|
||||
self.user32.EnumWindows(self.enum(each), 0)
|
||||
return found[0] if len(found) == 1 else None
|
||||
|
||||
def ask_for_the_foreground(self, hwnd: int) -> int:
|
||||
"""What a user does by clicking the window: the system may refuse it, and then the foreground is what the test reads."""
|
||||
self.user32.SetForegroundWindow(hwnd)
|
||||
return self.holder()
|
||||
|
||||
|
||||
def host_monitor_size() -> Optional[tuple]:
|
||||
"""Windows: the primary monitor in device pixels (the reading of a per-monitor-aware process, whatever the test's own awareness is); None elsewhere."""
|
||||
if sys.platform != "win32":
|
||||
return None
|
||||
user32 = ctypes.WinDLL("user32")
|
||||
user32.SetThreadDpiAwarenessContext.restype = ctypes.c_void_p
|
||||
user32.SetThreadDpiAwarenessContext.argtypes = (ctypes.c_void_p,)
|
||||
previous = user32.SetThreadDpiAwarenessContext(ctypes.c_void_p(-4))
|
||||
try:
|
||||
return (user32.GetSystemMetrics(0), user32.GetSystemMetrics(1))
|
||||
finally:
|
||||
if previous:
|
||||
user32.SetThreadDpiAwarenessContext(ctypes.c_void_p(previous))
|
||||
@@ -0,0 +1,110 @@
|
||||
"""A popup opened the way a page opens one, and what it reads of its own window.
|
||||
|
||||
Shared by `test_popup_geometry_is_the_declared_frame_e2e.py` and by the inner-size test of
|
||||
`test_fingerprint_surface.py`: both need a popup (`window.open` with features, from a click) whose document may carry an
|
||||
iframe of another site (so, under Fission, in another process), and both read the window geometry from inside it.
|
||||
|
||||
The popup is read with a CONDITION, not a pause: the reading is repeated (with the client's events being read between two
|
||||
looks) until the caller's `ready` holds or 30 s have passed, and the last reading is returned either way, so the caller's
|
||||
assertion names what was read when it never settled.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from typing import Any, Callable, Dict, Optional
|
||||
|
||||
from _fission_frames import Sites, wait_frame
|
||||
from _waits import wait_until
|
||||
|
||||
#: The scale at which the declared window frame is the one of `WINDOW_FRAME_BY_DPR[1.0]`: border 8, popup UI 72, default
|
||||
#: position 4 (device pixels, and CSS pixels at 1.0). The screen is the one the other surface tests pin.
|
||||
PIN = {"screen.width": 1920, "screen.height": 1080, "screen.dpr": 1.0}
|
||||
|
||||
#: A second declared window frame that no runner has: a border of 6, a popup UI of 53 above the content, a default position of 9. The declared frame at scale 1.0
|
||||
#: (8, 72, 4) is the frame of a retail Windows window, so a Windows runner's own popup has it too (outer - inner = 16 x 80) and a launch with the engine off
|
||||
#: cannot tell the declaration from the host there; a launch declared with ANOTHER frame can (the prefs are applied last, over the core's declaration).
|
||||
OTHER_FRAME = {"zoom.stealth.screen.frame_border": 6, "zoom.stealth.screen.popup_ui": 53, "zoom.stealth.screen.popup_position": 9}
|
||||
OTHER_BORDER, OTHER_POPUP_UI, OTHER_POSITION = 6, 53, 9
|
||||
|
||||
READ = """() => ({iw: innerWidth, ih: innerHeight, ow: outerWidth, oh: outerHeight,
|
||||
sx: screenX, sy: screenY, mx: mozInnerScreenX, my: mozInnerScreenY})"""
|
||||
|
||||
|
||||
def in_a_thread_of_its_own(fn: Callable[[], Any], timeout: float = 300) -> Any:
|
||||
"""Runs `fn` in a thread with no asyncio loop and gives back its result or raises its error.
|
||||
|
||||
For a module whose own fixture keeps a sync client open for the whole module: an open sync client leaves its loop marked as
|
||||
running in its thread, and a second sync client started in that thread refuses with "Playwright Sync API inside the asyncio
|
||||
loop". The second browser needs a thread of its own.
|
||||
"""
|
||||
box: Dict[str, Any] = {}
|
||||
|
||||
def run() -> None:
|
||||
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="second-sync-client", daemon=True)
|
||||
worker.start()
|
||||
worker.join(timeout)
|
||||
if worker.is_alive():
|
||||
raise AssertionError("the browser of the test did not end within %d s" % timeout)
|
||||
if "error" in box:
|
||||
raise box["error"]
|
||||
return box.get("value")
|
||||
|
||||
|
||||
def frame_of_the_declaration():
|
||||
"""The window frame the core declares at scale 1.0: what the engine adds to a popup's inner size."""
|
||||
from invisible_core.constants import WINDOW_FRAME_BY_DPR
|
||||
|
||||
return WINDOW_FRAME_BY_DPR[1.0]
|
||||
|
||||
|
||||
def frame_extra(border: int, popup_ui: int):
|
||||
"""What a popup adds to its inner size: (outer - inner) wide and high, for a border and a popup UI."""
|
||||
return (2 * border, popup_ui + border)
|
||||
|
||||
|
||||
def _plausible(reading: Dict[str, Any]) -> bool:
|
||||
"""Every size of every window read is above 0: the window (and its frame, if any) has been laid out."""
|
||||
return all(r["iw"] > 0 and r["ih"] > 0 and r["ow"] > 0 and r["oh"] > 0
|
||||
for r in (reading["popup"], reading["frame"]) if r is not None)
|
||||
|
||||
|
||||
def read_popup(binary: str, extra_prefs: Optional[Dict[str, Any]] = None, iframe: bool = False,
|
||||
ready: Optional[Callable[[Dict[str, Any]], bool]] = None,
|
||||
features: str = "width=500,height=400") -> Dict[str, Any]:
|
||||
"""Open `window.open(url, 'p', features)` (default `width=500,height=400`) from a click and read it.
|
||||
|
||||
Returns `{"popup": {...}, "frame": {...} or None}` with `iw ih ow oh sx sy mx my` (innerWidth, innerHeight,
|
||||
outerWidth, outerHeight, screenX, screenY, mozInnerScreenX, mozInnerScreenY) of the popup and, with `iframe`, of its
|
||||
iframe (another site, 200x150). `ready(reading)` says when the reading has settled (default: every size above 0).
|
||||
"""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with Sites() as s:
|
||||
s.route("A", "/main", "<!doctype html><title>main</title><button id='open' onclick=\"window.open('%s', 'p', "
|
||||
"'%s')\">open</button>" % (s.url("A", "/popup"), features))
|
||||
frame_html = ("<iframe id='f' src='%s' style='position:absolute;left:0;top:0;width:200px;height:150px;border:0'>"
|
||||
"</iframe>" % s.url("B", "/frame")) if iframe else ""
|
||||
s.route("A", "/popup", "<!doctype html><title>popup</title>" + frame_html)
|
||||
s.route("B", "/frame", "<!doctype html><title>frame</title>")
|
||||
with InvisiblePlaywright(seed=42, pin=PIN, binary_path=binary, headless=True, humanize=False,
|
||||
extra_prefs=extra_prefs) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(s.url("A", "/main"), wait_until="load", timeout=30000)
|
||||
with page.expect_popup(timeout=30000) as info:
|
||||
page.click("#open", timeout=30000)
|
||||
popup = info.value
|
||||
popup.wait_for_load_state("load", timeout=30000)
|
||||
frame = wait_frame(popup, s.origin["B"], "/frame", seconds=30) if iframe else None
|
||||
seen: Dict[str, Any] = {}
|
||||
|
||||
def settled() -> bool:
|
||||
seen["now"] = {"popup": popup.evaluate(READ), "frame": frame.evaluate(READ) if frame else None}
|
||||
return _plausible(seen["now"]) and (ready is None or bool(ready(seen["now"])))
|
||||
|
||||
wait_until(settled, 30, lambda: popup.wait_for_timeout(100))
|
||||
return seen["now"]
|
||||
+105
-6
@@ -21,10 +21,20 @@ test-only: the product never sets it) a content process that hosts a site is nam
|
||||
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.
|
||||
|
||||
Windows names no process, but the engine's own log names the type of every process it creates (`Setting remoteType of
|
||||
process <pid> to <type>` when a process is born with its type, `Changing remoteType of process <pid> from prealloc to
|
||||
<type>` when a spare one is given its site: `dom/ipc/ContentChild.cpp`, `RecvSetRemoteType`, log module `Process`). The
|
||||
type of a process that hosts a site is `webIsolated=<site>^<attributes>` (`dom/ipc/RemoteType.cpp`, `Stringify`), the
|
||||
same site the Linux name carries, and the process gets it before any document loads in it. So on Windows a test starts the
|
||||
engine with `LOG_ENV` and a file base (`MOZ_LOG_FILE`), and `remote_types(base)` reads which type each process was given (by pid and time, a pid being reused);
|
||||
liveness and the engine's own directory are still told by the process tree, so a process that has ended is not counted.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
@@ -57,9 +67,94 @@ def hosts_site(name, site):
|
||||
return len(prefix) >= NAME_LENGTH or name[len(prefix)] == "^"
|
||||
|
||||
|
||||
#: The environment that makes the engine write the type of each process it creates (`MOZ_LOG_FILE` is added by the
|
||||
#: test: a file base in its own temporary folder). Used where the system names no process (Windows).
|
||||
LOG_ENV = {"MOZ_LOG": "Process:5,timestamp,sync"}
|
||||
|
||||
_TYPE_GIVEN = re.compile(r"(?:Setting remoteType of process (\d+) to|Changing remoteType of process (\d+) from \S+ to) (\S+)")
|
||||
|
||||
#: The start of a line of `MOZ_LOG` with the `timestamp` option: `2026-11-22 10:11:12.123456 UTC - [Process 12: Thread]: ...`.
|
||||
_LOG_TIME = re.compile(r"^(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)\.(\d{6}) UTC - ")
|
||||
|
||||
#: How much earlier than the creation time of a process (psutil) its first log line may be stamped: the two clocks are
|
||||
#: read at different moments of its birth.
|
||||
BIRTH_SLACK = 0.25
|
||||
|
||||
|
||||
def _natural(path):
|
||||
"""The sort key that puts `base.child-2` before `base.child-10` (the plain order of names puts it after)."""
|
||||
return [int(part) if part.isdigit() else part for part in re.split(r"(\d+)", path.name)]
|
||||
|
||||
|
||||
def _stamp(line):
|
||||
"""The time of a log line in seconds since the epoch (UTC), or None when the line carries no timestamp."""
|
||||
match = _LOG_TIME.match(line)
|
||||
if match is None:
|
||||
return None
|
||||
year, month, day, hour, minute, second, micro = (int(g) for g in match.groups())
|
||||
return calendar.timegm((year, month, day, hour, minute, second)) + micro / 1e6
|
||||
|
||||
|
||||
def remote_types(base):
|
||||
"""`{pid: [(time, remote type), ...]}` of the processes the engine has logged to the files that start with the path
|
||||
`base` (`MOZ_LOG_FILE`: the parent writes `base`, each child its own `base.child-N`), each list in the order of the
|
||||
time the lines were logged (then the child number as a number, then the line). A pid alone does not name a process:
|
||||
the system gives the number of an ended process to a later one, and a later process of another site must not
|
||||
inherit the type of the old one. So the types stay stamped, and `type_of_process` chooses the ones of the process
|
||||
instance in hand. A process that logs twice (a spare one, then the site it is given) has two entries, the last wins."""
|
||||
entries = {}
|
||||
for order, path in enumerate(sorted(base.parent.glob(base.name + "*"), key=_natural)):
|
||||
for number, line in enumerate(path.read_text(encoding="utf-8", errors="replace").splitlines()):
|
||||
match = _TYPE_GIVEN.search(line)
|
||||
if match is None:
|
||||
continue
|
||||
stamp = _stamp(line)
|
||||
key = (stamp if stamp is not None else float("-inf"), order, number)
|
||||
entries.setdefault(int(match.group(1) or match.group(2)), []).append((key, stamp, match.group(3)))
|
||||
return {pid: [(stamp, remote_type) for _key, stamp, remote_type in sorted(found, key=lambda entry: entry[0])]
|
||||
for pid, found in entries.items()}
|
||||
|
||||
|
||||
def type_of_process(types, pid, created):
|
||||
"""The remote type the process `pid` born at `created` (epoch seconds, `psutil.Process.create_time()`) was given: the
|
||||
last one logged for the pid at or after its birth (less `BIRTH_SLACK`). Entries logged before the process existed
|
||||
are the ones of an earlier process that had the same pid, and are ignored. A line with no timestamp counts for any
|
||||
birth. `""` when the process has not logged its type yet."""
|
||||
chosen = ""
|
||||
for stamp, remote_type in types.get(pid, ()):
|
||||
if stamp is None or stamp >= created - BIRTH_SLACK:
|
||||
chosen = remote_type
|
||||
return chosen
|
||||
|
||||
|
||||
def hosts_site_by_type(remote_type, site):
|
||||
"""True when a process of the remote type `remote_type` hosts `site` (`http://a.test`): `<kind>=<site>` or
|
||||
`<kind>=<site>^<attributes>`. A process with no site (`web`, `prealloc`, `privilegedabout`, `extension`) has no `=`."""
|
||||
meta = remote_type.partition("=")[2]
|
||||
return meta == site or meta.startswith(site + "^")
|
||||
|
||||
|
||||
def site_pids_by_type(processes, site, types, engine_dir=None):
|
||||
"""Like `site_pids`, told by the remote types the engine logged (`remote_types`) instead of by the process name."""
|
||||
return _content_pids(processes, engine_dir, lambda proc, _name: hosts_site_by_type(_type_of(types, proc), site))
|
||||
|
||||
|
||||
def _type_of(types, proc):
|
||||
import psutil
|
||||
|
||||
try:
|
||||
return type_of_process(types, proc.pid, proc.create_time())
|
||||
except psutil.Error:
|
||||
return ""
|
||||
|
||||
|
||||
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."""
|
||||
return _content_pids(processes, engine_dir, lambda _proc, name: hosts_site(name, site))
|
||||
|
||||
|
||||
def _content_pids(processes, engine_dir, hosts):
|
||||
import psutil
|
||||
|
||||
pids = set()
|
||||
@@ -70,19 +165,23 @@ def site_pids(processes, site, engine_dir=None):
|
||||
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):
|
||||
if "-contentproc" in cmd and cmd and cmd[-1] == "tab" and hosts(proc, name):
|
||||
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."""
|
||||
def site_processes_below(root_pid, site, engine_dir=None, types=None):
|
||||
"""The pids of the processes below `root_pid` that host `site`. On Linux the name of the process says it; on Windows
|
||||
`types` (a function that returns `remote_types(base)` of the engine's log, see `LOG_ENV`) does. With neither, 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)
|
||||
if not sys.platform.startswith("linux") and types is None:
|
||||
pytest.skip("only Linux names a content process by the site it hosts; %s names none (pass `types`)" % sys.platform)
|
||||
try:
|
||||
children = psutil.Process(root_pid).children(recursive=True)
|
||||
except psutil.Error:
|
||||
return set()
|
||||
return site_pids(children, site, engine_dir)
|
||||
if sys.platform.startswith("linux"):
|
||||
return site_pids(children, site, engine_dir)
|
||||
return site_pids_by_type(children, site, types(), engine_dir)
|
||||
+155
-26
@@ -33,11 +33,20 @@ answer as the service; the plain-HTTP endpoint ``api.ipify.org:80`` is still
|
||||
answered here for the tests that ask it), and the UDP exit is what the fake STUN server puts in its XOR-MAPPED-ADDRESS.
|
||||
Both are chosen by the test (``tcp_exit`` and ``udp_exit`` arguments).
|
||||
|
||||
Any other CONNECT is really forwarded, and any other UDP datagram is really
|
||||
forwarded to its destination and the reply wrapped back, so a page, or an echo
|
||||
server on 127.0.0.1, can be reached through the gateway and the test can
|
||||
observe which road its bytes took (:attr:`Gateway.connects`,
|
||||
:attr:`Gateway.datagrams`).
|
||||
HERMETIC: a gateway of this module carries a CONNECT or a datagram only to the LAB (:func:`is_lab_destination`: loopback, the
|
||||
documentation ranges of RFC 5737 and RFC 3849 the tests use as lab exits and servers, the addresses of this host's own interfaces, where a server
|
||||
of a test may stand, and the name ``localhost``). These tests run in the gate of the candidate, where no test may depend on a real service, and the
|
||||
browser behind a gateway makes background requests of its own (a name of the vendor, a captive-portal check, a telemetry endpoint): such a
|
||||
destination is REFUSED, never forwarded (a CONNECT is answered with reply 2, "not allowed"; a datagram is dropped), and RECORDED
|
||||
(:class:`LabGuard`: the time since the gateway started, the SOCKS5 address type, the destination as it was received - the NAME for type 3 -, the
|
||||
port and the protocol, ``tcp`` or ``udp``). The record is always written, when the gateway is closed, under
|
||||
``$RUNNER_TEMP/invpw-evidence/<gateway>/<pid>-<ms>/refused-destinations.json`` (the folder the e2e jobs upload; off a runner nothing is
|
||||
written), so that a reader sees what the browser asked for besides what the test drives. There is no option that reopens it. A subclass can only
|
||||
narrow it (:meth:`Gateway._admits`); the destinations it serves itself (the fake STUN server, the page of ``WEB_NAME``, the exit questions) are
|
||||
answered before it, and a name mapped to a local server by :meth:`Gateway._target` is judged by the server it maps to. What a test sees of the
|
||||
road is :attr:`Gateway.connects`, :attr:`Gateway.datagrams` (every datagram the relay read, carried or dropped) and
|
||||
:attr:`Gateway.guard`. :class:`Socks5TcpOnly` and the SOCKS5 server of ``test_proxy_socks_auth_e2e.py`` are hermetic the same way (same rule,
|
||||
same record).
|
||||
|
||||
This is the ONE SOCKS5 gateway of the test suite. A road that needs more than the three above (a TURN server, a resolver,
|
||||
a page, by NAME: ``tests/_turn_chain.py``) subclasses :class:`Gateway` and overrides the small hooks (:meth:`Gateway._route`,
|
||||
@@ -46,7 +55,10 @@ ASSOCIATE, the relay or the round trip.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import select
|
||||
import socket
|
||||
import struct
|
||||
@@ -55,7 +67,7 @@ import time
|
||||
from typing import Callable, Dict, 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.
|
||||
#: to the fake STUN server; every other destination is the lab's to carry or is refused (``LabGuard``).
|
||||
STUN_NAME = "stun.l.google.com"
|
||||
STUN_PORT = 19302
|
||||
#: The same STUN server by NUMBER. A page cannot resolve a name behind the session (the engine forbids local
|
||||
@@ -79,19 +91,18 @@ _MAGIC = b"\x21\x12\xa4\x42"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# The exit of a proxy that forwards for real. The question "where do I leave from" is HTTPS (api.ipify.org:443), and no gateway
|
||||
# of the tests can answer a TLS request as the service: a proxy that FORWARDS (a CONNECT to anything outside loopback goes out for
|
||||
# real) would carry it to the internet, and the answer would be the address of whatever machine runs the test (a GitHub runner
|
||||
# that changes NAT in the middle of a session: ``ProxyEgressDrifted``). So such a proxy DECLARES its exit (``declare_exit``) and
|
||||
# ``tests/_lab_egress.DeclaredExit`` answers the question with it; and as a backstop each of them refuses to forward the question
|
||||
# (``asks_the_world``), which records it and makes the test fail (``nobody_asked_the_world``), so that a proxy that forgot to declare
|
||||
# is a red with its name and not a flaky green.
|
||||
# The exit of a proxy that relays CONNECTs. The question "where do I leave from" is HTTPS (api.ipify.org:443), and no gateway
|
||||
# of the tests can answer a TLS request as the service. A gateway of this module is hermetic (a CONNECT outside the lab is refused, see
|
||||
# ``LabGuard``), so the question could not reach the internet through it anyway; but the product would then be told no exit at all. So such a
|
||||
# proxy DECLARES its exit (``declare_exit``) and ``tests/_lab_egress.DeclaredExit`` answers the question with it; and as a backstop each of
|
||||
# them refuses the question itself (``asks_the_world``), which records it and makes the test fail (``nobody_asked_the_world``), so that a
|
||||
# proxy that forgot to declare is a red with its name and not a flaky green.
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
#: The hosts of the services of the core that tell a caller its address (``invisible_core._geo._IP_ECHO_ENDPOINTS`` and
|
||||
#: ``_IPV6_ECHO_ENDPOINTS``; ``tests/test_a_launch_asks_nobody_on_the_internet_where_it_leaves_from.py`` checks that this list covers them).
|
||||
EXIT_SERVICES = ("api.ipify.org", "api6.ipify.org", "icanhazip.com", "ipv6.icanhazip.com", "checkip.amazonaws.com", "ifconfig.me")
|
||||
|
||||
#: ``host:port`` of a proxy of the tests that forwards for real -> the exit it declares. Filled by the proxies themselves.
|
||||
#: ``host:port`` of a proxy of the tests that relays CONNECTs -> the exit it declares. Filled by the proxies themselves.
|
||||
_DECLARED_EXITS: Dict[str, str] = {}
|
||||
#: The questions of the exit that reached a forwarding proxy and were refused there: one sentence each, until a test reads them.
|
||||
_WORLD_QUESTIONS: List[str] = []
|
||||
@@ -103,7 +114,7 @@ def _endpoint(server: str) -> str:
|
||||
|
||||
|
||||
def declare_exit(server: str, exit_ip: str) -> None:
|
||||
"""The proxy at ``server`` forwards for real and says its exit is ``exit_ip``."""
|
||||
"""The proxy at ``server`` relays CONNECTs and says its exit is ``exit_ip``."""
|
||||
_DECLARED_EXITS[_endpoint(server)] = exit_ip
|
||||
|
||||
|
||||
@@ -117,10 +128,10 @@ def declared_exit_of(server: Optional[str]) -> Optional[str]:
|
||||
|
||||
|
||||
def asks_the_world(server: str, host: str, port: int) -> bool:
|
||||
"""True, and the question is recorded, when a CONNECT to ``host:port`` is the question of the exit: the proxy must refuse it, not forward it."""
|
||||
"""True, and the question is recorded, when a CONNECT to ``host:port`` is the question of the exit: the proxy must refuse it (the lab answers it with the declared exit)."""
|
||||
if host.lower() not in EXIT_SERVICES:
|
||||
return False
|
||||
_WORLD_QUESTIONS.append("%s was asked %s:%d: the question of the exit reached a proxy that would have forwarded it to the internet" % (
|
||||
_WORLD_QUESTIONS.append("%s was asked %s:%d: the question of the exit reached a proxy of the lab, which refuses it (its exit is declared, not asked of the internet)" % (
|
||||
server, host, port))
|
||||
return True
|
||||
|
||||
@@ -149,6 +160,91 @@ def _recv_exact(s: socket.socket, n: int) -> bytes:
|
||||
return data
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
# The lab. A gateway of the tests forwards nothing that is not the lab's: the destination is refused and recorded.
|
||||
# ----------------------------------------------------------------------------------------------------------------
|
||||
#: The networks that are the lab's whatever the host: loopback, and the documentation ranges (RFC 5737 TEST-NET-1/2/3, RFC 3849) that the tests use
|
||||
#: for their exits and their servers (nothing routes them: a test holds the ones a server stands at on ``lo``).
|
||||
LAB_NETWORKS = tuple(ipaddress.ip_network(net) for net in (
|
||||
"127.0.0.0/8", "::1/128", "192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24", "2001:db8::/32"))
|
||||
#: The folder under ``$RUNNER_TEMP`` the e2e workflows upload (``invpw-evidence-*``).
|
||||
EVIDENCE_FOLDER = "invpw-evidence"
|
||||
|
||||
|
||||
def _own_addresses() -> Set[str]:
|
||||
"""The addresses assigned to an interface of this host (a server of a test stands at one of them), or none when they cannot be listed."""
|
||||
try:
|
||||
from _witness import host_addresses
|
||||
|
||||
return host_addresses()
|
||||
except Exception:
|
||||
return set()
|
||||
|
||||
|
||||
def is_lab_destination(host: str) -> bool:
|
||||
"""Whether ``host`` (an address, or a name as a SOCKS5 client sent it) is the lab's: loopback, a documentation range, an address of one of this host's
|
||||
own interfaces, or ``localhost``. Any other NAME is not: nothing here resolves a name for the internet's sake, and the question would leave the machine."""
|
||||
text = host.strip().strip("[]").split("%", 1)[0].rstrip(".").lower()
|
||||
try:
|
||||
address = ipaddress.ip_address(text)
|
||||
except ValueError:
|
||||
return text == "localhost" or text.endswith(".localhost")
|
||||
mapped = getattr(address, "ipv4_mapped", None)
|
||||
if mapped is not None:
|
||||
address = mapped
|
||||
if any(address in network for network in LAB_NETWORKS):
|
||||
return True
|
||||
return address.compressed in _own_addresses()
|
||||
|
||||
|
||||
class LabGuard:
|
||||
"""What refuses a destination that is not the lab's and writes it down: one per gateway.
|
||||
|
||||
:meth:`admits` is asked with the destination as RECEIVED (``atyp`` is the SOCKS5 address type: 1 IPv4, 3 a name, 4 IPv6; ``protocol`` is ``"tcp"`` or
|
||||
``"udp"``); ``target`` is where it would really go, as (host, port), when that is not the destination itself (a name a gateway maps to a local server): the lab's
|
||||
decision is about the target. A refusal is recorded in :attr:`records` as a dict with ``t`` (seconds since ``t0``, the start of the gateway), ``atyp``,
|
||||
``destination`` (as received), ``port`` and ``protocol``. :meth:`write_evidence` leaves them, always, under ``$RUNNER_TEMP/invpw-evidence/<name>/``."""
|
||||
|
||||
def __init__(self, name: str, t0: Optional[float] = None):
|
||||
self.name = name
|
||||
self.t0 = time.monotonic() if t0 is None else t0
|
||||
#: Every refusal, in order.
|
||||
self.records: List[dict] = []
|
||||
self._lock = threading.Lock()
|
||||
self._written = False
|
||||
|
||||
def admits(self, host: str, port: int, atyp: int, protocol: str, target: Optional[Tuple[str, int]] = None) -> bool:
|
||||
if is_lab_destination(host if target is None else target[0]):
|
||||
return True
|
||||
self.refuse(host, port, atyp, protocol)
|
||||
return False
|
||||
|
||||
def refuse(self, host: str, port: int, atyp: int, protocol: str) -> None:
|
||||
"""Write down a destination that was refused (by this guard's rule, or by the narrower rule of a subclass)."""
|
||||
record = {"t": round(time.monotonic() - self.t0, 3), "atyp": atyp, "destination": host, "port": port, "protocol": protocol}
|
||||
with self._lock:
|
||||
self.records.append(record)
|
||||
|
||||
def refused(self, protocol: Optional[str] = None) -> List[Tuple[str, int]]:
|
||||
"""Every refused destination as (destination as received, port), in order; of one protocol when asked."""
|
||||
with self._lock:
|
||||
return [(r["destination"], r["port"]) for r in self.records if protocol is None or r["protocol"] == protocol]
|
||||
|
||||
def write_evidence(self, extra: Optional[dict] = None) -> Optional[pathlib.Path]:
|
||||
"""Write the record, once (a gateway may be closed twice): the file written, or None off a runner (no ``$RUNNER_TEMP``) or when already written."""
|
||||
runner_temp = os.environ.get("RUNNER_TEMP")
|
||||
with self._lock:
|
||||
if self._written or not runner_temp:
|
||||
return None
|
||||
self._written = True
|
||||
records = list(self.records)
|
||||
folder = pathlib.Path(runner_temp) / EVIDENCE_FOLDER / self.name / ("%d-%d" % (os.getpid(), int(time.time() * 1000)))
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
path = folder / "refused-destinations.json"
|
||||
path.write_text(json.dumps(dict({"gateway": self.name, "refused": records}, **(extra or {})), indent=2), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
class FakeStun:
|
||||
"""A UDP STUN server that answers every binding request with ``mapped_ip``."""
|
||||
|
||||
@@ -215,10 +311,12 @@ class FakeStun:
|
||||
class Gateway:
|
||||
"""A SOCKS5 server. ``udp`` is ``"relay"`` or ``"refuse"`` (reply code 7)."""
|
||||
|
||||
#: Whether a CONNECT that is not special is forwarded for real, past loopback: such a gateway declares ``tcp_exit`` as its exit
|
||||
#: Whether this gateway relays the CONNECTs that are not special (to the lab: it is hermetic): such a gateway declares ``tcp_exit`` as its exit
|
||||
#: (``declare_exit``). A subclass that refuses everything but loopback (``tests/_doh_servers.DohGateway``) sets False: it cannot carry the
|
||||
#: question of the exit anywhere, and the question is left to what answers it.
|
||||
forwards_for_real = True
|
||||
#: The name of the folder of the record of what this gateway refused under ``$RUNNER_TEMP/invpw-evidence/`` (a subclass may name its own).
|
||||
evidence_name = "socks5-gateway"
|
||||
|
||||
def __init__(self, *, udp: str, tcp_exit: str, udp_exit: str,
|
||||
user: Optional[str] = None, password: Optional[str] = None,
|
||||
@@ -269,6 +367,9 @@ class Gateway:
|
||||
self.associates = 0
|
||||
#: When the gateway started: the origin of the times below.
|
||||
self.t0 = time.monotonic()
|
||||
#: What refuses (and records, and writes under ``$RUNNER_TEMP/invpw-evidence/<evidence_name>/`` when the gateway is closed) every destination that is
|
||||
#: not the lab's, CONNECT or datagram: ``guard.records``, ``guard.refused()``.
|
||||
self.guard = LabGuard(self.evidence_name, self.t0)
|
||||
#: 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.
|
||||
@@ -287,8 +388,8 @@ class Gateway:
|
||||
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.
|
||||
#: The hosts the relay forwards a datagram to (the fake STUN server aside), among the lab's; None: any host of the lab. It only narrows: a host
|
||||
#: that is not the lab's is never forwarded (``guard``).
|
||||
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)
|
||||
@@ -330,6 +431,11 @@ class Gateway:
|
||||
except OSError:
|
||||
pass
|
||||
self.stun.close()
|
||||
self.guard.write_evidence(self._evidence())
|
||||
|
||||
def _evidence(self) -> dict:
|
||||
"""What a subclass adds to the record of the refusals written at the close (a dict of JSON values)."""
|
||||
return {}
|
||||
|
||||
def __enter__(self) -> "Gateway":
|
||||
return self
|
||||
@@ -397,9 +503,10 @@ class Gateway:
|
||||
self._send(c, b"\x01\x00")
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _read_address(c: socket.socket) -> Tuple[str, int]:
|
||||
def _read_address(self, c: socket.socket) -> Tuple[str, int]:
|
||||
"""The destination of a request, as received (the NAME for address type 3); its address type is left in ``self._local.atyp``."""
|
||||
atyp = _recv_exact(c, 1)[0]
|
||||
self._local.atyp = atyp
|
||||
if atyp == 1:
|
||||
host = socket.inet_ntoa(_recv_exact(c, 4))
|
||||
elif atyp == 3:
|
||||
@@ -442,6 +549,12 @@ 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 _admits(self, host: str, port: int, atyp: int, protocol: str, target: Optional[Tuple[str, int]] = None) -> bool:
|
||||
"""Whether the gateway carries a CONNECT (``protocol`` ``"tcp"``) or a datagram (``"udp"``) to ``host``:``port`` (as received; ``atyp`` is its SOCKS5
|
||||
address type), or to ``target`` (host, port) when it is mapped elsewhere: only the lab's, and the rest is refused and recorded (``guard``). A subclass may narrow
|
||||
it (never widen it: call this one first)."""
|
||||
return self.guard.admits(host, port, atyp, protocol, target)
|
||||
|
||||
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:
|
||||
@@ -478,8 +591,12 @@ class Gateway:
|
||||
if self.forwards_for_real and asks_the_world(self.server, host, port):
|
||||
self._send(c, self._reply(2)) # not allowed: the exit of this gateway is declared, it is not asked of the internet
|
||||
return
|
||||
target = self._target(host, port)
|
||||
if not self._admits(host, port, getattr(self._local, "atyp", 3), "tcp", target):
|
||||
self._send(c, self._reply(2)) # not allowed: the gateway carries nothing outside the lab
|
||||
return
|
||||
try:
|
||||
up = self._open_upstream(self._target(host, port))
|
||||
up = self._open_upstream(target)
|
||||
except OSError:
|
||||
self._send(c, self._reply(5))
|
||||
return
|
||||
@@ -536,13 +653,15 @@ class Gateway:
|
||||
``target`` is the real address the datagram is sent to from the exit socket (``out_port`` is that socket's port);
|
||||
``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."""
|
||||
mapped and everything else is forwarded when it is the lab's (``_admits``); a datagram to any other destination is dropped and recorded."""
|
||||
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 not self._admits(host, dport, atyp, "udp"):
|
||||
return None # not the lab's: dropped, and recorded
|
||||
if self.forward_only_to is not None and host not in self.forward_only_to:
|
||||
return None
|
||||
return (host, dport), None
|
||||
@@ -685,12 +804,15 @@ def silent_udp(*, exit_ip: str = EXIT, user: Optional[str] = None, password: Opt
|
||||
# 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.
|
||||
"""Minimal SOCKS5: no-auth, CONNECT (TCP) relayed to the lab, 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.
|
||||
|
||||
Hermetic like :class:`Gateway`: a CONNECT to a destination that is not the lab's (:func:`is_lab_destination`) is refused with reply 2 and
|
||||
recorded in :attr:`guard` (written under ``$RUNNER_TEMP/invpw-evidence/socks5-tcp-only/`` when the server is closed).
|
||||
"""
|
||||
|
||||
def __init__(self, exit_ip: Optional[str] = None):
|
||||
@@ -699,10 +821,12 @@ class Socks5TcpOnly:
|
||||
self._srv.bind(("127.0.0.1", 0))
|
||||
self._srv.listen(16)
|
||||
self.port = self._srv.getsockname()[1]
|
||||
#: It relays a CONNECT for real, so it declares its exit (what a launch behind it is told: the lab's, unless a test gives another).
|
||||
#: It relays a CONNECT (to the lab), so it declares its exit (what a launch behind it is told: the lab's, unless a test gives another).
|
||||
self.exit_ip = exit_ip or _lab_exit()
|
||||
declare_exit(self.server, self.exit_ip)
|
||||
self.udp_associate_attempts = 0
|
||||
#: What refuses (and records) every CONNECT that is not the lab's.
|
||||
self.guard = LabGuard("socks5-tcp-only")
|
||||
self._stop = False
|
||||
self._t = threading.Thread(target=self._serve, daemon=True)
|
||||
self._t.start()
|
||||
@@ -762,6 +886,10 @@ class Socks5TcpOnly:
|
||||
conn.sendall(b"\x05\x02\x00\x01\x00\x00\x00\x00\x00\x00") # not allowed: the exit is declared, not asked of the internet
|
||||
conn.close()
|
||||
return
|
||||
if not self.guard.admits(addr, port, atyp, "tcp"):
|
||||
conn.sendall(b"\x05\x02\x00\x01\x00\x00\x00\x00\x00\x00") # not allowed: nothing outside the lab is carried
|
||||
conn.close()
|
||||
return
|
||||
try:
|
||||
upstream = socket.create_connection((addr, port), timeout=30)
|
||||
except OSError:
|
||||
@@ -801,3 +929,4 @@ class Socks5TcpOnly:
|
||||
self._srv.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.guard.write_evidence()
|
||||
@@ -17,13 +17,25 @@ def install_route(context):
|
||||
context.route("**/*", lambda route: route.abort() if route.request.resource_type in BLOCKED else route.continue_())
|
||||
|
||||
|
||||
def navigate(page, url, *, idle_timeout_ms):
|
||||
def navigate(page, url, *, idle_timeout_ms, client_log=None):
|
||||
"""`client_log`, a list (default None: nothing kept), gets one entry per event the client heard (wall time `t`, time.time(), and `m`, time.perf_counter()):
|
||||
the navigation's start and end, and every request, its response and its end. A test that saves evidence when it fails passes it."""
|
||||
rec = {"idle": False, "err": None, "seconds": None}
|
||||
# The requests the client has heard of and not yet heard the end of: a navigation that does not idle says who is still in flight
|
||||
# (type, method, url, frame). The process that hosts a request is not readable by a client.
|
||||
open_requests = {}
|
||||
|
||||
def note(event, request=None, **more):
|
||||
if client_log is None:
|
||||
return
|
||||
entry = {"ev": event, "t": round(time.time(), 4), "m": round(time.perf_counter(), 6), "url": url}
|
||||
if request is not None:
|
||||
entry.update(req=id(request), type=request.resource_type, method=request.method, target=request.url[:160])
|
||||
entry.update(more)
|
||||
client_log.append(entry)
|
||||
|
||||
def started(request):
|
||||
note("request", request)
|
||||
try:
|
||||
frame = request.frame.url[:100]
|
||||
except Exception:
|
||||
@@ -33,11 +45,18 @@ def navigate(page, url, *, idle_timeout_ms):
|
||||
|
||||
def ended(request):
|
||||
open_requests.pop(id(request), None)
|
||||
note("ended", request)
|
||||
|
||||
def answered(response):
|
||||
note("response", response.request, status=response.status)
|
||||
|
||||
t0 = time.monotonic()
|
||||
page.on("request", started)
|
||||
if client_log is not None:
|
||||
page.on("response", answered)
|
||||
page.on("requestfinished", ended)
|
||||
page.on("requestfailed", ended)
|
||||
note("navigation_start")
|
||||
try:
|
||||
page.goto(url, wait_until="commit", timeout=15000)
|
||||
page.wait_for_load_state("networkidle", timeout=idle_timeout_ms)
|
||||
@@ -47,16 +66,17 @@ def navigate(page, url, *, idle_timeout_ms):
|
||||
rec["err"] = (text.splitlines()[0] if text else repr(exc))[:200]
|
||||
rec["in_flight"] = list(open_requests.values())[:30]
|
||||
finally:
|
||||
for event, handler in (("request", started), ("requestfinished", ended), ("requestfailed", ended)):
|
||||
for event, handler in (("request", started), ("response", answered), ("requestfinished", ended), ("requestfailed", ended)):
|
||||
try:
|
||||
page.remove_listener(event, handler)
|
||||
except Exception:
|
||||
pass
|
||||
rec["seconds"] = round(time.monotonic() - t0, 2)
|
||||
note("navigation_end", idle=rec["idle"], err=rec["err"])
|
||||
return rec
|
||||
|
||||
|
||||
def drive(browser, origin, patterns, repetitions, idle_timeout_ms=10000):
|
||||
def drive(browser, origin, patterns, repetitions, idle_timeout_ms=10000, client_log=None):
|
||||
"""Every pattern `repetitions` times, each followed by the canary. Returns a list of cells."""
|
||||
cells = []
|
||||
context = browser.new_context()
|
||||
@@ -66,7 +86,7 @@ def drive(browser, origin, patterns, repetitions, idle_timeout_ms=10000):
|
||||
for rep in range(1, repetitions + 1):
|
||||
for name in patterns:
|
||||
for pattern, canary in ((name, False), ("quiet", True)):
|
||||
cell = navigate(page, "%s/p/%s" % (origin, pattern), idle_timeout_ms=idle_timeout_ms)
|
||||
cell = navigate(page, "%s/p/%s" % (origin, pattern), idle_timeout_ms=idle_timeout_ms, client_log=client_log)
|
||||
cell.update(round=rep, pattern=pattern, canary=canary, after=name if canary else None)
|
||||
cells.append(cell)
|
||||
finally:
|
||||
|
||||
+43
-1
@@ -302,11 +302,27 @@ def frame_html(kind, own, other, params):
|
||||
) % (kind, kind, body)
|
||||
|
||||
|
||||
#: Most records kept per start(): a long run of the fake web is not a memory leak.
|
||||
MAX_RECORDS = 50000
|
||||
|
||||
|
||||
class State:
|
||||
def __init__(self):
|
||||
self.origins = ["", ""]
|
||||
self.hits = {}
|
||||
self.lock = threading.Lock()
|
||||
#: What the server itself saw, in order: one `accept` per TCP connection and one `request` per request, each with its
|
||||
#: wall times (time.time(): arrival of the request, answer written, handler done; the Windows wall clock ticks every 15 ms, so
|
||||
#: the same moments are also kept as `m_*`, time.perf_counter() of this process, the scale of the client's log) and, if the
|
||||
#: client went away, the error.
|
||||
#: Read by a test that saves it as evidence when it fails (`start(...)[2].state.records`); nothing else reads it.
|
||||
self.records = []
|
||||
|
||||
def note(self, record):
|
||||
with self.lock:
|
||||
if len(self.records) < MAX_RECORDS:
|
||||
self.records.append(record)
|
||||
return record
|
||||
|
||||
def hit(self, path):
|
||||
with self.lock:
|
||||
@@ -323,6 +339,11 @@ class Site(ThreadingHTTPServer):
|
||||
self.idx = idx
|
||||
self.state = state
|
||||
|
||||
def process_request(self, request, client_address):
|
||||
self.state.note({"ev": "accept", "t": round(time.time(), 4), "m": round(time.perf_counter(), 6), "site": self.idx,
|
||||
"peer": client_address[1]})
|
||||
super().process_request(request, client_address)
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
@@ -340,15 +361,34 @@ class Handler(BaseHTTPRequestHandler):
|
||||
for k, v in (extra or {}).items():
|
||||
self.send_header(k, v)
|
||||
self.end_headers()
|
||||
rec = getattr(self, "_rec", None)
|
||||
if rec is not None:
|
||||
rec["status"] = code
|
||||
if body and self.command != "HEAD":
|
||||
self.wfile.write(body)
|
||||
if rec is not None:
|
||||
rec["t_answer"] = round(time.time(), 4)
|
||||
rec["m_answer"] = round(time.perf_counter(), 6)
|
||||
|
||||
def _guard(self, fn):
|
||||
# Browsers abort requests on purpose; a dropped socket is not an error here.
|
||||
wanted = ("Host", "Origin", "Referer", "Content-Type", "Content-Length", "Sec-Fetch-Site", "Sec-Fetch-Dest")
|
||||
rec = self._rec = self.server.state.note({
|
||||
"ev": "request", "t_arrive": round(time.time(), 4), "m_arrive": round(time.perf_counter(), 6), "site": self.server.idx, "peer": self.client_address[1],
|
||||
"method": self.command, "path": self.path,
|
||||
"headers": {k: self.headers.get(k) for k in wanted if self.headers.get(k) is not None},
|
||||
"status": None, "t_body": None, "t_answer": None, "t_done": None, "error": None})
|
||||
try:
|
||||
fn()
|
||||
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, TimeoutError):
|
||||
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, TimeoutError) as exc:
|
||||
rec["error"] = type(exc).__name__
|
||||
self.close_connection = True
|
||||
except BaseException as exc:
|
||||
rec["error"] = type(exc).__name__
|
||||
raise
|
||||
finally:
|
||||
rec["t_done"] = round(time.time(), 4)
|
||||
rec["m_done"] = round(time.perf_counter(), 6)
|
||||
|
||||
def do_GET(self):
|
||||
self._guard(self._get)
|
||||
@@ -367,6 +407,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
if n:
|
||||
self.rfile.read(n)
|
||||
self._rec["t_body"] = round(time.time(), 4)
|
||||
self.server.state.hit(u.path)
|
||||
self._send(204, None, b"")
|
||||
|
||||
@@ -453,6 +494,7 @@ def start(ports=(8311, 8312), bind="127.0.0.1", public_host=("127.0.0.1", "local
|
||||
s.shutdown()
|
||||
s.server_close()
|
||||
|
||||
stop.state = state # the server's own record (`state.records`), kept after stop()
|
||||
return state.origins[0], state.origins[1], stop
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"""A real click inside an iframe: `screenX - clientX` is the iframe's own `mozInnerScreenX`.
|
||||
|
||||
What it fixes: the relation a page checks with one subtraction on every mouse event, `event.screenX - event.clientX ==
|
||||
window.mozInnerScreenX` (and the same on Y), INSIDE an iframe placed at (220, 150) of the page. The defect of 2026-08-10:
|
||||
`mozInnerScreenX/Y` answered the origin of the top-level content to every window, so the iframe read (top origin) while
|
||||
its events still carried the iframe's offset, and `screenX - clientX` was 220 against a `mozInnerScreenX` of 0.
|
||||
|
||||
Engine hook: `fingerprint/screen-window/geometry` of the engine series: `nsGlobalWindowOuter::GetMozInnerScreenX/Y` and
|
||||
`Event::GetScreenCoords` both add the ONE content origin shift (`nsGlobalWindowOuter::StealthContentOriginShift`, declared
|
||||
window against real one) to the window's OWN real rectangle, so the offset between frames stays true at every depth.
|
||||
|
||||
Control, in the same test: the top window's `mozInnerScreenX/Y` is a different number (the iframe sits 220 and 150 CSS
|
||||
pixels off it). The test asserts the iframe's `mozInnerScreenX/Y` is the top's plus the iframe's rectangle, and that what
|
||||
the events carry (`screenX - clientX`) is NOT the top's origin: a window that answered the top origin to every frame fails
|
||||
both.
|
||||
|
||||
The click is a real one (`page.mouse.click` at a point inside the iframe, the pointer events the engine makes), not a
|
||||
dispatched event. The page and the iframe are one site, so the page may read the iframe's `mozInnerScreenX`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from _fission_frames import Sites
|
||||
from _waits import wait_until
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
LEFT, TOP = 220, 150
|
||||
|
||||
PARENT = """<!doctype html><meta charset=utf-8><title>parent</title>
|
||||
<style>html,body{margin:0;padding:0;height:100%%}
|
||||
#f{position:absolute;left:%dpx;top:%dpx;width:360px;height:220px;border:0}</style>
|
||||
<body><iframe id=f src="/child"></iframe>
|
||||
<script>
|
||||
window.__geom = () => {
|
||||
const w = document.getElementById('f').contentWindow;
|
||||
const r = document.getElementById('f').getBoundingClientRect();
|
||||
return {top_x: window.mozInnerScreenX, top_y: window.mozInnerScreenY,
|
||||
ifr_x: w.mozInnerScreenX, ifr_y: w.mozInnerScreenY, rect_x: r.x, rect_y: r.y};
|
||||
};
|
||||
</script>""" % (LEFT, TOP)
|
||||
|
||||
CHILD = """<!doctype html><meta charset=utf-8><title>child</title>
|
||||
<style>html,body{margin:0;padding:0;height:100%}
|
||||
#g{position:absolute;left:30px;top:40px;width:220px;height:130px;background:#06c}</style>
|
||||
<body><div id=g>y</div>
|
||||
<script>
|
||||
window.__ev = [];
|
||||
for (const t of ['mousemove', 'mousedown', 'mouseup', 'click']) {
|
||||
window.addEventListener(t, e => {
|
||||
window.__ev.push({t: t, cx: e.clientX, cy: e.clientY, sx: e.screenX, sy: e.screenY});
|
||||
}, true);
|
||||
}
|
||||
window.__inner = () => [window.mozInnerScreenX, window.mozInnerScreenY];
|
||||
</script>"""
|
||||
|
||||
|
||||
def test_a_real_click_in_an_iframe_has_the_screen_origin_of_the_iframe(firefox_binary):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with Sites() as s:
|
||||
s.route("A", "/parent", PARENT)
|
||||
s.route("A", "/child", CHILD)
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, humanize=False) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(s.url("A", "/parent"), wait_until="load", timeout=30000)
|
||||
geom = page.evaluate("() => window.__geom()")
|
||||
frame = page.frames[1]
|
||||
frame.evaluate("() => { window.__ev = []; }")
|
||||
# a point inside the blue square of the iframe, in the coordinates of the page
|
||||
page.mouse.click(LEFT + 30 + 100, TOP + 40 + 60)
|
||||
kinds = {"mousedown", "mouseup", "click"}
|
||||
assert wait_until(lambda: kinds <= {e["t"] for e in frame.evaluate("() => window.__ev")}, 30,
|
||||
lambda: page.wait_for_timeout(100)), (
|
||||
"the iframe heard %r of the click" % [e["t"] for e in frame.evaluate("() => window.__ev")])
|
||||
events = frame.evaluate("() => window.__ev")
|
||||
inner = frame.evaluate("() => window.__inner()")
|
||||
|
||||
# the iframe is where it was put, and answers its OWN origin: the top's plus the iframe's rectangle
|
||||
assert (geom["rect_x"], geom["rect_y"]) == (LEFT, TOP)
|
||||
assert (geom["ifr_x"], geom["ifr_y"]) == (geom["top_x"] + geom["rect_x"], geom["top_y"] + geom["rect_y"]), (
|
||||
"the iframe reads mozInnerScreen (%r, %r), the page's is (%r, %r) and the iframe sits at (%d, %d)"
|
||||
% (geom["ifr_x"], geom["ifr_y"], geom["top_x"], geom["top_y"], LEFT, TOP))
|
||||
assert (inner[0], inner[1]) != (geom["top_x"], geom["top_y"]), "the iframe answers the origin of the top-level content"
|
||||
clicks = [e for e in events if e["t"] == "click"]
|
||||
assert clicks, "no click event in the iframe: %r" % events
|
||||
for e in events:
|
||||
assert e["sx"] - e["cx"] == inner[0], (
|
||||
"%s in the iframe: screenX - clientX = %r against mozInnerScreenX = %r" % (e["t"], e["sx"] - e["cx"], inner[0]))
|
||||
assert e["sy"] - e["cy"] == inner[1], (
|
||||
"%s in the iframe: screenY - clientY = %r against mozInnerScreenY = %r" % (e["t"], e["sy"] - e["cy"], inner[1]))
|
||||
# the control: the top window's origin is NOT what the events carry
|
||||
assert (e["sx"] - e["cx"], e["sy"] - e["cy"]) != (geom["top_x"], geom["top_y"])
|
||||
@@ -0,0 +1,162 @@
|
||||
"""A context's language is the Accept-Language of every request that context makes, byte for byte, whatever the kind of request.
|
||||
|
||||
Characterisation of firefox-68 for the hook of fingerprint/locale-time/accept-language (nsHttpHandler.cpp: the list a language override
|
||||
is prepared into). The sibling file
|
||||
``test_accept_language_on_the_wire_e2e.py`` pins the LAUNCH language; this one pins the language of a CONTEXT that asks for its own,
|
||||
which reaches the engine another way (``Browser.setLocaleOverride`` writes the BrowsingContext's LanguageOverride, where the launch
|
||||
language is seeded from a pref) and which a request that has no BrowsingContext (a fetch of a worker, a service worker's) gets from the
|
||||
owner's data instead.
|
||||
|
||||
The header is read where a server reads it: the raw header line on a local socket. A retail Firefox 151 whose only pref is the
|
||||
``intl.accept_languages`` the core writes for it-IT ("it-IT, it, en-US, en") sends ``it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7`` on every
|
||||
request below (measured, see the sibling file). The kinds: the navigation, a sub-frame, an image, a stylesheet, a script, a ``fetch``, an
|
||||
XHR, a dedicated worker's script and its ``fetch``, a shared worker's script and its ``fetch``, a service worker's script and its ``fetch``.
|
||||
|
||||
The control is the other context of the same browser, which asked for nothing and keeps the launch's de-DE: every one of ITS requests
|
||||
carries the de-DE header and none carries Italian, so the header the first context sends is its own and not the session's.
|
||||
|
||||
On firefox-68 the four kinds a shared worker and a service worker make (the worker's script and its ``fetch``) carry the SESSION's de-DE
|
||||
header even from the it-IT context, on Linux and on Windows alike: the engine does not give those workers the context's language. They
|
||||
are left out of the it-IT context's check here and pinned, asking for it-IT, in
|
||||
``test_accept_language_of_the_context_in_shared_and_service_workers_e2e.py``. The de-DE control is checked on all of them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
#: invisible_core's list for it-IT / de-DE, prepared the way Firefox prepares intl.accept_languages (retail 151, measured).
|
||||
RETAIL_IT_IT = "it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7"
|
||||
RETAIL_DE_DE = "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7"
|
||||
|
||||
#: A 1x1 PNG.
|
||||
PNG = bytes.fromhex(
|
||||
"89504e470d0a1a0a0000000d4948445200000001000000010806000000"
|
||||
"1f15c4890000000d49444154789c6360f8cfc0f01f0005000201a5f645400000000049454e44ae426082")
|
||||
|
||||
PAGE = b"""<!doctype html><meta charset=utf-8><title>al</title>
|
||||
<link rel=stylesheet href=/style.css><script src=/script.js></script>
|
||||
<iframe src=/frame></iframe><img src=/image.png>
|
||||
<script>
|
||||
(async () => {
|
||||
await fetch('/fetch').then((r) => r.text());
|
||||
await new Promise((ok) => { const x = new XMLHttpRequest(); x.open('GET', '/xhr'); x.onloadend = ok; x.send(); });
|
||||
await new Promise((ok) => { const w = new Worker('/worker.js'); w.onmessage = ok; });
|
||||
await new Promise((ok) => { const s = new SharedWorker('/shared.js'); s.port.onmessage = ok; });
|
||||
await navigator.serviceWorker.register('/sw.js');
|
||||
await navigator.serviceWorker.ready;
|
||||
document.title = 'done';
|
||||
})();
|
||||
</script>"""
|
||||
|
||||
BODIES = {
|
||||
"/": (PAGE, b"text/html"),
|
||||
"/frame": (b"<!doctype html><title>frame</title>", b"text/html"),
|
||||
"/style.css": (b"body{}", b"text/css"),
|
||||
"/script.js": (b"window.loaded = 1;", b"text/javascript"),
|
||||
"/image.png": (PNG, b"image/png"),
|
||||
"/worker.js": (b"fetch('/worker-fetch').then((r) => r.text()).then(() => postMessage(1));", b"text/javascript"),
|
||||
"/shared.js": (b"onconnect = (e) => { fetch('/shared-fetch').then((r) => r.text()).then(() => e.ports[0].postMessage(1)); };",
|
||||
b"text/javascript"),
|
||||
# The install waits for the service worker's own fetch, so `ready` resolves after it.
|
||||
"/sw.js": (b"addEventListener('install', (e) => e.waitUntil(fetch('/sw-fetch').then((r) => r.text())));", b"text/javascript"),
|
||||
}
|
||||
|
||||
#: Every path a page of the site makes a request for (the favicon is the browser's own and is left out).
|
||||
KINDS = {
|
||||
"/": "navigation", "/frame": "sub-frame navigation", "/style.css": "stylesheet", "/script.js": "script", "/image.png": "image",
|
||||
"/fetch": "fetch", "/xhr": "XHR", "/worker.js": "dedicated worker script", "/worker-fetch": "dedicated worker fetch",
|
||||
"/shared.js": "shared worker script", "/shared-fetch": "shared worker fetch", "/sw.js": "service worker script",
|
||||
"/sw-fetch": "service worker fetch",
|
||||
}
|
||||
|
||||
#: The kinds that carry the session's header, not the context's, on firefox-68 (the context's own list is asserted for them elsewhere).
|
||||
SESSION_HEADER_KINDS = {"shared worker script", "shared worker fetch", "service worker script", "service worker fetch"}
|
||||
|
||||
|
||||
def _serve(seen):
|
||||
"""A server that keeps each request's path and raw Accept-Language lines."""
|
||||
s = socket.socket()
|
||||
s.bind(("127.0.0.1", 0))
|
||||
s.listen(16)
|
||||
|
||||
def one(conn):
|
||||
buf = b""
|
||||
try:
|
||||
while True:
|
||||
while b"\r\n\r\n" not in buf:
|
||||
chunk = conn.recv(65536)
|
||||
if not chunk:
|
||||
return
|
||||
buf += chunk
|
||||
head, buf = buf.split(b"\r\n\r\n", 1)
|
||||
lines = head.split(b"\r\n")
|
||||
path = lines[0].split(b" ")[1].decode("latin-1").split("?", 1)[0]
|
||||
seen.append((path, [ln.decode("latin-1") for ln in lines[1:] if ln.lower().startswith(b"accept-language:")]))
|
||||
body, ctype = BODIES.get(path, (b"ok", b"text/plain"))
|
||||
conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: " + ctype + b"\r\nCache-Control: no-store\r\nContent-Length: "
|
||||
+ str(len(body)).encode() + b"\r\n\r\n" + body)
|
||||
except OSError:
|
||||
return
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def loop():
|
||||
while True:
|
||||
try:
|
||||
conn, _ = s.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=one, args=(conn,), daemon=True).start()
|
||||
|
||||
threading.Thread(target=loop, daemon=True).start()
|
||||
return s
|
||||
|
||||
|
||||
def _headers_by_kind(seen):
|
||||
"""Each kind of request -> the Accept-Language lines of EVERY request of that kind (a script is fetched again on an update check)."""
|
||||
out = {}
|
||||
for path, lines in seen:
|
||||
if path in KINDS:
|
||||
out.setdefault(KINDS[path], []).append(lines)
|
||||
return out
|
||||
|
||||
|
||||
def test_a_context_list_is_the_retail_accept_language_on_every_request_kind(firefox_binary):
|
||||
"""⛔ A CONTEXT'S LANGUAGE REACHED THE PAGE AND NOT EVERY REQUEST. ``new_context(locale=...)`` is the language of that context's
|
||||
pages, and the header of a navigation followed it while the requests that carry no BrowsingContext (a worker's ``fetch``, a service
|
||||
worker's) kept what the session sent, or the raw list with its spaces and no q-values; a server then saw two languages and two
|
||||
spellings from one client. The context asks for it-IT inside a de-DE session; every request kind of it carries the retail it-IT
|
||||
header (but for the four kinds of shared and service workers, see the module docstring), and the other context's, which asked for
|
||||
nothing, the retail de-DE one on every kind.
|
||||
"""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
seen = {"it": [], "de": []}
|
||||
servers = {name: _serve(log) for name, log in seen.items()}
|
||||
urls = {name: "http://127.0.0.1:%d/" % srv.getsockname()[1] for name, srv in servers.items()}
|
||||
try:
|
||||
with InvisiblePlaywright(seed=5150, binary_path=firefox_binary, headless=True, locale="de-DE", timezone="Europe/Berlin") as browser:
|
||||
for name, options in (("it", {"locale": "it-IT"}), ("de", {})):
|
||||
page = browser.new_context(**options).new_page()
|
||||
page.goto(urls[name], wait_until="load", timeout=30_000)
|
||||
page.wait_for_function("document.title === 'done'", timeout=30_000)
|
||||
languages = page.evaluate("[...navigator.languages]")
|
||||
assert languages == (["it-IT", "it", "en-US", "en"] if name == "it" else ["de-DE", "de", "en-US", "en"]), (
|
||||
"navigator.languages of the %s context" % name)
|
||||
finally:
|
||||
for srv in servers.values():
|
||||
srv.close()
|
||||
for name, retail, other, left_out in (("it", RETAIL_IT_IT, RETAIL_DE_DE, SESSION_HEADER_KINDS), ("de", RETAIL_DE_DE, RETAIL_IT_IT, set())):
|
||||
by_kind = _headers_by_kind(seen[name])
|
||||
assert set(by_kind) == set(KINDS.values()), "the %s context: kinds of request seen %r" % (name, sorted(by_kind))
|
||||
checked = {kind: sent for kind, sent in by_kind.items() if kind not in left_out}
|
||||
wrong = {kind: sent for kind, sent in checked.items() if any(lines != ["Accept-Language: " + retail] for lines in sent)}
|
||||
assert not wrong, "the %s context must send %r on every request kind: %r" % (name, retail, wrong)
|
||||
assert not any(other in " ".join(lines) for sent in checked.values() for lines in sent), (
|
||||
"the %s context sent the other context's language" % name)
|
||||
assert RETAIL_IT_IT != RETAIL_DE_DE
|
||||
@@ -16,7 +16,8 @@ from `http://127.0.0.1:<port>`; a site never includes the port). The browser sta
|
||||
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.
|
||||
says so. On Windows, which names no process, the engine is started with `LOG_ENV` and the type each process was given
|
||||
is read from its log (tests/_processes.py `remote_types`).
|
||||
|
||||
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.
|
||||
@@ -25,6 +26,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
@@ -32,7 +34,7 @@ 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 _processes import LOG_ENV, NAMED_BY_SITE, remote_types, site_processes_below # noqa: E402
|
||||
from _servers import LocalServer # noqa: E402
|
||||
from _waits import awatch # noqa: E402
|
||||
|
||||
@@ -110,17 +112,23 @@ DEADLINE_S = 30
|
||||
REGISTERED = ("navigator.serviceWorker.getRegistration().then(r => !!r && !!(r.installing || r.waiting || r.active))")
|
||||
|
||||
|
||||
def test_closed_contexts_with_a_never_stopping_service_worker_leave_no_process(firefox_binary, engine_at_least):
|
||||
def test_closed_contexts_with_a_never_stopping_service_worker_leave_no_process(firefox_binary, engine_at_least, monkeypatch, tmp_path):
|
||||
engine_at_least(ENGINE_WITH_THE_FIX)
|
||||
from invisible_playwright import launch_server
|
||||
|
||||
# Windows names no process: the engine's own log says which type (so which site) each one was given
|
||||
log_base = tmp_path / "process-types"
|
||||
if sys.platform == "win32":
|
||||
monkeypatch.setenv("MOZ_LOG", LOG_ENV["MOZ_LOG"])
|
||||
monkeypatch.setenv("MOZ_LOG_FILE", str(log_base))
|
||||
|
||||
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,
|
||||
extra_prefs=NAMED_BY_SITE)
|
||||
|
||||
def sites():
|
||||
return site_processes_below(launched.process.pid, SITE)
|
||||
return site_processes_below(launched.process.pid, SITE, types=lambda: remote_types(log_base))
|
||||
|
||||
async def drive():
|
||||
opened, left = [], []
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"""A `goto` to an address Firefox refuses before it opens a channel ends, and says why.
|
||||
|
||||
`http://127.0.0.1:9/` is a restricted port (Firefox's list of ports it will not
|
||||
connect to): the load is refused inside the docshell, before any channel exists
|
||||
(`DocumentChannelChild::AsyncOpen` -> `nsDocShell::DoURILoad` fails ->
|
||||
`InternalLoad` shows the error page). No channel ever reports progress, so
|
||||
nothing that watches a request can end the navigation: the engine reports the
|
||||
failure itself, with the load identifier and the status
|
||||
(`StealthNavigationLoad::Failed` in `nsDocShell::DoURILoad`, folder
|
||||
`automation/navigation` of the engine series, `docshell/base/StealthNavigation.cpp`),
|
||||
and the client's `goto` raises with the name of the status,
|
||||
`NS_ERROR_PORT_ACCESS_NOT_ALLOWED`. Until firefox-55 the navigation was announced
|
||||
(`Page.navigationStarted`) and never ended: `goto` waited out its timeout, and
|
||||
the reason was only in the URL of the error page.
|
||||
|
||||
**What is asserted, and not a clock.** The `goto` raises, the text of the error
|
||||
is the status (and not a timeout: a deadline of 30 s is only the longest a
|
||||
healthy run is given), and the page is usable afterwards.
|
||||
|
||||
**Negative control.** A `goto` to an allowed local port where nothing listens
|
||||
also ends, with a DIFFERENT error (the connection is refused by the peer, a
|
||||
channel did open): the first test's text is the answer to the port, not what
|
||||
every failed `goto` says.
|
||||
|
||||
Why a page cares: a script that loads a refused address must learn it at once,
|
||||
by the name Firefox gives, and not hang until its own deadline.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
|
||||
import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
REFUSED_PORT_URL = "http://127.0.0.1:9/"
|
||||
PORT_REASON = "NS_ERROR_PORT_ACCESS_NOT_ALLOWED"
|
||||
REFUSED_REASON = "NS_ERROR_CONNECTION_REFUSED"
|
||||
|
||||
|
||||
class _Page(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
body = b"<html><title>after</title><body>after</body></html>"
|
||||
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 _goto_error(page, url):
|
||||
"""The text of the error a `goto` ends with (the test fails if it ends without one).
|
||||
|
||||
A failed `goto` is followed by Firefox's error page, a navigation of its own that commits after the call has
|
||||
raised (on Windows, late enough to land inside the next `goto`, which then reads as "interrupted by another
|
||||
navigation to" the refused address). The call is therefore made inside a wait for that navigation's
|
||||
`framenavigated`: it returns only once the error page has committed and the frame is quiet.
|
||||
"""
|
||||
with page.expect_event("framenavigated", timeout=30_000):
|
||||
with pytest.raises(Exception) as ended:
|
||||
page.goto(url, timeout=30_000)
|
||||
return str(ended.value)
|
||||
|
||||
|
||||
def test_a_goto_to_a_refused_port_ends_with_its_reason(firefox_binary):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
# a port nobody listens on, and that Firefox allows: bound and never listening, so no other program can take it
|
||||
closed = socket.socket()
|
||||
closed.bind(("127.0.0.1", 0))
|
||||
closed_url = "http://127.0.0.1:%d/" % closed.getsockname()[1]
|
||||
site = LocalServer(("127.0.0.1", 0), _Page)
|
||||
threading.Thread(target=site.serve_forever, daemon=True).start()
|
||||
try:
|
||||
with InvisiblePlaywright(seed=4242, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
|
||||
refused = _goto_error(page, REFUSED_PORT_URL)
|
||||
assert PORT_REASON in refused, refused
|
||||
assert "Timeout" not in refused, refused
|
||||
|
||||
# the control: the same call to an allowed port that is closed ends with another reason
|
||||
control = _goto_error(page, closed_url)
|
||||
assert REFUSED_REASON in control, control
|
||||
assert PORT_REASON not in control, control
|
||||
|
||||
# and the page the refused navigation left behind is a page that navigates
|
||||
page.goto("http://127.0.0.1:%d/" % site.server_address[1], timeout=30_000)
|
||||
assert page.title() == "after"
|
||||
finally:
|
||||
site.shutdown()
|
||||
site.server_close()
|
||||
closed.close()
|
||||
@@ -0,0 +1,156 @@
|
||||
"""The zone a launch declares, and the one a context asks for, reach everything a page reads the time from.
|
||||
|
||||
Characterisation of firefox-68; the hooks of fingerprint/locale-time/timezone in the engine series cite
|
||||
``test_a_launch_and_a_context_timezone_reach_the_page``. A page learns the zone of a machine from more places than ``Intl``:
|
||||
|
||||
* the realm's ``Intl`` and the offset of ``Date`` (``getTimezoneOffset``, ``toLocaleTimeString``), in the page's own realm
|
||||
(read by an INLINE script, the way a site reads it) and in a dedicated worker;
|
||||
* ``document.lastModified``, which formats the ``Last-Modified`` of the response, or the present moment when there is none, as a wall
|
||||
clock in the zone (Document.cpp, GetFormattedTimeString);
|
||||
* EXSLT's ``date:date-time()`` in an XSLT transform (txEXSLTFunctions.cpp), which is the wall clock too.
|
||||
|
||||
None of them may be read from the host. A launch declares its zone (``timezone="Pacific/Chatham"``, a zone with a quarter-hour offset
|
||||
and daylight time, which no runner has) and a context may ask for its own (``timezone_id="Asia/Kolkata"``, +05:30, no daylight time);
|
||||
every one of those places answers the zone of the context the page is in.
|
||||
|
||||
The control is the same reads on a launch whose declaration is EMPTY (``juggler.timezone.override`` empty, and a context that asks for no
|
||||
zone): the engine then has nothing to give and the values are the host's, which are not Chatham's. A control that agreed with Chatham
|
||||
would mean the test cannot tell a declared zone from the host's.
|
||||
|
||||
Expected values: the offsets of Pacific/Chatham on a date in January (daylight time, +13:45) and in July (+12:45) and of Asia/Kolkata
|
||||
(+05:30 all year) are the IANA database's; ``Last-Modified: Mon, 15 Jan 2024 10:00:00 GMT`` is 23:45:00 in Chatham and 15:30:00 in
|
||||
Kolkata. The present moment, with no ``Last-Modified``, is compared with the page's own offset: the wall clock minus the clock of the
|
||||
machine, rounded to a quarter of an hour, has to be the offset of the zone.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
import _locale_probe as probe
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
CHATHAM = "Pacific/Chatham"
|
||||
KOLKATA = "Asia/Kolkata"
|
||||
|
||||
#: Minutes AHEAD of UTC, the sign of ``-getTimezoneOffset()``: what the zone is on 15 January and on 15 July 2024.
|
||||
EXPECTED = {
|
||||
CHATHAM: {"january": 825, "july": 765, "time": "23:45:00", "last_modified": "01/15/2024 23:45:00"},
|
||||
KOLKATA: {"january": 330, "july": 330, "time": "15:30:00", "last_modified": "01/15/2024 15:30:00"},
|
||||
}
|
||||
|
||||
LAST_MODIFIED = "Mon, 15 Jan 2024 10:00:00 GMT"
|
||||
|
||||
#: An XSLT sheet whose only output is the current date-time of EXSLT.
|
||||
EXSLT_SHEET = (
|
||||
'<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" '
|
||||
'xmlns:date="http://exslt.org/dates-and-times" extension-element-prefixes="date">'
|
||||
'<xsl:output method="text"/><xsl:template match="/"><xsl:value-of select="date:date-time()"/></xsl:template></xsl:stylesheet>'
|
||||
)
|
||||
|
||||
#: What an inline script of the page reads. ``wall`` turns "MM/DD/YYYY HH:MM:SS" or an ISO date-time into the minutes it is AHEAD of the
|
||||
#: clock of the machine, to a quarter of an hour: the zone's offset, whatever the date.
|
||||
PAGE_READ = """
|
||||
const o = Intl.DateTimeFormat().resolvedOptions();
|
||||
const instant = new Date(Date.UTC(2024, 0, 15, 10, 0, 0));
|
||||
const ahead = (y, mo, d, h, mi, s) => Math.round((Date.UTC(y, mo - 1, d, h, mi, s) - Date.now()) / 60000 / 15) * 15;
|
||||
const lm = document.lastModified.match(/(\\d\\d)\\/(\\d\\d)\\/(\\d{4}) (\\d\\d):(\\d\\d):(\\d\\d)/);
|
||||
const processor = new XSLTProcessor();
|
||||
processor.importStylesheet(new DOMParser().parseFromString(%(sheet)s, 'application/xml'));
|
||||
const exslt = processor.transformToDocument(document).documentElement.textContent;
|
||||
const ex = exslt.match(/(\\d{4})-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)/);
|
||||
return {
|
||||
timeZone: o.timeZone,
|
||||
january: -new Date(Date.UTC(2024, 0, 15, 12)).getTimezoneOffset(),
|
||||
july: -new Date(Date.UTC(2024, 6, 15, 12)).getTimezoneOffset(),
|
||||
now: -new Date().getTimezoneOffset(),
|
||||
time: instant.toLocaleTimeString('en-GB'),
|
||||
lastModified: document.lastModified,
|
||||
lastModifiedAhead: lm ? ahead(+lm[3], +lm[1], +lm[2], +lm[4], +lm[5], +lm[6]) : null,
|
||||
exslt: exslt,
|
||||
exsltAhead: ex ? ahead(+ex[1], +ex[2], +ex[3], +ex[4], +ex[5], +ex[6]) : null,
|
||||
};
|
||||
""" % {"sheet": "`" + EXSLT_SHEET + "`"}
|
||||
|
||||
WORKER = b"""
|
||||
onmessage = () => postMessage({
|
||||
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
january: -new Date(Date.UTC(2024, 0, 15, 12)).getTimezoneOffset(),
|
||||
july: -new Date(Date.UTC(2024, 6, 15, 12)).getTimezoneOffset(),
|
||||
time: new Date(Date.UTC(2024, 0, 15, 10, 0, 0)).toLocaleTimeString('en-GB'),
|
||||
});
|
||||
"""
|
||||
|
||||
WORKER_JS = """() => new Promise((ok) => {
|
||||
const w = new Worker('/zone-worker.js');
|
||||
w.onmessage = (e) => { ok(e.data); w.terminate(); };
|
||||
w.postMessage(0);
|
||||
})"""
|
||||
|
||||
SITE = {
|
||||
"/with": (probe.PAGE, "text/html; charset=utf-8", {"Last-Modified": LAST_MODIFIED}),
|
||||
"/without": probe.PAGE,
|
||||
"/zone-worker.js": (WORKER, "text/javascript"),
|
||||
}
|
||||
|
||||
|
||||
def _read(page, base, with_last_modified):
|
||||
"""The page's reads of the zone, from an inline script of its own realm, and a dedicated worker's."""
|
||||
page.goto("%s/%s" % (base, "with" if with_last_modified else "without"), wait_until="load", timeout=30_000)
|
||||
return {"page": probe.read_in_page_realm(page, PAGE_READ), "worker": page.evaluate(WORKER_JS)}
|
||||
|
||||
|
||||
def _assert_zone(read, zone, label):
|
||||
want = EXPECTED[zone]
|
||||
page, worker = read["with"]["page"], read["with"]["worker"]
|
||||
assert page["timeZone"] == zone, "%s: Intl timeZone in the page realm" % label
|
||||
assert (page["january"], page["july"]) == (want["january"], want["july"]), "%s: getTimezoneOffset in the page realm: %r" % (label, page)
|
||||
assert page["time"] == want["time"], "%s: a date's wall clock in the page realm" % label
|
||||
assert page["lastModified"] == want["last_modified"], "%s: document.lastModified with a Last-Modified header" % label
|
||||
assert worker == {"timeZone": zone, "january": want["january"], "july": want["july"], "time": want["time"]}, (
|
||||
"%s: a dedicated worker" % label)
|
||||
# With no Last-Modified the page, the clock of the document and EXSLT's date-time agree on the zone's present offset.
|
||||
now = read["without"]["page"]
|
||||
assert now["timeZone"] == zone, "%s: Intl timeZone on a page with no Last-Modified" % label
|
||||
assert now["lastModifiedAhead"] == now["now"], (
|
||||
"%s: document.lastModified with no Last-Modified is %r, %d minutes ahead of the machine, the offset says %d"
|
||||
% (label, now["lastModified"], now["lastModifiedAhead"] or 0, now["now"]))
|
||||
assert now["exsltAhead"] == now["now"], (
|
||||
"%s: EXSLT date:date-time() is %r, %r minutes ahead of the machine, the offset says %d" % (label, now["exslt"], now["exsltAhead"], now["now"]))
|
||||
|
||||
|
||||
def test_a_launch_and_a_context_timezone_reach_the_page(firefox_binary):
|
||||
"""⛔ THE ZONE OF A MACHINE LEAKS FROM MANY PLACES, AND ONE OF THEM IS ALWAYS THE LAST TO BE CLOSED. ``Intl`` and ``Date`` were
|
||||
declared first; ``document.lastModified`` and EXSLT's ``date:date-time()`` format a time in the C library's local zone, which is the
|
||||
host's, and a worker's realm took the process's zone. A page reads all of them in one breath.
|
||||
|
||||
A launch with ``timezone="Pacific/Chatham"``: its default context reads Chatham in every place above. A second context with
|
||||
``timezone_id="Asia/Kolkata"`` of the same browser reads Kolkata in every place, with and without a ``Last-Modified`` header. The
|
||||
control is a launch whose declaration is empty (``juggler.timezone.override`` empty, a context that asks for no zone): there the
|
||||
values are the host's, and none of them is Chatham's, so the declared zone is what the first reads had.
|
||||
"""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
srv, base = probe.serve(SITE)
|
||||
try:
|
||||
with InvisiblePlaywright(seed=5150, binary_path=firefox_binary, headless=True, locale="en-US", timezone=CHATHAM) as browser:
|
||||
for label, zone, options in (("the launch's context", CHATHAM, {}), ("a context with timezone_id", KOLKATA, {"timezone_id": KOLKATA})):
|
||||
page = browser.new_context(**options).new_page()
|
||||
read = {"with": _read(page, base, True), "without": _read(page, base, False)}
|
||||
_assert_zone(read, zone, label)
|
||||
|
||||
with InvisiblePlaywright(seed=5150, binary_path=firefox_binary, headless=True, locale="en-US", timezone=CHATHAM,
|
||||
extra_prefs={"juggler.timezone.override": ""}) as browser:
|
||||
page = browser.new_context(timezone_id=None).new_page()
|
||||
host = {"with": _read(page, base, True), "without": _read(page, base, False)}
|
||||
chatham = EXPECTED[CHATHAM]
|
||||
seen = host["with"]["page"]
|
||||
assert seen["timeZone"] != CHATHAM, "the launch with no declared zone reads Chatham: the control cannot tell a declaration from the host"
|
||||
assert (seen["january"], seen["july"]) != (chatham["january"], chatham["july"]), seen
|
||||
assert seen["lastModified"] != chatham["last_modified"], seen
|
||||
assert host["with"]["worker"]["timeZone"] != CHATHAM, host["with"]["worker"]
|
||||
# What the host reads is consistent with itself: the same clock in every place (the offset the page has now is the wall clock's).
|
||||
now = host["without"]["page"]
|
||||
assert now["lastModifiedAhead"] == now["now"] and now["exsltAhead"] == now["now"], now
|
||||
finally:
|
||||
probe.stop(srv)
|
||||
@@ -48,9 +48,13 @@ from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import threading
|
||||
import time
|
||||
import types
|
||||
|
||||
import pytest
|
||||
|
||||
from _evidence_on_failure import FailureEvidence
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
ROUNDS = 5
|
||||
@@ -64,6 +68,14 @@ def _landing(url: str) -> str:
|
||||
#: The address each page (by `id`) was last sent to, or the page it went with instead (`_goto`).
|
||||
_SENT: dict = {}
|
||||
|
||||
#: What the client heard, for the evidence a failing test leaves (`FailureEvidence`; it only listens and changes no wait or assertion).
|
||||
_CLIENT_LOG: list = []
|
||||
|
||||
|
||||
def _note(what: str, **fields) -> None:
|
||||
"""One line of the client's own view of the module: what the test sent or heard, on the clocks of the evidence (`t` wall, `m` perf_counter)."""
|
||||
_CLIENT_LOG.append({"t": round(time.time(), 4), "m": round(time.perf_counter(), 6), "what": what, **fields})
|
||||
|
||||
|
||||
def _goto(page, url, *, the_page_before_may_move, our_page_may_stop_ours, **kwargs) -> str:
|
||||
"""`page.goto`, and the address of the page the frame went with: `url` when `goto` answers.
|
||||
@@ -82,11 +94,14 @@ def _goto(page, url, *, the_page_before_may_move, our_page_may_stop_ours, **kwar
|
||||
|
||||
before = _SENT.get(id(page)) if the_page_before_may_move else None
|
||||
_SENT[id(page)] = url
|
||||
_note("goto", url=url, before=before)
|
||||
try:
|
||||
page.goto(url, **kwargs)
|
||||
_note("goto-answered", url=url)
|
||||
return url
|
||||
except Error as e:
|
||||
text = str(e)
|
||||
_note("goto-raised", url=url, error=text[:300])
|
||||
if "NS_BINDING_ABORTED" in text:
|
||||
ends = tuple(_landing(u) for u in (before, url if our_page_may_stop_ours else None) if u)
|
||||
assert ends, e
|
||||
@@ -160,12 +175,18 @@ for _name, _held in (("0", False), ("50", True)):
|
||||
HELD_DOCUMENTS = {"/hdr": _replace_while_the_document_is_held(False), "/hdx": _replace_while_the_document_is_held(True)}
|
||||
|
||||
|
||||
#: The test server's own record of every request it served, in the shape `FailureEvidence.watch_server` reads (`.state.lock`, `.state.records`).
|
||||
RECORD = types.SimpleNamespace(lock=threading.Lock(), records=[])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def site():
|
||||
release = threading.Event()
|
||||
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
with RECORD.lock:
|
||||
RECORD.records.append({"t": round(time.time(), 4), "m": round(time.perf_counter(), 6), "method": "GET", "path": self.path})
|
||||
if self.path.split("?")[0] == "/hold":
|
||||
# a response that has begun and does not end: 16 KiB so the first chunk is delivered at once,
|
||||
# then it stays open until the page that asked for it moves away (or the module's teardown)
|
||||
@@ -215,17 +236,60 @@ def site():
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def page(firefox_binary):
|
||||
def evidence():
|
||||
"""What a failing test of this module leaves for a reader (only on a failure; nothing is changed in what the tests wait for or assert):
|
||||
the client's view of every request and navigation, the Juggler wire, the engine's own trace, the record of the test server.
|
||||
Armed before the browser is launched (the engine reads its trace folder at launch) and held for the module."""
|
||||
held = FailureEvidence("a-page-that-moves-on")
|
||||
held.client_log = _CLIENT_LOG
|
||||
held.watch_server(types.SimpleNamespace(state=RECORD))
|
||||
held.arm()
|
||||
try:
|
||||
yield held
|
||||
finally:
|
||||
held.__exit__(None, None, None)
|
||||
|
||||
|
||||
class _on_failure:
|
||||
"""``with _on_failure(evidence):`` around the body of a test: when the body raises, the evidence held for the module is saved
|
||||
(the folder the e2e jobs upload), and the exception goes on."""
|
||||
|
||||
def __init__(self, held):
|
||||
self.held = held
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
if exc_type is not None:
|
||||
self.held._save(exc_type, exc)
|
||||
return False
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def page(firefox_binary, evidence):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=4321, binary_path=firefox_binary,
|
||||
headless=True) as browser:
|
||||
yield browser.new_page()
|
||||
new = browser.new_page()
|
||||
new.on("request", lambda r: _note("request", url=r.url, navigation=r.is_navigation_request()))
|
||||
new.on("requestfinished", lambda r: _note("requestfinished", url=r.url))
|
||||
new.on("requestfailed", lambda r: _note("requestfailed", url=r.url, failure=str(r.failure)))
|
||||
new.on("framenavigated", lambda f: _note("framenavigated", url=f.url, main=f.parent_frame is None))
|
||||
new.on("domcontentloaded", lambda p: _note("domcontentloaded", url=p.url))
|
||||
new.on("load", lambda p: _note("load", url=p.url))
|
||||
yield new
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["/head", "/r0", "/r50", "/r300",
|
||||
"/x0", "/x50", "/x300"])
|
||||
def test_a_read_right_after_goto_answers(page, site, path, engine_reaches):
|
||||
def test_a_read_right_after_goto_answers(page, site, path, engine_reaches, evidence):
|
||||
with _on_failure(evidence):
|
||||
_a_read_right_after_goto_answers(page, site, path, engine_reaches)
|
||||
|
||||
|
||||
def _a_read_right_after_goto_answers(page, site, path, engine_reaches):
|
||||
older = not engine_reaches("firefox-68")
|
||||
for i in range(ROUNDS):
|
||||
_goto(page, "%s%s?i=%s-%d" % (site, path, path[1:], i), the_page_before_may_move=True,
|
||||
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
"""``measureText`` of a regional-indicator pair does not depend on what the page measured before it (e2e, every OS, firefox-68).
|
||||
|
||||
What the engine fixes. A flag (two regional-indicator code points, U+1F1EE U+1F1F9) set in Arial is a run that needs a FALLBACK font. The fallback
|
||||
search may skip a family whose character maps are not loaded yet, start an asynchronous load and go on (``gfx.font_rendering.fallback.async``);
|
||||
then the answer depends on which maps this process happens to have loaded already, and a page sees it in the width. Measured on the engine when
|
||||
the site was missed: the pair through "Arial" gave 52.63 on both platforms when it was the first thing a fresh page measured, and 63.53 (Windows)
|
||||
against 80.07 (Linux) once other families had been measured first: same binary, same page, another answer by load order. The font list is the
|
||||
bundle (always bundle-only), so there is nothing to defer: ``gfxPlatformFontList::MayDeferCmapLoading`` answers false and both sites that ask it
|
||||
(``GlobalFontFallback`` and ``gfxFontGroup::FindFallbackFaceForChar``) search synchronously (folders ``fingerprint/fonts/bundle`` and
|
||||
``fingerprint/fonts/font-list`` of the series; ``StealthFallbackMayDefer`` in ``gfx/thebes/StealthBundleFontList.cpp``).
|
||||
|
||||
What the test reads. A browser is launched and its first page is opened on ``about:blank``; the pair of three flags is measured through
|
||||
``16px Arial`` and ``40px Arial`` as the FIRST text the page measures. Then the page measures a string of Latin, Han, Arabic and an emoji through
|
||||
EVERY family of the bundle manifest (the manifest the core hands the engine, ``tests/_font_names.py``), which loads the character maps of the
|
||||
bundle, and measures the pairs again: the widths must be the same numbers as the first time. A second context's first page of the same browser
|
||||
measures them as its first text too, and must read the same. Nothing is a timer: each read is the answer of the page to one call.
|
||||
|
||||
The negative control, in the same test. The assertion is about what a changed load order does; the same test runs again with the engine not declared
|
||||
(``zoom.stealth.fpp.hw_seed`` = 0). On 68 bundle-only does not depend on the declaration, so the relation holds in both runs; the widths themselves
|
||||
are written in the failure message and the test does not fix them (they are measurements of the first CI round: see the report of the filone).
|
||||
|
||||
Why a page reads it: ``CanvasRenderingContext2D.measureText().width`` is plain web API, and a flag emoji is in every fingerprinting canvas probe.
|
||||
|
||||
Run: pytest tests/test_a_regional_indicator_pair_measures_the_same_first_and_after_other_families_e2e.py -m e2e -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
import _font_names as fn
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
#: Flags of Italy, the United States and Japan: pairs of regional indicators.
|
||||
PAIRS = ["\U0001F1EE\U0001F1F9", "\U0001F1FA\U0001F1F8", "\U0001F1EF\U0001F1F5"]
|
||||
SIZES = [16, 40]
|
||||
|
||||
#: Latin, Han, Arabic and an emoji: what makes the engine look for a fallback face in every family.
|
||||
SAMPLE = "Hamburgefonstiv 日本語 中文 مرحبا \U0001F600"
|
||||
|
||||
MEASURE_PAIRS = """(args) => {
|
||||
const [pairs, sizes] = args;
|
||||
const ctx = document.createElement('canvas').getContext('2d');
|
||||
const out = {};
|
||||
for (const size of sizes) {
|
||||
ctx.font = size + 'px Arial';
|
||||
for (const pair of pairs) out[size + 'px ' + Array.from(pair).map(c => c.codePointAt(0).toString(16)).join('+')] = ctx.measureText(pair).width;
|
||||
}
|
||||
return out;
|
||||
}"""
|
||||
|
||||
MEASURE_FAMILIES = """(args) => {
|
||||
const [families, sample] = args;
|
||||
const ctx = document.createElement('canvas').getContext('2d');
|
||||
const out = {};
|
||||
for (const family of families) {
|
||||
ctx.font = '24px "' + family + '"';
|
||||
out[family] = ctx.measureText(sample).width;
|
||||
}
|
||||
return out;
|
||||
}"""
|
||||
|
||||
|
||||
def _readings(firefox_binary, families, engine_declared):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
prefs = {} if engine_declared else {"zoom.stealth.fpp.hw_seed": 0}
|
||||
with InvisiblePlaywright(seed=21, binary_path=firefox_binary, headless=True, extra_prefs=prefs) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto("about:blank", timeout=30_000)
|
||||
first = page.evaluate(MEASURE_PAIRS, [PAIRS, SIZES])
|
||||
measured = page.evaluate(MEASURE_FAMILIES, [families, SAMPLE])
|
||||
after = page.evaluate(MEASURE_PAIRS, [PAIRS, SIZES])
|
||||
other = browser.new_context().new_page()
|
||||
other.goto("about:blank", timeout=30_000)
|
||||
in_a_fresh_page = other.evaluate(MEASURE_PAIRS, [PAIRS, SIZES])
|
||||
return first, after, in_a_fresh_page, len(measured)
|
||||
|
||||
|
||||
def test_a_regional_indicator_pair_measures_the_same_first_and_after_other_families(firefox_binary):
|
||||
families = fn.bundle_manifest().families
|
||||
for declared in (True, False):
|
||||
mode = "engine declared" if declared else "engine not declared (hw_seed 0)"
|
||||
first, after, fresh, measured = _readings(firefox_binary, families, declared)
|
||||
assert measured == len(families), "%s: the page measured %d families, not the %d of the bundle" % (mode, measured, len(families))
|
||||
assert set(first) == {"%dpx %s" % (size, "+".join(format(ord(c), "x") for c in pair)) for size in SIZES for pair in PAIRS}
|
||||
assert all(width > 0 for width in first.values()), "%s: a flag measures no width at all: %r" % (mode, first)
|
||||
assert first == after, (
|
||||
"%s: the regional-indicator pairs measure %r as the first thing on a fresh page and %r once every family of the bundle was measured: "
|
||||
"the answer depends on the load order of the character maps" % (mode, first, after))
|
||||
assert first == fresh, (
|
||||
"%s: the pairs measure %r in the first page and %r as the first text of another context's page: the answer depends on what the "
|
||||
"process measured before" % (mode, first, fresh))
|
||||
@@ -0,0 +1,54 @@
|
||||
"""`AudioContext.outputLatency` and `destination.maxChannelCount` are the values the session declares.
|
||||
|
||||
What it fixes, in the published engine (firefox-68, series folder `fingerprint/audio/context-values`): the hooks at the top of
|
||||
`AudioContext::OutputLatency` and `AudioContext::MaxChannelCount` (`dom/media/webaudio/AudioContext.cpp`) answer
|
||||
`zoom.stealth.audio.output_latency_ms` / 1000 and `zoom.stealth.audio.max_channel_count` when the pref is > 0, before the engine
|
||||
asks the audio device. The core declares both for every persona, because the host's answer is the machine's sound card.
|
||||
|
||||
A page reads both on a new `AudioContext()` with no permission. The values declared here (37 ms and 6 channels) are ones no runner
|
||||
produces: a runner with no audio device answers 0 or 2.
|
||||
|
||||
Negative control, in the same test: with the engine off (`hw_seed` 0, stock Firefox: an active engine refuses a declaration pref cleared) the same page reads the host's values,
|
||||
and they differ from the declared ones. The control reads what the host answers without asserting what it is: a runner with no audio
|
||||
device may refuse the context, and that refusal is also not the declared value.
|
||||
|
||||
The prefs are set through `extra_prefs`, the overlay the core applies last.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
OUTPUT_LATENCY = "zoom.stealth.audio.output_latency_ms"
|
||||
MAX_CHANNELS = "zoom.stealth.audio.max_channel_count"
|
||||
HW_SEED = "zoom.stealth.fpp.hw_seed"
|
||||
|
||||
READ = """() => {
|
||||
try {
|
||||
const ctx = new (window.AudioContext || window.webkitAudioContext)();
|
||||
return {outputLatency: ctx.outputLatency, maxChannelCount: ctx.destination.maxChannelCount};
|
||||
} catch (e) {
|
||||
return {error: String(e)};
|
||||
}
|
||||
}"""
|
||||
|
||||
|
||||
def read(binary, prefs):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=binary, headless=True, locale="en-US",
|
||||
timezone="America/New_York", extra_prefs=prefs) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank", timeout=60_000)
|
||||
return page.evaluate(READ)
|
||||
|
||||
|
||||
def test_the_audio_context_answers_the_declared_latency_and_channel_count(firefox_binary):
|
||||
declared = read(firefox_binary, {OUTPUT_LATENCY: 37, MAX_CHANNELS: 6})
|
||||
assert declared == {"outputLatency": 0.037, "maxChannelCount": 6}, declared
|
||||
|
||||
host = read(firefox_binary, {HW_SEED: 0})
|
||||
assert host != declared, (host, declared)
|
||||
assert host.get("outputLatency") != 0.037, host
|
||||
assert host.get("maxChannelCount") != 6, host
|
||||
@@ -0,0 +1,103 @@
|
||||
"""The audio values a page reads follow the seed only when the audio noise is on.
|
||||
|
||||
What it fixes, in the published engine (firefox-68, series folder `fingerprint/audio/noise`): the audio noise hooks of
|
||||
`dom/media/webaudio/` (`AnalyserNode.cpp` for `getFloatFrequencyData` and `getFloatTimeDomainData`, `AudioDestinationNode.cpp` for the
|
||||
`OfflineAudioContext` render, `DynamicsCompressorNode.h` for `compressor.reduction`). When `zoom.stealth.audio.fp_noise` is true the
|
||||
engine adds noise derived from `zoom.stealth.fpp.hw_seed` to those four values; the wrapper ships the pref false, so the values
|
||||
of a product session are the stock ones.
|
||||
|
||||
Four values are read in one rendered graph (oscillator, compressor, analyser, destination of an `OfflineAudioContext(1, 5000, 44100)`):
|
||||
the rendered samples, the analyser's frequency data, the analyser's time-domain data and the compressor's reduction.
|
||||
Each is hashed over its float bits in the page, so a one-bit change shows.
|
||||
|
||||
With the noise ON: the same `hw_seed` gives the same four values on a fresh browser, and two seeds (11 and 22) give different ones;
|
||||
the values also differ from the noise-off ones. The negative control is the same two seeds with `fp_noise` false: the four values are equal
|
||||
across seeds, because the noise is the only thing that carries the seed. A page reads these values with no permission and no device (an
|
||||
offline context renders without an audio output), so a runner with no sound card gives the same answers.
|
||||
|
||||
The seed is the engine's `hw_seed`, set directly (`extra_prefs`): the wrapper maps its own seed to a small pool of render seeds, so two
|
||||
wrapper seeds can share one.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
NOISE = "zoom.stealth.audio.fp_noise"
|
||||
HW_SEED = "zoom.stealth.fpp.hw_seed"
|
||||
VALUES = ("offline", "frequency", "time", "reduction")
|
||||
|
||||
# FNV-1a over the 32-bit patterns of a float array, so equality is bit equality and -Infinity (a silent analyser bin) needs no JSON.
|
||||
RENDER = """async () => {
|
||||
const hash = (floats) => {
|
||||
const bits = new Uint32Array(new Float32Array(floats).buffer);
|
||||
let h = 0x811c9dc5;
|
||||
for (let i = 0; i < bits.length; i++) { h ^= bits[i]; h = Math.imul(h, 0x01000193) >>> 0; }
|
||||
return h.toString(16) + ':' + bits.length;
|
||||
};
|
||||
const ctx = new OfflineAudioContext(1, 5000, 44100);
|
||||
const osc = ctx.createOscillator();
|
||||
osc.type = 'triangle';
|
||||
osc.frequency.value = 10000;
|
||||
const comp = ctx.createDynamicsCompressor();
|
||||
comp.threshold.value = -50;
|
||||
comp.knee.value = 40;
|
||||
comp.ratio.value = 12;
|
||||
comp.attack.value = 0;
|
||||
comp.release.value = 0.25;
|
||||
const analyser = ctx.createAnalyser();
|
||||
osc.connect(comp);
|
||||
comp.connect(analyser);
|
||||
analyser.connect(ctx.destination);
|
||||
osc.start(0);
|
||||
const rendered = await ctx.startRendering();
|
||||
const freq = new Float32Array(analyser.frequencyBinCount);
|
||||
analyser.getFloatFrequencyData(freq);
|
||||
const time = new Float32Array(analyser.fftSize);
|
||||
analyser.getFloatTimeDomainData(time);
|
||||
return {
|
||||
offline: hash(rendered.getChannelData(0)),
|
||||
frequency: hash(freq),
|
||||
time: hash(time),
|
||||
reduction: hash([comp.reduction]),
|
||||
};
|
||||
}"""
|
||||
|
||||
|
||||
def read_values(binary, fixture_server, noise, hw_seed):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
prefs = {NOISE: noise, HW_SEED: hw_seed}
|
||||
with InvisiblePlaywright(seed=42, binary_path=binary, headless=True, locale="en-US",
|
||||
timezone="America/New_York", extra_prefs=prefs) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(fixture_server + "/from-network", timeout=60_000)
|
||||
return page.evaluate(RENDER)
|
||||
|
||||
|
||||
def test_audio_values_follow_the_seed_only_when_fp_noise_is_on(firefox_binary, fixture_server):
|
||||
on_11 = read_values(firefox_binary, fixture_server, True, 11)
|
||||
on_11_again = read_values(firefox_binary, fixture_server, True, 11)
|
||||
on_22 = read_values(firefox_binary, fixture_server, True, 22)
|
||||
off_11 = read_values(firefox_binary, fixture_server, False, 11)
|
||||
off_22 = read_values(firefox_binary, fixture_server, False, 22)
|
||||
|
||||
# Every value was read (a hash of N floats, N > 0).
|
||||
for name in VALUES:
|
||||
for run in (on_11, on_22, off_11, off_22):
|
||||
assert not run[name].endswith(":0"), (name, run)
|
||||
|
||||
# Noise on: the same seed, the same values, on a fresh browser.
|
||||
assert on_11 == on_11_again, (on_11, on_11_again)
|
||||
|
||||
# Noise on: two seeds, different values, one by one.
|
||||
for name in VALUES:
|
||||
assert on_11[name] != on_22[name], (name, on_11, on_22)
|
||||
|
||||
# Noise on is not noise off: the noise is what moves each value.
|
||||
for name in VALUES:
|
||||
assert on_11[name] != off_11[name], (name, on_11, off_11)
|
||||
|
||||
# Control, noise off: the seed carries nothing, the values are equal across seeds.
|
||||
assert off_11 == off_22, (off_11, off_22)
|
||||
@@ -0,0 +1,50 @@
|
||||
"""`new AudioContext().sampleRate` is the rate the session declares.
|
||||
|
||||
What it fixes, in the published engine (firefox-68, series folder `fingerprint/audio/sample-rate`): the hook in
|
||||
`mozilla::CubebUtils::PreferredSampleRate` (`dom/media/CubebUtils.cpp`) returns `zoom.stealth.audio.sample_rate` when it is > 0,
|
||||
before the resist-fingerprinting 44100 and before the audio device is asked. The core declares a rate for every persona, because the
|
||||
host's rate is the machine's sound card (44100, 48000, 96000...).
|
||||
|
||||
A page reads it on a new `AudioContext()` with no permission. The rate declared here, 22050, is one no sound card reports.
|
||||
|
||||
Negative control, in the same test: with the engine off (`hw_seed` 0, stock Firefox: an active engine refuses a declaration pref cleared) the same page reads the host's rate,
|
||||
which is not 22050. The control does not assert what the host answers: a runner with no audio device answers its fallback, and a
|
||||
refused context is also not the declared rate.
|
||||
|
||||
The pref is set through `extra_prefs`, the overlay the core applies last.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
SAMPLE_RATE = "zoom.stealth.audio.sample_rate"
|
||||
HW_SEED = "zoom.stealth.fpp.hw_seed"
|
||||
|
||||
READ = """() => {
|
||||
try {
|
||||
return {sampleRate: new (window.AudioContext || window.webkitAudioContext)().sampleRate};
|
||||
} catch (e) {
|
||||
return {error: String(e)};
|
||||
}
|
||||
}"""
|
||||
|
||||
|
||||
def read(binary, prefs):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=binary, headless=True, locale="en-US",
|
||||
timezone="America/New_York", extra_prefs=prefs) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank", timeout=60_000)
|
||||
return page.evaluate(READ)
|
||||
|
||||
|
||||
def test_the_audio_context_answers_the_declared_sample_rate(firefox_binary):
|
||||
declared = read(firefox_binary, {SAMPLE_RATE: 22050})
|
||||
assert declared == {"sampleRate": 22050}, declared
|
||||
|
||||
host = read(firefox_binary, {HW_SEED: 0})
|
||||
assert host != declared, (host, declared)
|
||||
assert host.get("sampleRate") != 22050, host
|
||||
@@ -0,0 +1,131 @@
|
||||
"""``@font-face { src: local(<name>) }`` finds the faces of the bundle by their PostScript name, and never a font that only the host has (e2e, every OS, firefox-68).
|
||||
|
||||
What the engine fixes. A page can ask for an installed font by name with ``src: local("ArialMT")`` (the PostScript name or the full name of a face)
|
||||
and learn from ``FontFace.status`` whether the browser has it. The font list of the engine is the bundle and nothing else
|
||||
(``gfxPlatformFontList::mStealthBundleOnly``, set in the constructor, on every platform and whether or not the engine is declared): the face
|
||||
names the ``local()`` lookup searches are read from the ``name`` tables of the bundle's files (``RecordFaceNamesFromTable``,
|
||||
``ReadFaceNamesForFamily``; folders ``fingerprint/fonts/font-list`` and ``fingerprint/fonts/bundle`` of the series), never from DirectWrite
|
||||
or fontconfig. So the PostScript name of a bundled face resolves, a name that only the host's fonts carry does not, and the answer is the same
|
||||
on every machine: a page that probes ``local()`` learns the bundle, not the machine.
|
||||
|
||||
What the test reads. One page declares, for each name, ``@font-face { font-family: <probe>; src: local("<name>") }`` and loads it
|
||||
(``document.fonts.load``), then reads the ``status`` of that face (``loaded`` or ``error``, an event of the page: no timer) and the width of one
|
||||
string through the probe family. Four PostScript names of the bundle come from the manifest the core hands to the engine (``ArialMT``,
|
||||
``TimesNewRomanPSMT``, and the faces ``MS-PGothic`` and ``NSimSun``, which are NOT the first face of their ``.ttc`` file): each must be ``loaded``
|
||||
and draw with the same width as the family it belongs to (the same face, not another one that happened to load). The host-only face is read from
|
||||
the host's own font files (``tests/_font_names.py``: the ``name`` table of every file of the folders the system installs fonts in, minus every
|
||||
name the bundle knows): its PostScript name AND its full name must be ``error``. On Linux the face asked for is DejaVu Sans when the host has
|
||||
it, on Windows the first font of ``%WINDIR%\\Fonts`` the bundle does not carry; no value is typed in the test, and a host that has no such font
|
||||
fails the test (there would be nothing the control could find).
|
||||
|
||||
The negative control, in the same test. The names the host has are the ones that must NOT resolve, so the same page runs a second time with the
|
||||
engine not declared (``zoom.stealth.fpp.hw_seed`` = 0, the pref the core uses to tell the engine to stay stock). On firefox-68 bundle-only
|
||||
does NOT depend on the engine being declared (the member is set unconditionally in the constructor), so the control reads the same: the bundled
|
||||
names resolve and the host-only names do not, engine on or off. The test asserts that equality; it is the characterization of what 68 does, and
|
||||
the day the engine changes it (the host fonts reaching ``local()`` with the engine off) this test is red. A name that exists nowhere
|
||||
(``NoSuchFace-ZZ``) is read in both runs as the control of the probe itself: it is ``error``, so the probe can tell a missing face from a
|
||||
loaded one.
|
||||
|
||||
Why a page reads it: ``FontFace.status`` after ``document.fonts.load()`` is plain web API; fingerprinting scripts probe installed fonts this
|
||||
way as well as by width.
|
||||
|
||||
Run: pytest tests/test_bundle_font_names_e2e.py -m e2e -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
import _font_names as fn
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
#: PostScript name -> the family it belongs to in the bundle manifest. The last two are faces of a collection that are not face 0 of their file.
|
||||
BUNDLED = [("ArialMT", "Arial"), ("TimesNewRomanPSMT", "Times New Roman"), ("MS-PGothic", "MS PGothic"), ("NSimSun", "NSimSun")]
|
||||
|
||||
#: Declared by no machine: the control of the probe.
|
||||
NOWHERE = "NoSuchFace-ZZ"
|
||||
|
||||
TEXT = "mmmmmmmmmmlliWWW0Oq@"
|
||||
|
||||
#: The page. `cases` is [[local name, family it must draw like or null], ...]. It reports, for each: the status of the face once its load settled
|
||||
#: and the widths of TEXT through the probe family, through the target family, and through the generics (the width of a face that is not there).
|
||||
PROBE = """async (args) => {
|
||||
const [cases, text] = args;
|
||||
const span = document.createElement('span');
|
||||
span.style.cssText = 'position:absolute;left:-9999px;top:0;white-space:pre;font-size:48px;font-style:normal;font-weight:400;';
|
||||
span.textContent = text;
|
||||
document.body.appendChild(span);
|
||||
const width = (family) => { span.style.fontFamily = family; return span.getBoundingClientRect().width; };
|
||||
const generics = ['monospace', 'sans-serif', 'serif'].map(width);
|
||||
const out = [];
|
||||
let n = 0;
|
||||
for (const [name, target] of cases) {
|
||||
const probe = 'LocalProbe' + (n++);
|
||||
const style = document.createElement('style');
|
||||
style.textContent = '@font-face { font-family: ' + probe + '; src: local("' + name + '"); }';
|
||||
document.head.appendChild(style);
|
||||
await document.fonts.load('48px ' + probe).catch(() => null);
|
||||
const face = Array.from(document.fonts).find(f => f.family.replace(/["']/g, '') === probe);
|
||||
out.push({
|
||||
name: name, status: face ? face.status : 'no-face',
|
||||
probe: width(probe + ', monospace'),
|
||||
target: target ? width('"' + target + '", monospace') : null,
|
||||
generics: generics,
|
||||
});
|
||||
}
|
||||
span.remove();
|
||||
return out;
|
||||
}"""
|
||||
|
||||
|
||||
def _read(firefox_binary, cases, engine_declared):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
prefs = {} if engine_declared else {"zoom.stealth.fpp.hw_seed": 0}
|
||||
with InvisiblePlaywright(seed=21, binary_path=firefox_binary, headless=True, extra_prefs=prefs) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto("about:blank", timeout=30_000)
|
||||
return page.evaluate(PROBE, [cases, TEXT])
|
||||
|
||||
|
||||
def test_src_local_resolves_a_bundled_postscript_name_and_not_a_host_only_name(firefox_binary):
|
||||
manifest = fn.bundle_manifest()
|
||||
for psname, family in BUNDLED:
|
||||
assert manifest.family_of_psname(psname) == family, (
|
||||
"the manifest of the core has no face %r in the family %r: the names this test asks for are not the bundle's" % (psname, family))
|
||||
|
||||
known = fn.bundle_file_names(manifest, firefox_binary)
|
||||
prefer = ["DejaVu Sans"] if sys.platform != "win32" else []
|
||||
host = fn.a_host_only_face(manifest, prefer=prefer, extra_known=known)
|
||||
|
||||
cases = [[psname, family] for psname, family in BUNDLED]
|
||||
cases += [[host["psname"], None], [host["full"], None], [NOWHERE, None]]
|
||||
host_names = (host["psname"], host["full"])
|
||||
|
||||
runs = {declared: {row["name"]: row for row in _read(firefox_binary, cases, declared)} for declared in (True, False)}
|
||||
|
||||
for declared, rows in runs.items():
|
||||
mode = "engine declared" if declared else "engine not declared (hw_seed 0)"
|
||||
# the probe tells a missing face from a loaded one
|
||||
assert rows[NOWHERE]["status"] == "error", "%s: a name that exists nowhere read as %r, not error: the probe cannot tell a missing face" % (mode, rows[NOWHERE])
|
||||
# the bundle: found, and it is the face of its family
|
||||
for psname, family in BUNDLED:
|
||||
row = rows[psname]
|
||||
assert row["status"] == "loaded", "%s: src:local(%s) is %r, not loaded: a PostScript name of the bundle does not resolve (%r)" % (mode, psname, row["status"], row)
|
||||
assert row["probe"] == row["target"], (
|
||||
"%s: src:local(%s) draws %r wide and the family %s %r wide: it loaded another face than the bundle's" % (mode, psname, row["probe"], family, row["target"]))
|
||||
assert any(row["probe"] != g for g in row["generics"]), (
|
||||
"%s: src:local(%s) draws as a generic (%r): the face drew nothing of its own" % (mode, psname, row))
|
||||
# the host: the file is on this machine's disk, and the engine does not know its names
|
||||
for name in host_names:
|
||||
row = rows[name]
|
||||
assert row["status"] == "error", (
|
||||
"%s: src:local(%s) is %r: the name belongs to the host font %s (%s) and the bundle has no such face, so a page learns the machine "
|
||||
"from it" % (mode, name, row["status"], host["file"], host["families"]))
|
||||
|
||||
# on 68 the bundle-only list does not depend on the engine being declared: the same answers with it off
|
||||
on = {name: runs[True][name]["status"] for name in runs[True]}
|
||||
off = {name: runs[False][name]["status"] for name in runs[False]}
|
||||
assert on == off, "the statuses of src:local() differ between the engine declared (%r) and not declared (%r)" % (on, off)
|
||||
@@ -0,0 +1,135 @@
|
||||
"""``createPattern`` of a WebGL canvas reads the pixels the page would read from it, with the engine's projection; a 2D source is untouched (e2e, every OS, firefox-68).
|
||||
|
||||
What the engine fixes. The engine's per-seed noise (the projection, ``fingerprint/canvas/noise-projection``) is applied where a WebGL or WebGPU
|
||||
canvas hands its pixels out: readPixels, toDataURL, and the snapshot a canvas gives when another canvas draws it. ``CanvasRenderingContext2D::
|
||||
CreatePattern`` used to read its source canvas through the pattern's own context, a path the noise does not pass, so
|
||||
``createPattern(webglCanvas)`` + ``fill`` + ``getImageData`` returned the CLEAN pixels of the render while ``drawImage(webglCanvas)`` returned the
|
||||
projected ones: a page compared the two and read the difference. On firefox-68 two lines of ``CreatePattern`` (the HTMLCanvasElement and the
|
||||
OffscreenCanvas overloads; folder ``fingerprint/canvas/text-metrics`` of the series, ``dom/canvas/CanvasRenderingContext2D.cpp``) read the snapshot
|
||||
from the element, so the pattern carries the projection. A 2D canvas is not projected at all (a 2D canvas reads back exactly as drawn,
|
||||
``tests/test_canvas_reads_as_drawn.py``), so a pattern of a 2D canvas is the same pixels with the engine on and off.
|
||||
|
||||
What the test reads. One page builds a source (a WebGL canvas, a WebGL OffscreenCanvas, or a 2D canvas), fills a 2D canvas with
|
||||
``createPattern(source, 'no-repeat')`` and reads it back with ``getImageData``, then clears it and draws the source with ``drawImage`` and reads that.
|
||||
The WebGL render is a triangle with per-vertex colours and antialiased edges on a white clear (what a fingerprinting page draws, and where the
|
||||
projection acts: ``tests/test_webgl_noise_active.py``); the 2D source is a gradient, an antialiased arc and a rotated rectangle.
|
||||
|
||||
The negative control, in the same module. The same page runs with the engine not declared (``zoom.stealth.fpp.hw_seed`` = 0: no projection): the
|
||||
WebGL pattern pixels with the engine declared must DIFFER from those (the projection is what changed them), and the 2D pattern pixels must be the
|
||||
SAME bytes with the engine on and off. A render that is not drawn (a blank source) fails the test: the pixels are checked to hold more than one
|
||||
colour. WebGL being unavailable on the runner is a failure, not a skip.
|
||||
|
||||
Run: pytest tests/test_canvas_create_pattern_projection_e2e.py -m e2e -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
SIZE = 64
|
||||
|
||||
READ = """(args) => {
|
||||
const [kind, size] = args;
|
||||
let source;
|
||||
if (kind === 'webgl' || kind === 'offscreen-webgl') {
|
||||
source = kind === 'webgl' ? document.createElement('canvas') : new OffscreenCanvas(size, size);
|
||||
source.width = size; source.height = size;
|
||||
const gl = source.getContext('webgl', {preserveDrawingBuffer: true, antialias: true});
|
||||
if (!gl) return {error: 'no webgl context for ' + kind};
|
||||
const vs = gl.createShader(gl.VERTEX_SHADER);
|
||||
gl.shaderSource(vs, 'attribute vec2 p; attribute vec3 c; varying vec3 v; void main(){v=c;gl_Position=vec4(p,0.,1.);}');
|
||||
gl.compileShader(vs);
|
||||
const fs = gl.createShader(gl.FRAGMENT_SHADER);
|
||||
gl.shaderSource(fs, 'precision mediump float; varying vec3 v; void main(){gl_FragColor=vec4(v,1.);}');
|
||||
gl.compileShader(fs);
|
||||
const pr = gl.createProgram(); gl.attachShader(pr, vs); gl.attachShader(pr, fs);
|
||||
gl.linkProgram(pr); gl.useProgram(pr);
|
||||
const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(
|
||||
[-0.9, -0.8, 1, 0, 0, 0.85, -0.6, 0, 1, 0, 0.1, 0.9, 0, 0, 1]), gl.STATIC_DRAW);
|
||||
const pl = gl.getAttribLocation(pr, 'p'), cl = gl.getAttribLocation(pr, 'c');
|
||||
gl.enableVertexAttribArray(pl); gl.vertexAttribPointer(pl, 2, gl.FLOAT, false, 20, 0);
|
||||
gl.enableVertexAttribArray(cl); gl.vertexAttribPointer(cl, 3, gl.FLOAT, false, 20, 8);
|
||||
gl.clearColor(1, 1, 1, 1); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 3);
|
||||
gl.finish();
|
||||
} else {
|
||||
source = document.createElement('canvas'); source.width = size; source.height = size;
|
||||
const s = source.getContext('2d');
|
||||
const g = s.createLinearGradient(0, 0, size, size);
|
||||
g.addColorStop(0, '#f60'); g.addColorStop(0.5, '#069'); g.addColorStop(1, '#6c0');
|
||||
s.fillStyle = g; s.fillRect(0, 0, size, size);
|
||||
s.strokeStyle = 'rgba(20, 20, 20, 0.8)'; s.lineWidth = 3.3;
|
||||
s.beginPath(); s.arc(size * 0.5, size * 0.45, size * 0.31, 0, 2 * Math.PI * 0.83); s.stroke();
|
||||
s.save(); s.translate(size * 0.6, size * 0.6); s.rotate(0.37); s.fillStyle = 'rgba(255, 255, 255, 0.6)';
|
||||
s.fillRect(-size * 0.2, -size * 0.1, size * 0.4, size * 0.2); s.restore();
|
||||
}
|
||||
const dst = document.createElement('canvas'); dst.width = size; dst.height = size;
|
||||
const d = dst.getContext('2d');
|
||||
d.fillStyle = d.createPattern(source, 'no-repeat');
|
||||
d.fillRect(0, 0, size, size);
|
||||
const viaPattern = Array.from(d.getImageData(0, 0, size, size).data);
|
||||
d.clearRect(0, 0, size, size);
|
||||
d.drawImage(source, 0, 0);
|
||||
const viaDraw = Array.from(d.getImageData(0, 0, size, size).data);
|
||||
return {viaPattern: viaPattern, viaDraw: viaDraw};
|
||||
}"""
|
||||
|
||||
KINDS = ["webgl", "offscreen-webgl", "2d"]
|
||||
|
||||
|
||||
def _read(firefox_binary, engine_declared):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
prefs = {} if engine_declared else {"zoom.stealth.fpp.hw_seed": 0}
|
||||
out = {}
|
||||
with InvisiblePlaywright(seed=21, binary_path=firefox_binary, headless=True, extra_prefs=prefs) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto("about:blank", timeout=30_000)
|
||||
for kind in KINDS:
|
||||
got = page.evaluate(READ, [kind, SIZE])
|
||||
assert "error" not in got, got["error"]
|
||||
out[kind] = {name: bytes(values) for name, values in got.items()}
|
||||
return out
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def readings(firefox_binary):
|
||||
"""kind -> {viaPattern, viaDraw} bytes, with the engine declared and not declared. The browsers are closed before the tests run."""
|
||||
declared = _read(firefox_binary, True)
|
||||
stock = _read(firefox_binary, False)
|
||||
for mode, rows in (("engine declared", declared), ("engine not declared", stock)):
|
||||
for kind, row in rows.items():
|
||||
assert len(row["viaPattern"]) == SIZE * SIZE * 4 and len(set(row["viaPattern"])) > 1, (
|
||||
"%s: the %s pattern read back is blank or has the wrong size: the source was not drawn" % (mode, kind))
|
||||
return {"declared": declared, "stock": stock}
|
||||
|
||||
|
||||
def test_create_pattern_from_a_webgl_canvas_carries_the_projection(readings):
|
||||
declared, stock = readings["declared"]["webgl"], readings["stock"]["webgl"]
|
||||
assert declared["viaPattern"] != stock["viaPattern"], (
|
||||
"createPattern(webglCanvas) reads the same pixels with the engine declared and not declared: the pattern is the clean render, the "
|
||||
"projection does not reach it")
|
||||
|
||||
|
||||
def test_create_pattern_from_an_offscreen_webgl_canvas_carries_the_projection(readings):
|
||||
declared, stock = readings["declared"]["offscreen-webgl"], readings["stock"]["offscreen-webgl"]
|
||||
assert declared["viaPattern"] != stock["viaPattern"], (
|
||||
"createPattern(offscreenWebglCanvas) reads the same pixels with the engine declared and not declared: the pattern is the clean render, "
|
||||
"the projection does not reach it")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["webgl", "offscreen-webgl"])
|
||||
def test_a_pattern_of_a_webgl_canvas_reads_what_drawimage_of_it_reads(readings, kind):
|
||||
declared = readings["declared"][kind]
|
||||
assert declared["viaPattern"] == declared["viaDraw"], (
|
||||
"%s: the pixels of createPattern + fill and of drawImage differ with the engine declared: the two reads of one canvas carry "
|
||||
"different projections" % kind)
|
||||
|
||||
|
||||
def test_create_pattern_from_a_2d_canvas_reads_the_same_with_the_engine_on_and_off(readings):
|
||||
declared, stock = readings["declared"]["2d"], readings["stock"]["2d"]
|
||||
assert declared["viaPattern"] == stock["viaPattern"], (
|
||||
"createPattern(2dCanvas) differs between the engine declared and not declared: a 2D source must be read as drawn")
|
||||
assert declared["viaDraw"] == stock["viaDraw"], "drawImage(2dCanvas) differs between the engine declared and not declared"
|
||||
assert declared["viaPattern"] == declared["viaDraw"], "a pattern of a 2D canvas is not the pixels drawImage reads"
|
||||
@@ -0,0 +1,122 @@
|
||||
"""``measureText`` answers the vertical metrics of the bundled font as whole numbers, as retail Windows Firefox does (e2e, every OS, firefox-68).
|
||||
|
||||
What the engine fixes. With the engine declared, ``CanvasRenderingContext2D::DrawOrMeasureText`` hands the run to ``StealthHostIndepTextMetrics``
|
||||
(``fingerprint/canvas/text-metrics``, ``dom/canvas/StealthCanvasTextMetrics.h`` of the series), which takes the font's vertical metrics from the
|
||||
bundled font's own OS/2 table (usWinAscent and usWinDescent, from the manifest the core hands to the engine) instead of the host's rasteriser, and
|
||||
ROUNDS them the way a Windows Firefox does (``gfxDWriteFont::ComputeMetrics`` rounds the pair, then derives the em box from the rounded pair). On
|
||||
retail, ``fontBoundingBoxAscent`` and ``fontBoundingBoxDescent`` are therefore whole numbers at every size, and so are the four
|
||||
``actualBoundingBox*`` of the empty string (it has no ink); a public fingerprinting page measures exactly that
|
||||
string and flags any value that is not whole. Fractional values (65.1796875 for 72px Arial) are what a FreeType host computes from the same table.
|
||||
|
||||
What the test reads. One page measures ``Hamburgefonstiv`` and the empty string through ``Arial`` at 10, 12, 16, 20 and 72 px
|
||||
(``ctx.font = "<n>px Arial"``) and returns the twelve fields of every TextMetrics. The expected font-box values are the rounded
|
||||
``usWin`` metrics of the Arial face in the bundle manifest (``tests/_font_names.py``: ascent 1854, descent 434, unit 2048): round(1854 x px / 2048)
|
||||
and round(434 x px / 2048); four of them are also written as the retail measurements recorded with the engine source (72px ascent 65, 20px
|
||||
ascent 18, 12px ascent 11, 10px descent 2).
|
||||
|
||||
The negative control, in the same test. The page runs again with the engine not declared (``zoom.stealth.fpp.hw_seed`` = 0), which keeps the
|
||||
stock code. The control is adapted to the OS because the stock code is a different one on each:
|
||||
|
||||
* Linux: the stock path is FreeType's, which does not round like DirectWrite: the twelve fields over the five sizes DIFFER from the engine's.
|
||||
The page is the one that tells the host's values from the declared ones.
|
||||
* Windows: the stock path IS DirectWrite's (the retail path the engine reproduces), so the font box with the engine off is the same whole numbers
|
||||
the engine declares: the test asserts that they are equal, which is the engine matching the Windows rasteriser and not an invented rounding.
|
||||
|
||||
Why a page reads it: ``CanvasRenderingContext2D.measureText`` is plain web API; ``fontBoundingBoxAscent`` is in the probe of every canvas
|
||||
fingerprint.
|
||||
|
||||
Run: pytest tests/test_canvas_measure_text_metrics_e2e.py -m e2e -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
import _font_names as fn
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
SIZES = [10, 12, 16, 20, 72]
|
||||
TEXT = "Hamburgefonstiv"
|
||||
|
||||
FIELDS = ["width", "actualBoundingBoxLeft", "actualBoundingBoxRight", "actualBoundingBoxAscent", "actualBoundingBoxDescent",
|
||||
"fontBoundingBoxAscent", "fontBoundingBoxDescent", "emHeightAscent", "emHeightDescent", "hangingBaseline", "alphabeticBaseline",
|
||||
"ideographicBaseline"]
|
||||
|
||||
#: Retail Windows Firefox, Arial, recorded with the engine source: (size, field) -> value.
|
||||
RETAIL = {(72, "fontBoundingBoxAscent"): 65, (20, "fontBoundingBoxAscent"): 18, (12, "fontBoundingBoxAscent"): 11,
|
||||
(10, "fontBoundingBoxDescent"): 2}
|
||||
|
||||
MEASURE = """(args) => {
|
||||
const [sizes, text, fields] = args;
|
||||
const ctx = document.createElement('canvas').getContext('2d');
|
||||
const read = (m) => { const o = {}; for (const f of fields) o[f] = m[f]; return o; };
|
||||
const out = {};
|
||||
for (const size of sizes) {
|
||||
ctx.font = size + 'px Arial';
|
||||
out[size] = {text: read(ctx.measureText(text)), empty: read(ctx.measureText(''))};
|
||||
}
|
||||
return out;
|
||||
}"""
|
||||
|
||||
|
||||
def _read(firefox_binary, engine_declared):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
prefs = {} if engine_declared else {"zoom.stealth.fpp.hw_seed": 0}
|
||||
with InvisiblePlaywright(seed=21, binary_path=firefox_binary, headless=True, extra_prefs=prefs) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto("about:blank", timeout=30_000)
|
||||
raw = page.evaluate(MEASURE, [SIZES, TEXT, FIELDS])
|
||||
return {int(size): rows for size, rows in raw.items()}
|
||||
|
||||
|
||||
def _whole(value):
|
||||
return float(value).is_integer()
|
||||
|
||||
|
||||
def _round(value):
|
||||
"""std::round: halves away from zero (the values here are positive)."""
|
||||
return int(math.floor(value + 0.5))
|
||||
|
||||
|
||||
def test_measure_text_vertical_metrics_are_whole_and_retail(firefox_binary):
|
||||
arial = fn.bundle_manifest().face_with_psname("ArialMT")
|
||||
upem, ascent, descent = arial["upem"], arial["ascent"], arial["descent"]
|
||||
expected = {size: {"fontBoundingBoxAscent": _round(ascent * size / upem), "fontBoundingBoxDescent": _round(descent * size / upem)}
|
||||
for size in SIZES}
|
||||
for (size, field), value in RETAIL.items():
|
||||
assert expected[size][field] == value, (
|
||||
"the rounded OS/2 metric of the manifest's Arial (%s at %dpx = %r) is not the retail value %r the engine source records: the manifest "
|
||||
"is not the face this test was written for" % (field, size, expected[size][field], value))
|
||||
|
||||
declared = _read(firefox_binary, True)
|
||||
for size in SIZES:
|
||||
for kind in ("text", "empty"):
|
||||
row = declared[size][kind]
|
||||
for field in ("fontBoundingBoxAscent", "fontBoundingBoxDescent"):
|
||||
assert _whole(row[field]), "engine declared: %dpx Arial %s of %r is %r, not a whole number" % (size, field, kind, row[field])
|
||||
assert row[field] == expected[size][field], (
|
||||
"engine declared: %dpx Arial %s of %r is %r, the rounded OS/2 metric of the bundled face is %r"
|
||||
% (size, field, kind, row[field], expected[size][field]))
|
||||
for field in ("actualBoundingBoxLeft", "actualBoundingBoxRight", "actualBoundingBoxAscent", "actualBoundingBoxDescent"):
|
||||
assert _whole(declared[size]["empty"][field]), (
|
||||
"engine declared: %dpx Arial %s of the empty string is %r, not a whole number: a page that measures the empty string reads a "
|
||||
"host rasteriser" % (size, field, declared[size]["empty"][field]))
|
||||
|
||||
stock = _read(firefox_binary, False)
|
||||
if sys.platform == "win32":
|
||||
for size in SIZES:
|
||||
for kind in ("text", "empty"):
|
||||
for field in ("fontBoundingBoxAscent", "fontBoundingBoxDescent"):
|
||||
assert stock[size][kind][field] == declared[size][kind][field], (
|
||||
"engine not declared: %dpx Arial %s of %r is %r on the DirectWrite path and %r with the engine: the engine's rounding is "
|
||||
"not the Windows rasteriser's" % (size, field, kind, stock[size][kind][field], declared[size][kind][field]))
|
||||
else:
|
||||
different = [(size, kind, field) for size in SIZES for kind in ("text", "empty") for field in FIELDS
|
||||
if stock[size][kind][field] != declared[size][kind][field]]
|
||||
assert different, (
|
||||
"engine not declared: the twelve fields over five sizes are the same as with the engine declared: the page cannot tell the host's "
|
||||
"values from the declared ones, so the control proves nothing")
|
||||
@@ -15,6 +15,9 @@ known-bad:
|
||||
same text canvas: what separates two machines is how they draw, never a
|
||||
per-seed change at readback.
|
||||
* A toDataURL PNG carries the deBG chunk retail 151 writes.
|
||||
* A WebGL canvas that is not premultiplied (premultipliedAlpha:false, half
|
||||
transparent) reads the same pixels through toDataURL and toBlob, noised with the
|
||||
engine on (hw_seed > 0); the control is the engine off (hw_seed 0: as drawn).
|
||||
|
||||
Runs against about:blank and a local http page, no network/proxy. Part of the
|
||||
e2e release gate.
|
||||
@@ -154,3 +157,84 @@ def test_two_seeds_on_the_same_machine_draw_the_same_text(firefox_binary):
|
||||
assert hashlib.sha256(bytes(a)).digest() == hashlib.sha256(bytes(b)).digest(), (
|
||||
"two seeds declaring the same display scale and ClearType tuning read "
|
||||
"different text pixels: something per-seed still changes a 2D canvas")
|
||||
|
||||
|
||||
_NON_PREMULTIPLIED_JS = """async () => {
|
||||
const c = document.createElement('canvas'); c.width = 128; c.height = 128;
|
||||
const gl = c.getContext('webgl', {premultipliedAlpha: false, alpha: true,
|
||||
preserveDrawingBuffer: true, antialias: true});
|
||||
if (!gl) return null;
|
||||
const alpha = 128 / 255;
|
||||
const vs = gl.createShader(gl.VERTEX_SHADER);
|
||||
gl.shaderSource(vs, 'attribute vec2 p; attribute vec3 c; varying vec3 v;'
|
||||
+ ' void main(){v=c;gl_Position=vec4(p,0.,1.);}');
|
||||
gl.compileShader(vs);
|
||||
const fs = gl.createShader(gl.FRAGMENT_SHADER);
|
||||
gl.shaderSource(fs, 'precision mediump float; varying vec3 v; void main(){gl_FragColor=vec4(v,'
|
||||
+ alpha.toFixed(8) + ');}');
|
||||
gl.compileShader(fs);
|
||||
const pr = gl.createProgram(); gl.attachShader(pr, vs); gl.attachShader(pr, fs);
|
||||
gl.linkProgram(pr); gl.useProgram(pr);
|
||||
const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(
|
||||
[-0.9, -0.8, 1, 0, 0, 0.85, -0.6, 0, 1, 0, 0.1, 0.9, 0, 0, 1]), gl.STATIC_DRAW);
|
||||
const pl = gl.getAttribLocation(pr, 'p'), cl = gl.getAttribLocation(pr, 'c');
|
||||
gl.enableVertexAttribArray(pl); gl.vertexAttribPointer(pl, 2, gl.FLOAT, false, 20, 0);
|
||||
gl.enableVertexAttribArray(cl); gl.vertexAttribPointer(cl, 3, gl.FLOAT, false, 20, 8);
|
||||
gl.clearColor(1, 1, 1, alpha); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 3);
|
||||
gl.finish();
|
||||
const url = c.toDataURL();
|
||||
const blob = await new Promise(resolve => c.toBlob(resolve, 'image/png'));
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
let binary = '';
|
||||
for (let i = 0; i < bytes.length; i += 8192) binary += String.fromCharCode.apply(null, bytes.subarray(i, i + 8192));
|
||||
return {url, blob: btoa(binary), premultipliedAlpha: gl.getContextAttributes().premultipliedAlpha};
|
||||
}"""
|
||||
|
||||
|
||||
def _non_premultiplied(firefox_binary, hw_seed):
|
||||
"""(the pixels of toDataURL, the pixels of toBlob) of one half-transparent, non-premultiplied WebGL canvas,
|
||||
as 128x128 RGBA bytes, with the engine on (hw_seed > 0) or off (0)."""
|
||||
import base64
|
||||
|
||||
from _page_bytes import unfiltered
|
||||
|
||||
with InvisiblePlaywright(
|
||||
seed=7, binary_path=firefox_binary, headless=True,
|
||||
extra_prefs={"zoom.stealth.fpp.hw_seed": hw_seed},
|
||||
) as b:
|
||||
p = b.new_context().new_page()
|
||||
p.goto("about:blank", timeout=30_000)
|
||||
got = p.evaluate(_NON_PREMULTIPLIED_JS)
|
||||
assert got is not None, "webgl is unavailable: a WebGL canvas cannot be read"
|
||||
assert got["premultipliedAlpha"] is False, "the context is premultiplied: %r" % got["premultipliedAlpha"]
|
||||
images = [unfiltered(base64.b64decode(got["url"].split(",", 1)[1])), unfiltered(base64.b64decode(got["blob"]))]
|
||||
for png in images:
|
||||
assert (png["w"], png["h"], png["channels"]) == (128, 128, 4), png
|
||||
return images[0]["data"], images[1]["data"]
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_non_premultiplied_webgl_canvas_reads_the_same_through_todataurl_and_toblob(firefox_binary):
|
||||
"""toDataURL and toBlob of a premultipliedAlpha:false WebGL canvas give the same pixels, noised with the engine on.
|
||||
|
||||
The canvas noise is applied to the snapshot with its alpha type: a context that is not premultiplied stores
|
||||
the colours as drawn, and a reader that took it for premultiplied would noise (or convert) them wrongly.
|
||||
Both PNG readers go through the same hook (GetImageBuffer, GetInputStream in ClientWebGLContext.cpp). The
|
||||
canvas is half transparent (alpha 128/255, colours as drawn), so a premultiplied reading changes the bytes.
|
||||
Negative control, in the same test: with the engine off the two readers are the bytes as drawn, their alpha is
|
||||
the 128 drawn, and the engine-on PNG differs from them."""
|
||||
on_url, on_blob = _non_premultiplied(firefox_binary, 12345)
|
||||
off_url, off_blob = _non_premultiplied(firefox_binary, 0)
|
||||
alphas = {off_url[i] for i in range(3, len(off_url), 4)}
|
||||
assert alphas <= set(range(126, 131)), (
|
||||
"engine off: the alpha of the PNG is %s, not the 128 that was drawn" % sorted(alphas))
|
||||
differing = lambda a, b: sum(1 for x, y in zip(a, b) if x != y)
|
||||
assert off_blob == off_url, (
|
||||
"engine off: %d of %d bytes of toBlob differ from toDataURL" % (differing(off_blob, off_url), len(off_url)))
|
||||
assert differing(on_url, off_url), (
|
||||
"toDataURL of a non-premultiplied WebGL canvas is the same with the engine on and off: no noise reaches "
|
||||
"the page, so comparing the two readers says nothing")
|
||||
assert on_blob == on_url, (
|
||||
"engine on: %d of %d bytes of toBlob differ from toDataURL of the same non-premultiplied WebGL canvas"
|
||||
% (differing(on_blob, on_url), len(on_url)))
|
||||
@@ -0,0 +1,162 @@
|
||||
"""scripts/ci_suite_run.py runs one row of the whole-e2e suite and hands the judge ONE junit (no browser here: the run of the core is a fake).
|
||||
|
||||
What is held: the arguments of the run are the files and node ids of the row, in its order, and nothing else of the row (the passes bring their own marker); the
|
||||
two junit files of the passes become one xunit2 file with every testcase kept as pytest wrote it, counted from the cases and not from the headers, and the judge
|
||||
reads it; the run reaches the judge when a test is red (exit 0 for the passes that ran to their end) and does not when a pass did not run to its end or nothing
|
||||
was written; the variable that tells the core where its junit goes is set for the run and put back after it.
|
||||
|
||||
Known-bad inputs: a pass that wrote nothing, a second pass with no test, a skipped and a failed case among the passed, a row that is not in the list, a row of
|
||||
the other system, a pass that died (exit 2), a run that wrote no junit at all.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _load(name):
|
||||
spec = importlib.util.spec_from_file_location(name + "_under_test", ROOT / "scripts" / (name + ".py"))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
suite_run = _load("ci_suite_run")
|
||||
from invisible_core.testing import e2e as core_e2e # noqa: E402
|
||||
|
||||
ROW = "s.e2e.one"
|
||||
TESTS = ["tests/test_a_e2e.py", "tests/test_b_e2e.py::test_one", "tests/test_c_e2e.py"]
|
||||
|
||||
|
||||
def _required(tmp_path, **over):
|
||||
row = {"id": ROW, "giro": "G2", "os": ["linux"], "min_tests": 4, "exact": True, "tests": TESTS, "marker": "e2e", "needs_root": False}
|
||||
row.update(over)
|
||||
path = tmp_path / "required.json"
|
||||
path.write_text(json.dumps([row]), encoding="utf-8")
|
||||
return str(path)
|
||||
|
||||
|
||||
def _case(classname, name, outcome="passed", seconds="1.500"):
|
||||
case = ET.Element("testcase", {"classname": classname, "name": name, "time": seconds})
|
||||
if outcome != "passed":
|
||||
ET.SubElement(case, outcome, {"message": "x"})
|
||||
return case
|
||||
|
||||
|
||||
def _write(path, cases):
|
||||
suite = ET.Element("testsuite", {"name": "pytest", "errors": "0", "failures": "0", "skipped": "0", "tests": str(len(cases)), "time": "9.999"})
|
||||
suite.extend(cases)
|
||||
root = ET.Element("testsuites")
|
||||
root.append(suite)
|
||||
ET.ElementTree(root).write(path, encoding="utf-8", xml_declaration=True)
|
||||
|
||||
|
||||
def _fake_run(code, per_pass, seen):
|
||||
"""A stand-in for ``invisible_core.testing.e2e.main``: records its call and writes the junit of each pass where the core would."""
|
||||
def run(argv, repo):
|
||||
seen.append({"argv": list(argv), "repo": repo, "dir": suite_run.os.environ.get(core_e2e.JUNIT_DIR_ENV)})
|
||||
for (_width, selection), cases in zip(core_e2e.passes("4"), per_pass):
|
||||
if cases is not None:
|
||||
_write(core_e2e.junit_file(Path(seen[-1]["dir"]), selection), cases)
|
||||
return code
|
||||
return run
|
||||
|
||||
|
||||
def test_the_arguments_are_the_files_and_the_nodes_of_the_row_in_its_order(tmp_path):
|
||||
assert suite_run.row_arguments(_required(tmp_path), ROW, "linux") == TESTS
|
||||
|
||||
|
||||
def test_a_row_that_is_not_in_the_list_or_is_of_the_other_system_is_refused(tmp_path):
|
||||
required = _required(tmp_path)
|
||||
for suite, os_name in (("s.e2e.none", "linux"), (ROW, "windows")):
|
||||
with pytest.raises(suite_run.ci_verdict.Usage):
|
||||
suite_run.row_arguments(required, suite, os_name)
|
||||
assert suite_run.main(["--required", required, "--suite", "s.e2e.none", "--os", "linux", "--binary", "x", "--junit", str(tmp_path / "o.xml")]) == 2
|
||||
|
||||
|
||||
def test_the_two_junit_files_of_the_passes_become_one_xunit2_file_the_judge_reads(tmp_path):
|
||||
first, second, out = tmp_path / "a.xml", tmp_path / "b.xml", tmp_path / "out" / "merged.xml"
|
||||
_write(first, [_case("tests.test_a_e2e", "test_x"), _case("tests.test_b_e2e", "test_one[p1]", "failure"), _case("tests.test_c_e2e", "test_y", "skipped")])
|
||||
_write(second, [_case("tests.test_c_e2e", "test_clock", "error", "2.000")])
|
||||
assert suite_run.merge_junits([first, second], out) == 4
|
||||
root = ET.parse(out).getroot()
|
||||
suites = list(root.iter("testsuite"))
|
||||
assert len(suites) == 1 and suites[0].attrib["tests"] == "4"
|
||||
assert (suites[0].attrib["failures"], suites[0].attrib["errors"], suites[0].attrib["skipped"]) == ("1", "1", "1")
|
||||
assert suites[0].attrib["time"] == "6.500"
|
||||
cases, no_class = suite_run.ci_verdict.parse_junit(out)
|
||||
assert no_class == [] and [n for n, _o in cases] == ["tests/test_a_e2e.py::test_x", "tests/test_b_e2e.py::test_one[p1]", "tests/test_c_e2e.py::test_y",
|
||||
"tests/test_c_e2e.py::test_clock"]
|
||||
assert [o for _n, o in cases] == ["passed", "failed", "skipped", "errors"]
|
||||
|
||||
|
||||
def test_a_pass_that_wrote_nothing_is_not_an_error_of_the_merge_and_a_pass_with_no_test_adds_none(tmp_path):
|
||||
first, empty, out = tmp_path / "a.xml", tmp_path / "e.xml", tmp_path / "m.xml"
|
||||
_write(first, [_case("tests.test_a_e2e", "test_x")])
|
||||
_write(empty, [])
|
||||
assert suite_run.merge_junits([first, tmp_path / "never.xml", empty], out) == 1
|
||||
assert suite_run.merge_junits([tmp_path / "never.xml"], out) == 0
|
||||
assert ET.parse(out).getroot().find("testsuite").attrib["tests"] == "0"
|
||||
|
||||
|
||||
def test_the_counts_are_those_of_the_cases_and_not_of_the_headers(tmp_path):
|
||||
path, out = tmp_path / "a.xml", tmp_path / "m.xml"
|
||||
_write(path, [_case("tests.test_a_e2e", "test_x")])
|
||||
root = ET.parse(path).getroot()
|
||||
root.find("testsuite").attrib.update(tests="99", failures="7")
|
||||
ET.ElementTree(root).write(path)
|
||||
suite_run.merge_junits([path], out)
|
||||
attrs = ET.parse(out).getroot().find("testsuite").attrib
|
||||
assert (attrs["tests"], attrs["failures"]) == ("1", "0")
|
||||
|
||||
|
||||
def test_a_run_with_a_red_test_still_hands_the_junit_to_the_judge_and_exits_zero(tmp_path):
|
||||
seen, out = [], tmp_path / "result" / "s.xml"
|
||||
run = _fake_run(1, [[_case("tests.test_a_e2e", "test_x"), _case("tests.test_c_e2e", "test_z", "failure")], [_case("tests.test_c_e2e", "test_clock")]], seen)
|
||||
code = suite_run.run(_required(tmp_path), ROW, "linux", "/ff/firefox", str(out), repo=tmp_path, run_e2e=run)
|
||||
assert code == 0
|
||||
assert seen[0]["argv"] == ["/ff/firefox"] + TESTS and seen[0]["repo"] == tmp_path
|
||||
assert [o for _n, o in suite_run.ci_verdict.parse_junit(out)[0]] == ["passed", "failed", "passed"]
|
||||
|
||||
|
||||
def test_the_number_of_browsers_is_passed_to_the_run_only_when_asked(tmp_path):
|
||||
seen = []
|
||||
suite_run.run(_required(tmp_path), ROW, "linux", "ff", str(tmp_path / "o.xml"), repo=tmp_path, procs="2", run_e2e=_fake_run(0, [[_case("tests.t", "a")], None], seen))
|
||||
assert seen[0]["argv"][:3] == ["ff", "-n", "2"] and seen[0]["argv"][3:] == TESTS
|
||||
|
||||
|
||||
def test_a_pass_that_did_not_run_to_its_end_is_not_zero(tmp_path):
|
||||
seen, out = [], tmp_path / "o.xml"
|
||||
code = suite_run.run(_required(tmp_path), ROW, "linux", "ff", str(out), repo=tmp_path, run_e2e=_fake_run(2, [[_case("tests.t", "a")], None], seen))
|
||||
assert code == 2
|
||||
assert out.is_file(), "what the passes wrote is still handed to the judge, which says the suite is short"
|
||||
|
||||
|
||||
def test_a_run_that_wrote_no_junit_is_not_zero(tmp_path):
|
||||
out = tmp_path / "o.xml"
|
||||
assert suite_run.run(_required(tmp_path), ROW, "linux", "ff", str(out), repo=tmp_path, run_e2e=_fake_run(0, [None, None], [])) == 3
|
||||
assert suite_run.run(_required(tmp_path), ROW, "linux", "ff", str(out), repo=tmp_path, run_e2e=_fake_run(5, [None, None], [])) == 3
|
||||
|
||||
|
||||
def test_the_directory_of_the_junit_is_set_for_the_run_and_put_back_after_it(tmp_path, monkeypatch):
|
||||
monkeypatch.delenv(core_e2e.JUNIT_DIR_ENV, raising=False)
|
||||
seen = []
|
||||
suite_run.run(_required(tmp_path), ROW, "linux", "ff", str(tmp_path / "o.xml"), repo=tmp_path, run_e2e=_fake_run(0, [[_case("tests.t", "a")], None], seen))
|
||||
assert seen[0]["dir"] and core_e2e.JUNIT_DIR_ENV not in suite_run.os.environ
|
||||
monkeypatch.setenv(core_e2e.JUNIT_DIR_ENV, "somewhere")
|
||||
suite_run.run(_required(tmp_path), ROW, "linux", "ff", str(tmp_path / "o.xml"), repo=tmp_path, run_e2e=_fake_run(0, [[_case("tests.t", "a")], None], seen))
|
||||
assert suite_run.os.environ[core_e2e.JUNIT_DIR_ENV] == "somewhere"
|
||||
|
||||
|
||||
def test_the_passes_of_the_run_are_the_core_s_and_the_junit_names_are_its_own():
|
||||
names = [p.name for p in suite_run.pass_junits(Path("d"))]
|
||||
assert names == ["e2e-junit-e2e-and-not-wall_clock.xml", "e2e-junit-e2e-and-wall_clock.xml"], names
|
||||
assert [p.name for p in suite_run.pass_junits(Path("d"), "1")] == ["e2e-junit-e2e.xml"]
|
||||
@@ -163,3 +163,269 @@ def test_a_context_locale_reaches_navigator_intl_and_the_header(firefox_binary):
|
||||
ctx.close()
|
||||
finally:
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------
|
||||
# What a worker, a worklet, a canvas and the page's own realm say of the language and the zone of their context.
|
||||
#
|
||||
# Characterisation of firefox-68 (the hooks of fingerprint/locale-time/{workers,language,timezone} in the engine series cite these
|
||||
# tests by name): each one is green on the published engine and has to stay green on the one that replaces its hooks. The language
|
||||
# and the zone are read where a page reads them (a worker's own `navigator` and `Intl`, a worklet's processor, a canvas's text
|
||||
# metrics, an inline script of the page). Where a context's value is compared with another value, the other is a control that can
|
||||
# fail: the context left on the launch language, or a context with a language of its own that the change must not reach.
|
||||
# ---------------------------------------------------------------------------------------------------------------------------------
|
||||
import _locale_probe as probe # noqa: E402
|
||||
|
||||
DE_LIST = ["de-DE", "de", "en-US", "en"]
|
||||
|
||||
#: One page for every tab the tests below open: the URL is what tells the tabs apart for the chrome scope, so each one carries a query.
|
||||
SITE = {
|
||||
"/page": probe.PAGE,
|
||||
"/lang-worker.js": (probe.LANG_WORKER, "text/javascript"),
|
||||
"/measure-worker.js": (probe.MEASURE_WORKER, "text/javascript"),
|
||||
}
|
||||
|
||||
|
||||
def _wait_for(condition, page):
|
||||
"""True once ``condition()`` holds, polled with the page's event loop as the pump; the deadline is the one of ``wait_until``."""
|
||||
from _waits import wait_until
|
||||
|
||||
return wait_until(condition, 30, lambda: page.wait_for_timeout(100))
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_worker_with_its_own_language_ignores_the_accept_languages_pref(firefox_binary, monkeypatch):
|
||||
"""⛔ ``intl.accept_languages`` IS THE LANGUAGE OF A BROWSER THAT DECLARED NONE. When the pref changes Firefox tells every worker, and
|
||||
a worker that has no language of its own takes the new list. A worker whose context declares a language reads that list from its
|
||||
owner and has to ignore the broadcast (WorkerPrivate::UpdateLanguagesInternal): a site cannot see two languages move apart in
|
||||
one browser because a pref moved. The engine's own refusal is what is pinned here.
|
||||
|
||||
One session with nothing declared at launch (``juggler.locale.override`` empty: no language falls back to the session) and two
|
||||
contexts: one asks for de-DE, the other for nothing (``locale=None``). The pref goes to "ja, en-US" from the chrome scope. The worker
|
||||
of the context with nothing declared takes it (the control: the broadcast reaches workers, so the other worker's silence is
|
||||
its own); the worker with de-DE keeps de-DE and its four entries. The two contexts are in different content processes, so the change of
|
||||
the other worker proves nothing about the process of the silent one: before the silent worker is read, the test waits on the
|
||||
CONDITION "the content process of each of the two tabs reports ``intl.accept_languages`` = "ja, en-US"" (a process script reads the pref
|
||||
in each process). A process that reports it has applied the change and queued the broadcast to its workers before it answered, so the
|
||||
answer of the worker with de-DE comes after the broadcast was handled in its own process.
|
||||
"""
|
||||
import webfont_probe
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
monkeypatch.setenv("MOZ_REMOTE_ALLOW_SYSTEM_ACCESS", "1") # the chrome-scope write below
|
||||
srv, base = probe.serve(SITE)
|
||||
marionette = None
|
||||
try:
|
||||
with InvisiblePlaywright(seed=5150, binary_path=firefox_binary, headless=True, locale="it-IT", timezone="Europe/Rome",
|
||||
extra_args=probe.MARIONETTE_ARGS,
|
||||
extra_prefs={"marionette.port": 0, "juggler.locale.override": ""}) as browser:
|
||||
own = browser.new_context(locale="de-DE").new_page()
|
||||
none = browser.new_context(locale=None).new_page()
|
||||
for name, page in (("own", own), ("none", none)):
|
||||
page.goto("%s/page?%s" % (base, name), wait_until="load", timeout=30_000)
|
||||
page.evaluate(probe.START_LANG_WORKER_JS)
|
||||
kept = {"languages": DE_LIST, "intl": "de-DE"}
|
||||
assert own.evaluate(probe.ASK_LANG_WORKER_JS) == kept, "the worker with its own language before the pref moves"
|
||||
before = none.evaluate(probe.ASK_LANG_WORKER_JS)["languages"]
|
||||
assert before != ["ja", "en-US"], "the control worker already speaks the list the pref is about to take: %r" % (before,)
|
||||
|
||||
marionette = probe.open_chrome(webfont_probe.marionette_active_port())
|
||||
assert probe.set_pref(marionette, "intl.accept_languages", "ja, en-US") == "ja, en-US"
|
||||
|
||||
# The barrier: the content process of EACH tab holds the new value (read in that process), so the worker with de-DE is read after its
|
||||
# own process handled the change.
|
||||
processes = []
|
||||
|
||||
def every_process_has_it():
|
||||
processes.append(probe.content_process_prefs(marionette, "intl.accept_languages", ("own", "none")))
|
||||
return processes[-1].get("prefs") == {"own": "ja, en-US", "none": "ja, en-US"}
|
||||
|
||||
assert _wait_for(every_process_has_it, none), (
|
||||
"a content process never reported the new intl.accept_languages (last answers: %r)" % (processes[-3:],))
|
||||
|
||||
seen = []
|
||||
|
||||
def follows():
|
||||
seen.append(none.evaluate(probe.ASK_LANG_WORKER_JS)["languages"])
|
||||
return seen[-1] == ["ja", "en-US"]
|
||||
|
||||
assert _wait_for(follows, none), (
|
||||
"the worker with no language of its own never took the pref (it answered %r): the broadcast does not reach workers, "
|
||||
"so the silence of the other worker proves nothing" % (seen[-3:],))
|
||||
assert own.evaluate(probe.ASK_LANG_WORKER_JS) == kept, (
|
||||
"the worker with its own language followed intl.accept_languages instead of its context")
|
||||
finally:
|
||||
if marionette is not None:
|
||||
marionette.close()
|
||||
probe.stop(srv)
|
||||
|
||||
|
||||
SW_ZONE = b"""
|
||||
const read = () => ({timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
january: new Date(Date.UTC(2024, 0, 15, 12)).getTimezoneOffset()});
|
||||
onmessage = (e) => e.source.postMessage(read());
|
||||
"""
|
||||
|
||||
SW_JS = """async () => {
|
||||
const reg = await navigator.serviceWorker.register('/sw-zone.js');
|
||||
const sw = reg.active || reg.waiting || reg.installing;
|
||||
return await new Promise((ok) => {
|
||||
navigator.serviceWorker.onmessage = (e) => ok(e.data);
|
||||
const send = () => sw.postMessage(0);
|
||||
if (sw.state === 'activated') send();
|
||||
else sw.addEventListener('statechange', () => sw.state === 'activated' && send());
|
||||
});
|
||||
}"""
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_service_worker_of_a_context_with_its_own_zone_has_it(firefox_binary):
|
||||
"""⛔ A SERVICE WORKER IS BORN FAR FROM ITS PAGE. It has no window; the engine hands it the language and the zone of its context in
|
||||
the data it is started with (ServiceWorkerPrivate::RefreshRemoteWorkerData), and a worker that missed them told a site the
|
||||
SESSION's zone while the page in the same context told another: the one clock of a context, read twice. A context asks for its own
|
||||
zone with ``timezone_id``; the service worker it registers reads it back in ``Intl`` and in the offset of a date.
|
||||
|
||||
An Europe/Rome session, a context with ``timezone_id="Asia/Tokyo"``: its service worker answers Asia/Tokyo and -540 (no daylight
|
||||
time, one answer all year). The control is the session's own context: its service worker answers Europe/Rome and -60 in January.
|
||||
"""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
srv, base = probe.serve(dict(SITE, **{"/sw-zone.js": (SW_ZONE, "text/javascript")}))
|
||||
try:
|
||||
with InvisiblePlaywright(seed=5150, binary_path=firefox_binary, headless=True, locale="it-IT",
|
||||
timezone="Europe/Rome") as browser:
|
||||
answers = {}
|
||||
for name, options in (("session", {}), ("tokyo", {"timezone_id": "Asia/Tokyo"})):
|
||||
page = browser.new_context(**options).new_page()
|
||||
page.goto("%s/page?%s" % (base, name), wait_until="load", timeout=30_000)
|
||||
answers[name] = page.evaluate(SW_JS)
|
||||
assert answers["tokyo"] == {"timeZone": "Asia/Tokyo", "january": -540}, "the service worker of the Asia/Tokyo context"
|
||||
assert answers["session"] == {"timeZone": "Europe/Rome", "january": -60}, (
|
||||
"the service worker of the context that asked for no zone (the session's)")
|
||||
finally:
|
||||
probe.stop(srv)
|
||||
|
||||
|
||||
WORKLET = b"""
|
||||
class Probe extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super();
|
||||
const options = Intl.DateTimeFormat().resolvedOptions();
|
||||
this.port.postMessage({locale: options.locale, timeZone: options.timeZone,
|
||||
january: new Date(Date.UTC(2024, 0, 15, 12)).getTimezoneOffset()});
|
||||
}
|
||||
process() { return false; }
|
||||
}
|
||||
registerProcessor('probe', Probe);
|
||||
"""
|
||||
|
||||
# An OfflineAudioContext: a worklet needs no sound device, and the processor is built when its node is.
|
||||
WORKLET_JS = """async () => {
|
||||
const ctx = new OfflineAudioContext(1, 128, 44100);
|
||||
await ctx.audioWorklet.addModule('/worklet.js');
|
||||
const node = new AudioWorkletNode(ctx, 'probe');
|
||||
const heard = new Promise((ok) => { node.port.onmessage = (e) => ok(e.data); });
|
||||
node.connect(ctx.destination);
|
||||
ctx.startRendering();
|
||||
return await heard;
|
||||
}"""
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_an_audio_worklet_of_a_context_speaks_its_language_and_zone(firefox_binary):
|
||||
"""⛔ A WORKLET IS A GLOBAL OF ITS OWN AND ASKS ITS OWN QUESTIONS. An AudioWorkletProcessor runs on the audio thread in a realm that is
|
||||
not the page's and not a worker's (WorkletGlobalScope::CreateRealmOptions); a realm built from the process's sources told a site that
|
||||
reads ``Intl`` in a processor the host's language and zone. The engine reads the language and the zone from the window that added the
|
||||
module (WorkletLoadInfo) and gives them to the realm it builds.
|
||||
|
||||
An it-IT, Europe/Rome session; a context with ``locale="de-DE"`` and ``timezone_id="Asia/Tokyo"``; the processor posts what its own
|
||||
``Intl`` says. The context's worklet answers de-DE, Asia/Tokyo and -540 for a January date. The control is the context that asked
|
||||
for neither: its worklet answers it-IT, Europe/Rome and -60. The two answers differ in each field.
|
||||
"""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
srv, base = probe.serve(dict(SITE, **{"/worklet.js": (WORKLET, "text/javascript")}))
|
||||
try:
|
||||
with InvisiblePlaywright(seed=5150, binary_path=firefox_binary, headless=True, locale="it-IT",
|
||||
timezone="Europe/Rome") as browser:
|
||||
answers = {}
|
||||
for name, options in (("session", {}), ("own", {"locale": "de-DE", "timezone_id": "Asia/Tokyo"})):
|
||||
page = browser.new_context(**options).new_page()
|
||||
page.goto("%s/page?%s" % (base, name), wait_until="load", timeout=30_000)
|
||||
answers[name] = page.evaluate(WORKLET_JS)
|
||||
assert answers["own"] == {"locale": "de-DE", "timeZone": "Asia/Tokyo", "january": -540}, (
|
||||
"the worklet of the de-DE, Asia/Tokyo context")
|
||||
assert answers["session"] == {"locale": "it-IT", "timeZone": "Europe/Rome", "january": -60}, (
|
||||
"the worklet of the context that asked for neither (the session's)")
|
||||
assert all(answers["own"][key] != answers["session"][key] for key in answers["own"]), answers
|
||||
finally:
|
||||
probe.stop(srv)
|
||||
|
||||
|
||||
def _canvas_widths(page):
|
||||
return page.evaluate(probe.MEASURE_PAGE_JS, ["ja", "en"])
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_text_without_lang_takes_the_language_group_of_the_session_language(firefox_binary):
|
||||
"""⛔ TEXT WITH NO ``lang`` TAKES THE LANGUAGE OF THE MACHINE, AND THE MACHINE IS THE SESSION. An OffscreenCanvas on the main thread has
|
||||
no element and no document: its font comes from nsLanguageAtomService::GetLocaleLanguage, which asked the host's regional settings
|
||||
and now asks the language the session declares. Two sessions launched with two languages measure the same strings differently, each
|
||||
as the canvas of its own language group.
|
||||
|
||||
A ja-JP launch and an en-US launch (one browser at a time). In each, a main-thread OffscreenCanvas with no ``lang`` measures as the
|
||||
canvas element with the session's language and not as the one with the other language, and as a worker of the session's own context
|
||||
(another reader of the same language). The control is the pair of sessions: their OffscreenCanvases do not measure alike.
|
||||
"""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
srv, base = probe.serve(SITE)
|
||||
try:
|
||||
read = {}
|
||||
for name, locale, zone in (("ja", "ja-JP", "Asia/Tokyo"), ("en", "en-US", "America/New_York")):
|
||||
with InvisiblePlaywright(seed=5150, binary_path=firefox_binary, headless=True, locale=locale, timezone=zone) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto("%s/page?%s" % (base, name), wait_until="load", timeout=30_000)
|
||||
read[name] = _canvas_widths(page)
|
||||
for name, other in (("ja", "en"), ("en", "ja")):
|
||||
got = read[name]
|
||||
assert got["element"]["ja"] != got["element"]["en"], (
|
||||
"the two language groups draw these strings alike here, so nothing can tell them apart: %r" % (got["element"],))
|
||||
assert got["offscreen"] == got["element"][name], (
|
||||
"the %s session's OffscreenCanvas measures %r, a canvas of the %s group %r" % (name, got["offscreen"], name, got["element"][name]))
|
||||
assert got["offscreen"] != got["element"][other], "the %s session's OffscreenCanvas measures as the %s group" % (name, other)
|
||||
assert got["offscreen"] == got["worker"], "the %s session: the main thread and a worker of the session's context disagree" % name
|
||||
assert read["ja"]["offscreen"] != read["en"]["offscreen"], "the two sessions' OffscreenCanvases measure alike"
|
||||
finally:
|
||||
probe.stop(srv)
|
||||
|
||||
|
||||
INTL_JS = "const o = Intl.DateTimeFormat().resolvedOptions(); return {locale: o.locale, timeZone: o.timeZone};"
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_intl_in_the_page_realm_follows_the_language_and_zone_of_its_context(firefox_binary):
|
||||
"""The page's own global is built from the language and the zone of its context (xpc::InitGlobalObjectOptions, fed by
|
||||
nsGlobalWindowOuter::CreateNativeGlobalForInner), and that realm is the one a site's inline script runs in. It is read here the way a
|
||||
site reads it: an INLINE script writes ``Intl.DateTimeFormat().resolvedOptions()`` into the DOM (``page.evaluate`` is not necessarily
|
||||
that realm on this engine, so a read through it would say nothing about it).
|
||||
|
||||
An it-IT, Europe/Rome launch: the default context's page realm says it-IT and Europe/Rome. A context with ``locale="de-DE"`` and
|
||||
``timezone_id="Asia/Tokyo"``: de-DE and Asia/Tokyo. The control is the pair: the two contexts' answers differ in both fields.
|
||||
"""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
srv, base = probe.serve(SITE)
|
||||
try:
|
||||
with InvisiblePlaywright(seed=5150, binary_path=firefox_binary, headless=True, locale="it-IT",
|
||||
timezone="Europe/Rome") as browser:
|
||||
read = {}
|
||||
for name, options in (("session", {}), ("own", {"locale": "de-DE", "timezone_id": "Asia/Tokyo"})):
|
||||
page = browser.new_context(**options).new_page()
|
||||
page.goto("%s/page?%s" % (base, name), wait_until="load", timeout=30_000)
|
||||
read[name] = probe.read_in_page_realm(page, INTL_JS)
|
||||
assert read["session"] == {"locale": "it-IT", "timeZone": "Europe/Rome"}, "the page realm of the default context"
|
||||
assert read["own"] == {"locale": "de-DE", "timeZone": "Asia/Tokyo"}, "the page realm of the de-DE, Asia/Tokyo context"
|
||||
assert all(read["own"][key] != read["session"][key] for key in read["own"]), read
|
||||
finally:
|
||||
probe.stop(srv)
|
||||
@@ -0,0 +1,136 @@
|
||||
"""The size and pointer media queries answer the declaration, not the host.
|
||||
|
||||
What it fixes, from the page's side (`matchMedia`):
|
||||
|
||||
* `(device-width: Wpx)` / `(device-height: Hpx)` are the declared screen (`zoom.stealth.screen.width/height`), not the
|
||||
host's monitor.
|
||||
* `(pointer: ...)` / `(any-pointer: ...)` / `(hover: ...)` are the declared pointer capabilities
|
||||
(`zoom.stealth.pointer.primary` / `.all`, the bitmask Coarse 1, Fine 2, Hover 4), not the host's (a Windows machine
|
||||
with a digitizer adds Coarse by itself).
|
||||
* A context made with `has_touch=True` (Juggler's touch override) still reads a COARSE pointer when a fine one is
|
||||
declared: the override of the context decides before the declaration does.
|
||||
|
||||
Engine hook: `fingerprint/screen-window/css-media` of the engine series (`layout/style/nsMediaFeatures.cpp`:
|
||||
`GetDeviceSize`, `GetPointerCapabilities`; the declarations in `StealthMediaFeatures.h`).
|
||||
|
||||
Negative controls, in the same test: the device size is read on a launch declared with ANOTHER screen (2623x1411): the
|
||||
wrapper hands the declared screen to the browser by two roads (the screen prefs and the screen of the context, which Juggler
|
||||
emulates), so a launch with the prefs at 0 still reads the pinned screen; the queries must follow each declaration. The
|
||||
pointer is read with the engine off (`hw_seed` 0, stock Firefox: an active engine refuses a declaration cleared with -1), the
|
||||
host's answer; and has_touch is read in a context without it, on the same launch.
|
||||
|
||||
Linux and Windows run the same assertions: the declared values are the ones no runner has (a 2731x1537 screen; a coarse
|
||||
primary pointer on a machine with a mouse).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
#: A screen no runner has.
|
||||
SCREEN = {"screen.width": 2731, "screen.height": 1537, "screen.dpr": 1.0}
|
||||
|
||||
#: Another screen no runner has: the control of the device size is a launch declared with this one.
|
||||
OTHER_SCREEN = {"screen.width": 2623, "screen.height": 1411, "screen.dpr": 1.0}
|
||||
|
||||
#: The engine off (stock Firefox): the control of the pointer. The engine refuses an active launch with a declaration cleared.
|
||||
ENGINE_OFF = {"zoom.stealth.fpp.hw_seed": 0}
|
||||
|
||||
COARSE, FINE, HOVER = 1, 2, 4
|
||||
|
||||
QUERIES = {name: "matchMedia('%s').matches" % query for name, query in {
|
||||
"pointer_coarse": "(pointer: coarse)", "pointer_fine": "(pointer: fine)",
|
||||
"any_coarse": "(any-pointer: coarse)", "any_fine": "(any-pointer: fine)",
|
||||
"hover_none": "(hover: none)", "any_hover_none": "(any-hover: none)"}.items()}
|
||||
|
||||
READ_POINTER = "() => ({%s})" % ", ".join("%s: %s" % (k, v) for k, v in QUERIES.items())
|
||||
|
||||
|
||||
def _launch(binary, pin=None, extra_prefs=None):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
return InvisiblePlaywright(seed=42, pin=pin, binary_path=binary, headless=True, humanize=False,
|
||||
extra_prefs=extra_prefs)
|
||||
|
||||
|
||||
def _read_pointer(binary, primary=None, every=None):
|
||||
"""Declared pointer prefs, or (both None) the engine off."""
|
||||
prefs = ENGINE_OFF if primary is None else {"zoom.stealth.pointer.primary": primary, "zoom.stealth.pointer.all": every}
|
||||
with _launch(binary, extra_prefs=prefs) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank", timeout=30000)
|
||||
return page.evaluate(READ_POINTER)
|
||||
|
||||
|
||||
def test_a_declared_pointer_is_what_the_media_queries_read(firefox_binary):
|
||||
declared = _read_pointer(firefox_binary, COARSE, COARSE)
|
||||
assert declared == {"pointer_coarse": True, "pointer_fine": False, "any_coarse": True, "any_fine": False,
|
||||
"hover_none": True, "any_hover_none": True}, (
|
||||
"a coarse pointer without hover is declared and the page reads %r" % declared)
|
||||
|
||||
# The control: the engine off is not that machine. A fine pointer with hover is the declaration of a desktop; the host
|
||||
# with no declaration answers its own, and it is not a coarse one without hover.
|
||||
undeclared = _read_pointer(firefox_binary)
|
||||
assert undeclared != declared, "with no pointer declared the page reads the same as with a coarse one: %r" % undeclared
|
||||
assert undeclared["pointer_coarse"] is False and undeclared["any_coarse"] is False, (
|
||||
"with no pointer declared the page reads %r" % undeclared)
|
||||
|
||||
fine = _read_pointer(firefox_binary, FINE | HOVER, FINE | HOVER)
|
||||
assert fine == {"pointer_coarse": False, "pointer_fine": True, "any_coarse": False, "any_fine": True,
|
||||
"hover_none": False, "any_hover_none": False}, (
|
||||
"a fine pointer with hover is declared and the page reads %r" % fine)
|
||||
|
||||
|
||||
def test_has_touch_reads_a_coarse_pointer_even_when_a_fine_one_is_declared(firefox_binary):
|
||||
with _launch(firefox_binary, extra_prefs={"zoom.stealth.pointer.primary": FINE | HOVER,
|
||||
"zoom.stealth.pointer.all": FINE | HOVER}) as browser:
|
||||
plain = browser.new_context().new_page()
|
||||
plain.goto("about:blank", timeout=30000)
|
||||
touch = browser.new_context(has_touch=True).new_page()
|
||||
touch.goto("about:blank", timeout=30000)
|
||||
without = plain.evaluate(READ_POINTER)
|
||||
with_touch = touch.evaluate(READ_POINTER)
|
||||
# the control: the same launch, a context without the override, reads the declared fine pointer
|
||||
assert without["pointer_fine"] is True and without["pointer_coarse"] is False, (
|
||||
"a context without has_touch reads %r under a declared fine pointer" % without)
|
||||
assert with_touch["pointer_coarse"] is True and with_touch["pointer_fine"] is False, (
|
||||
"a context with has_touch reads %r under a declared fine pointer: the touch override must win" % with_touch)
|
||||
assert with_touch["any_coarse"] is True, "any-pointer in a has_touch context reads %r" % with_touch
|
||||
|
||||
|
||||
def _read_device_size(binary, pin, ask):
|
||||
"""The page of a launch pinned to ``pin``, asked for the device size ``ask`` (width, height) and for its own."""
|
||||
with _launch(binary, pin=pin) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank", timeout=30000)
|
||||
return page.evaluate("""([w, h]) => ({
|
||||
screen_w: screen.width, screen_h: screen.height,
|
||||
device_width: matchMedia('(device-width: ' + w + 'px)').matches,
|
||||
device_height: matchMedia('(device-height: ' + h + 'px)').matches,
|
||||
own_width: matchMedia('(device-width: ' + screen.width + 'px)').matches,
|
||||
own_height: matchMedia('(device-height: ' + screen.height + 'px)').matches})""", list(ask))
|
||||
|
||||
|
||||
def test_the_device_size_media_queries_read_the_declared_screen(firefox_binary):
|
||||
first = (SCREEN["screen.width"], SCREEN["screen.height"])
|
||||
second = (OTHER_SCREEN["screen.width"], OTHER_SCREEN["screen.height"])
|
||||
|
||||
declared = _read_device_size(firefox_binary, SCREEN, first)
|
||||
assert declared["device_width"] is True and declared["device_height"] is True, (
|
||||
"(device-width: 2731px) and (device-height: 1537px) do not match under a declared 2731x1537 screen: %r" % declared)
|
||||
assert (declared["screen_w"], declared["screen_h"]) == first
|
||||
assert declared["own_width"] is True and declared["own_height"] is True, (
|
||||
"the device size the media queries read is not the screen the page reads: %r" % declared)
|
||||
|
||||
# The control: the wrapper hands the declared screen to the browser by two roads (the prefs, and the screen of the context
|
||||
# that Juggler emulates), so the absent declaration is not a control. A launch with ANOTHER declared screen is: the same
|
||||
# query for the first size does not match there, and the queries follow that declaration.
|
||||
other = _read_device_size(firefox_binary, OTHER_SCREEN, first)
|
||||
assert (other["screen_w"], other["screen_h"]) == second, other
|
||||
assert other["device_width"] is False and other["device_height"] is False, (
|
||||
"(device-width: 2731px) matches under a declared %dx%d screen: the media queries do not follow the declaration, %r"
|
||||
% (second + (other,)))
|
||||
assert other["own_width"] is True and other["own_height"] is True, (
|
||||
"the device size the media queries read is not the screen the page reads: %r" % other)
|
||||
assert second != first and other != declared
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Iterating a DOM iterable from `page.evaluate` works, one case per iterable.
|
||||
|
||||
Upstream Playwright evaluates in the page's main world, so `[...x]` of any
|
||||
iterable works there. Our wrapper evaluates in the caller's world (Xrays), and
|
||||
on retail-like Windows `page.evaluate("async () => [...(await
|
||||
navigator.gpu.requestAdapter()).features]")` failed with "Xray wrapping of
|
||||
iterators not supported". This file holds the iterables that do work: one
|
||||
test per case, each spreading an iterable inside `evaluate` and returning plain
|
||||
values, so a case that fails names the iterable that does and the error text.
|
||||
|
||||
A page reads these iterables with its own scripts (every site does
|
||||
`[...new URLSearchParams(location.search)]` or `[...document.querySelectorAll(..)]`)
|
||||
and a framework or a test harness does the same from `evaluate`, so a call that
|
||||
throws where stock Playwright answers is a product difference.
|
||||
|
||||
Cases: URLSearchParams, FormData (empty and with a field), Headers, `document.fonts`,
|
||||
`querySelectorAll`, and a Map created by the PAGE's own script: all green on firefox-68
|
||||
(run 44979351495, Linux and Windows), so this file characterizes them. The WebGPU
|
||||
`adapter.features` Set-like is NOT here: on firefox-68 spreading it from `evaluate` throws
|
||||
"Xray wrapping of iterators not supported" on both systems; its red proof is kept on the
|
||||
branch tests/dom-iterables-from-evaluate.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
PAGE = b"""<!doctype html><html><head><meta charset="utf-8"><title>iterables</title></head>
|
||||
<body><p>one</p><p>two</p>
|
||||
<script>window.m = new Map([["x", 1]]);</script></body></html>"""
|
||||
|
||||
|
||||
# id -> (expression run by page.evaluate, check on its answer, what is expected)
|
||||
CASES = {
|
||||
"url-search-params": (
|
||||
'() => [...new URLSearchParams("a=1")]',
|
||||
lambda v: v == [["a", "1"]], '[["a", "1"]]'),
|
||||
"form-data-empty": (
|
||||
"() => [...new FormData()]",
|
||||
lambda v: v == [], "[]"),
|
||||
"form-data-with-a-field": (
|
||||
'() => { const f = new FormData(); f.append("k", "v"); return [...f]; }',
|
||||
lambda v: v == [["k", "v"]], '[["k", "v"]]'),
|
||||
"headers": (
|
||||
'() => [...new Headers({a: "1"})]',
|
||||
lambda v: v == [["a", "1"]], '[["a", "1"]]'),
|
||||
"document-fonts": (
|
||||
"() => { const a = [...document.fonts]; return [Array.isArray(a), a.length >= 0]; }",
|
||||
lambda v: v == [True, True], "[true, true]"),
|
||||
"query-selector-all": (
|
||||
'() => [...document.querySelectorAll("*")].length',
|
||||
lambda v: isinstance(v, int) and v > 0, "a length > 0"),
|
||||
"a-map-made-by-the-page": (
|
||||
"() => [...window.m]",
|
||||
lambda v: v == [["x", 1]], '[["x", 1]]'),
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def site():
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(PAGE)))
|
||||
self.end_headers()
|
||||
self.wfile.write(PAGE)
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
from _servers import LocalServer
|
||||
|
||||
srv = LocalServer(("127.0.0.1", 0), H)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
yield f"http://127.0.0.1:{srv.server_address[1]}/"
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def browser(firefox_binary):
|
||||
# One browser per case: a crash in one case reddens that case only, not the ones after it.
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=4321, binary_path=firefox_binary,
|
||||
headless=True) as b:
|
||||
yield b
|
||||
|
||||
|
||||
@pytest.mark.parametrize("case", list(CASES), ids=list(CASES))
|
||||
def test_iterating_from_evaluate_works(browser, site, case):
|
||||
expression, ok, expected = CASES[case]
|
||||
page = browser.new_page()
|
||||
try:
|
||||
page.goto(site, wait_until="domcontentloaded")
|
||||
try:
|
||||
answer = page.evaluate(expression)
|
||||
except Exception as exc: # noqa: BLE001 - the error text of any kind is the finding
|
||||
pytest.fail(f"{case}: evaluate threw {type(exc).__name__}: {exc}")
|
||||
assert ok(answer), f"{case}: evaluate answered {answer!r}, expected {expected}"
|
||||
finally:
|
||||
page.close()
|
||||
@@ -11,23 +11,82 @@ reports completion from OnSaveComplete and Cancel. Reported 2026-10-30 on the
|
||||
|
||||
Known-bad input: the engine before the fix -> every test here goes red
|
||||
(expect_download times out).
|
||||
|
||||
**The end of a download, and what is left to Firefox.** Two more tests hold the
|
||||
other half of the hook (`StealthDownloadIntercept`, folder `automation/downloads`
|
||||
of the engine series, hooks in `uriloader/exthandler/nsExternalHelperAppService.cpp`):
|
||||
|
||||
* a download the client cancels (`download.cancel()`) reports its end ONCE, as
|
||||
`canceled`: `Cancel` and `OnSaveComplete` both end in the interceptor's
|
||||
`onDownloadComplete`, and a second `Browser.downloadFinished` for the same
|
||||
uuid would be a second report of one download. Counted on the engine's own
|
||||
events (the connection's listener), not on the client's objects: the client
|
||||
ignores a repeated finish.
|
||||
* a context that has NO download options is not intercepted: the engine sends
|
||||
no `Browser.downloadCreated` and no `Browser.downloadFinished`, and the file
|
||||
goes where Firefox puts it (`browser.download.dir`). The same context, with
|
||||
its options, is the control: its download is announced and saved in the
|
||||
wrapper's directory, so the silence of the second download is the absence of
|
||||
the hook and not a page that never downloaded.
|
||||
|
||||
**A slow save is kept, not judged.** Firefox's own save of the last test has taken, on the runners, from about ten seconds to
|
||||
more than eighty for the same bytes: that is the product (a user's download would wait as long), so nothing of it is switched
|
||||
off. The seconds from the click to the file are recorded (a junit property), and a run slower than any healthy one
|
||||
(``SLOW_SAVE_S``, judged after the fact, never a verdict) keeps what says where the time went, in
|
||||
``$RUNNER_TEMP/invpw-evidence/download-left-to-firefox/`` (``tests/_evidence_on_failure.py``, the same on a failure): the requests
|
||||
the test's server saw, with times; every request the client heard (request, response, requestfinished, requestfailed), with
|
||||
times; the Juggler wire and the engine's Juggler trace; the engine's log of the download machinery (``DOWNLOAD_LOG``).
|
||||
|
||||
Why a page cares: a download that ends twice, or that lands in the wrong place,
|
||||
is a script that waits for a file that never comes, and a context that was given
|
||||
no options must behave as retail Firefox does.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import types
|
||||
|
||||
import pytest
|
||||
|
||||
from _evidence_on_failure import FailureEvidence
|
||||
from _waits import wait_until, watch
|
||||
|
||||
BODY = b"invisible download body\n" * 64
|
||||
|
||||
#: Seconds from the click to the file in Firefox's directory beyond which a run keeps its evidence: no healthy run comes near
|
||||
#: it. Judged after the fact, never a verdict (the test's deadline is the `watch` below).
|
||||
SLOW_SAVE_S = 40.0
|
||||
|
||||
#: The engine's log of the download machinery, kept in the evidence: the external helper (`nsExternalHelperAppService.cpp`,
|
||||
#: `HelperAppService`), the URI loader that hands it the response (`URILoader`), the reputation check of a finished download
|
||||
#: (`ApplicationReputation`) and the url-classifier it asks (`UrlClassifierDbService`, `UrlClassifierStreamUpdater`).
|
||||
DOWNLOAD_LOG = ("HelperAppService:5,URILoader:5,ApplicationReputation:5,UrlClassifierDbService:5,UrlClassifierStreamUpdater:5,"
|
||||
"timestamp,sync")
|
||||
|
||||
|
||||
def _note(state, **fields):
|
||||
"""One line of a record, on the clocks of the evidence (`t` wall, `m` perf_counter)."""
|
||||
with state.lock:
|
||||
state.records.append({"t": round(time.time(), 4), "m": round(time.perf_counter(), 6), **fields})
|
||||
|
||||
|
||||
def _serve(record=None):
|
||||
"""The site of the quick download. `record` (``.lock``, ``.records``), when given, gets every request the server saw and the
|
||||
end of every answer it wrote, with times."""
|
||||
def note(handler, what, **more):
|
||||
if record is not None:
|
||||
_note(record, what=what, method=handler.command, path=handler.path, peer=handler.client_address[1],
|
||||
agent=handler.headers.get("User-Agent"), **more)
|
||||
|
||||
def _serve():
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
note(self, "request")
|
||||
if self.path.startswith("/file"):
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "application/octet-stream")
|
||||
@@ -35,11 +94,13 @@ def _serve():
|
||||
self.send_header("content-length", str(len(BODY)))
|
||||
self.end_headers()
|
||||
self.wfile.write(BODY)
|
||||
note(self, "answered", bytes=len(BODY))
|
||||
return
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "text/html")
|
||||
self.end_headers()
|
||||
self.wfile.write(b'<title>d</title><a id=dl href="/file">get</a>')
|
||||
note(self, "answered")
|
||||
|
||||
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
srv.daemon_threads = True
|
||||
@@ -56,6 +117,17 @@ def served():
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def served_and_recorded():
|
||||
"""The same site, and its record of every request (``.lock``, ``.records``), for the evidence of a slow run."""
|
||||
record = types.SimpleNamespace(lock=threading.Lock(), records=[])
|
||||
srv, url = _serve(record)
|
||||
try:
|
||||
yield url, record
|
||||
finally:
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_clicked_download_is_reported_and_saved(firefox_binary, served, tmp_path):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
@@ -86,3 +158,219 @@ def test_a_navigation_that_ends_in_a_download_is_reported(firefox_binary, served
|
||||
# not hang until the timeout.
|
||||
assert "download" in str(nav.value).lower(), str(nav.value)
|
||||
assert info.value.suggested_filename == "report.bin"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------------------------------
|
||||
# The end of a download, and the context that has no download options
|
||||
# --------------------------------------------------------------------------------------------------------------------
|
||||
#: What the held answer promises: far more than the first chunk, so the transfer cannot end by itself.
|
||||
HELD_LENGTH = 64 * 1024 * 1024
|
||||
|
||||
#: The longest the held answer waits for the test to let it go (only so that a failed test leaves no thread behind).
|
||||
HELD_GIVES_UP_AFTER = 120
|
||||
|
||||
|
||||
def _serve_held():
|
||||
"""A site with `/file` (a quick attachment) and `/slow` (an attachment whose answer stops after its first chunk
|
||||
and goes on only when `release` is set): the held transfer is what a `cancel()` interrupts, with no clock."""
|
||||
release = threading.Event()
|
||||
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
try:
|
||||
if self.path.startswith("/file"):
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "application/octet-stream")
|
||||
self.send_header("content-disposition", 'attachment; filename="report.bin"')
|
||||
self.send_header("content-length", str(len(BODY)))
|
||||
self.end_headers()
|
||||
self.wfile.write(BODY)
|
||||
elif self.path.startswith("/slow"):
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "application/octet-stream")
|
||||
self.send_header("content-disposition", 'attachment; filename="held.bin"')
|
||||
self.send_header("content-length", str(HELD_LENGTH))
|
||||
self.end_headers()
|
||||
self.wfile.write(b"x" * 65536)
|
||||
self.wfile.flush()
|
||||
release.wait(HELD_GIVES_UP_AFTER)
|
||||
else:
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "text/html")
|
||||
self.end_headers()
|
||||
self.wfile.write(b'<title>d</title><a id=dl href="/file">get</a>'
|
||||
b'<a id=slow href="/slow">slow</a>')
|
||||
except OSError:
|
||||
pass # the browser dropped the connection: that is the cancel
|
||||
|
||||
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], release
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def held_site():
|
||||
srv, url, release = _serve_held()
|
||||
try:
|
||||
yield url
|
||||
finally:
|
||||
release.set()
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
def _engine_side(context):
|
||||
"""The browser dispatcher (with the engine connection, `.conn`) and the context dispatcher of the in-process server
|
||||
that answers this context.
|
||||
|
||||
The server runs IN THIS PROCESS (as `test_injected_node_surface.py` uses it), so the test can listen to the
|
||||
engine's own events and send the one command the client API never sends: `Browser.setDownloadOptions` with no
|
||||
options, which is a context that was never given any."""
|
||||
impl = context._impl_obj
|
||||
server = impl._connection._transport._server
|
||||
dispatcher = server.object(impl._guid)
|
||||
return dispatcher.browser, dispatcher
|
||||
|
||||
|
||||
def _record(conn):
|
||||
"""Every `Browser.downloadCreated` and `Browser.downloadFinished` the engine sends, as `(method, params)`."""
|
||||
events = []
|
||||
|
||||
def listener(method, params, session):
|
||||
if method in ("Browser.downloadCreated", "Browser.downloadFinished"):
|
||||
events.append((method, dict(params or {})))
|
||||
|
||||
conn.add_listener(listener)
|
||||
return events
|
||||
|
||||
|
||||
def _of(events, method, uuid=None):
|
||||
return [p for m, p in events if m == method and (uuid is None or p.get("uuid") == uuid)]
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_canceled_download_reports_once_as_canceled(firefox_binary, held_site):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=4242, binary_path=firefox_binary, headless=True) as browser:
|
||||
context = browser.new_context(accept_downloads=True)
|
||||
page = context.new_page()
|
||||
engine, _context = _engine_side(context)
|
||||
events = _record(engine.conn)
|
||||
page.goto(held_site, timeout=30_000)
|
||||
|
||||
with page.expect_download(timeout=30_000) as info:
|
||||
page.click("#slow")
|
||||
held = info.value
|
||||
assert held.suggested_filename == "held.bin"
|
||||
held.cancel()
|
||||
assert held.failure() == "canceled"
|
||||
|
||||
# The engine announced this download once, and it must say its end once. A later duplicate of the same end
|
||||
# would follow the first one on the same stream, so a second download, run to its end, is the barrier: the
|
||||
# events are read in order, and when the second download has finished anything the first had left to say has
|
||||
# been said.
|
||||
created = _of(events, "Browser.downloadCreated")
|
||||
assert len(created) == 1, created
|
||||
held_uuid = created[0]["uuid"]
|
||||
|
||||
with page.expect_download(timeout=30_000) as info:
|
||||
page.click("#dl")
|
||||
quick = info.value
|
||||
assert quick.failure() is None
|
||||
quick_uuid = _of(events, "Browser.downloadCreated")[1]["uuid"]
|
||||
assert wait_until(lambda: _of(events, "Browser.downloadFinished", quick_uuid), 60,
|
||||
pump=lambda: page.wait_for_timeout(100)), events
|
||||
|
||||
ended = _of(events, "Browser.downloadFinished", held_uuid)
|
||||
assert len(ended) == 1, "the canceled download reported its end %d times: %r" % (len(ended), events)
|
||||
assert ended[0].get("canceled") is True, ended
|
||||
assert not ended[0].get("error"), ended
|
||||
# and the quick one, after it, ends clean: a cancel does not leave the interceptor in a state of its own
|
||||
assert len(_of(events, "Browser.downloadFinished", quick_uuid)) == 1, events
|
||||
assert not _of(events, "Browser.downloadFinished", quick_uuid)[0].get("canceled"), events
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_context_without_download_options_is_left_to_firefox(firefox_binary, served_and_recorded, tmp_path, record_property):
|
||||
"""The negative control of the interception: the same context, the same link, the same file.
|
||||
|
||||
With its options the download is taken (announced, saved in the wrapper's directory). After
|
||||
`Browser.setDownloadOptions` with no options the engine does not take it: no `downloadCreated`, no
|
||||
`downloadFinished`, no `download` event of the client, and the file is where Firefox's own preference says."""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
served, record = served_and_recorded
|
||||
where = tmp_path / "firefox"
|
||||
where.mkdir()
|
||||
prefs = {"browser.download.folderList": 2,
|
||||
"browser.download.dir": str(where),
|
||||
"browser.download.useDownloadDir": True}
|
||||
with FailureEvidence("download-left-to-firefox") as evidence:
|
||||
evidence.note_records("server-record", record)
|
||||
client = types.SimpleNamespace(lock=threading.Lock(), records=[])
|
||||
evidence.client_log = client.records
|
||||
evidence.arm(moz_log=DOWNLOAD_LOG)
|
||||
with InvisiblePlaywright(seed=4242, binary_path=firefox_binary, headless=True,
|
||||
extra_prefs=prefs) as browser:
|
||||
context = browser.new_context(accept_downloads=True)
|
||||
page = context.new_page()
|
||||
# what the client heard of every request, with times (it only listens)
|
||||
page.on("request", lambda r: _note(client, what="request", url=r.url, navigation=r.is_navigation_request()))
|
||||
page.on("response", lambda r: _note(client, what="response", url=r.url, status=r.status))
|
||||
page.on("requestfinished", lambda r: _note(client, what="requestfinished", url=r.url))
|
||||
page.on("requestfailed", lambda r: _note(client, what="requestfailed", url=r.url, failure=str(r.failure)))
|
||||
engine, ctx = _engine_side(context)
|
||||
events = _record(engine.conn)
|
||||
announced = []
|
||||
|
||||
def on_download(download):
|
||||
announced.append(download)
|
||||
_note(client, what="download", url=download.url)
|
||||
|
||||
page.on("download", on_download)
|
||||
page.goto(served, timeout=30_000)
|
||||
|
||||
# the control: with its options the download is taken
|
||||
with page.expect_download(timeout=30_000) as info:
|
||||
page.click("#dl")
|
||||
info.value.path()
|
||||
assert wait_until(lambda: _of(events, "Browser.downloadFinished"), 60,
|
||||
pump=lambda: page.wait_for_timeout(100)), events
|
||||
assert len(_of(events, "Browser.downloadCreated")) == 1, events
|
||||
assert len(_of(events, "Browser.downloadFinished")) == 1, events
|
||||
downloads_dir = engine._downloads_dir(ctx.context_id)
|
||||
saved_by_the_wrapper = sorted(os.listdir(downloads_dir))
|
||||
assert len(saved_by_the_wrapper) == 1, saved_by_the_wrapper
|
||||
assert os.listdir(str(where)) == [], "the taken download landed in Firefox's directory"
|
||||
|
||||
# the context loses its download options: Firefox's own path takes the download
|
||||
engine.conn.send("Browser.setDownloadOptions",
|
||||
{"browserContextId": ctx.context_id, "downloadOptions": None}, timeout=None)
|
||||
# The click on a download Firefox keeps plans a navigation that never completes (nothing commits: the response is a download),
|
||||
# so the click does not wait for it; the end of the test waits on the CONDITION, the file in Firefox's directory.
|
||||
_note(client, what="click", target="#dl", download_options=None)
|
||||
clicked = time.perf_counter()
|
||||
page.click("#dl", no_wait_after=True, timeout=30_000)
|
||||
landed = where / "report.bin"
|
||||
landing = watch(lambda: landed.exists() and landed.read_bytes() == BODY, bool, 120,
|
||||
pump=lambda: page.wait_for_timeout(100))
|
||||
seconds_to_the_file = time.perf_counter() - clicked
|
||||
_note(client, what="file-landed" if landing.ok else "file-not-landed", history=landing.history)
|
||||
# not a verdict: how long Firefox's own save took, from the click to the file
|
||||
record_property("seconds_until_the_file_landed", "%.1f" % seconds_to_the_file)
|
||||
assert landing.ok, os.listdir(str(where))
|
||||
|
||||
assert len(_of(events, "Browser.downloadCreated")) == 1, "the engine took a download of a context with no options"
|
||||
assert len(_of(events, "Browser.downloadFinished")) == 1, events
|
||||
assert len(announced) == 1, announced
|
||||
assert sorted(os.listdir(downloads_dir)) == saved_by_the_wrapper, "the wrapper's directory got a second file"
|
||||
# The browser is closed, so its log and its trace are whole. A save slower than any healthy run is kept to be read, not judged.
|
||||
slow = seconds_to_the_file > SLOW_SAVE_S
|
||||
record_property("evidence_kept_for_a_slow_save", str(slow))
|
||||
if slow:
|
||||
evidence.keep("Firefox's own save took %.1f s from the click to the file (more than %.0f s)"
|
||||
% (seconds_to_the_file, SLOW_SAVE_S))
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Every road by which a page reads a WebGL canvas gives it the same bytes: the element, an OffscreenCanvas, the placeholder of
|
||||
``transferControlToOffscreen`` (e2e, every OS; written on firefox-68, which the engine of the series must keep).
|
||||
|
||||
The engine applies its canvas noise (``gfx::StealthProjectPixels``, a pure function of the seed and of what the canvas holds) when a page
|
||||
reads a WebGL or WebGPU canvas, and does not touch a 2D canvas, as on retail. Until firefox-50 the noise was bolted onto five read methods
|
||||
and every other road read the real pixels: a page saw it by reading the canvas twice. The hooks that keep it one function are the page snapshot of
|
||||
``HTMLCanvasElement`` (``GetSurfaceSnapshot``, whose Mozilla body is the as-drawn reader), the snapshot of ``OffscreenCanvas``, and the snapshot of
|
||||
the display helper behind a transferred placeholder (``fingerprint/canvas/noise-projection``: dom/html/HTMLCanvasElement.cpp,
|
||||
dom/canvas/OffscreenCanvas.cpp, dom/canvas/OffscreenCanvasDisplayHelper.cpp). A page reads each of these roads with its own API and compares
|
||||
the answers.
|
||||
|
||||
Three properties, each with its control IN THE SAME TEST (the canvas noise declared off, ``zoom.stealth.canvas.substitute_pixels`` false, every
|
||||
other declaration the same: a second launch of the same page):
|
||||
|
||||
* ``test_every_reader_of_a_webgl_canvas_element_reads_the_same_bytes``: ``readPixels``, ``drawImage``, ``createImageBitmap``, the PNG of
|
||||
``toDataURL`` and of ``toBlob`` read the same bytes, which are not the bytes of the un-noised canvas (the noise is there) and differ from them
|
||||
only in the low bit of R, G and B. A 2D canvas drawn with the same triangles, translucent fills and a shadow reads as drawn through every reader,
|
||||
noised or not: its bytes are equal in the two launches.
|
||||
* ``test_an_offscreen_webgl_canvas_reads_as_its_element_does``: an ``OffscreenCanvas`` on the page's thread and one in a worker, each with a WebGL
|
||||
context, read through every reader (``drawImage`` onto a 2D canvas, ``createImageBitmap``, ``convertToBlob``, ``transferToImageBitmap``,
|
||||
``readPixels``) the bytes the element of the same scene reads.
|
||||
* ``test_a_transferred_placeholder_reads_noised_like_its_worker``: the worker draws WebGL on the offscreen canvas it was given by
|
||||
``transferControlToOffscreen``; the page reads the placeholder element (``drawImage``, ``createImageBitmap``) once the frame reached it, and reads
|
||||
what the worker reads from its own canvas.
|
||||
|
||||
The scene and the readers are in ``tests/_canvas_readers.py``. The noise seed (12345) is one no runner has, so a passing run is not the host's.
|
||||
The page ends its readers on events (a promise, a message of the worker, a frame of the page); the one wait that polls (the frame reaching the
|
||||
placeholder) ends on the placeholder holding the frame, and the deadline is the test's, not a measure of speed.
|
||||
|
||||
Kept apart from other canvas modules: each test launches two short-lived browsers one after the other (the sync API does not nest).
|
||||
Run: pytest tests/test_every_reader_of_a_webgl_canvas_agrees_e2e.py -m e2e -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
import _canvas_readers as cr
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
PAGE_JS = r"""
|
||||
async function theElement() {
|
||||
const g = document.createElement('canvas'); g.width = W; g.height = H;
|
||||
const gl = drawGL(g);
|
||||
const c = document.createElement('canvas'); c.width = W; c.height = H;
|
||||
const x = c.getContext('2d'); draw2D(x);
|
||||
return {webgl: await readersOf(g, () => readGL(gl), makeElement, false),
|
||||
flat2d: await readersOf(c, () => readCtx(x), makeElement, false)};
|
||||
}
|
||||
|
||||
const WORKER_OFFSCREEN = `
|
||||
onmessage = async () => {
|
||||
try {
|
||||
const c = new OffscreenCanvas(W, H); const gl = drawGL(c);
|
||||
postMessage({readers: await readersOf(c, () => readGL(gl), makeOffscreen, true)});
|
||||
} catch (e) { postMessage({err: String((e && e.stack) || e)}); }
|
||||
};`;
|
||||
|
||||
async function theOffscreens() {
|
||||
const g = document.createElement('canvas'); g.width = W; g.height = H;
|
||||
const gl = drawGL(g);
|
||||
const element = await readersOf(g, () => readGL(gl), makeElement, false);
|
||||
const o = new OffscreenCanvas(W, H);
|
||||
const ogl = drawGL(o);
|
||||
const main = await readersOf(o, () => readGL(ogl), makeOffscreen, true);
|
||||
const w = new Worker(URL.createObjectURL(new Blob([WORKER_LIB + WORKER_OFFSCREEN])));
|
||||
const worker = await new Promise((ok, bad) => {
|
||||
w.onmessage = e => (e.data.err ? bad(new Error(e.data.err)) : ok(e.data.readers));
|
||||
w.onerror = e => bad(new Error('worker: ' + e.message));
|
||||
w.postMessage(0);
|
||||
});
|
||||
w.terminate();
|
||||
return {element, main, worker};
|
||||
}
|
||||
|
||||
const WORKER_PLACEHOLDER = `
|
||||
onmessage = async (e) => {
|
||||
try {
|
||||
const c = e.data.canvas; const gl = drawGL(c);
|
||||
postMessage({readers: await readersOf(c, () => readGL(gl), makeOffscreen, false)});
|
||||
} catch (err) { postMessage({err: String((err && err.stack) || err)}); }
|
||||
};`;
|
||||
|
||||
async function thePlaceholder() {
|
||||
const el = document.createElement('canvas'); el.width = W; el.height = H;
|
||||
document.body.appendChild(el);
|
||||
const off = el.transferControlToOffscreen();
|
||||
const w = new Worker(URL.createObjectURL(new Blob([WORKER_LIB + WORKER_PLACEHOLDER])));
|
||||
const worker = await new Promise((ok, bad) => {
|
||||
w.onmessage = e => (e.data.err ? bad(new Error(e.data.err)) : ok(e.data.readers));
|
||||
w.onerror = e => bad(new Error('worker: ' + e.message));
|
||||
w.postMessage({canvas: off}, [off]);
|
||||
});
|
||||
// the frame the worker drew reaches the placeholder after the worker's task: the page waits on what it can read (the alpha of
|
||||
// the middle pixel, 255 in the whole scene, 0 before the frame), one frame of the page at a time
|
||||
const seen = () => pixelsOf(makeElement, x => x.drawImage(el, 0, 0));
|
||||
const middle = ((H / 2) * W + W / 2) * 4 + 3;
|
||||
while (seen()[middle] !== 255) await new Promise(r => requestAnimationFrame(r));
|
||||
const placeholder = {drawImage: b64(seen())};
|
||||
const bm = await createImageBitmap(el);
|
||||
placeholder.createImageBitmap = b64(pixelsOf(makeElement, x => x.drawImage(bm, 0, 0)));
|
||||
bm.close();
|
||||
w.terminate();
|
||||
return {placeholder, worker};
|
||||
}
|
||||
"""
|
||||
|
||||
HTML = cr.page_html(PAGE_JS)
|
||||
|
||||
|
||||
def _read(firefox_binary, noised, call):
|
||||
with cr.launched(firefox_binary, HTML, noised=noised) as page:
|
||||
return cr.run(page, call)
|
||||
|
||||
|
||||
def _the_noise_is_a_change_of_low_bits(what, noised, plain):
|
||||
"""The control: the noise is there (the reads differ), and it is only the low bit of R, G and B."""
|
||||
n = cr.differing_pixels(noised, plain)
|
||||
assert n > 0, (
|
||||
"%s: the canvas read with the noise declared on is byte for byte the canvas read with it declared off: no pixel of the scene was "
|
||||
"touched, so this test would pass on an engine that applies no noise at all" % what)
|
||||
beyond = cr.only_the_low_bit_of_rgb(noised, plain)
|
||||
assert not beyond, (
|
||||
"%s: %d pixels of the noised read differ from the plain one by more than the low bit of R, G and B (first: %r); the noise writes "
|
||||
"nothing else" % (what, len(beyond), beyond[:5]))
|
||||
return n
|
||||
|
||||
|
||||
@pytest.mark.timeout(300, method="thread")
|
||||
def test_every_reader_of_a_webgl_canvas_element_reads_the_same_bytes(firefox_binary):
|
||||
on = _read(firefox_binary, True, "theElement()")
|
||||
off = _read(firefox_binary, False, "theElement()")
|
||||
webgl_on, webgl_off = cr.decode(on["webgl"]), cr.decode(off["webgl"])
|
||||
flat_on, flat_off = cr.decode(on["flat2d"]), cr.decode(off["flat2d"])
|
||||
|
||||
cr.assert_agree("WebGL element, noise on", webgl_on)
|
||||
cr.assert_agree("WebGL element, noise declared off", webgl_off)
|
||||
_the_noise_is_a_change_of_low_bits("WebGL element", webgl_on["direct"], webgl_off["direct"])
|
||||
|
||||
# the control of the other side: a 2D canvas is not noised by any reader, with the engine on or off
|
||||
assert cr.distinct_colours(flat_off["direct"]) > 100, (
|
||||
"the 2D scene holds %d colours: too flat to be a canvas the noise would touch" % cr.distinct_colours(flat_off["direct"]))
|
||||
cr.assert_agree("2D canvas, noise on", flat_on)
|
||||
cr.assert_agree("2D canvas, noise declared off", flat_off)
|
||||
assert flat_on["direct"] == flat_off["direct"], (
|
||||
"the 2D canvas reads differently with the canvas noise on and off (%d pixels): a 2D canvas reads as drawn, as on retail"
|
||||
% cr.differing_pixels(flat_on["direct"], flat_off["direct"]))
|
||||
|
||||
|
||||
@pytest.mark.timeout(300, method="thread")
|
||||
def test_an_offscreen_webgl_canvas_reads_as_its_element_does(firefox_binary):
|
||||
on = _read(firefox_binary, True, "theOffscreens()")
|
||||
off = _read(firefox_binary, False, "theOffscreens()")
|
||||
|
||||
def every(group):
|
||||
merged = {}
|
||||
for place in ("element", "main", "worker"):
|
||||
merged.update(cr.decode(group[place], place + "/"))
|
||||
return merged
|
||||
|
||||
webgl_on, webgl_off = every(on), every(off)
|
||||
cr.assert_agree("an element, an OffscreenCanvas and an OffscreenCanvas in a worker, noise on", webgl_on, "element/direct")
|
||||
cr.assert_agree("an element, an OffscreenCanvas and an OffscreenCanvas in a worker, noise declared off", webgl_off, "element/direct")
|
||||
_the_noise_is_a_change_of_low_bits("OffscreenCanvas", webgl_on["worker/direct"], webgl_off["worker/direct"])
|
||||
|
||||
|
||||
@pytest.mark.timeout(300, method="thread")
|
||||
def test_a_transferred_placeholder_reads_noised_like_its_worker(firefox_binary):
|
||||
on = _read(firefox_binary, True, "thePlaceholder()")
|
||||
off = _read(firefox_binary, False, "thePlaceholder()")
|
||||
|
||||
def every(group):
|
||||
merged = cr.decode(group["worker"], "worker/")
|
||||
merged.update(cr.decode(group["placeholder"], "placeholder/"))
|
||||
return merged
|
||||
|
||||
webgl_on, webgl_off = every(on), every(off)
|
||||
cr.assert_agree("the placeholder and its worker, noise on", webgl_on, "worker/direct")
|
||||
cr.assert_agree("the placeholder and its worker, noise declared off", webgl_off, "worker/direct")
|
||||
_the_noise_is_a_change_of_low_bits("the placeholder", webgl_on["placeholder/drawImage"], webgl_off["placeholder/drawImage"])
|
||||
@@ -15,6 +15,7 @@ import pathlib
|
||||
|
||||
import pytest
|
||||
|
||||
from _evidence_on_failure import FailureEvidence
|
||||
from _waits import wait_until
|
||||
from fakeweb import profile_p2, sites
|
||||
|
||||
@@ -134,30 +135,35 @@ def test_the_page_that_leaves_with_beacons_reaches_networkidle_every_time_under_
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
loader = pathlib.Path(__file__).resolve().parent / "fakeweb" / "loader.py"
|
||||
ready_dir = pathlib.Path(tempfile.mkdtemp(prefix="fakeweb-loaders-"))
|
||||
ready = [ready_dir / ("loader-%d.ready" % i) for i in range(LOADERS)]
|
||||
procs = [subprocess.Popen([sys.executable, str(loader), firefox_binary, str(mark)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
for mark in ready]
|
||||
origin, _other, stop = sites.start((0, 0))
|
||||
try:
|
||||
# the loaders are up and loading when each has finished its first page and said so (a file), not after a fixed pause
|
||||
assert wait_until(lambda: all(mark.exists() for mark in ready), 180, lambda: time.sleep(0.25)), "the loaders did not start loading: %s" % [m.name for m in ready if not m.exists()]
|
||||
cells = profile_p2.run_on_candidate(_stock_client(), firefox_binary, origin, ["leaving_beacons_subframe"], 10)
|
||||
finally:
|
||||
stop()
|
||||
for proc in procs:
|
||||
proc.terminate()
|
||||
for proc in procs:
|
||||
try:
|
||||
proc.wait(timeout=60)
|
||||
except Exception:
|
||||
proc.kill()
|
||||
if not engine_reaches("firefox-68"):
|
||||
assert len(cells) == 20, "the run made %d navigations, not 20" % len(cells)
|
||||
return
|
||||
bad = ["round %d%s: %s -- in flight: %s" % (c["round"], " (canary)" if c["canary"] else "", c["err"],
|
||||
[(r["type"], r["method"], r["frame"]) for r in c.get("in_flight", [])[:3]])
|
||||
for c in cells if not c["idle"]]
|
||||
assert not bad, "%d of %d navigations did not reach networkidle under load:%s" % (
|
||||
len(bad), len(cells), "".join("\n " + line for line in bad[:6]))
|
||||
with FailureEvidence("fakeweb-leaving-beacons-under-load") as evidence:
|
||||
loader = pathlib.Path(__file__).resolve().parent / "fakeweb" / "loader.py"
|
||||
ready_dir = pathlib.Path(tempfile.mkdtemp(prefix="fakeweb-loaders-"))
|
||||
ready = [ready_dir / ("loader-%d.ready" % i) for i in range(LOADERS)]
|
||||
procs = [subprocess.Popen([sys.executable, str(loader), firefox_binary, str(mark)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
for mark in ready]
|
||||
origin, _other, stop = sites.start((0, 0))
|
||||
evidence.watch_server(stop)
|
||||
try:
|
||||
# the loaders are up and loading when each has finished its first page and said so (a file), not after a fixed pause
|
||||
assert wait_until(lambda: all(mark.exists() for mark in ready), 180, lambda: time.sleep(0.25)), "the loaders did not start loading: %s" % [m.name for m in ready if not m.exists()]
|
||||
evidence.arm()
|
||||
cells = profile_p2.run_on_candidate(_stock_client(), firefox_binary, origin, ["leaving_beacons_subframe"], 10,
|
||||
client_log=evidence.client_log)
|
||||
evidence.note_cells(cells)
|
||||
finally:
|
||||
stop()
|
||||
for proc in procs:
|
||||
proc.terminate()
|
||||
for proc in procs:
|
||||
try:
|
||||
proc.wait(timeout=60)
|
||||
except Exception:
|
||||
proc.kill()
|
||||
if not engine_reaches("firefox-68"):
|
||||
assert len(cells) == 20, "the run made %d navigations, not 20" % len(cells)
|
||||
return
|
||||
bad = ["round %d%s: %s -- in flight: %s" % (c["round"], " (canary)" if c["canary"] else "", c["err"],
|
||||
[(r["type"], r["method"], r["frame"]) for r in c.get("in_flight", [])[:3]])
|
||||
for c in cells if not c["idle"]]
|
||||
assert not bad, "%d of %d navigations did not reach networkidle under load:%s" % (
|
||||
len(bad), len(cells), "".join("\n " + line for line in bad[:6]))
|
||||
@@ -313,3 +313,105 @@ def test_webgl_readpixels_no_masking_signature(page):
|
||||
f"WebGL readPixels shows {res['spikes']} high-frequency noise spikes "
|
||||
f"(pixelscan-maskable); the stealth noise must be a smooth gamma remap."
|
||||
)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# The declared screen, and the inner size of the top level (characterisation of
|
||||
# the engine hooks fingerprint/screen-window/screen: nsScreen.cpp, nsPresContext.cpp)
|
||||
# ===========================================================================
|
||||
|
||||
#: A screen no runner has: 2731x1537, a 41 px taskbar, 30-bit colour, at scale 1.0.
|
||||
_DECLARED_SCREEN = {"screen.width": 2731, "screen.height": 1537, "screen.taskbar_px": 41,
|
||||
"screen.color_depth": 30, "screen.dpr": 1.0}
|
||||
|
||||
#: Another screen no runner has, for the control: the wrapper hands the declared screen to the browser by two roads (the prefs and
|
||||
#: the screen of the context that Juggler emulates), so a launch with the prefs at 0 still reads the pinned screen.
|
||||
_OTHER_SCREEN = {"screen.width": 2623, "screen.height": 1411, "screen.taskbar_px": 37,
|
||||
"screen.color_depth": 24, "screen.dpr": 1.0}
|
||||
|
||||
_READ_SCREEN = """() => ({width: screen.width, height: screen.height, availWidth: screen.availWidth,
|
||||
availHeight: screen.availHeight, pixelDepth: screen.pixelDepth,
|
||||
colorDepth: screen.colorDepth})"""
|
||||
|
||||
|
||||
def _read_screen(firefox_binary, pin=_DECLARED_SCREEN):
|
||||
with InvisiblePlaywright(seed=42, pin=pin, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank", timeout=30_000)
|
||||
return page.evaluate(_READ_SCREEN)
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_declared_screen_that_no_runner_has_is_what_the_page_reads(firefox_binary):
|
||||
"""The page reads the screen the core declares (nsScreen::GetRect, GetAvailRect, PixelDepth), not the host's.
|
||||
|
||||
The available height is the declared height less the declared taskbar (2731x1537, taskbar 41, depth 30 -> availWidth
|
||||
2731, availHeight 1496). The control is a launch declared with ANOTHER screen (2623x1411, taskbar 37, depth 24: the wrapper
|
||||
hands the declared screen to the browser by two roads, so the absent declaration is not a control): the page reads that one, and
|
||||
none of the first declaration's numbers.
|
||||
"""
|
||||
from _popup_geometry import in_a_thread_of_its_own
|
||||
|
||||
# The module's `page` fixture keeps a sync client open in this thread: a second browser needs a thread of its own.
|
||||
declared = in_a_thread_of_its_own(lambda: _read_screen(firefox_binary))
|
||||
assert declared == {"width": 2731, "height": 1537, "availWidth": 2731, "availHeight": 1537 - 41,
|
||||
"pixelDepth": 30, "colorDepth": 30}, "the page reads %r under a declared 2731x1537 screen" % declared
|
||||
|
||||
host = in_a_thread_of_its_own(lambda: _read_screen(firefox_binary, _OTHER_SCREEN))
|
||||
assert host == {"width": 2623, "height": 1411, "availWidth": 2623, "availHeight": 1411 - 37,
|
||||
"pixelDepth": 24, "colorDepth": 24}, "the page reads %r under another declared screen" % host
|
||||
for key in ("width", "height", "availWidth", "availHeight", "pixelDepth"):
|
||||
assert host[key] != declared[key], (
|
||||
"under another declared screen screen.%s reads %r, the first declared value: the control reads the first declaration "
|
||||
"(%r)" % (key, host[key], host))
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_the_inner_size_of_the_top_is_synced_with_the_engine_active_and_not_without(firefox_binary):
|
||||
"""A popup's iframe reads the top level's inner size (nsPresContext::UpdateInnerSizeSpoofedForRFP).
|
||||
|
||||
With the engine active the top-level inner size is synced to every process of the browsing context, so an iframe of
|
||||
another site in a popup (200x150, in its own process) answers the outer size of the POPUP: the top's inner size plus the
|
||||
declared frame, 2 * border wide and popup UI + border high, and not the size of its own 200x150. The popup itself
|
||||
answers the same. The control is the same page in a launch declared with a SECOND frame that no runner has (border 6, popup
|
||||
UI 53): the iframe then answers the top's inner size plus THAT frame, and none of the first declaration's. The engine off is
|
||||
not the control: the declared frame is the one of a retail Windows window at scale 1.0, so a Windows runner's own popup
|
||||
reads it with the engine off too (measured: 516x480 for a 500x400 popup) and the test could not fail there.
|
||||
"""
|
||||
from _popup_geometry import (OTHER_BORDER, OTHER_FRAME, OTHER_POPUP_UI, frame_extra, frame_of_the_declaration,
|
||||
in_a_thread_of_its_own, read_popup)
|
||||
|
||||
frame = frame_of_the_declaration()
|
||||
extra = frame_extra(frame.border, frame.popup_ui)
|
||||
other_extra = frame_extra(OTHER_BORDER, OTHER_POPUP_UI)
|
||||
assert other_extra != extra
|
||||
|
||||
def synced_to(wanted):
|
||||
def synced(reading):
|
||||
top = reading["popup"]
|
||||
return (reading["frame"]["ow"], reading["frame"]["oh"]) == (top["iw"] + wanted[0], top["ih"] + wanted[1])
|
||||
return synced
|
||||
|
||||
# The module's `page` fixture keeps a sync client open in this thread: a second browser needs a thread of its own.
|
||||
on = in_a_thread_of_its_own(lambda: read_popup(firefox_binary, iframe=True, ready=synced_to(extra)))
|
||||
top, inner = on["popup"], on["frame"]
|
||||
assert (top["ow"], top["oh"]) == (top["iw"] + extra[0], top["ih"] + extra[1]), (
|
||||
"the popup reads outer %dx%d for inner %dx%d, the declared frame adds %r" % (top["ow"], top["oh"], top["iw"],
|
||||
top["ih"], extra))
|
||||
assert (inner["ow"], inner["oh"]) == (top["iw"] + extra[0], top["ih"] + extra[1]), (
|
||||
"the iframe of the popup reads outer %dx%d, the top level's inner %dx%d plus the declared frame %r is %dx%d (the "
|
||||
"iframe's own inner size is %dx%d)" % (inner["ow"], inner["oh"], top["iw"], top["ih"], extra,
|
||||
top["iw"] + extra[0], top["ih"] + extra[1], inner["iw"], inner["ih"]))
|
||||
assert (inner["iw"], inner["ih"]) != (top["iw"], top["ih"]), "the iframe has the size of the popup: the read proves nothing"
|
||||
|
||||
other = in_a_thread_of_its_own(lambda: read_popup(firefox_binary, extra_prefs=OTHER_FRAME, iframe=True, ready=synced_to(other_extra)))
|
||||
other_top, other_inner = other["popup"], other["frame"]
|
||||
assert (other_inner["ow"], other_inner["oh"]) == (other_top["iw"] + other_extra[0], other_top["ih"] + other_extra[1]), (
|
||||
"declared with another frame the iframe of a popup reads outer %dx%d, the top's inner %dx%d plus the second declared frame %r is %dx%d: %r"
|
||||
% (other_inner["ow"], other_inner["oh"], other_top["iw"], other_top["ih"], other_extra,
|
||||
other_top["iw"] + other_extra[0], other_top["ih"] + other_extra[1], other))
|
||||
assert (other_top["ow"], other_top["oh"]) == (other_top["iw"] + other_extra[0], other_top["ih"] + other_extra[1]), (
|
||||
"declared with another frame the popup reads outer %dx%d for inner %dx%d, the second declared frame adds %r"
|
||||
% (other_top["ow"], other_top["oh"], other_top["iw"], other_top["ih"], other_extra))
|
||||
assert (other_inner["ow"] - other_top["iw"], other_inner["oh"] - other_top["ih"]) != (inner["ow"] - top["iw"], inner["oh"] - top["ih"]), (
|
||||
"the iframe reads the same frame under two declarations: it does not follow the declaration: %r vs %r" % (other, on))
|
||||
@@ -10,21 +10,24 @@ site changes its process.
|
||||
navigation and `go_back()` restore the page with its frame of another site, and the frame answers `evaluate`.
|
||||
The outcome asserted is what stock Firefox does (see the docstrings).
|
||||
* Processes. A context whose page had frames of other sites leaves no content process behind once it is closed:
|
||||
the count of web content processes under the engine, read after each of several such contexts, stays within the
|
||||
pool of spare processes retail Firefox keeps (see the test).
|
||||
judged by identity (the processes that host the frames' sites, by name on Linux and by the engine's logged remote
|
||||
type on Windows), not by a count that also holds the pool of spare processes (see the test).
|
||||
|
||||
The first test proves the frame is in another process, so the file cannot turn into a same-process suite.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import pytest
|
||||
|
||||
from _fission_frames import Sites, assert_other_process, launch, new_page, wait_for, wait_frame
|
||||
from _waits import spare_processes, watch
|
||||
from _processes import LOG_ENV, NAMED_BY_SITE, remote_types, site_processes_below
|
||||
from _waits import watch
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
@@ -138,98 +141,79 @@ def test_a_top_level_navigation_and_back_restore_the_page_with_its_frame_usable(
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _content_processes(engine_dir):
|
||||
"""The pids of the engine's web content processes (`-contentproc ... tab`) below this test."""
|
||||
import psutil
|
||||
|
||||
found = 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
|
||||
command = child.cmdline()
|
||||
except psutil.Error:
|
||||
continue
|
||||
if "-contentproc" in command and command[-1] == "tab":
|
||||
found.add(child.pid)
|
||||
return found
|
||||
|
||||
|
||||
def _settled(engine_dir, seconds=2.0, limit=25.0):
|
||||
"""The set of content processes once it has not changed for ``seconds``."""
|
||||
end = time.monotonic() + limit
|
||||
last, since = _content_processes(engine_dir), time.monotonic()
|
||||
while time.monotonic() < end:
|
||||
time.sleep(0.25)
|
||||
now = _content_processes(engine_dir)
|
||||
if now != last:
|
||||
last, since = now, time.monotonic()
|
||||
elif time.monotonic() - since >= seconds:
|
||||
break
|
||||
return last
|
||||
|
||||
|
||||
CONTEXTS = 5
|
||||
#: How long a count of processes may take to reach what it must be (a process starts or ends in well under a
|
||||
#: second; this is the only clock the verdict has).
|
||||
#: How long a process may take to appear or to end (one starts or ends in well under a second; this is the only clock
|
||||
#: the verdict has).
|
||||
DEADLINE = 25.0
|
||||
|
||||
|
||||
def test_a_closed_context_with_frames_of_other_sites_leaves_no_content_process(firefox_binary, sites):
|
||||
def _site(url):
|
||||
"""The site of a url: scheme and host, never the port."""
|
||||
parts = urlsplit(url)
|
||||
return "%s://%s" % (parts.scheme, parts.hostname)
|
||||
|
||||
|
||||
def test_a_closed_context_with_frames_of_other_sites_leaves_no_content_process(
|
||||
firefox_binary, sites, monkeypatch, tmp_path):
|
||||
"""Five contexts in a row, each with a page whose frames are on B and (nested) on C. The processes the frames
|
||||
took are gone once the context is closed.
|
||||
|
||||
What retail Firefox does, and so what is allowed: with Fission on it keeps a pool of preallocated content
|
||||
processes, `dom.ipc.processPrelaunch.fission.number` of them (3 on desktop, 1 on a machine of 4 GB or less),
|
||||
refilled one at a time after a page takes one (`_waits.spare_processes` has the source). So between two looks
|
||||
the number of content processes moves by up to that pool and no more: after the first context is closed
|
||||
(``counts[0]``) every later count is at most ``counts[0]`` plus the pool, and a frame process that is never
|
||||
released grows the count by at least one per context, so it passes the bound within the five (a pool that is
|
||||
emptier at the last look than at the first could hide it: the bound is as wide as the pool, no wider). While a context
|
||||
is open the count rises above ``counts[0]``: the frames' processes are on top of a refilled pool.
|
||||
The verdict is told by identity, not by a count: the number of content processes under the engine also holds the
|
||||
preallocated pool and whatever the browser starts for itself (the New Tab page's own Mozilla site), which move
|
||||
with the load of the machine and are not what the test is about. A process that hosts a site says so: on Linux
|
||||
its name is the site (`fission.processSiteNames`, test-only), on Windows the remote type the engine logs for
|
||||
every process it creates (`webIsolated=<site>^userContextId=N`, `_processes.py`). So:
|
||||
|
||||
Each count is a WAIT for that bound (up to 25 s), not a look after a fixed pause; the message gives the counts
|
||||
over time of every context."""
|
||||
import psutil
|
||||
* while a context is open the frames of B and C each have a content process of their own (the processes that host
|
||||
B and C exist: a lookup that finds nothing cannot pass);
|
||||
* once the context is closed no process that hosts B or C is left below this test (B and C are only ever framed,
|
||||
by a context that is closed, so nothing may host them).
|
||||
|
||||
On Linux a name keeps 15 characters, so `http://127.0.0.2` is told from nothing but the start `http://127.0.0.` (the
|
||||
site of A, which closes with the context as well): the lookup of C is then no narrower than that of A and B's is the
|
||||
exact one.
|
||||
|
||||
Each look is a WAIT for that condition (up to 25 s), not a look after a fixed pause; the message gives what was
|
||||
seen over time for every context."""
|
||||
sites.route("B", "/leak-b", "<!doctype html><title>b</title><iframe src='%s'></iframe>" % sites.url("C", "/h3"))
|
||||
sites.route("A", "/leak", "<!doctype html><title>leak</title><iframe id='b' src='%s'></iframe>"
|
||||
% sites.url("B", "/leak-b"))
|
||||
engine_dir = str(Path(firefox_binary).resolve().parent)
|
||||
spare = spare_processes(psutil.virtual_memory().total)
|
||||
framed = {"B": _site(sites.url("B")), "C": _site(sites.url("C"))}
|
||||
base = tmp_path / "process-types"
|
||||
if sys.platform == "win32":
|
||||
# Windows names no process: the engine's log tells the remote type of each one it creates
|
||||
monkeypatch.setenv("MOZ_LOG", LOG_ENV["MOZ_LOG"])
|
||||
monkeypatch.setenv("MOZ_LOG_FILE", str(base))
|
||||
|
||||
def number():
|
||||
return len(_content_processes(engine_dir))
|
||||
def hosting():
|
||||
"""`{name of the site: pids}` of the live processes below this test that host a framed site."""
|
||||
return {name: site_processes_below(os.getpid(), site, engine_dir, types=lambda: remote_types(base))
|
||||
for name, site in framed.items()}
|
||||
|
||||
def both_hosted(found):
|
||||
return all(found.values())
|
||||
|
||||
def none_hosted(found):
|
||||
return not any(found.values())
|
||||
|
||||
def pause():
|
||||
time.sleep(0.25)
|
||||
|
||||
with launch(firefox_binary) as browser:
|
||||
counts, during, trail = [], [], []
|
||||
with launch(firefox_binary, extra_prefs=NAMED_BY_SITE) as browser:
|
||||
trail = []
|
||||
for n in range(CONTEXTS):
|
||||
context, page = new_page(browser)
|
||||
page.goto(sites.url("A", "/leak"), wait_until="load")
|
||||
wait_frame(page, sites.url("C"), "/h3")
|
||||
if not counts:
|
||||
during.append(len(_settled(engine_dir)))
|
||||
trail.append("context %d open: %d" % (n, during[-1]))
|
||||
else:
|
||||
opened = watch(number, lambda count: count > counts[0], DEADLINE, pause)
|
||||
during.append(opened.history[-1][1])
|
||||
trail.append("context %d open, waiting for more than %d: %s" % (n, counts[0], opened.render()))
|
||||
assert opened.ok, (
|
||||
"the frames of other sites took no process of their own: %r while open, %r after; %s" % (
|
||||
during, counts, " | ".join(trail)))
|
||||
opened = watch(hosting, both_hosted, DEADLINE, pause)
|
||||
trail.append("context %d open: %s" % (n, opened.render()))
|
||||
assert opened.ok, (
|
||||
"the frames of B and C took no process of their own (a site with no process of its own shows an empty "
|
||||
"set): %s" % " | ".join(trail))
|
||||
context.close()
|
||||
if not counts:
|
||||
counts.append(len(_settled(engine_dir)))
|
||||
trail.append("context %d closed: %d (the reference)" % (n, counts[0]))
|
||||
else:
|
||||
closed = watch(number, lambda count: count <= counts[0] + spare, DEADLINE, pause)
|
||||
counts.append(closed.history[-1][1])
|
||||
trail.append("context %d closed, waiting for at most %d (%d + a pool of %d): %s" % (
|
||||
n, counts[0] + spare, counts[0], spare, closed.render()))
|
||||
assert closed.ok, (
|
||||
"web content processes after each closed context: %r (open: %r); more than the %d the first "
|
||||
"left plus the pool of %d the engine keeps: %s" % (counts, during, counts[0], spare,
|
||||
" | ".join(trail)))
|
||||
closed = watch(hosting, none_hosted, DEADLINE, pause)
|
||||
trail.append("context %d closed: %s" % (n, closed.render()))
|
||||
assert closed.ok, (
|
||||
"a process that hosts the site of a frame of the closed context is still there: %s"
|
||||
% " | ".join(trail))
|
||||
@@ -94,8 +94,7 @@ def test_the_crash_of_an_iframe_s_process_leaves_the_tab(firefox_binary, engine_
|
||||
port = server.server_address[1]
|
||||
marionette = None
|
||||
try:
|
||||
marionette_port = webfont_probe.marionette_port()
|
||||
prefs = dict(FISSION, **{"marionette.port": marionette_port})
|
||||
prefs = dict(FISSION, **{"marionette.port": 0})
|
||||
with InvisiblePlaywright(binary_path=firefox_binary, headless=True, humanize=False,
|
||||
extra_args=["-marionette"], extra_prefs=prefs) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
@@ -107,7 +106,7 @@ def test_the_crash_of_an_iframe_s_process_leaves_the_tab(firefox_binary, engine_
|
||||
# the iframe's document is not read, nor its address: what the client can see of a frame in another
|
||||
# process is what the rest of Fission builds
|
||||
|
||||
marionette = webfont_probe._Marionette(marionette_port)
|
||||
marionette = webfont_probe._Marionette(webfont_probe.marionette_active_port())
|
||||
marionette.call("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {}}})
|
||||
marionette.call("Marionette:SetContext", {"value": "chrome"})
|
||||
# the tabs of the engine whose document has a child, each [top pid, child pid]: a count of TABS read from the
|
||||
|
||||
@@ -27,13 +27,16 @@ ask for the processes of one site and never compare two counts. Counting was wro
|
||||
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.
|
||||
for the frame's site; a same-site one leaves the page's site in its single process. Windows names no process, so there
|
||||
the same two questions are answered by the engine's own log, which says the remote type of every process it creates
|
||||
(`webIsolated=http://a.test^userContextId=N` for the process of a site): the browser is started with `LOG_ENV` and a file
|
||||
base, and a process counts when it is alive in the tree and its logged type is that of the site (tests/_processes.py).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
@@ -42,7 +45,7 @@ from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
import pytest
|
||||
|
||||
from _processes import NAMED_BY_SITE, site_processes_below
|
||||
from _processes import LOG_ENV, NAMED_BY_SITE, remote_types, site_processes_below
|
||||
from _servers import LocalServer
|
||||
|
||||
SITE_A = "http://a.test"
|
||||
@@ -135,13 +138,26 @@ def engine_dir(firefox_binary):
|
||||
return str(Path(firefox_binary).resolve().parent)
|
||||
|
||||
|
||||
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
|
||||
def engine_log(monkeypatch, tmp_path):
|
||||
"""Windows only: the engine logs the remote type of each process it creates, to files that start with the returned
|
||||
base (Linux names the process by its site instead, and the environment stays as it is there)."""
|
||||
base = tmp_path / "process-types"
|
||||
if sys.platform == "win32":
|
||||
monkeypatch.setenv("MOZ_LOG", LOG_ENV["MOZ_LOG"])
|
||||
monkeypatch.setenv("MOZ_LOG_FILE", str(base))
|
||||
return base
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def browser(firefox_binary):
|
||||
def processes_of(engine_dir, engine_log):
|
||||
"""`processes_of(site)`: the pids of the engine's processes below this test that host `site` (tests/_processes.py:
|
||||
by the name of the process on Linux, by the type the engine logged on Windows)."""
|
||||
return lambda site: site_processes_below(os.getpid(), site, engine_dir, types=lambda: remote_types(engine_log))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def browser(firefox_binary, engine_log):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, humanize=False, headless=True,
|
||||
@@ -195,7 +211,7 @@ def frame_with_origin(page, origin):
|
||||
# ── 1, 2: the bench itself ─────────────────────────────────────────────────────
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_cross_site_iframe_gets_its_own_process(page, cross_site_loop, engine_dir):
|
||||
def test_cross_site_iframe_gets_its_own_process(page, cross_site_loop, processes_of):
|
||||
"""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
|
||||
@@ -204,20 +220,20 @@ def test_cross_site_iframe_gets_its_own_process(page, cross_site_loop, engine_di
|
||||
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"])
|
||||
here = processes_of(SITE_A, engine_dir)
|
||||
here = processes_of(SITE_A)
|
||||
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"
|
||||
assert not processes_of(SITE_B), "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"]))
|
||||
framed = processes_of(SITE_B, engine_dir)
|
||||
framed = processes_of(SITE_B)
|
||||
assert len(framed) >= 1, "no process for the site of the frame (b.test)"
|
||||
tops = processes_of(SITE_A, engine_dir)
|
||||
tops = processes_of(SITE_A)
|
||||
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):
|
||||
def test_same_site_other_port_stays_in_process(page, cross_site_loop, processes_of):
|
||||
"""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
|
||||
@@ -233,15 +249,15 @@ def test_same_site_other_port_stays_in_process(page, cross_site_loop, engine_dir
|
||||
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 = processes_of(SITE_A, engine_dir)
|
||||
before = processes_of(SITE_A)
|
||||
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)
|
||||
after = processes_of(SITE_A)
|
||||
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"
|
||||
assert not processes_of(SITE_B), "a process for b.test, which no page here belongs to"
|
||||
|
||||
|
||||
# ── 3 .. 10: what the product does not do yet ──────────────────────────────────
|
||||
|
||||
@@ -14,12 +14,24 @@ still reads ``hasFocus()`` true and has recorded no ``blur``. Then A opens a sec
|
||||
|
||||
The control, in the same test: ``extra_prefs={"zoom.stealth.focus.ignore_os_deactivation": False}``, the same steps up to B taking the display, and A's page
|
||||
reads ``hasFocus()`` false. It runs first, so a runner where the second session does not take the focus is red there and not a green that means nothing.
|
||||
Both sessions are headed on one display (the Linux e2e runs under ``xvfb-run``; Windows has the interactive desktop of the runner).
|
||||
|
||||
Both sessions are headed on one display, and the test owns it: on Linux a private Xvfb started for the test (the ``xvfb-run`` display that the four workers
|
||||
share is never used, so no neighbour's headed window moves the focus); on Windows the interactive desktop of the runner, which only this test touches because
|
||||
it is ``wall_clock`` (the e2e run gives such a test the machine alone, after the parallel tests).
|
||||
|
||||
What the verdict waits for is the operating system, not a pause: before anything is judged the test reads from the OS that the focus really is where the step
|
||||
says (the X input focus on Linux, ``GetForegroundWindow`` on Windows: first the first session's window, then the second session's window). "No blur" is judged
|
||||
after that and after a round trip to the first page's own process (two painted frames), which handles everything the parent sent it before: the deactivation
|
||||
that would cause a blur has been delivered by then, so a late one cannot give a false green.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from _os_focus import ForegroundWindow, XFocus, a_display_of_its_own
|
||||
from _window_sessions import in_a_thread_of_its_own, launch, wait_for_condition
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
@@ -33,28 +45,76 @@ RECORD = """() => {
|
||||
}"""
|
||||
HAS_FOCUS = "() => document.hasFocus()"
|
||||
EVENTS = "() => window.__events"
|
||||
TWO_FRAMES = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))"
|
||||
#: A round trip to the page's own process: it has handled what the parent sent it before this ran (the deactivation, if the parent had one to send).
|
||||
ROUND_TRIP = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))"
|
||||
#: Names the page, so that on Windows its top-level window is found by its title.
|
||||
NAME = "(name) => { document.title = name; return document.title; }"
|
||||
FIRST_TITLE, SECOND_TITLE = "focus-first-session", "focus-second-session"
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def the_os_focus(monkeypatch):
|
||||
"""What tells where the OS has put the focus, on a display this test owns (see the module docstring)."""
|
||||
if sys.platform == "win32":
|
||||
yield ForegroundWindow()
|
||||
return
|
||||
with a_display_of_its_own(monkeypatch) as display:
|
||||
reader = XFocus(display)
|
||||
try:
|
||||
yield reader
|
||||
finally:
|
||||
reader.close()
|
||||
|
||||
|
||||
def takes_the_focus(b):
|
||||
"""Runs in the second session's own thread: opens a window and waits until its page has the focus."""
|
||||
"""Runs in the second session's own thread: opens a window, names it, and waits until its page has the focus."""
|
||||
taker = b.new_page()
|
||||
taker.goto("about:blank")
|
||||
taker.evaluate(NAME, SECOND_TITLE)
|
||||
wait_for_condition(taker, lambda: taker.evaluate(HAS_FOCUS), lambda focused: focused is True, "the second session's page never took the focus")
|
||||
|
||||
|
||||
def another_session_takes_the_display(firefox_binary, keeps, with_own_page=False):
|
||||
def os_focus_is_on_the_first_window(first, os_focus):
|
||||
"""Waits until the OS says the first session's window holds the focus; gives what holds it."""
|
||||
if sys.platform == "win32":
|
||||
window = wait_for_condition(first, lambda: os_focus.window_titled(FIRST_TITLE), lambda hwnd: hwnd is not None,
|
||||
"no single visible top-level window is titled %r" % FIRST_TITLE).history[-1][1]
|
||||
wait_for_condition(first, lambda: os_focus.ask_for_the_foreground(window), lambda holder: holder == window,
|
||||
"the first session's window never became the foreground window")
|
||||
return window
|
||||
seen = wait_for_condition(first, os_focus.holder, os_focus.is_a_window, "no window of the display ever held the X input focus")
|
||||
return seen.history[-1][1]
|
||||
|
||||
|
||||
def os_focus_is_on_the_second_window(first, os_focus, before):
|
||||
"""Waits until the OS says a window other than the first one holds the focus (on Windows: the second session's window, by its title)."""
|
||||
if sys.platform == "win32":
|
||||
window = wait_for_condition(first, lambda: os_focus.window_titled(SECOND_TITLE), lambda hwnd: hwnd is not None,
|
||||
"no single visible top-level window is titled %r" % SECOND_TITLE).history[-1][1]
|
||||
assert window != before, "the second session's window is the first one's"
|
||||
wait_for_condition(first, lambda: os_focus.ask_for_the_foreground(window), lambda holder: holder == window,
|
||||
"the second session's window never became the foreground window")
|
||||
return
|
||||
wait_for_condition(first, os_focus.holder, lambda holder: os_focus.is_a_window(holder) and holder != before,
|
||||
"the X input focus never left the first session's window %r" % before)
|
||||
|
||||
|
||||
def another_session_takes_the_display(firefox_binary, os_focus, keeps, with_own_page=False):
|
||||
"""What A's page reads once B's window has the focus, and (``with_own_page``) once A has opened a page of its own."""
|
||||
extra = None if keeps else {PREF: False}
|
||||
with launch(firefox_binary, extra_prefs=extra) as a:
|
||||
first = a.new_page()
|
||||
first.goto("about:blank")
|
||||
first.evaluate(NAME, FIRST_TITLE)
|
||||
first.evaluate(RECORD)
|
||||
wait_for_condition(first, lambda: first.evaluate(HAS_FOCUS), lambda focused: focused is True, "the page never had the focus of its own window")
|
||||
before = os_focus_is_on_the_first_window(first, os_focus)
|
||||
with in_a_thread_of_its_own(firefox_binary) as b:
|
||||
b.run(takes_the_focus)
|
||||
os_focus_is_on_the_second_window(first, os_focus, before)
|
||||
if keeps:
|
||||
first.evaluate(TWO_FRAMES)
|
||||
# the OS has moved the focus; one round trip to the page's process orders the read after the deactivation that would have followed
|
||||
first.evaluate(ROUND_TRIP)
|
||||
else:
|
||||
wait_for_condition(first, lambda: first.evaluate(HAS_FOCUS), lambda focused: focused is False,
|
||||
"the first page still has the focus although another session's window took it")
|
||||
@@ -69,11 +129,13 @@ def another_session_takes_the_display(firefox_binary, keeps, with_own_page=False
|
||||
return seen
|
||||
|
||||
|
||||
def test_a_page_keeps_focus_when_another_session_takes_the_display(firefox_binary):
|
||||
control = another_session_takes_the_display(firefox_binary, keeps=False)
|
||||
assert control["has_focus"] is False, "control: without the pref the first page still has the focus: %r" % control
|
||||
@pytest.mark.wall_clock
|
||||
def test_a_page_keeps_focus_when_another_session_takes_the_display(firefox_binary, monkeypatch):
|
||||
with the_os_focus(monkeypatch) as os_focus:
|
||||
control = another_session_takes_the_display(firefox_binary, os_focus, keeps=False)
|
||||
assert control["has_focus"] is False, "control: without the pref the first page still has the focus: %r" % control
|
||||
|
||||
kept = another_session_takes_the_display(firefox_binary, keeps=True, with_own_page=True)
|
||||
kept = another_session_takes_the_display(firefox_binary, os_focus, keeps=True, with_own_page=True)
|
||||
assert kept["has_focus"] is True, "with the pref the first page lost the focus to another session: %r" % kept
|
||||
assert "blur" not in kept["events"], "with the pref the first page recorded a blur when another session took the display: %r" % kept
|
||||
assert kept["has_focus"] != control["has_focus"]
|
||||
|
||||
@@ -9,14 +9,19 @@ The hook: ``nsWindow::MakeFullScreen`` in ``widget/gtk/nsWindow.cpp`` of the ser
|
||||
``fingerprint/screen-window/geometry``, whose function ``StealthMakeFullScreenWithoutWM`` in ``widget/gtk/StealthFullscreenGtk.cpp`` it calls). On Windows
|
||||
the same reading is held by ``nsIWidget::InfallibleMakeFullScreen`` and the Win32 rules of the same folder (``geometry``).
|
||||
|
||||
The screen is pinned to 1600x900, which no runner has (the Linux display is 1920x1080, the Windows runner's monitor 1024x768 or 1920x1080), so a window that
|
||||
filled the host would read differently from the declared one.
|
||||
The screen is pinned to 1600x900, which no Linux runner has (the display is 1920x1080); on Windows the test reads the runner's monitor first (the primary one, in
|
||||
device pixels, and in CSS pixels at the usual scale factors) and declares the first of 1600x900, 1366x768 and 1280x720 that is none of them, so a window that
|
||||
filled the host always reads differently from the declared one, whatever monitor the runner has.
|
||||
|
||||
The control, in the same test: the engine inactive (``zoom.stealth.fpp.hw_seed`` 0: the engine is on when it is above 0) keeps Mozilla's behaviour. On
|
||||
Linux without a window manager that is the refusal (``display-mode: fullscreen`` false and the window not the declared screen); on Windows, which always has a
|
||||
window manager and a widget that decides fullscreen, it is the host's monitor, not the declared screen. The same click, the same pinned screen; only the engine
|
||||
differs.
|
||||
|
||||
What the verdict waits for is the condition itself, not a count of equal looks: with the engine on, until the page reads the declared size AND ``display-mode:
|
||||
fullscreen`` AND a ``fullscreenElement`` (a red names the last geometry seen); with the engine off, until ``fullscreenchange`` (or ``fullscreenerror``) was heard
|
||||
and, where the window really changes size (Windows), the ``resize`` the change causes was heard too, then one round trip to the page's own process.
|
||||
|
||||
The click is real input (``page.mouse``): ``requestFullscreen`` needs a user gesture. A page reads it from ``innerWidth``, ``innerHeight``,
|
||||
``matchMedia('(display-mode: fullscreen)')`` and ``document.fullscreenElement``.
|
||||
"""
|
||||
@@ -28,20 +33,37 @@ import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from _os_focus import host_monitor_size
|
||||
from _servers import LocalServer
|
||||
from _window_sessions import launch, wait_for_condition
|
||||
from _waits import watch
|
||||
from _window_sessions import DEADLINE_S, launch
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
#: The device pixel ratio is pinned too: the core declares 1.5 for some personas (Windows runner), and a page reads the screen and the window in
|
||||
#: CSS pixels, declared / dpr (1067x600), which is not what this test is about.
|
||||
DECLARED = {"screen.width": 1600, "screen.height": 900, "screen.dpr": 1.0}
|
||||
CANDIDATES = ((1600, 900), (1366, 768), (1280, 720))
|
||||
#: The scale factors at which a monitor of the host reads, in CSS pixels, smaller than it is.
|
||||
SCALES = (1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0)
|
||||
|
||||
|
||||
def declared_screen():
|
||||
"""The declared screen: 1600x900 unless the host's monitor (Windows) is that size, at any usual scale; then the first candidate that it is not."""
|
||||
monitor = host_monitor_size()
|
||||
if monitor is None:
|
||||
return CANDIDATES[0]
|
||||
taken = {(round(monitor[0] / scale), round(monitor[1] / scale)) for scale in SCALES}
|
||||
for width, height in CANDIDATES:
|
||||
if not any(abs(width - w) <= 1 and abs(height - h) <= 1 for w, h in taken):
|
||||
return width, height
|
||||
raise AssertionError("every candidate declared screen %r is a size of the host's monitor %r" % (CANDIDATES, monitor))
|
||||
|
||||
PAGE = (b"<!doctype html><html><head><meta charset=utf-8><title>fullscreen</title></head><body style=\"margin:0\">"
|
||||
b"<button id=go style=\"position:fixed;left:20px;top:20px;width:160px;height:40px;margin:0\">fullscreen</button>"
|
||||
b"<script>"
|
||||
b"window.__how = null; window.__error = null;"
|
||||
b"for (const t of ['fullscreenchange', 'fullscreenerror']) document.addEventListener(t, () => { window.__how = window.__how || t; });"
|
||||
b"window.__how = null; window.__error = null; window.__order = [];"
|
||||
b"for (const t of ['fullscreenchange', 'fullscreenerror']) document.addEventListener(t, () => { window.__how = window.__how || t; window.__order.push(t); });"
|
||||
b"window.addEventListener('resize', () => window.__order.push('resize'));"
|
||||
b"document.getElementById('go').addEventListener('click', () => {"
|
||||
b" document.documentElement.requestFullscreen().catch(e => { window.__error = String(e); });"
|
||||
b"});"
|
||||
@@ -54,6 +76,9 @@ GEOMETRY = """() => ({
|
||||
fullscreenElement: document.fullscreenElement !== null,
|
||||
})"""
|
||||
HOW = "() => [window.__how, window.__error]"
|
||||
ORDER = "() => window.__order"
|
||||
#: A round trip to the page's own process: it has handled what the parent sent it before this ran.
|
||||
ROUND_TRIP = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -77,35 +102,47 @@ def page_url():
|
||||
server.shutdown()
|
||||
|
||||
|
||||
def fullscreen_geometry(firefox_binary, page_url, engine_on):
|
||||
"""The page's geometry once the window has held still after a click on a button that asks for fullscreen."""
|
||||
def fullscreen_geometry(firefox_binary, page_url, engine_on, declared):
|
||||
"""The page's geometry once the fullscreen request has been answered: the condition with the engine on, the events with it off (see the module docstring)."""
|
||||
extra = None if engine_on else {"zoom.stealth.fpp.hw_seed": 0}
|
||||
with launch(firefox_binary, extra_prefs=extra, pin=DECLARED, headless=True) as browser:
|
||||
pin = {"screen.width": declared[0], "screen.height": declared[1], "screen.dpr": 1.0}
|
||||
with launch(firefox_binary, extra_prefs=extra, pin=pin, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(page_url)
|
||||
page.mouse.move(90, 40)
|
||||
page.mouse.click(100, 40)
|
||||
wait_for_condition(page, lambda: page.evaluate(HOW), lambda how: how[0] is not None,
|
||||
"the click on a button that asks for fullscreen was followed by neither fullscreenchange nor fullscreenerror")
|
||||
seen = []
|
||||
|
||||
def held_still(geometry):
|
||||
seen.append(geometry)
|
||||
return len(seen) >= 4 and all(g == geometry for g in seen[-4:])
|
||||
def pump():
|
||||
page.wait_for_timeout(100)
|
||||
|
||||
# a transition resizes in steps: the geometry counts once it has been the same for four looks in a row
|
||||
wait_for_condition(page, lambda: page.evaluate(GEOMETRY), held_still, "the window never held still after the fullscreen request")
|
||||
return dict(seen[-1], how=page.evaluate(HOW))
|
||||
answered = watch(lambda: page.evaluate(HOW), lambda how: how[0] is not None, DEADLINE_S, pump)
|
||||
assert answered.ok, ("the click on a button that asks for fullscreen was followed by neither fullscreenchange nor fullscreenerror; seen: %s"
|
||||
% answered.render())
|
||||
if engine_on:
|
||||
def is_the_declared_fullscreen(geometry):
|
||||
return ((geometry["innerWidth"], geometry["innerHeight"]) == declared
|
||||
and geometry["displayModeFullscreen"] is True and geometry["fullscreenElement"] is True)
|
||||
|
||||
# the assertions of the test judge the last geometry seen: a window that never gets there is red there, with what it read
|
||||
watch(lambda: page.evaluate(GEOMETRY), is_the_declared_fullscreen, DEADLINE_S, pump)
|
||||
else:
|
||||
if sys.platform == "win32":
|
||||
# the window really changes size: the change is over once the resize that goes with fullscreenchange was heard (a window that was
|
||||
# already the size of the screen has none to hear: the geometry read below is then what judges)
|
||||
watch(lambda: page.evaluate(ORDER), lambda order: "fullscreenchange" in order and "resize" in order, DEADLINE_S, pump)
|
||||
page.evaluate(ROUND_TRIP)
|
||||
return dict(page.evaluate(GEOMETRY), how=page.evaluate(HOW))
|
||||
|
||||
|
||||
def test_fullscreen_without_a_window_manager_is_the_declared_screen(firefox_binary, page_url):
|
||||
on = fullscreen_geometry(firefox_binary, page_url, engine_on=True)
|
||||
assert on["screen"] == [1600, 900], "the pinned screen is not what the page reads: %r" % on
|
||||
assert (on["innerWidth"], on["innerHeight"]) == (1600, 900), "with the engine on the fullscreen window is not the declared screen: %r" % on
|
||||
declared = declared_screen()
|
||||
on = fullscreen_geometry(firefox_binary, page_url, engine_on=True, declared=declared)
|
||||
assert on["screen"] == list(declared), "the pinned screen is not what the page reads: %r" % on
|
||||
assert (on["innerWidth"], on["innerHeight"]) == declared, "with the engine on the fullscreen window is not the declared screen: %r" % on
|
||||
assert on["displayModeFullscreen"] is True and on["fullscreenElement"] is True, "with the engine on the page does not read fullscreen: %r" % on
|
||||
|
||||
off = fullscreen_geometry(firefox_binary, page_url, engine_on=False)
|
||||
assert (off["innerWidth"], off["innerHeight"]) != (1600, 900), "control: the engine inactive also gives the declared screen: %r" % off
|
||||
off = fullscreen_geometry(firefox_binary, page_url, engine_on=False, declared=declared)
|
||||
assert (off["innerWidth"], off["innerHeight"]) != declared, "control: the engine inactive also gives the declared screen: %r" % off
|
||||
if sys.platform != "win32":
|
||||
# no window manager: Mozilla's refusal, the DOM fullscreen without the window
|
||||
assert off["displayModeFullscreen"] is False, "control: without a window manager and without the engine the window went fullscreen: %r" % off
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
"""The engine never asks the host where it is: a page that asks for a position starts no location process and loads no location module.
|
||||
|
||||
What it fixes, in the published engine (firefox-68), for the hooks of `fingerprint/geolocation/no-host-provider`
|
||||
(`GeolocationService::Init`, `GeolocationSystem::*`, `PermissionObserver`, in `dom/geolocation` and `netwerk/...`): the position a page reads comes only
|
||||
from the declaration (the standard `geolocation` option of the context, which the core fills for every session). The engine does not ask the
|
||||
operating system for a position, for a Wi-Fi scan or for the privacy switch of the location. Retail Firefox on Windows does: the first position
|
||||
request makes the parent start a utility process of the kind `WINDOWS_UTILS` (`-sandboxingKind 3`, which runs the WinRT location provider) and load
|
||||
`geolocation.dll`, `locationframeworkps.dll`, `wlanapi.dll` and `capabilityaccessmanagerclient.dll`. A page cannot see a process, but it sees what
|
||||
that road gives (the position of the host, a delay, an error), and a host that has a location service answers differently from one that has not.
|
||||
|
||||
What the test does. One session (seed 42, no proxy), a context that declares a position no runner has (12.345, -45.678) and grants the permission, a
|
||||
page served from 127.0.0.1 (a secure context). The page runs `permissions.query`, `getCurrentPosition` and `watchPosition`. Then the test lists the
|
||||
engine processes below the test process (the executable is in the engine's folder) and reads, for each one it may read, the files mapped into it
|
||||
(`psutil` `memory_maps`: the DLLs on Windows, the shared objects on Linux) and its command line.
|
||||
|
||||
What it asserts:
|
||||
* Windows: none of `geolocation.dll`, `locationframeworkps.dll`, `wlanapi.dll`, `capabilityaccessmanagerclient.dll` is mapped in any engine process, and
|
||||
no process has `-sandboxingKind 3`;
|
||||
* Linux (the engine has no `WINDOWS_UTILS` there, so the Windows modules cannot exist; the form that holds on Linux is "no host location library"): none
|
||||
of the files mapped in an engine process is a location library of the host (`libgeoclue`, `libgeocode`, `libportal`), and no utility process
|
||||
is of a kind other than the generic one (`-sandboxingKind` 0) or the inference one;
|
||||
* the control, on both systems: the page was told the DECLARED position by `getCurrentPosition` and by `watchPosition` (so the calls ran to the end,
|
||||
and the answer came from the declaration, not from the host), `permissions.query` says `granted`, and the reading of the mapped files is not blind
|
||||
(the parent was readable and has `xul.dll` / `libxul.so` mapped). A test that listed nothing would pass without this.
|
||||
|
||||
The retail Firefox of the same window, which loads these modules, is not in this file (a test never runs another browser in the gate): the
|
||||
control is the declared answer plus the reading that sees a module that is certainly there.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
WINDOWS = sys.platform == "win32"
|
||||
|
||||
#: What retail Firefox on Windows maps once a page asks for a position (the WinRT provider and its capability checks).
|
||||
WINDOWS_LOCATION_MODULES = ("geolocation.dll", "locationframeworkps.dll", "wlanapi.dll", "capabilityaccessmanagerclient.dll")
|
||||
#: The Linux forms of the same idea: the location services of the desktop (GeoClue) and the portal.
|
||||
LINUX_LOCATION_LIBRARIES = ("libgeoclue", "libgeocode", "libportal")
|
||||
#: `SandboxingKind::WINDOWS_UTILS` of the engine's `ipc/glue/UtilityProcessSandboxing.h`: GENERIC_UTILITY 0, UTILITY_AUDIO_DECODING_WMF 1,
|
||||
#: MF_MEDIA_ENGINE_CDM 2, WINDOWS_UTILS 3.
|
||||
WINDOWS_UTILS_KIND = "3"
|
||||
#: Linux: GENERIC_UTILITY 0, HW_INFERENCE 1 (the only kinds the Linux engine has).
|
||||
LINUX_UTILITY_KINDS = ("0", "1")
|
||||
|
||||
#: A position no runner has: the page must read exactly this.
|
||||
POSITION = {"latitude": 12.345, "longitude": -45.678, "accuracy": 25}
|
||||
|
||||
PAGE = b"<!doctype html><html><head><meta charset=utf-8><title>geolocation</title></head><body><p>where</p></body></html>"
|
||||
|
||||
READ = """async () => {
|
||||
const position = (p) => ({lat: p.coords.latitude, lon: p.coords.longitude});
|
||||
const failure = (e) => ({error: e.code, message: e.message});
|
||||
const out = {secure: isSecureContext};
|
||||
out.permission = (await navigator.permissions.query({name: 'geolocation'})).state;
|
||||
out.current = await new Promise(resolve => {
|
||||
navigator.geolocation.getCurrentPosition(p => resolve(position(p)), e => resolve(failure(e)), {timeout: 30000});
|
||||
});
|
||||
out.watched = await new Promise(resolve => {
|
||||
const id = navigator.geolocation.watchPosition(
|
||||
p => { navigator.geolocation.clearWatch(id); resolve(position(p)); },
|
||||
e => { navigator.geolocation.clearWatch(id); resolve(failure(e)); },
|
||||
{timeout: 30000});
|
||||
});
|
||||
return out;
|
||||
}"""
|
||||
|
||||
|
||||
def _a_page_server():
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
timeout = 5
|
||||
|
||||
def do_GET(self):
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(PAGE)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(PAGE)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
server.daemon_threads = True
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server, "http://127.0.0.1:%d/" % server.server_address[1]
|
||||
|
||||
|
||||
def _engine_processes(binary):
|
||||
"""The processes below this one whose executable is in the engine's folder (the tree of THIS test, not the machine)."""
|
||||
import psutil
|
||||
|
||||
folder = os.path.normcase(os.path.dirname(os.path.realpath(binary)))
|
||||
found = []
|
||||
for proc in psutil.Process().children(recursive=True):
|
||||
try:
|
||||
exe = os.path.normcase(os.path.realpath(proc.exe()))
|
||||
except psutil.Error:
|
||||
continue
|
||||
if exe.startswith(folder):
|
||||
found.append(proc)
|
||||
return found
|
||||
|
||||
|
||||
def _describe(proc):
|
||||
"""(kind, command line, mapped file names in lower case or None when the process cannot be read)."""
|
||||
import psutil
|
||||
|
||||
try:
|
||||
cmd = proc.cmdline()
|
||||
except psutil.Error:
|
||||
cmd = []
|
||||
kind = cmd[-1] if "-contentproc" in cmd else "parent"
|
||||
try:
|
||||
mapped = {os.path.basename(m.path).lower() for m in proc.memory_maps(grouped=True)}
|
||||
except (psutil.Error, OSError):
|
||||
mapped = None
|
||||
return kind, cmd, mapped
|
||||
|
||||
|
||||
def _sandboxing_kind(cmd):
|
||||
return cmd[cmd.index("-sandboxingKind") + 1] if "-sandboxingKind" in cmd and cmd.index("-sandboxingKind") + 1 < len(cmd) else None
|
||||
|
||||
|
||||
def test_no_host_location_module_loads_and_no_windows_utils_process_starts(firefox_binary):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
server, url = _a_page_server()
|
||||
try:
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, humanize=False,
|
||||
locale="en-US", timezone="America/New_York") as browser:
|
||||
context = browser.new_context(geolocation=POSITION, permissions=["geolocation"])
|
||||
page = context.new_page()
|
||||
page.goto(url, wait_until="load", timeout=60_000)
|
||||
answer = page.evaluate(READ)
|
||||
described = [_describe(proc) for proc in _engine_processes(firefox_binary)]
|
||||
context.close()
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
# The control: the calls ran to the end and the answer is the declaration.
|
||||
declared = {"lat": POSITION["latitude"], "lon": POSITION["longitude"]}
|
||||
assert answer["secure"] is True and answer["permission"] == "granted", answer
|
||||
assert answer["current"] == declared, "getCurrentPosition did not answer the declared position: %r" % (answer,)
|
||||
assert answer["watched"] == declared, "watchPosition did not answer the declared position: %r" % (answer,)
|
||||
|
||||
# The reading is not blind: the parent was readable and has the engine's own library mapped.
|
||||
parents = [(cmd, mapped) for kind, cmd, mapped in described if kind == "parent"]
|
||||
assert parents, "no engine parent process below the test: %r" % ([(k, m is not None) for k, _c, m in described],)
|
||||
engine_library = "xul.dll" if WINDOWS else "libxul.so"
|
||||
readable_parent = [mapped for _cmd, mapped in parents if mapped is not None]
|
||||
assert readable_parent and any(engine_library in mapped for mapped in readable_parent), (
|
||||
"the mapped files of the parent cannot be read, or %s is not among them: the check below would pass with an empty list (%r)"
|
||||
% (engine_library, [sorted(m)[:8] if m else m for _c, m in parents]))
|
||||
|
||||
found = []
|
||||
kinds = []
|
||||
for kind, cmd, mapped in described:
|
||||
sandboxing = _sandboxing_kind(cmd)
|
||||
if sandboxing is not None:
|
||||
kinds.append((kind, sandboxing))
|
||||
for name in mapped or ():
|
||||
if WINDOWS and name in WINDOWS_LOCATION_MODULES:
|
||||
found.append((kind, name))
|
||||
if not WINDOWS and any(name.startswith(prefix) or prefix in name for prefix in LINUX_LOCATION_LIBRARIES):
|
||||
found.append((kind, name))
|
||||
assert found == [], "a process of the engine mapped a host location module: %s" % (found,)
|
||||
if WINDOWS:
|
||||
assert not [k for k in kinds if k[1] == WINDOWS_UTILS_KIND], "a utility process of the kind WINDOWS_UTILS was started: %s" % (kinds,)
|
||||
else:
|
||||
assert not [k for k in kinds if k[1] not in LINUX_UTILITY_KINDS], "a utility process of an unexpected kind was started: %s" % (kinds,)
|
||||
@@ -0,0 +1,108 @@
|
||||
"""`navigator.maxTouchPoints`, `navigator.hardwareConcurrency` and `navigator.storage.estimate().quota` are the values the session declares.
|
||||
|
||||
What it fixes, in the published engine (firefox-68), one test per hook:
|
||||
|
||||
* `fingerprint/hardware/profile`, `Navigator::MaxTouchPoints` (`dom/base/Navigator.cpp`): while the engine is active
|
||||
(`zoom.stealth.fpp.hw_seed` > 0) a page's `navigator.maxTouchPoints` is `zoom.stealth.max_touch_points`; the core derives it from the
|
||||
persona (0 for every persona today: a desktop) and a pin (`hardware.max_touch_points`) changes it.
|
||||
* `fingerprint/hardware/profile` and `fingerprint/hardware/concurrency`, `Navigator::HardwareConcurrency` (`dom/base/Navigator.cpp`) and
|
||||
`WorkerNavigator::HardwareConcurrency` (`dom/workers/WorkerNavigator.cpp`): `zoom.stealth.hw_concurrency` when it is > 0, in the page, in a
|
||||
worker and in an iframe, so the three agree. The core declares the count of the persona; the host's count is the runner's CPUs.
|
||||
* `fingerprint/hardware/storage-quota`, `EstimateOp::GetResponse` (`dom/quota/OriginOperations.cpp`): `zoom.stealth.storage.quota_mb` MiB when
|
||||
it is > 0, otherwise the quota Mozilla computed from the disk of the host.
|
||||
|
||||
A page reads all three with no permission (the storage estimate needs a secure context: the page is served from 127.0.0.1).
|
||||
The values declared here (5 touch points, 7 cores, 123 MiB) are ones no runner has.
|
||||
|
||||
Negative controls, in each test: touch points with no pin (the persona's own value, 0) and with the engine off (`hw_seed` 0, the host's
|
||||
answer, which is not 5); cores and quota with the engine off (`hw_seed` 0, stock Firefox: the engine refuses a launch that is active with a declaration pref cleared),
|
||||
which are not 7 and not 123 MiB.
|
||||
The prefs are set through `extra_prefs` (the overlay the core applies last), the touch points through the pin the wrapper exposes.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
HW_SEED = "zoom.stealth.fpp.hw_seed"
|
||||
CORES = "zoom.stealth.hw_concurrency"
|
||||
QUOTA_MB = "zoom.stealth.storage.quota_mb"
|
||||
PAGE = "/from-network"
|
||||
|
||||
TOUCH = "() => navigator.maxTouchPoints"
|
||||
|
||||
CORE_COUNTS = """async () => {
|
||||
const code = 'self.onmessage = () => self.postMessage(self.navigator.hardwareConcurrency);';
|
||||
const worker = new Worker(URL.createObjectURL(new Blob([code], {type: 'application/javascript'})));
|
||||
const inWorker = await new Promise((resolve, reject) => {
|
||||
worker.onmessage = (e) => resolve(e.data);
|
||||
worker.onerror = (e) => reject(new Error(e.message));
|
||||
worker.postMessage(0);
|
||||
});
|
||||
worker.terminate();
|
||||
const frame = document.createElement('iframe');
|
||||
document.body.appendChild(frame);
|
||||
const inFrame = frame.contentWindow.navigator.hardwareConcurrency;
|
||||
frame.remove();
|
||||
return {main: navigator.hardwareConcurrency, worker: inWorker, iframe: inFrame};
|
||||
}"""
|
||||
|
||||
QUOTA = """async () => {
|
||||
try {
|
||||
return {secure: isSecureContext, quota: (await navigator.storage.estimate()).quota};
|
||||
} catch (e) {
|
||||
return {error: String(e)};
|
||||
}
|
||||
}"""
|
||||
|
||||
|
||||
def read(binary, url, expression, extra_prefs=None, pin=None):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
options = {}
|
||||
if pin:
|
||||
options["pin"] = pin
|
||||
with InvisiblePlaywright(seed=42, binary_path=binary, headless=True, locale="en-US",
|
||||
timezone="America/New_York", extra_prefs=extra_prefs, **options) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(url, timeout=60_000)
|
||||
return page.evaluate(expression)
|
||||
|
||||
|
||||
def test_max_touch_points_is_the_pinned_count_while_the_engine_is_active(firefox_binary, fixture_server):
|
||||
url = fixture_server + PAGE
|
||||
pinned = read(firefox_binary, url, TOUCH, pin={"hardware.max_touch_points": 5})
|
||||
assert pinned == 5
|
||||
|
||||
# Control 1: no pin, the persona's own count (a desktop: 0).
|
||||
unpinned = read(firefox_binary, url, TOUCH)
|
||||
assert unpinned == 0
|
||||
assert unpinned != pinned
|
||||
|
||||
# Control 2: the same pin with the engine off (hw_seed 0): the page reads what the host answers, not the declaration.
|
||||
engine_off = read(firefox_binary, url, TOUCH, extra_prefs={HW_SEED: 0}, pin={"hardware.max_touch_points": 5})
|
||||
assert engine_off != 5, engine_off
|
||||
|
||||
|
||||
def test_hardware_concurrency_is_the_declared_count_in_the_page_the_worker_and_the_iframe(firefox_binary, fixture_server):
|
||||
url = fixture_server + PAGE
|
||||
declared = read(firefox_binary, url, CORE_COUNTS, extra_prefs={CORES: 7})
|
||||
assert declared == {"main": 7, "worker": 7, "iframe": 7}, declared
|
||||
|
||||
# Control: the engine off (hw_seed 0), the three read the host's count (the same one, and not 7).
|
||||
host = read(firefox_binary, url, CORE_COUNTS, extra_prefs={HW_SEED: 0})
|
||||
assert host["main"] != 7, host
|
||||
assert host["worker"] == host["main"], host
|
||||
assert host["iframe"] == host["main"], host
|
||||
|
||||
|
||||
def test_the_storage_quota_is_the_declared_megabytes(firefox_binary, fixture_server):
|
||||
url = fixture_server + PAGE
|
||||
declared = read(firefox_binary, url, QUOTA, extra_prefs={QUOTA_MB: 123})
|
||||
assert declared == {"secure": True, "quota": 123 * 1024 * 1024}, declared
|
||||
|
||||
# Control: the engine off (hw_seed 0), the quota Mozilla computed from the host's disk.
|
||||
host = read(firefox_binary, url, QUOTA, extra_prefs={HW_SEED: 0})
|
||||
assert host.get("secure") is True, host
|
||||
assert host.get("quota") != 123 * 1024 * 1024, host
|
||||
@@ -0,0 +1,259 @@
|
||||
"""An IPv6 literal a page asks for is judged by the declared network, and a destination behind a SOCKS proxy is left to the proxy.
|
||||
|
||||
What this fixes in place (characterisation of the published engine firefox-68; the engine hook is `nsSocketTransport::InitiateSocket` in
|
||||
`netwerk/base/nsSocketTransport2.cpp`, the decision is `StealthConnect` / `StealthConnectError` in `netwerk/base/StealthIPv6Literal.cpp`, series folder
|
||||
`network/ipv6-literal`):
|
||||
|
||||
* The session declares its host network in `STEALTHFOX_WEBRTC_NETWORK` (`v6=0`: no IPv6). A hostname then never resolves to AAAA, but a LITERAL
|
||||
(`http://[2001:db8::1]/`) is handed to the socket by Firefox without any lookup, and the route table of the machine under the browser would decide.
|
||||
The engine decides instead: a direct connection to a routable IPv6 literal fails before `connect()` is called, the way a Windows machine that has the
|
||||
IPv6 stack and no IPv6 route fails it, and nothing is sent. The client reads it as `NS_ERROR_CONNECTION_REFUSED` (a failed `fetch` is a `TypeError`,
|
||||
and `requestfailed` carries that text). A page reads this: whether `fetch("http://[<global IPv6>]/")` fails at once or hangs, and with which error, is
|
||||
the first thing that tells a machine with an IPv6 route from one without.
|
||||
* An IPv4-mapped literal (`::ffff:127.0.0.1`) is refused on every system and whatever the declaration says: Windows refuses `connect()` to a mapped
|
||||
address on a socket that is IPv6-only (Firefox's are), and a dual-stack Linux socket would connect over IPv4. The listener below never sees it.
|
||||
* A destination behind a SOCKS proxy is never judged: the proxy reaches it, not this host. The same literal that is refused with no proxy reaches the
|
||||
proxy as a CONNECT whose destination is that address and port, as an IPv6 address (SOCKS5 address type 4), never as a name. How many times the
|
||||
browser tries it (Mozilla retries a connection that did not answer at once) is Mozilla's code and is not fixed here: every CONNECT of the
|
||||
navigation to the documentation destination has that shape, and there is at least one.
|
||||
|
||||
Not clocks: "refused by the engine" and "timed out" are told apart by the error (`TypeError` with the failure text `NS_ERROR_CONNECTION_REFUSED`, against a
|
||||
`TimeoutError` of the 30 s deadline of the fetch), and by the listener having heard nothing; no duration is read anywhere.
|
||||
|
||||
Negative controls, in the same test:
|
||||
|
||||
* the listener is real: the same address by its IPv4 literal (`127.0.0.1`) reaches it, once, in the launches where the mapped literal does not;
|
||||
* the mapped literal is refused with IPv6 declared on as well as off (a rule of its own: the declaration decides the other literals, not this one);
|
||||
* behind the proxy the documentation-prefix literal that is refused direct IS carried: an engine that judged it behind SOCKS (or that always passed
|
||||
`kDirect`) would make the proxy record no CONNECT, and the fetch would fail; and an engine that handed the proxy the literal in another shape (a
|
||||
name, an IPv4 address) fails the shape assertion.
|
||||
|
||||
What this test cannot tell, by design: with IPv6 declared on, a global IPv6 literal goes to the OS, whose answer depends on the machine (a runner with no
|
||||
IPv6 route answers `ENETUNREACH`, the same `NS_ERROR_CONNECTION_REFUSED` as the engine's), so the documentation-prefix fetch is judged only in the
|
||||
declared-off launch and behind the proxy. The port is 80: Firefox bans port 9 (discard) before any connect, so a fetch to it never reaches the gate.
|
||||
|
||||
Hermetic: a local listener, a local SOCKS5 gateway of `tests/_socks_servers.py` that maps the documentation address to the listener and forwards
|
||||
NOTHING else: the browser's own background traffic also arrives at the gateway, and every CONNECT that is not the one carried to the listener is refused
|
||||
(reply 2) and recorded. Every gateway of that module is hermetic the same way (it carries only the lab's, see its docstring); this one is narrower still:
|
||||
the lab for it is the listener alone. Every request, refused or carried, is recorded with its time since the launch, its SOCKS5 address type, its destination
|
||||
as received and its port. The refused list is written, always, when the gateway is closed, under `$RUNNER_TEMP/invpw-evidence/` (the folder the e2e jobs
|
||||
upload), so that a reader sees what the browser asked for besides the literal.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socketserver
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from _servers import LocalServer
|
||||
from _socks_servers import EXIT, Gateway
|
||||
from _udp_line import egress_by_proxy, measure_servers
|
||||
from _waits import wait_until
|
||||
from test_declared_host_network_e2e import DUAL, NETWORK_ENV, V4_ONLY
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
#: A global-unicast-looking address that no host routes (RFC 3849 documentation prefix): the gate answers for it, whatever the machine has.
|
||||
DOCUMENTATION = "2001:db8::1"
|
||||
DOCUMENTATION_HTTP = 80
|
||||
#: What a failed connect of the engine is called by the browser (NSPR's PR_NETWORK_UNREACHABLE_ERROR and PR_ADDRESS_NOT_AVAILABLE_ERROR both end here).
|
||||
REFUSED = "NS_ERROR_CONNECTION_REFUSED"
|
||||
#: SOCKS5 address type of an IPv6 address (RFC 1928); 1 is IPv4, 3 a domain name.
|
||||
ATYP_IPV6 = 4
|
||||
#: The deadline of a fetch that must END (refused, or carried): far beyond a healthy run; what the page reads on a timeout is a `TimeoutError`, never a verdict.
|
||||
FETCH_SECONDS = 30
|
||||
|
||||
_FETCH_JS = """async (url) => {
|
||||
try {
|
||||
const response = await fetch(url, {mode: 'no-cors', cache: 'no-store', signal: AbortSignal.timeout(%d)});
|
||||
return {ok: true, type: response.type};
|
||||
} catch (e) {
|
||||
return {ok: false, name: e.name, message: String(e.message)};
|
||||
}
|
||||
}""" % (FETCH_SECONDS * 1000)
|
||||
|
||||
|
||||
class _Listener:
|
||||
"""A local HTTP-ish listener that remembers every connection it accepted and answers each with a tiny 200."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.connections: list = []
|
||||
outer = self
|
||||
|
||||
class Handler(socketserver.BaseRequestHandler):
|
||||
def handle(self) -> None:
|
||||
outer.connections.append(self.client_address)
|
||||
self.request.settimeout(FETCH_SECONDS)
|
||||
try:
|
||||
self.request.recv(65536)
|
||||
self.request.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
self.server = LocalServer(("127.0.0.1", 0), Handler)
|
||||
self.port: int = self.server.server_address[1]
|
||||
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
||||
|
||||
def __enter__(self) -> "_Listener":
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.server.shutdown()
|
||||
self.server.server_close()
|
||||
|
||||
|
||||
class _GatewayToALocalListener(Gateway):
|
||||
"""The SOCKS5 gateway of the tests (UDP refused) that carries the documentation address to a local listener and forwards nothing else: the destination
|
||||
it is asked for is what it records in ``connects`` (with its SOCKS5 address type in ``addresses``), what the listener hears is what it carried, and
|
||||
every CONNECT that is not carried to the listener is refused (the base gateway refuses what is not the lab's; here the lab is the listener alone) and
|
||||
recorded in ``refused``."""
|
||||
|
||||
evidence_name = "ipv6-literal-refused-connects"
|
||||
|
||||
def __init__(self, carried: dict) -> None:
|
||||
self._carried = dict(carried)
|
||||
#: Every address of a request the gateway read, as (host, port, address type), in order.
|
||||
self.addresses: list = []
|
||||
#: Every request, as a dict, for the evidence file: ``t`` (seconds, monotonic, since ``launch_started``), ``atyp`` (SOCKS5 address type: 1 IPv4,
|
||||
#: 3 domain name, 4 IPv6), ``destination`` (as received: the NAME when the type is 3), ``port``, ``outcome``.
|
||||
self.records: list = []
|
||||
self._launch_t0 = time.monotonic()
|
||||
self._current = threading.local()
|
||||
super().__init__(udp="refuse", tcp_exit=EXIT, udp_exit=EXIT)
|
||||
|
||||
@property
|
||||
def refused(self) -> list:
|
||||
"""Every CONNECT that was refused, as (destination as received, port), in order."""
|
||||
return self.guard.refused("tcp")
|
||||
|
||||
def launch_started(self) -> None:
|
||||
"""Call just before the launch of the browser behind this gateway: the origin of the times of ``records``."""
|
||||
self._launch_t0 = time.monotonic()
|
||||
|
||||
def _read_address(self, c):
|
||||
host, port = super()._read_address(c)
|
||||
atyp = self._local.atyp
|
||||
self.addresses.append((host, port, atyp))
|
||||
record = {"t": round(time.monotonic() - self._launch_t0, 3), "atyp": atyp, "destination": host, "port": port,
|
||||
"outcome": "answered by the lab (or not a CONNECT)"}
|
||||
self.records.append(record)
|
||||
self._current.record = record
|
||||
return host, port
|
||||
|
||||
def _target(self, host: str, port: int):
|
||||
return self._carried.get((host, port), (host, port))
|
||||
|
||||
def _admits(self, host, port, atyp, protocol, target=None):
|
||||
if (target or (host, port)) not in self._carried.values():
|
||||
self.guard.refuse(host, port, atyp, protocol)
|
||||
self._current.record["outcome"] = "refused"
|
||||
return False
|
||||
self._current.record["outcome"] = "carried to the listener of the lab"
|
||||
return super()._admits(host, port, atyp, protocol, target)
|
||||
|
||||
def _evidence(self) -> dict:
|
||||
"""The refusals are written by the base gateway at the close, with every request of the launch, so that a reader sees what the browser asked for."""
|
||||
return {"requests": self.records}
|
||||
|
||||
def documentation_connects(self) -> list:
|
||||
"""Every request of the navigation to the documentation destination, in whatever shape it arrived: the host is told by its digits."""
|
||||
return [(host, port, atyp) for host, port, atyp in self.addresses if "2001:db8" in host.lower()]
|
||||
|
||||
|
||||
def _launch(firefox_binary, gateway=None):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
kw = {"seed": 42, "binary_path": firefox_binary, "headless": True, "timezone": "America/New_York"}
|
||||
if gateway is not None:
|
||||
kw.update(proxy=gateway.proxy, udp_stun_servers=measure_servers(gateway))
|
||||
return InvisiblePlaywright(**kw)
|
||||
|
||||
|
||||
def _try(page, failures, url, needle):
|
||||
"""One fetch of ``url`` from the page: what the page read, and the failure texts the client reported for the request whose URL holds ``needle``."""
|
||||
result = page.evaluate(_FETCH_JS, url)
|
||||
if not result["ok"]:
|
||||
wait_until(lambda: [text for seen, text in failures if needle in seen], FETCH_SECONDS, lambda: page.wait_for_timeout(50))
|
||||
return result, [text for seen, text in failures if needle in seen]
|
||||
|
||||
|
||||
def _page_of(browser):
|
||||
page = browser.new_context().new_page()
|
||||
failures: list = []
|
||||
page.on("requestfailed", lambda request: failures.append((request.url, request.failure)))
|
||||
page.goto("about:blank")
|
||||
return page, failures
|
||||
|
||||
|
||||
def _direct_launch(firefox_binary, monkeypatch, declaration, listener, with_documentation_prefix):
|
||||
"""One launch with no proxy and ``declaration``: the IPv4 literal of the listener (control), the mapped literal of the same listener, and, when
|
||||
asked, the documentation-prefix literal. Returns what was read and the connections the listener heard after each step."""
|
||||
monkeypatch.setenv(NETWORK_ENV, declaration)
|
||||
seen = {}
|
||||
with _launch(firefox_binary) as browser:
|
||||
page, failures = _page_of(browser)
|
||||
before = len(listener.connections)
|
||||
seen["control"] = _try(page, failures, "http://127.0.0.1:%d/" % listener.port, "127.0.0.1")
|
||||
wait_until(lambda: len(listener.connections) > before, FETCH_SECONDS, lambda: page.wait_for_timeout(50))
|
||||
seen["after_control"] = len(listener.connections) - before
|
||||
seen["mapped"] = _try(page, failures, "http://[::ffff:127.0.0.1]:%d/" % listener.port, "[::ffff:")
|
||||
seen["after_mapped"] = len(listener.connections) - before
|
||||
if with_documentation_prefix:
|
||||
seen["documentation"] = _try(page, failures, "http://[%s]:%d/" % (DOCUMENTATION, DOCUMENTATION_HTTP), "[%s]" % DOCUMENTATION)
|
||||
return seen
|
||||
|
||||
|
||||
def test_a_direct_ipv6_literal_is_refused_and_one_behind_socks_is_left_to_the_proxy(firefox_binary, monkeypatch):
|
||||
from invisible_core import _geo
|
||||
|
||||
with _Listener() as direct, _Listener() as behind:
|
||||
off = _direct_launch(firefox_binary, monkeypatch, V4_ONLY, direct, with_documentation_prefix=True)
|
||||
on = _direct_launch(firefox_binary, monkeypatch, DUAL, direct, with_documentation_prefix=False)
|
||||
|
||||
# Behind a SOCKS5 gateway, IPv6 declared off as in the first launch: the documentation-prefix literal is the proxy's to reach.
|
||||
gateway = _GatewayToALocalListener({(DOCUMENTATION, DOCUMENTATION_HTTP): ("127.0.0.1", behind.port)})
|
||||
try:
|
||||
monkeypatch.setattr(_geo, "discover_egress_ip", egress_by_proxy(gateway))
|
||||
monkeypatch.setenv(NETWORK_ENV, V4_ONLY)
|
||||
gateway.launch_started()
|
||||
with _launch(firefox_binary, gateway) as browser:
|
||||
page, failures = _page_of(browser)
|
||||
proxied = _try(page, failures, "http://[%s]:%d/" % (DOCUMENTATION, DOCUMENTATION_HTTP), "[%s]" % DOCUMENTATION)
|
||||
wait_until(lambda: behind.connections, FETCH_SECONDS, lambda: page.wait_for_timeout(50))
|
||||
documentation = gateway.documentation_connects()
|
||||
finally:
|
||||
gateway.close() # writes what it refused and every request, under $RUNNER_TEMP/invpw-evidence/
|
||||
|
||||
# The listener is real: its IPv4 literal reaches it, once per launch.
|
||||
for name, seen in (("declared off", off), ("declared on", on)):
|
||||
control, _failed = seen["control"]
|
||||
assert control["ok"], "%s: the IPv4 literal of the local listener was not reached: %s" % (name, seen)
|
||||
assert seen["after_control"] == 1, "%s: the listener heard %d connections for one fetch of its IPv4 literal: %s" % (name, seen["after_control"], seen)
|
||||
|
||||
# An IPv4-mapped literal is refused by the engine, declared off or on, and the listener hears nothing for it.
|
||||
for name, seen in (("declared off", off), ("declared on", on)):
|
||||
result, failed = seen["mapped"]
|
||||
assert result["ok"] is False and result["name"] == "TypeError", (
|
||||
"%s: the fetch of the mapped literal did not fail as a refused connection (a TimeoutError would be a connect that was attempted): %s" % (name, seen))
|
||||
assert failed == [REFUSED], "%s: the client reported %r for the mapped literal, not the engine's refusal: %s" % (name, failed, seen)
|
||||
assert seen["after_mapped"] == seen["after_control"], "%s: the listener heard a connection through the mapped literal: %s" % (name, seen)
|
||||
|
||||
# With IPv6 declared off, a direct documentation-prefix literal is refused by the engine: the same failure as a machine with no IPv6 route.
|
||||
result, failed = off["documentation"]
|
||||
assert result["ok"] is False and result["name"] == "TypeError", (
|
||||
"declared off: the direct fetch of %s did not fail as a refused connection (a TimeoutError means a connect was attempted): %s" % (DOCUMENTATION, off))
|
||||
assert failed == [REFUSED], "declared off: the client reported %r for the direct documentation-prefix literal: %s" % (failed, off)
|
||||
|
||||
# The same literal behind the SOCKS5 gateway is carried: every CONNECT of the navigation to the documentation destination is the IPv6 literal and port,
|
||||
# as an IPv6 address (how many the browser makes is Mozilla's), and the listener behind it answered.
|
||||
assert proxied[0] == {"ok": True, "type": "opaque"}, (
|
||||
"the fetch of %s behind the SOCKS5 gateway was not carried (it is refused with no proxy): %s; failures %s; gateway requests %s" % (
|
||||
DOCUMENTATION, proxied[0], proxied[1], gateway.addresses))
|
||||
assert documentation, "the gateway was asked for no CONNECT to %s:%d: %s" % (DOCUMENTATION, DOCUMENTATION_HTTP, gateway.addresses)
|
||||
assert set(documentation) == {(DOCUMENTATION, DOCUMENTATION_HTTP, ATYP_IPV6)}, (
|
||||
"every CONNECT to the documentation destination should carry the IPv6 literal %s port %d as an IPv6 address (type %d): %s" % (
|
||||
DOCUMENTATION, DOCUMENTATION_HTTP, ATYP_IPV6, documentation))
|
||||
assert (DOCUMENTATION, DOCUMENTATION_HTTP) not in gateway.refused, "the gateway refused the destination of the lab: %s" % gateway.refused
|
||||
assert len(behind.connections) >= 1, "the listener behind the gateway heard nothing"
|
||||
@@ -0,0 +1,103 @@
|
||||
"""``-moz-element()`` paints a WebGL canvas as it was drawn, not as a page reads it (e2e, every OS; written on firefox-68, which the engine of the series must keep).
|
||||
|
||||
The engine's canvas noise belongs to a PAGE's reads of a WebGL canvas (``readPixels``, ``toDataURL``, ``drawImage``...). The browser's own readers
|
||||
that SHOW a canvas must not carry it: ``-moz-element`` (``nsLayoutUtils::SurfaceFromElement`` and ``nsImageRenderer::PrepareImage``), the drag image
|
||||
and the taskbar preview read the snapshot AS DRAWN (``HTMLCanvasElement::GetSurfaceSnapshotAsDrawn``, flag ``kStealthSfeAsDrawn``;
|
||||
``fingerprint/canvas/as-drawn``). A real Firefox paints the canvas the page drew, and a screenshot of the page is the page's own pixels. If the
|
||||
painter read the noised snapshot, a page could draw a canvas, paint it with ``-moz-element`` and see through a screenshot that the two differ. The
|
||||
drag image and the taskbar preview are not visible to a page: no test, the build and the hook list cover them.
|
||||
|
||||
What the page does: a WebGL2 canvas drawn with the scene of ``tests/_canvas_readers.py`` (ten triangles with random vertex colours, which the
|
||||
noise touches; a flat clear it would not), and a ``div`` of the same size with ``background: -moz-element(#c)``. The test takes a screenshot at a
|
||||
device pixel ratio of 1, cuts the div's box out of it, and compares it, pixel for pixel, with
|
||||
|
||||
* the canvas read by the page's own ``readPixels`` with the noise ON: they must differ (the page's road is noised; this is the control that
|
||||
fails on an engine without the noise, since a flat canvas would pass it without any);
|
||||
* the canvas read by ``readPixels`` with the canvas noise declared off (``zoom.stealth.canvas.substitute_pixels`` false, a second launch of the
|
||||
same page, every other declaration the same): they must be equal, and the div's box of that launch must be the same too.
|
||||
|
||||
The noise seed (12345) is one no runner has.
|
||||
Run: pytest tests/test_moz_element_paints_a_webgl_canvas_as_drawn_e2e.py -m e2e -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
import _canvas_readers as cr
|
||||
import _page_bytes as pb
|
||||
from _waits import wait_until
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
#: A device pixel ratio of 1 and a window that holds the canvas and the div whole, at integer positions.
|
||||
PIN = {"screen.dpr": 1.0}
|
||||
VIEWPORT = {"width": 300, "height": 300}
|
||||
|
||||
PAGE_JS = r"""
|
||||
async function paint() {
|
||||
const c = document.getElementById('c');
|
||||
const gl = drawGL(c, 'webgl2');
|
||||
// one frame after the drawing, so that what the painters hold is what was drawn
|
||||
await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
|
||||
const box = id => { const r = document.getElementById(id).getBoundingClientRect();
|
||||
return {x: r.x, y: r.y, width: r.width, height: r.height, dpr: window.devicePixelRatio}; };
|
||||
return {direct: b64(readGL(gl)), div: box('d'), canvas: box('c')};
|
||||
}
|
||||
"""
|
||||
|
||||
HTML = cr.page_html(PAGE_JS).replace(
|
||||
"<body>",
|
||||
'<style>html, body { margin: 0; background: #fff; }'
|
||||
' #c { position: absolute; left: 10px; top: 10px; width: 128px; height: 128px; }'
|
||||
' #d { position: absolute; left: 10px; top: 150px; width: 128px; height: 128px; background: -moz-element(#c) no-repeat 0 0; }</style>'
|
||||
'<body><canvas id="c" width="128" height="128"></canvas><div id="d"></div>')
|
||||
|
||||
|
||||
def _div_pixels(shot, box):
|
||||
"""The RGBA bytes of the div's box in a screenshot (the box must be on whole device pixels)."""
|
||||
for key in ("x", "y", "width", "height"):
|
||||
assert box[key] == int(box[key]), "the div is not on whole device pixels (%s = %r)" % (key, box[key])
|
||||
assert box["dpr"] == 1, "the device pixel ratio is %r, not 1: the box would be resampled" % box["dpr"]
|
||||
whole = pb.unfiltered(shot)
|
||||
cut = pb.crop(whole, int(box["x"]), int(box["y"]), int(box["width"]), int(box["height"]))
|
||||
assert (cut["w"], cut["h"]) == (cr.SIZE, cr.SIZE), cut
|
||||
return cr.rgba_of_image(cut)
|
||||
|
||||
|
||||
def _paint_and_shoot(firefox_binary, noised):
|
||||
"""(what the page reads with readPixels, the div's box of a screenshot taken once the painter has drawn the canvas)."""
|
||||
with cr.launched(firefox_binary, HTML, noised=noised, pin=PIN, viewport=VIEWPORT) as page:
|
||||
measured = cr.run(page, "paint()")
|
||||
direct = cr.rgba("direct", measured["direct"])
|
||||
seen = {}
|
||||
|
||||
def painted():
|
||||
seen["pixels"] = _div_pixels(page.screenshot(type="png"), measured["div"])
|
||||
# a div that has not painted the canvas yet is one flat colour: the scene has hundreds
|
||||
return cr.distinct_colours(seen["pixels"]) > 100
|
||||
|
||||
assert wait_until(painted, 120, lambda: page.wait_for_timeout(200)), (
|
||||
"-moz-element(#c) never painted the canvas into the div: its box holds %d colours" % cr.distinct_colours(seen["pixels"]))
|
||||
return direct, seen["pixels"]
|
||||
|
||||
|
||||
@pytest.mark.timeout(300, method="thread")
|
||||
def test_moz_element_paints_a_webgl_canvas_as_drawn(firefox_binary):
|
||||
page_on, shot_on = _paint_and_shoot(firefox_binary, True)
|
||||
page_off, shot_off = _paint_and_shoot(firefox_binary, False)
|
||||
|
||||
# the control: the page's own road is noised with the engine on (and only that), so the engine is active in this launch
|
||||
n = cr.differing_pixels(page_on, page_off)
|
||||
assert n > 0, (
|
||||
"readPixels reads the canvas byte for byte the same with the canvas noise declared on and off: the page's road is not noised, so "
|
||||
"this test would pass on an engine that applies no noise to the painter either")
|
||||
# what the painter shows is what was drawn: not the page's noised read, and exactly the read of the canvas with no noise
|
||||
assert shot_on != page_on, (
|
||||
"the div painted by -moz-element holds exactly the pixels the page reads with readPixels (noised): the painter reads the page's "
|
||||
"snapshot, not the canvas as drawn")
|
||||
assert shot_on == page_off, (
|
||||
"the div painted by -moz-element is not the canvas as it was drawn: %d pixels differ from the canvas read with the noise declared off"
|
||||
% cr.differing_pixels(shot_on, page_off))
|
||||
assert shot_on == shot_off, (
|
||||
"the screenshot of the painted div differs between noise on and off (%d pixels): the browser's own readers carry the noise"
|
||||
% cr.differing_pixels(shot_on, shot_off))
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Native line endings are Windows' on every host.
|
||||
|
||||
On retail Windows Firefox a `Blob` made with `endings: 'native'` converts every
|
||||
"\n" to "\r\n" (dom/file/BlobSet.cpp, under `XP_WIN`), and the plain-text
|
||||
serializer used by `getSelection().toString()` puts "\r\n" between blocks
|
||||
(dom/serializers/nsPlainTextSerializer.cpp, `DetermineLineBreak`); on retail
|
||||
Linux both stay "\n". A page reads both, so the engine gives the lines of
|
||||
Windows everywhere, with no pref (hook `fingerprint/js-surface/line-endings`:
|
||||
`StealthNativeEOL.h`, `StealthPlainTextLineBreak.h`). The test is the same on
|
||||
Linux and Windows, where the engine's answer is the same.
|
||||
|
||||
Control: the conversion is the one of `native`, not a global change of every
|
||||
line break: the default `endings` (transparent) leaves a Blob's "\n" alone
|
||||
(size 1), and `innerText` of the same two blocks keeps "\n". The stock
|
||||
Firefox of the same candidate (1 and "\n" on Linux) cannot be asked from the
|
||||
candidate: the hook is not behind the engine's gate, as it is not in the
|
||||
retail.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
#: Raw: the backslash-n of the JS source is an escape the page reads, not a line break written into the string literal.
|
||||
PROBE = r"""() => {
|
||||
document.body.innerHTML = '<div>one</div><div>two</div>';
|
||||
const sel = getSelection();
|
||||
sel.removeAllRanges();
|
||||
sel.selectAllChildren(document.body);
|
||||
return {
|
||||
native: new Blob(['\n'], {endings: 'native'}).size,
|
||||
native_text: new Blob(['a\nb'], {endings: 'native'}).size,
|
||||
transparent: new Blob(['\n'], {endings: 'transparent'}).size,
|
||||
default: new Blob(['\n']).size,
|
||||
selection: sel.toString(),
|
||||
inner_text: document.body.innerText,
|
||||
};
|
||||
}"""
|
||||
|
||||
|
||||
def test_native_line_endings_are_windows(firefox_binary):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank")
|
||||
got = page.evaluate(PROBE)
|
||||
assert got["native"] == 2, got
|
||||
assert got["native_text"] == 4, got
|
||||
# The text between two blocks is "\r\n" and nothing is a bare "\n".
|
||||
assert "\r\n" in got["selection"], got
|
||||
assert got["selection"].replace("\r\n", "\n") == "one\ntwo", got
|
||||
assert "\n" not in got["selection"].replace("\r\n", ""), got
|
||||
# Control: the conversion belongs to `native` and to the serializer.
|
||||
assert got["transparent"] == 1 and got["default"] == 1, got
|
||||
assert "\r" not in got["inner_text"], got
|
||||
@@ -0,0 +1,84 @@
|
||||
"""`Page.elementAtom` answers for an element the way Marionette's atoms do: is it displayed, and what text it shows.
|
||||
|
||||
The engine's Juggler runs the source of Marionette's Selenium atoms
|
||||
(`isElementDisplayed`, `getVisibleText`, from `remote/marionette/atom.sys.mjs`)
|
||||
in a sandbox of its own over the page's window, with the element handed through
|
||||
an Xray, so a page that replaced `getComputedStyle` or `getBoundingClientRect`
|
||||
sees none of the calls. The sources come from the constant `ATOM_SOURCES` that
|
||||
the engine's hook exports from `atom.sys.mjs` (folder `automation/element-atoms`
|
||||
of the engine series, `remote/marionette/atom.sys.mjs`; consumer
|
||||
`juggler/content/PageAgent.js` `_elementAtom`). If that export is missing,
|
||||
`ATOM_SOURCES[atom]` throws and the command answers with an error.
|
||||
|
||||
**What is asserted.** On a visible and on a hidden element (`display: none`,
|
||||
`visibility: hidden`, and one inside a hidden parent) the atom says what the
|
||||
client API says for `is_visible`, and the text of the visible one is its
|
||||
`inner_text`; the answers for the visible element and the hidden ones DIFFER
|
||||
(the control is functional: not on/off, but one element against another, so an
|
||||
atom that always answered the same could not pass).
|
||||
|
||||
The client API (`is_visible`, `inner_text`) does not use the command: it runs
|
||||
Playwright's injected script. So the command is sent the way the engine's other
|
||||
clients send it, on the in-process connection of the page's session, with the
|
||||
frame and the object of an element handle.
|
||||
|
||||
Why a page cares: the atoms are how a client learns what a page shows without running
|
||||
code in the page's realm, so a page that replaced `getComputedStyle` or
|
||||
`getBoundingClientRect` does not see the lookups; this test holds that the atoms run
|
||||
at all and answer for what the page shows.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
PAGE = """<!doctype html><html><body>
|
||||
<p id="shown">hello visible world</p>
|
||||
<p id="none" style="display:none">secret none</p>
|
||||
<p id="invisible" style="visibility:hidden">secret invisible</p>
|
||||
<div style="display:none"><p id="nested">secret nested</p></div>
|
||||
</body></html>"""
|
||||
|
||||
HIDDEN = ("none", "invisible", "nested")
|
||||
|
||||
|
||||
def _atom(page, selector, atom):
|
||||
"""What `Page.elementAtom` answers for the element `selector` names, sent on the in-process connection of the
|
||||
page's session (the server runs in this process, as `test_injected_node_surface.py` uses it)."""
|
||||
handle = page.query_selector(selector)
|
||||
assert handle is not None, selector
|
||||
impl = handle._impl_obj
|
||||
server = impl._connection._transport._server
|
||||
element = server.object(impl._guid)
|
||||
injected = server.object(page._impl_obj._guid).injected
|
||||
answer = injected.c.send(
|
||||
"Page.elementAtom",
|
||||
{"frameId": element.frame.frame_id, "objectId": element.object_id, "atom": atom},
|
||||
session=injected.session, timeout=None)
|
||||
return answer["result"]
|
||||
|
||||
|
||||
def test_the_atoms_run_in_a_sandbox_and_tell_a_visible_element_from_a_hidden_one(firefox_binary):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=4242, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.set_content(PAGE)
|
||||
|
||||
# what the client API says: the visible element is visible, the others are not
|
||||
assert page.is_visible("#shown") is True
|
||||
assert [page.is_visible("#" + name) for name in HIDDEN] == [False, False, False]
|
||||
assert page.inner_text("#shown") == "hello visible world"
|
||||
|
||||
# what the atoms say, for the same elements
|
||||
assert _atom(page, "#shown", "isElementDisplayed") is True
|
||||
assert [_atom(page, "#" + name, "isElementDisplayed") for name in HIDDEN] == [False, False, False]
|
||||
|
||||
shown_text = _atom(page, "#shown", "getVisibleText")
|
||||
assert shown_text == page.inner_text("#shown"), shown_text
|
||||
hidden_texts = [_atom(page, "#" + name, "getVisibleText") for name in HIDDEN]
|
||||
assert hidden_texts == ["", "", ""], hidden_texts
|
||||
|
||||
# the control: one element against another gives different answers, whatever the atoms do with a page
|
||||
assert shown_text not in hidden_texts
|
||||
@@ -0,0 +1,120 @@
|
||||
"""A popup reads the window frame the core declares, not the one of the host.
|
||||
|
||||
What it fixes: the geometry of a window a page opens with `window.open(url, 'p', 'width=500,height=400')`, read from
|
||||
inside the popup. A popup is its real inner size plus the declared frame (retail Windows Firefox, measured by the core at
|
||||
scale 1.0: a border of 8 on the left, right and bottom, the popup UI of 72 above the content, and a default position of
|
||||
4,4 when the page names no left/top):
|
||||
|
||||
* `outerWidth == innerWidth + 2 * border`
|
||||
* `outerHeight == innerHeight + popup_ui + border`
|
||||
* `screenX == screenY ==` the declared default position (the page named none)
|
||||
* `mozInnerScreenX == screenX + border`, `mozInnerScreenY == screenY + popup_ui`
|
||||
|
||||
Engine hook: `fingerprint/screen-window/geometry` of the engine series (`nsGlobalWindowOuter::GetOuterSize`,
|
||||
`GetScreenXY`, `GetMozInnerScreenX/Y`, with the content origin shift of `StealthScreenCoords`) and
|
||||
`fingerprint/screen-window/popup-position` (`nsWindowWatcher`, the default position of a popup).
|
||||
|
||||
Negative control, in the same test: the same page in a launch declared with a SECOND frame that no runner has (border 6,
|
||||
popup UI 53, default position 9). The popup reads that one (outer - inner = 12 x 59, screen 9, mozInnerScreen 15 x 62) and
|
||||
none of the first declaration's numbers, and the two readings DIFFER. The engine off is not the control: the declared frame
|
||||
is the one of a retail Windows window at scale 1.0, so on a Windows runner the host's own popup has the very same frame
|
||||
(measured: 16 x 80 with the engine off) and the test could not tell a hook that answers from one that does not.
|
||||
|
||||
A popup that names ONLY `left` (`window.open(url, 'p', 'width=500,height=400,left=137')`, `test_a_popup_naming_only_left_..`): the
|
||||
hook (`StealthPlacePopupAtDefault`, `fingerprint/screen-window/popup-position`) fills in only the coordinate the page did not give, so
|
||||
`screenX` is the 137 the page asked for (the opener's CSS-to-desktop scale is 1.0 here, no second conversion) and `screenY` is the
|
||||
declared default position, 4 (9 under the second frame); the frame relations are the same as for a popup with no position at all.
|
||||
|
||||
Why a page reads it: `outerWidth - innerWidth`, `screenX` and `mozInnerScreenX/Y` are one line each, and a popup whose
|
||||
frame is not a Windows frame is a browser that does not run on Windows. Linux and Windows run the same assertions: the
|
||||
declaration, not the host, is what is read.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from _popup_geometry import (OTHER_BORDER, OTHER_FRAME, OTHER_POPUP_UI, OTHER_POSITION, frame_extra, frame_of_the_declaration,
|
||||
read_popup)
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
|
||||
def test_a_popup_is_its_inner_size_plus_the_declared_frame(firefox_binary):
|
||||
frame = frame_of_the_declaration()
|
||||
declared = (2 * frame.border, frame.popup_ui + frame.border)
|
||||
|
||||
def has_the_frame(reading):
|
||||
p = reading["popup"]
|
||||
return (p["ow"] - p["iw"], p["oh"] - p["ih"]) == declared
|
||||
|
||||
on = read_popup(firefox_binary, ready=has_the_frame)["popup"]
|
||||
assert (on["ow"] - on["iw"], on["oh"] - on["ih"]) == declared, (
|
||||
"the popup reads outer %dx%d for inner %dx%d: the frame is %r, the declaration is %r"
|
||||
% (on["ow"], on["oh"], on["iw"], on["ih"], (on["ow"] - on["iw"], on["oh"] - on["ih"]), declared))
|
||||
assert (on["sx"], on["sy"]) == (frame.popup_position, frame.popup_position), (
|
||||
"a popup that names no position reads screen %r, the declared default is %d" % ((on["sx"], on["sy"]),
|
||||
frame.popup_position))
|
||||
assert on["mx"] == pytest.approx(on["sx"] + frame.border, abs=0.01), (
|
||||
"mozInnerScreenX %r is not screenX %r plus the border %d" % (on["mx"], on["sx"], frame.border))
|
||||
assert on["my"] == pytest.approx(on["sy"] + frame.popup_ui, abs=0.01), (
|
||||
"mozInnerScreenY %r is not screenY %r plus the popup UI %d" % (on["my"], on["sy"], frame.popup_ui))
|
||||
|
||||
# The control: a launch declared with another frame reads that one, and none of the first declaration's relations.
|
||||
other_declared = frame_extra(OTHER_BORDER, OTHER_POPUP_UI)
|
||||
assert other_declared != declared
|
||||
|
||||
def has_the_other_frame(reading):
|
||||
p = reading["popup"]
|
||||
return (p["ow"] - p["iw"], p["oh"] - p["ih"]) == other_declared
|
||||
|
||||
other = read_popup(firefox_binary, extra_prefs=OTHER_FRAME, ready=has_the_other_frame)["popup"]
|
||||
assert (other["ow"] - other["iw"], other["oh"] - other["ih"]) == other_declared, (
|
||||
"declared with another frame the popup reads outer %dx%d for inner %dx%d: the frame is %r, the second declaration is %r"
|
||||
% (other["ow"], other["oh"], other["iw"], other["ih"], (other["ow"] - other["iw"], other["oh"] - other["ih"]), other_declared))
|
||||
assert (other["sx"], other["sy"]) == (OTHER_POSITION, OTHER_POSITION), (
|
||||
"declared with another default position the popup reads screen %r, the second declaration is %d" % ((other["sx"], other["sy"]), OTHER_POSITION))
|
||||
assert other["mx"] == pytest.approx(other["sx"] + OTHER_BORDER, abs=0.01)
|
||||
assert other["my"] == pytest.approx(other["sy"] + OTHER_POPUP_UI, abs=0.01)
|
||||
assert (other["ow"] - other["iw"], other["oh"] - other["ih"]) != (on["ow"] - on["iw"], on["oh"] - on["ih"]), (
|
||||
"the two declared frames read the same frame: the declaration decides nothing")
|
||||
assert (other["sx"], other["sy"]) != (on["sx"], on["sy"]) and other["my"] - other["sy"] != on["my"] - on["sy"], (
|
||||
"the two declared frames read the same position or content origin: %r vs %r" % (other, on))
|
||||
|
||||
|
||||
LEFT = 137
|
||||
|
||||
|
||||
def test_a_popup_naming_only_left_reads_that_x_and_the_declared_default_y(firefox_binary):
|
||||
frame = frame_of_the_declaration()
|
||||
features = "width=500,height=400,left=%d" % LEFT
|
||||
declared = (2 * frame.border, frame.popup_ui + frame.border)
|
||||
|
||||
def has_the_frame(reading):
|
||||
p = reading["popup"]
|
||||
return (p["ow"] - p["iw"], p["oh"] - p["ih"]) == declared
|
||||
|
||||
on = read_popup(firefox_binary, ready=has_the_frame, features=features)["popup"]
|
||||
assert (on["ow"] - on["iw"], on["oh"] - on["ih"]) == declared, (
|
||||
"the popup reads outer %dx%d for inner %dx%d: the frame is %r, the declaration is %r"
|
||||
% (on["ow"], on["oh"], on["iw"], on["ih"], (on["ow"] - on["iw"], on["oh"] - on["ih"]), declared))
|
||||
assert on["sx"] == LEFT, "a popup that names left=%d reads screenX %r: the page's own x is lost" % (LEFT, on["sx"])
|
||||
assert on["sy"] == frame.popup_position, (
|
||||
"a popup that names no top reads screenY %r, the declared default is %d" % (on["sy"], frame.popup_position))
|
||||
assert on["mx"] == pytest.approx(on["sx"] + frame.border, abs=0.01)
|
||||
assert on["my"] == pytest.approx(on["sy"] + frame.popup_ui, abs=0.01)
|
||||
|
||||
# The control: a launch declared with a second frame keeps the page's x and reads the second default for y.
|
||||
other_declared = frame_extra(OTHER_BORDER, OTHER_POPUP_UI)
|
||||
|
||||
def has_the_other_frame(reading):
|
||||
p = reading["popup"]
|
||||
return (p["ow"] - p["iw"], p["oh"] - p["ih"]) == other_declared
|
||||
|
||||
other = read_popup(firefox_binary, extra_prefs=OTHER_FRAME, ready=has_the_other_frame, features=features)["popup"]
|
||||
assert (other["ow"] - other["iw"], other["oh"] - other["ih"]) == other_declared
|
||||
assert other["sx"] == LEFT, "declared with another frame the popup reads screenX %r, the page asked for %d" % (other["sx"], LEFT)
|
||||
assert other["sy"] == OTHER_POSITION, (
|
||||
"declared with another default position the popup reads screenY %r, the second declaration is %d" % (other["sy"], OTHER_POSITION))
|
||||
assert other["mx"] == pytest.approx(LEFT + OTHER_BORDER, abs=0.01)
|
||||
assert other["my"] == pytest.approx(OTHER_POSITION + OTHER_POPUP_UI, abs=0.01)
|
||||
assert other["sy"] != on["sy"] and other["sx"] == on["sx"], (
|
||||
"the declaration decides y alone when the page names x: %r vs %r" % (other, on))
|
||||
@@ -363,10 +363,13 @@ def test_window_open_features_headed_humanized(firefox_binary, harness):
|
||||
"""Headed + `humanize=True` (the real-user shape): a `window.open` WITH a
|
||||
feature string is captured, usable and closable like any page."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
if not os.environ.get("DISPLAY"):
|
||||
# A headed run needs a display: on Linux that is X11 (DISPLAY, which the runner's xvfb sets); Windows has no DISPLAY
|
||||
# and does not need one, it always has a desktop (the runner's own, or the hidden one the wrapper creates).
|
||||
if sys.platform != "win32" and not os.environ.get("DISPLAY"):
|
||||
pytest.skip("headed test needs a display")
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
|
||||
@@ -9,6 +9,10 @@ handshake and relays traffic.
|
||||
Fully hermetic - a local SOCKS5 server + a local HTTP target, with the localhost
|
||||
target forced through the proxy via ``allow_hijacking_localhost`` - so it runs
|
||||
identically on a dev box and on a GitHub runner (no external site, no secrets).
|
||||
The SOCKS5 server carries only the lab's (``_socks_servers.is_lab_destination``: loopback, the documentation ranges, the addresses of this host): the
|
||||
browser behind it also makes background requests of its own, and a CONNECT to any other destination is refused (reply 2) and recorded
|
||||
(``_socks_servers.LabGuard``: time since the server started, address type, destination as received, port, protocol), the record written when the server is
|
||||
closed under ``$RUNNER_TEMP/invpw-evidence/socks5-auth-recorder/`` (the folder the e2e jobs upload; off a runner nothing is written).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -22,7 +26,7 @@ import pytest
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
from _servers import LocalServer
|
||||
from _socks_servers import asks_the_world, declare_exit, forget_exit
|
||||
from _socks_servers import LabGuard, asks_the_world, declare_exit, forget_exit
|
||||
|
||||
_USER = "ferd_socks_user"
|
||||
_PASS = "ferd_socks_pw_42"
|
||||
@@ -30,7 +34,8 @@ _PASS = "ferd_socks_pw_42"
|
||||
|
||||
class _Socks5AuthRecorder:
|
||||
"""SOCKS5 that REQUIRES RFC1929 user/pass auth, records the creds it saw,
|
||||
then relays CONNECT to the requested target."""
|
||||
then relays CONNECT to the requested target when it is the lab's (loopback, the documentation ranges, this host); any other CONNECT is refused and
|
||||
recorded in :attr:`guard`."""
|
||||
|
||||
def __init__(self):
|
||||
self._srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
@@ -44,6 +49,8 @@ class _Socks5AuthRecorder:
|
||||
|
||||
declare_exit(self.server, LAB_EGRESS_IP)
|
||||
self.seen_creds: list[tuple[str, str]] = []
|
||||
#: What refuses (and records) every CONNECT that is not the lab's.
|
||||
self.guard = LabGuard("socks5-auth-recorder")
|
||||
self._stop = False
|
||||
threading.Thread(target=self._serve, daemon=True).start()
|
||||
|
||||
@@ -102,6 +109,8 @@ class _Socks5AuthRecorder:
|
||||
conn.sendall(b"\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00"); conn.close(); return
|
||||
if asks_the_world(self.server, addr, port): # the exit is declared above, not asked of the internet
|
||||
conn.sendall(b"\x05\x02\x00\x01\x00\x00\x00\x00\x00\x00"); conn.close(); return
|
||||
if not self.guard.admits(addr, port, atyp, "tcp"): # nothing outside the lab is carried
|
||||
conn.sendall(b"\x05\x02\x00\x01\x00\x00\x00\x00\x00\x00"); conn.close(); return
|
||||
try:
|
||||
up = socket.create_connection((addr, port), timeout=30)
|
||||
except OSError:
|
||||
@@ -140,6 +149,7 @@ class _Socks5AuthRecorder:
|
||||
self._srv.close()
|
||||
except OSError:
|
||||
pass
|
||||
self.guard.write_evidence()
|
||||
|
||||
|
||||
class _LocalHTTP:
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
"""A fresh profile keeps the startup script cache it wrote as a file mapping, not as a second copy on the heap (firefox-68, Linux and Windows).
|
||||
|
||||
What it fixes, in the published engine (firefox-68), for the hooks of `platform/script-cache` (`js/xpconnect/loader/ScriptPreloader.cpp` and `.h`, the own
|
||||
file `StealthScriptCache-inl.h`): the script preloader writes `<profile>/startupCache/scriptCache.bin` once the startup is over. On a WARM profile the
|
||||
cache is a file mapping (`explicit/script-preloader/non-heap/memmapped-cache`) and costs no heap. On a FRESH profile the same bytes were built in memory
|
||||
for the write and stayed on the heap for the whole session (16.5 MB measured in the parent, with the 13.3 MB file already on disk): the engine now maps the
|
||||
file it wrote and points every entry into the mapping (`AdoptWrittenCache`), and reports the mapping as
|
||||
`explicit/script-preloader/non-heap/memmapped-written-cache`, so the megabytes that left the heap appear somewhere. It is a memory property, not a
|
||||
fingerprint one: a page cannot read it. The preloader exists TWICE in the parent: `gScriptPreloader` (`scriptCache.bin`, the parent's scripts, about 14 MB) and `gChildScriptPreloader` (`scriptCache-child.bin`,
|
||||
the scripts for content processes, about 1.2 MB; `ScriptPreloader::GetChildSingleton` runs `InitCache(u"scriptCache-child")` in the parent too). Both register the
|
||||
same weak memory reporter, so the parent's report carries every path TWICE under the process name `""`, once per instance, in an order the engine does not fix; the
|
||||
test keeps ALL the amounts of a path (a dict that kept the last one made the warm session look as if it mapped 1.2 MB while 14.3 MB was on disk: run 44985244053,
|
||||
Linux 1207724 and Windows 1207732 reported, 14296776 and 14475288 on disk). The test also records, in every assertion message, the size of every file in
|
||||
`startupCache/` (when the cache was adopted, when the fresh session was over, at the warm start and when the warm report was read). The test reads the memory report of the parent (the engine's own reporters, `nsIMemoryReporterManager.getReports`,
|
||||
in chrome scope through Marionette: the route of `tests/webfont_probe.py`; `MOZ_REMOTE_ALLOW_SYSTEM_ACCESS` is set with `monkeypatch`).
|
||||
|
||||
What the test does. A NEW profile directory, a session on it. It waits on the CONDITION "`startupCache/scriptCache.bin` exists" (not on a timer), then on the
|
||||
condition "the parent reports a non-zero `memmapped-written-cache`" (the file appears when the write is moved into place and is adopted a moment after).
|
||||
It asserts, for that session: `memmapped-written-cache` equals the size of the file (non-zero), and `heap/saved-scripts` is below the size of the file (the
|
||||
heap copies are gone: without the hook it is about the size of the file). Then the SAME profile is opened again (warm): `memmapped-cache` equals the size of
|
||||
the file left on disk when the fresh session ended (it can be a rewrite of the shutdown, smaller than the adopted one) (the file is mapped under the name `scriptCache-current.bin`: a warm session moves `scriptCache.bin` aside when it opens it), and
|
||||
`memmapped-written-cache` is 0 unless the session wrote the cache again, in which case `scriptCache.bin` is back and it equals the new size.
|
||||
|
||||
Negative control: the warm session of the same profile. The fresh and the warm session differ in the two reporters in the way described (written is the size
|
||||
of the file in one and 0 in the other, read is 0 in one and the size in the other), so the reading cannot give the same number whatever the engine does.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from _waits import wait_until
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
MARIONETTE_ARGS = ["-marionette", "-remote-allow-system-access"]
|
||||
WRITTEN = "explicit/script-preloader/non-heap/memmapped-written-cache"
|
||||
READ_CACHE = "explicit/script-preloader/non-heap/memmapped-cache"
|
||||
SAVED = "explicit/script-preloader/heap/saved-scripts"
|
||||
LAUNCH = dict(seed=42, headless=True, humanize=False, locale="en-US", timezone="America/New_York")
|
||||
|
||||
#: The reports of the parent process (the process name of a reporter of this process is the empty string) under the script preloader.
|
||||
REPORT_JS = """
|
||||
const done = arguments[arguments.length - 1];
|
||||
const out = {};
|
||||
const manager = Cc["@mozilla.org/memory-reporter-manager;1"].getService(Ci.nsIMemoryReporterManager);
|
||||
manager.getReports(
|
||||
{callback(process, path, kind, units, amount, description) {
|
||||
if (process === "" && path.startsWith("explicit/script-preloader/")) { (out[path] = out[path] || []).push(amount); }
|
||||
}},
|
||||
null,
|
||||
{callback() { done(JSON.stringify(out)); }},
|
||||
null,
|
||||
false);
|
||||
"""
|
||||
|
||||
|
||||
def _reports(marionette):
|
||||
"""path -> sorted list of every amount reported under it (one per preloader instance: the parent's and the child's)."""
|
||||
answer = marionette.call("WebDriver:ExecuteAsyncScript", {"script": REPORT_JS, "args": []})
|
||||
return {path: sorted(amounts) for path, amounts in json.loads(answer["value"]).items()}
|
||||
|
||||
|
||||
def _files(profile):
|
||||
"""name -> size of every file in `<profile>/startupCache/` (empty if the folder is not there)."""
|
||||
folder = profile / "startupCache"
|
||||
if not folder.is_dir():
|
||||
return {}
|
||||
return {entry.name: entry.stat().st_size for entry in sorted(folder.iterdir()) if entry.is_file()}
|
||||
|
||||
|
||||
def _amounts(reports, path):
|
||||
return reports.get(path, [])
|
||||
|
||||
|
||||
def _session(binary, profile):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
return InvisiblePlaywright(binary_path=binary, profile_dir=profile, extra_args=MARIONETTE_ARGS,
|
||||
extra_prefs={"marionette.port": 0}, **LAUNCH)
|
||||
|
||||
|
||||
def _open_marionette(profile):
|
||||
"""Marionette of the browser on ``profile``: the port is the one the browser got (it was asked for port 0), read from the profile."""
|
||||
import webfont_probe
|
||||
|
||||
marionette = webfont_probe._Marionette(webfont_probe.marionette_active_port(profile))
|
||||
marionette.call("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {}}})
|
||||
marionette.call("WebDriver:SetTimeouts", {"script": 240000})
|
||||
marionette.call("Marionette:SetContext", {"value": "chrome"})
|
||||
return marionette
|
||||
|
||||
|
||||
def test_a_fresh_profile_reports_its_written_cache_as_mapped(firefox_binary, monkeypatch, tmp_path):
|
||||
import webfont_probe
|
||||
|
||||
monkeypatch.setenv("MOZ_REMOTE_ALLOW_SYSTEM_ACCESS", "1") # the chrome-scope read of the memory report
|
||||
profile = tmp_path / "profile"
|
||||
cache = profile / "startupCache" / "scriptCache.bin"
|
||||
|
||||
# The fresh session: the cache is written during it and adopted.
|
||||
marionette = None
|
||||
try:
|
||||
with _session(firefox_binary, profile) as context:
|
||||
page = context.new_page()
|
||||
page.goto("about:blank", timeout=60_000)
|
||||
written_file = wait_until(lambda: cache.exists() and cache.stat().st_size > 0, 180, lambda: page.wait_for_timeout(500))
|
||||
assert written_file, "the profile never got %s (the startup script cache is written once the startup is over)" % cache
|
||||
marionette = _open_marionette(profile)
|
||||
seen = {}
|
||||
sampled = []
|
||||
|
||||
def reported():
|
||||
# ONE sample per poll: the size of the file read here is the one the report is compared with and the one the test keeps (the
|
||||
# file can be written again between two reads).
|
||||
seen.clear()
|
||||
seen.update(_reports(marionette))
|
||||
sampled.append(cache.stat().st_size if cache.exists() else 0)
|
||||
return sampled[-1] > 0 and sampled[-1] in _amounts(seen, WRITTEN)
|
||||
|
||||
adopted = wait_until(reported, 60, lambda: page.wait_for_timeout(500))
|
||||
size = sampled[-1]
|
||||
fresh = dict(seen)
|
||||
files_adopted = _files(profile)
|
||||
finally:
|
||||
if marionette is not None:
|
||||
marionette.close()
|
||||
# The parent's own file is `scriptCache.bin`; the other amount under a path is the child preloader's (`scriptCache-child.bin`).
|
||||
assert adopted, "the parent never reported its written cache (%d bytes) as mapped (%s); reports (all amounts per path): %r; startupCache/ when adopted: %r" % (size, WRITTEN, fresh, files_adopted)
|
||||
assert size in _amounts(fresh, WRITTEN), "no mapping reported (%r) is the file written (%d bytes): %r; startupCache/: %r" % (_amounts(fresh, WRITTEN), size, fresh, files_adopted)
|
||||
assert max(_amounts(fresh, SAVED), default=0) < size, "the heap still holds the scripts of the cache that is on disk: %r (file %d bytes); startupCache/: %r" % (fresh, size, files_adopted)
|
||||
assert not any(_amounts(fresh, READ_CACHE)), "a fresh profile has no cache to read: %r; startupCache/: %r" % (fresh, files_adopted)
|
||||
|
||||
# Control: the same profile, warm. The cache of the file is read as a mapping and nothing written this session is reported unless it was rewritten.
|
||||
# The warm session maps the file that is on disk when the fresh session is OVER, not the one that was adopted while it ran: the cache can be written
|
||||
# again during the shutdown (`ScriptPreloader::InvalidateCache` starts a new write when the cache is invalidated after it was saved, and the file is
|
||||
# replaced), so the size to compare with is read here, after the exit.
|
||||
files_left = _files(profile)
|
||||
started_with = cache.stat().st_size if cache.exists() else 0
|
||||
assert started_with > 0, "the fresh session left no script cache for the warm session to open: %s; startupCache/: %r" % (cache, files_left)
|
||||
marionette = None
|
||||
try:
|
||||
with _session(firefox_binary, profile) as context:
|
||||
page = context.new_page()
|
||||
page.goto("about:blank", timeout=60_000)
|
||||
marionette = _open_marionette(profile)
|
||||
warm = _reports(marionette)
|
||||
# A warm session MOVES the file it found to `scriptCache-current.bin` when it opens the cache (`ScriptPreloader::OpenCache`) and maps that
|
||||
# one; `scriptCache.bin` is there again only once this session has written a cache of its own (about 3 s after the startup, and only if
|
||||
# it has something to save). So the file of this session is absent until then, and nothing is reported as written until it exists
|
||||
# (`WriteCache` moves the file into place BEFORE it adopts it, so a report that carries a written cache finds the file here).
|
||||
now = cache.stat().st_size if cache.exists() else 0
|
||||
files_warm = _files(profile)
|
||||
finally:
|
||||
if marionette is not None:
|
||||
marionette.close()
|
||||
# What the warm session opens: every file the fresh session left (`scriptCache.bin`, the parent's, and `scriptCache-child.bin`, the child's, when it was
|
||||
# written) is moved to `<name>-current.bin` and mapped, and each mapping is reported once under `memmapped-cache`.
|
||||
left = sorted(size for name, size in files_left.items() if name in ("scriptCache.bin", "scriptCache-child.bin"))
|
||||
details = "startupCache/ at the end of the fresh session %r (%d bytes adopted while it ran), at the warm start %r, when the warm report was read %r; warm reports (all amounts per path): %r" % (files_left, size, files_left, files_warm, warm)
|
||||
assert sorted(_amounts(warm, READ_CACHE)) == left, "the warm session did not map the cache files it found (%r bytes on disk when the fresh session ended): %s" % (left, details)
|
||||
assert started_with in _amounts(warm, READ_CACHE), "the warm session did not map the parent's cache (%d bytes): %s" % (started_with, details)
|
||||
current = sorted(size for name, size in files_warm.items() if name in ("scriptCache.bin", "scriptCache-child.bin"))
|
||||
assert all(amount in [0] + current for amount in _amounts(warm, WRITTEN)), "the warm session reports a written cache that is not one of its files (%r): %s" % (current, details)
|
||||
assert _amounts(warm, READ_CACHE) != _amounts(fresh, READ_CACHE), details
|
||||
@@ -30,10 +30,12 @@ import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from pathlib import Path
|
||||
|
||||
@@ -116,17 +118,94 @@ def _engine_env(work: Path) -> dict:
|
||||
return env
|
||||
|
||||
|
||||
def _run_to_the_end(argv, env, cwd, timeout_s):
|
||||
"""Runs `argv` with nothing on stdout and stderr; (exit code, None) or (None, "timed out ...") with its whole tree ended."""
|
||||
def _run_to_the_end(argv, env, cwd, timeout_s, *, output_to=None, core_dumps=False):
|
||||
"""Runs `argv` with nothing on stdout and stderr (or, with `output_to`, with both written to files `<output_to>.stdout` and `<output_to>.stderr`, which is all
|
||||
that changes); (exit code, None) or (None, "timed out ...") with its whole tree ended. `core_dumps` (Linux only) lifts the core size limit of the process, so that
|
||||
a crash leaves a core file where `kernel.core_pattern` says (e2e.yml sets it)."""
|
||||
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0) if sys.platform == "win32" else 0
|
||||
proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env, cwd=str(cwd), creationflags=flags)
|
||||
if core_dumps and sys.platform.startswith("linux"):
|
||||
argv = ["sh", "-c", 'ulimit -c unlimited 2>/dev/null; exec "$@"', "sh", *argv]
|
||||
sinks = [subprocess.DEVNULL, subprocess.DEVNULL]
|
||||
opened = []
|
||||
if output_to is not None:
|
||||
for index, suffix in enumerate((".stdout", ".stderr")):
|
||||
opened.append(open(str(output_to) + suffix, "wb"))
|
||||
sinks[index] = opened[-1]
|
||||
try:
|
||||
proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=sinks[0], stderr=sinks[1], env=env, cwd=str(cwd), creationflags=flags)
|
||||
try:
|
||||
return proc.wait(timeout=timeout_s), None
|
||||
except subprocess.TimeoutExpired:
|
||||
return None, "did not finish within %s s" % timeout_s
|
||||
try:
|
||||
return proc.wait(timeout=timeout_s), None
|
||||
except subprocess.TimeoutExpired:
|
||||
return None, "did not finish within %s s" % timeout_s
|
||||
finally:
|
||||
_kill_tree(proc)
|
||||
finally:
|
||||
_kill_tree(proc)
|
||||
for sink in opened:
|
||||
sink.close()
|
||||
|
||||
|
||||
def _evidence_folder(work):
|
||||
"""Where the e2e jobs pick up what a test saved (`$RUNNER_TEMP/invpw-evidence`), under this test's own name; the work folder outside a runner."""
|
||||
base = os.environ.get("RUNNER_TEMP")
|
||||
folder = (Path(base) / "invpw-evidence" if base else Path(work)) / "security-state-generate"
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
return folder
|
||||
|
||||
|
||||
def _save_what_the_failed_generation_left(ff, profile, work, output, started_at, code, why):
|
||||
"""ONLY after a generation that did not exit 0: the engine's stdout and stderr, what the profile holds (the result and the folder `security_state/`, with every file's
|
||||
size), and, on Linux, the backtrace of every thread of the core the crash left (gdb), all in the evidence folder the e2e jobs upload. Saves; asserts nothing and never
|
||||
raises (the assertion of the test is what reports the failure)."""
|
||||
folder = _evidence_folder(work)
|
||||
notes = ["exit code %r; %s" % (code, why or "the engine exited")]
|
||||
try:
|
||||
for suffix in (".stdout", ".stderr"):
|
||||
source = Path(str(output) + suffix)
|
||||
if source.is_file():
|
||||
shutil.copyfile(str(source), str(folder / ("engine" + suffix)))
|
||||
notes.append("%s: %d bytes" % (source.name, source.stat().st_size))
|
||||
listing = ["%s\t%d" % (path.relative_to(profile).as_posix(), path.stat().st_size) for path in sorted(profile.rglob("*")) if path.is_file()]
|
||||
(folder / "profile-files.tsv").write_text("\n".join(listing) + "\n", encoding="utf-8")
|
||||
notes.append("profile files: %d" % len(listing))
|
||||
for name in (RESULT_NAME, "user.js"):
|
||||
if (profile / name).is_file():
|
||||
shutil.copyfile(str(profile / name), str(folder / name))
|
||||
if (profile / STATE_DIR).is_dir():
|
||||
shutil.copytree(str(profile / STATE_DIR), str(folder / STATE_DIR), dirs_exist_ok=True)
|
||||
if sys.platform.startswith("linux"):
|
||||
notes.append(_core_backtrace(ff, work, folder, started_at))
|
||||
except Exception as exc: # the evidence is best effort: the test reports the failure
|
||||
notes.append("saving the evidence failed: %r" % (exc,))
|
||||
(folder / "notes.txt").write_text("\n".join(notes) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def _core_backtrace(ff, work, folder, started_at):
|
||||
"""The core the generation left (in `$INVPW_CORE_DIR`, the folder e2e.yml points `kernel.core_pattern` at; else in the work folder, the engine's working directory):
|
||||
gdb's `thread apply all bt` of it, written to `gdb-backtrace.txt`; the core itself is deleted (it is hundreds of MB). A one-line account of what was done."""
|
||||
try:
|
||||
pattern = Path("/proc/sys/kernel/core_pattern").read_text(encoding="utf-8").strip()
|
||||
except OSError as exc:
|
||||
pattern = "unreadable: %r" % (exc,)
|
||||
where = Path(os.environ.get("INVPW_CORE_DIR") or work)
|
||||
cores = sorted((path for path in where.glob("core*") if path.is_file() and path.stat().st_mtime >= started_at - 2), key=lambda path: path.stat().st_mtime)
|
||||
if not cores:
|
||||
return "no core file in %s (kernel.core_pattern is %r, INVPW_CORE_DIR is %r, gdb is %s)" % (where, pattern, os.environ.get("INVPW_CORE_DIR"), shutil.which("gdb"))
|
||||
core = cores[-1]
|
||||
size = core.stat().st_size
|
||||
gdb = shutil.which("gdb")
|
||||
if gdb is None:
|
||||
return "core %s (%d bytes, kernel.core_pattern %r) but gdb is not installed" % (core.name, size, pattern)
|
||||
try:
|
||||
done = subprocess.run([gdb, "-batch", "-nx", "-ex", "set pagination off", "-ex", "bt", "-ex", "info registers", "-ex", "x/8i $pc", "-ex", "info sharedlibrary",
|
||||
"-ex", "thread apply all bt", ff, str(core)], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=600)
|
||||
(folder / "gdb-backtrace.txt").write_bytes(done.stdout)
|
||||
account = "core %s (%d bytes, kernel.core_pattern %r): gdb exited %d, %d bytes of backtrace" % (core.name, size, pattern, done.returncode, len(done.stdout))
|
||||
except Exception as exc:
|
||||
account = "core %s (%d bytes, kernel.core_pattern %r): gdb failed: %r" % (core.name, size, pattern, exc)
|
||||
for leftover in cores:
|
||||
leftover.unlink()
|
||||
return account
|
||||
|
||||
|
||||
# --- the files the core would write ----------------------------------------------------------------------------------------------------------------------------
|
||||
@@ -255,7 +334,11 @@ def test_the_engine_generates_the_security_state_it_is_given(ff, inputs, tmp_pat
|
||||
profile = work / "profile"
|
||||
profile.mkdir()
|
||||
(profile / "user.js").write_bytes(_user_js(files))
|
||||
code, why = _run_to_the_end([ff, "-headless", "-no-remote", "-profile", str(profile)], _engine_env(work), work, GENERATE_TIMEOUT_S)
|
||||
output = work / "engine-output"
|
||||
started_at = time.time()
|
||||
code, why = _run_to_the_end([ff, "-headless", "-no-remote", "-profile", str(profile)], _engine_env(work), work, GENERATE_TIMEOUT_S, output_to=output, core_dumps=True)
|
||||
if code != 0:
|
||||
_save_what_the_failed_generation_left(ff, profile, work, output, started_at, code, why)
|
||||
said = (profile / RESULT_NAME).read_bytes().decode("utf-8") if (profile / RESULT_NAME).is_file() else "no %s" % RESULT_NAME
|
||||
assert code == 0, "the engine in generate mode %s (exit code %r); its result: %s" % (why or "exited", code, said)
|
||||
|
||||
|
||||
@@ -68,10 +68,10 @@ return JSON.stringify(out);
|
||||
"""
|
||||
|
||||
|
||||
def _marionette(port):
|
||||
def _marionette():
|
||||
import webfont_probe
|
||||
|
||||
m = webfont_probe._Marionette(port)
|
||||
m = webfont_probe._Marionette(webfont_probe.marionette_active_port())
|
||||
m.call("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {}}})
|
||||
m.call("Marionette:SetContext", {"value": "chrome"})
|
||||
return m
|
||||
@@ -108,16 +108,15 @@ def test_the_compositor_is_webrender_software_whatever_the_machine(firefox_binar
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
monkeypatch.setenv("MOZ_REMOTE_ALLOW_SYSTEM_ACCESS", "1") # the chrome-scope reads below
|
||||
port = webfont_probe.marionette_port()
|
||||
pref_names = ["zoom.stealth.gfx.feature_status", "gfx.webrender.software", "gfx.webrender.software.d3d11"]
|
||||
server, url = _a_page_server("<!doctype html><title>compositor</title><body>x</body>")
|
||||
marionette = None
|
||||
try:
|
||||
with InvisiblePlaywright(binary_path=firefox_binary, extra_args=MARIONETTE_ARGS,
|
||||
extra_prefs={"marionette.port": port}, **LAUNCH) as browser:
|
||||
extra_prefs={"marionette.port": 0}, **LAUNCH) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(url, wait_until="load", timeout=60000)
|
||||
marionette = _marionette(port)
|
||||
marionette = _marionette()
|
||||
# a window gets its layer manager a moment after it is shown: the same wait for the answer as about:support has none, so poll
|
||||
windows, end = [], time.time() + 30
|
||||
while time.time() < end:
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
"""A page loads the branding from the archive the core declares, with the
|
||||
content sandbox on.
|
||||
|
||||
`chrome://branding/content/` is content-accessible, and what a page reads there
|
||||
tells a build from the retail one (`resource://usercontext-content/branding/`,
|
||||
the other place the engine serves the archive, is not readable by a page: it
|
||||
answers `error` to an image load, so it is not asserted). The core declares
|
||||
where the files are (`zoom.stealth.branding.archive`, the zip of a set it ships
|
||||
or one of the caller's own, `pin={"branding": <archive>}`); the engine serves them as `jar:` at the places
|
||||
that resolve those URIs (netwerk/protocol/res, `fingerprint/js-surface/
|
||||
branding`) and grants the content processes read access to exactly that file
|
||||
(Windows: `sandboxBroker.cpp`; Linux: `SandboxBrokerPolicyFactory.cpp`), for the
|
||||
archive lives wherever the package is installed, outside what the sandbox opens.
|
||||
So a page that loads the files shows both the redirect (the declared files, not
|
||||
the build's) and the sandbox grant (the load works at all). Both are read here
|
||||
as the page reads them: the size of the image a page loads, from a page on
|
||||
127.0.0.1, on Linux and on Windows.
|
||||
|
||||
Negative control: the same page with the declaration pointed at another archive
|
||||
sees that archive's file, and the dimensions differ from the shipped retail
|
||||
set's, so a launch that ignored the declaration, or whose content process could
|
||||
not read it, fails here. (An undeclared archive with the engine on is refused
|
||||
at launch by the declaration gate, which the core's own tests hold: the browser
|
||||
does not start to be read.) The archive of the caller's own is the shipped
|
||||
`official` set with `about-logo.png` replaced by a 7x5 image.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
import zlib
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
#: An image no brand has: the declaration, not the build's file.
|
||||
_MINE = (7, 5)
|
||||
_FILE = "about-logo.png"
|
||||
|
||||
URLS = {
|
||||
"chrome": "chrome://branding/content/" + _FILE,
|
||||
}
|
||||
|
||||
LOAD = """async (urls) => {
|
||||
const out = {};
|
||||
for (const [way, url] of Object.entries(urls)) {
|
||||
out[way] = await new Promise(resolve => {
|
||||
const img = new Image();
|
||||
img.onload = () => resolve([img.naturalWidth, img.naturalHeight]);
|
||||
img.onerror = () => resolve('error');
|
||||
img.src = url;
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}"""
|
||||
|
||||
|
||||
def _png(width, height):
|
||||
def chunk(kind, data):
|
||||
body = kind + data
|
||||
return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF)
|
||||
rows = b"".join(b"\x00" + b"\xff\x00\x00\xff" * width for _ in range(height))
|
||||
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0))
|
||||
+ chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b""))
|
||||
|
||||
|
||||
def _size_in(archive):
|
||||
with zipfile.ZipFile(archive) as z:
|
||||
head = z.read(_FILE)[:24]
|
||||
return list(struct.unpack(">II", head[16:24]))
|
||||
|
||||
|
||||
def _own_archive(tmp_path):
|
||||
from invisible_core._fpforge.profile import branding_archive
|
||||
|
||||
with zipfile.ZipFile(branding_archive("official")) as z:
|
||||
entries = {n: z.read(n) for n in z.namelist()}
|
||||
entries[_FILE] = _png(*_MINE)
|
||||
path = tmp_path / "mine.zip"
|
||||
with zipfile.ZipFile(path, "w") as z:
|
||||
for name, data in entries.items():
|
||||
z.writestr(name, data)
|
||||
return path
|
||||
|
||||
|
||||
def _load(firefox_binary, url, pin):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, pin=pin) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(url)
|
||||
return page.evaluate(LOAD, URLS)
|
||||
|
||||
|
||||
def test_the_branding_a_page_loads_is_the_declared_archive(firefox_binary, fixture_server, tmp_path):
|
||||
from invisible_core._fpforge.profile import branding_archive
|
||||
|
||||
retail = _size_in(branding_archive("official"))
|
||||
assert retail != list(_MINE), retail
|
||||
shipped = _load(firefox_binary, fixture_server + "/from-network", None)
|
||||
assert shipped == {"chrome": retail}, (shipped, retail)
|
||||
|
||||
# Control: another declared archive is the one a page sees.
|
||||
own = _load(firefox_binary, fixture_server + "/from-network", {"branding": str(_own_archive(tmp_path))})
|
||||
assert own == {"chrome": list(_MINE)}, own
|
||||
assert own != shipped, (own, shipped)
|
||||
@@ -10,11 +10,27 @@ of its token field from an evaluate got the clearance refused on the reload,
|
||||
native one, every other name is the page's. These tests hold both halves on
|
||||
a page that counts every call to the APIs it wrapped, and the one change the
|
||||
rule declares.
|
||||
|
||||
Two more tests hold the ends of the rule (hooks `StealthHybridXray*` in
|
||||
`js/xpconnect/src` of the engine, folder `automation/hybrid-xrays` of the engine
|
||||
series):
|
||||
|
||||
* the control of the probe: the same lookups made from the PAGE's realm
|
||||
(`add_script_tag`) are counted, each one, so the zeros above are the caller's
|
||||
world and not a probe that cannot count;
|
||||
* what the caller hands the page from a cross-origin iframe (its window and its
|
||||
location, and from inside that iframe the `top` that is cross-origin to it)
|
||||
stays what the page would get for itself: a cross-origin object, whose
|
||||
properties throw `SecurityError` for what is not allowed and answer for what
|
||||
is (`CrossOriginObjectWrapper`), not a transparent wrapper that opens the
|
||||
other site to the page.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from _fission_frames import Sites, launch, new_page, wait_frame
|
||||
|
||||
PAGE = """<!doctype html><html><head><script>
|
||||
window.__calls = 0;
|
||||
function wrap(owner, name) {
|
||||
@@ -132,3 +148,90 @@ def test_what_the_caller_hands_the_page_has_the_pages_own_prototypes(page):
|
||||
f.constructor === Function,
|
||||
f.constructor('return globalThis')() === window];""")
|
||||
assert page.evaluate("() => probe([1, 2], () => 1)") == [True, True, True, True]
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_the_same_lookups_from_the_pages_realm_are_counted(page):
|
||||
"""The control of the probe: what the caller's world does not make the page count, the page's own realm does.
|
||||
|
||||
Each lookup the first test makes through `evaluate` (and its siblings) is made here by a script of the page
|
||||
(`add_script_tag` runs in the page's realm), one script each, and the counter must rise after every one: a
|
||||
counter that only ever read 0 would also pass the tests above."""
|
||||
assert _calls(page) == 0
|
||||
# the tag itself costs the page no counted call, so what rises below is the lookup
|
||||
page.add_script_tag(content=";")
|
||||
assert _calls(page) == 0
|
||||
lookups = [
|
||||
"document.querySelector('input[name=\"cf-turnstile-response\"]')",
|
||||
"document.querySelectorAll('input')",
|
||||
"document.getElementById('x')",
|
||||
"document.body.querySelector('#x')",
|
||||
"[1, 2].map(n => n)",
|
||||
"JSON.stringify({a: 1})",
|
||||
]
|
||||
seen = 0
|
||||
for code in lookups:
|
||||
page.add_script_tag(content=code + ";")
|
||||
now = _calls(page)
|
||||
assert now > seen, "the page's own %s was not counted (%d before, %d after)" % (code, seen, now)
|
||||
seen = now
|
||||
assert seen > 0
|
||||
|
||||
|
||||
#: The page's function that touches what it is handed, and says for each property whether it answered or what it threw.
|
||||
#: Defined by the page (in both documents), so a caller can only HAND it objects.
|
||||
CROSS_ORIGIN_PROBE = """
|
||||
window.crossProbe = (w, loc) => {
|
||||
const attempt = (f) => { try { f(); return 'ok'; } catch (e) { return 'throws ' + e.name; } };
|
||||
return {
|
||||
document: attempt(() => w.document),
|
||||
href: attempt(() => loc.href),
|
||||
closed: attempt(() => w.closed),
|
||||
top: attempt(() => w.top),
|
||||
frames: attempt(() => w.frames),
|
||||
replace: attempt(() => typeof loc.replace),
|
||||
};
|
||||
};
|
||||
"""
|
||||
|
||||
#: What a page gets from a cross-origin window and its location: the contents are refused, the few names the web
|
||||
#: platform allows across origins answer.
|
||||
CROSS_ORIGIN_ANSWERS = {"document": "throws SecurityError", "href": "throws SecurityError",
|
||||
"closed": "ok", "top": "ok", "frames": "ok", "replace": "ok"}
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_what_the_caller_hands_the_page_from_a_cross_origin_frame_stays_cross_origin(firefox_binary):
|
||||
"""A caller that holds the window and the location of a cross-origin iframe, and hands them to the page, gives it
|
||||
what the page would get for itself: `CrossOriginObjectWrapper`'s answers, from the page's side and from the frame's
|
||||
(where the cross-origin one is `window.top`)."""
|
||||
with Sites() as sites:
|
||||
sites.route("B", "/inner", "<!doctype html><script>%s</script><body>inner</body>" % CROSS_ORIGIN_PROBE)
|
||||
sites.route("A", "/", "<!doctype html><script>%s</script><iframe id=\"f\" src=\"%s\"></iframe>"
|
||||
% (CROSS_ORIGIN_PROBE, sites.url("B", "/inner")))
|
||||
with launch(firefox_binary) as browser:
|
||||
_context, page = new_page(browser)
|
||||
page.goto(sites.url("A", "/"))
|
||||
frame = wait_frame(page, sites.origin["B"], "/inner", seconds=30)
|
||||
|
||||
# from the page: what the page's own script gets for the cross-origin iframe is the control
|
||||
page.add_script_tag(content="""
|
||||
(() => {
|
||||
const w = document.getElementById('f').contentWindow;
|
||||
window.__own = crossProbe(w, w.location);
|
||||
})();""")
|
||||
own = page.evaluate("() => window.__own")
|
||||
assert own == CROSS_ORIGIN_ANSWERS, own
|
||||
# and the caller hands the page the same two objects
|
||||
handed = page.evaluate("""() => {
|
||||
const w = document.getElementById('f').contentWindow;
|
||||
return crossProbe(w, w.location);
|
||||
}""")
|
||||
assert handed == own, (handed, own)
|
||||
|
||||
# from inside the iframe: its `top` is the cross-origin one
|
||||
frame.add_script_tag(content="window.__own = crossProbe(window.top, window.top.location);")
|
||||
own_top = frame.evaluate("() => window.__own")
|
||||
assert own_top == CROSS_ORIGIN_ANSWERS, own_top
|
||||
handed_top = frame.evaluate("() => crossProbe(window.top, window.top.location)")
|
||||
assert handed_top == own_top, (handed_top, own_top)
|
||||
@@ -108,3 +108,83 @@ def test_the_engine_waits_the_declared_time_and_never_asks_the_host(firefox_bina
|
||||
declared = generate_profile(_SEED).hardware.media_enumeration_ms
|
||||
assert text.count("declared wait: %d ms" % declared) == 1, text[-2000:]
|
||||
assert "host speakers asked: yes" not in text, text[-2000:]
|
||||
|
||||
|
||||
# --- the two ways the declaration is told apart from its absence ------------
|
||||
# The engine's hook is the pref `zoom.stealth.media.enumeration_ms`: non-zero,
|
||||
# the speakers are not asked of the host (neither for the list nor for the
|
||||
# groupId correlation of a camera) and the first list waits the declared time;
|
||||
# 0, Firefox's own path. 0 is the negative control of both tests below.
|
||||
|
||||
#: A time no host has: the declaration, not a coincidence of the machine.
|
||||
_DECLARED_MS = 777
|
||||
|
||||
#: Camera only: the correlation of a camera's groupId with the speakers
|
||||
#: (MediaManager::EnumerateRawDevices) runs after a video stream was granted.
|
||||
CAMERA_ONLY = """async () => {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({video: true});
|
||||
const list = await navigator.mediaDevices.enumerateDevices();
|
||||
stream.getTracks().forEach(t => t.stop());
|
||||
return list.map(d => d.kind).join(',');
|
||||
}"""
|
||||
|
||||
|
||||
def _engine_log(firefox_binary, tmp_path, monkeypatch, name, script, enumeration_ms):
|
||||
"""Launch with the enumeration declared as `enumeration_ms` (0 = not
|
||||
declared), run `script` on a page of 127.0.0.1 and return the text the
|
||||
engine logged (MOZ_LOG=StealthMediaEnumeration) together with the result."""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
log = tmp_path / name
|
||||
monkeypatch.setenv("MOZ_LOG", "sync,StealthMediaEnumeration:4")
|
||||
monkeypatch.setenv("MOZ_LOG_FILE", str(log))
|
||||
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Page)
|
||||
srv.daemon_threads = True
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
try:
|
||||
with InvisiblePlaywright(
|
||||
seed=_SEED, binary_path=firefox_binary, headless=True,
|
||||
extra_prefs={"zoom.stealth.media.enumeration_ms": enumeration_ms,
|
||||
# getUserMedia without a prompt, as the fake devices are
|
||||
# asked for by a page of a test
|
||||
"media.navigator.permission.disabled": True}) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("http://127.0.0.1:%d/" % srv.server_address[1])
|
||||
result = page.evaluate(script)
|
||||
finally:
|
||||
srv.shutdown()
|
||||
text = "".join(open(f, encoding="utf-8", errors="replace").read()
|
||||
for f in glob.glob(str(log) + "*"))
|
||||
return text, result
|
||||
|
||||
|
||||
def test_the_enumeration_with_no_declaration_does_not_wait_and_asks_the_host(
|
||||
firefox_binary, tmp_path, monkeypatch):
|
||||
"""Negative control of the declared wait: the same seed and the same four
|
||||
calls with the declaration at 0 log no declared wait and ask the host's
|
||||
speakers; with it declared they log ONE wait and never ask them."""
|
||||
if _engine_release() < 57:
|
||||
pytest.skip("the engine logs the enumeration from firefox-57")
|
||||
declared, _ = _engine_log(firefox_binary, tmp_path, monkeypatch, "on", MEASURE, _DECLARED_MS)
|
||||
undeclared, rows = _engine_log(firefox_binary, tmp_path, monkeypatch, "off", MEASURE, 0)
|
||||
assert declared.count("declared wait: %d ms" % _DECLARED_MS) == 1, declared[-2000:]
|
||||
assert "host speakers asked: yes" not in declared, declared[-2000:]
|
||||
assert "declared wait" not in undeclared, undeclared[-2000:]
|
||||
assert "host speakers asked: yes" in undeclared, undeclared[-2000:]
|
||||
# The list is still a list of the session's devices without the declaration.
|
||||
assert len(rows) == 4 and all("audioinput" in k and "videoinput" in k for _t, k in rows), rows
|
||||
|
||||
|
||||
def test_the_camera_only_enumeration_never_asks_the_host_speakers(
|
||||
firefox_binary, tmp_path, monkeypatch):
|
||||
"""The path of the groupId correlation: a camera granted, then a list. With
|
||||
the enumeration declared the host's speakers are never asked; at 0 they
|
||||
are (the negative control: without the declaration the hook is the only
|
||||
difference)."""
|
||||
if _engine_release() < 57:
|
||||
pytest.skip("the engine logs the enumeration from firefox-57")
|
||||
declared, kinds = _engine_log(firefox_binary, tmp_path, monkeypatch, "on", CAMERA_ONLY, _DECLARED_MS)
|
||||
undeclared, _ = _engine_log(firefox_binary, tmp_path, monkeypatch, "off", CAMERA_ONLY, 0)
|
||||
assert "videoinput" in kinds, kinds
|
||||
assert "host speakers asked: yes" not in declared, declared[-2000:]
|
||||
assert "host speakers asked: yes" in undeclared, undeclared[-2000:]
|
||||
@@ -0,0 +1,292 @@
|
||||
"""Every e2e test of the wrapper is in exactly one row of the whole-e2e suite on each system, or is a named exclusion with its reason: nothing falls between.
|
||||
|
||||
The candidate's gate runs the e2e of the wrapper on the engine under test as rows of ``ci/required-suites.json``: ``wrapper.e2e.suite.linux.1`` to ``.3`` on Linux,
|
||||
``wrapper.e2e.suite.windows.1`` to ``.4`` on Windows, and ``wrapper.e2e.suite.windows.control_a`` (the keyboard shortcut, alone on its own runner). The judge takes
|
||||
files and node ids only, and a skipped test is red, so the partition is a list written by hand and this test is what keeps it whole. With no browser, from the
|
||||
collection of ``-m e2e``:
|
||||
|
||||
* every collected test is covered by exactly ONE row of each system (a file entry covers all its tests, a node entry covers the parameters of that test), unless it
|
||||
is excluded on that system, and an excluded test is covered by NO row: a file entry that would hold an excluded test is refused, its tests go by name;
|
||||
* every entry of a row is a file or a ``file::test`` of ``tests/`` that has a collected test, the entries are sorted and unique, and the minimum of the row
|
||||
is the number of tests it covers (the judge's rows are exact: a test added to a file moves the count here, by hand);
|
||||
* the exclusions are a named list, each with the system it holds for and the reason, and the list cannot grow without its count: the tests of the rows of
|
||||
``wrapper.e2e.udp.exit`` and ``wrapper.e2e.udp.sandbox`` (root, user namespaces: their own rows), the file of Linux that has no Windows counterpart, and the tests
|
||||
that skip on a system (a skip is red in the verdict, so a test that is for one system is not collected on the other: its row says so);
|
||||
* the Control+A row is that one file, which is also in a row of each system's partition.
|
||||
|
||||
The files of the round after the publication (``tests/_post_publication.py``) are not collected by ``-m e2e`` and are in no row.
|
||||
|
||||
Known-bad inputs: a new test that no row names, a test in two rows, an excluded test named by a file entry, an exclusion added without the count or without a
|
||||
reason or that matches nothing, a row that names a file with no collected test, a node entry with a parameter, a folder or an option, entries that are not sorted,
|
||||
a minimum that is not the count, a Control+A row that is not that file. The green case is the state of the repository.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
REQUIRED = ROOT / "ci" / "required-suites.json"
|
||||
MARKER = "e2e"
|
||||
|
||||
PARTITION = {
|
||||
"linux": ["wrapper.e2e.suite.linux.1", "wrapper.e2e.suite.linux.2", "wrapper.e2e.suite.linux.3"],
|
||||
"windows": ["wrapper.e2e.suite.windows.1", "wrapper.e2e.suite.windows.2", "wrapper.e2e.suite.windows.3", "wrapper.e2e.suite.windows.4"],
|
||||
}
|
||||
CONTROL_A_ROW = "wrapper.e2e.suite.windows.control_a"
|
||||
CONTROL_A_FILE = "tests/test_control_a_selects_all_in_a_field_e2e.py"
|
||||
|
||||
_BOTH = ("linux", "windows")
|
||||
#: What no row of the suite runs, by file or by ``file::test`` (every parameter of the test), the systems it holds for, and why. The skip reasons are the ones the
|
||||
#: junit of run 44942540063 carries.
|
||||
EXCLUDED = {
|
||||
"tests/test_a_proxy_that_cannot_carry_udp_leaks_nothing_direct_e2e.py":
|
||||
(_BOTH, "wrapper.e2e.udp.exit: the lab's exit is an address held on lo as root (Linux only), run in the root step"),
|
||||
"tests/test_the_whole_udp_chain_by_name_e2e.py::test_a_turn_srflx_by_name_arrives_through_the_relay_before_the_tick":
|
||||
(_BOTH, "wrapper.e2e.udp.exit: as root, with the exit of the lab on lo"),
|
||||
"tests/test_the_socket_process_is_sandboxed_e2e.py":
|
||||
(_BOTH, "wrapper.e2e.udp.sandbox: needs unprivileged user namespaces, which the runner refuses a normal user until its own step turns them on"),
|
||||
"tests/test_webrtc_realness.py::test_the_gather_is_real_without_a_proxy":
|
||||
(_BOTH, "wrapper.e2e.udp.sandbox: runs with the sandbox of the socket process, in its own row"),
|
||||
"tests/test_webrtc_realness.py::test_a_gateway_with_coherent_udp_gives_the_page_a_srflx_born_through_its_relay":
|
||||
(_BOTH, "wrapper.e2e.udp.sandbox: runs with the sandbox of the socket process, in its own row"),
|
||||
"tests/test_ice_names_by_the_context_proxy_e2e.py::test_a_gateway_without_udp_resolves_the_ice_name_then_ends_in_701":
|
||||
(_BOTH, "wrapper.e2e.udp.sandbox: runs with the sandbox of the socket process, in its own row"),
|
||||
"tests/test_juggler_injected.py::test_OUR_CLIENT_DOES_NOT_CROSS_into_the_page_realm":
|
||||
(_BOTH, "skips on every system: the trap page lives in the workbench, not in this checkout"),
|
||||
"tests/test_the_engine_is_born_in_the_job_e2e.py::test_when_the_client_is_killed_no_engine_process_is_left":
|
||||
(("linux",), "skips on Linux: the job object is Windows; Linux has no equivalent here"),
|
||||
"tests/test_hidden_desktop.py::test_hidden_desktop_takes_the_window_off_screen_but_keeps_rendering":
|
||||
(("linux",), "skips on Linux: the hidden desktop is the Windows path; Linux hides via Xvfb"),
|
||||
"tests/test_first_launch_from_a_new_path.py::test_the_first_launch_from_a_new_path_works":
|
||||
(("linux",), "skips on Linux: the launcher process exists only on Windows"),
|
||||
"tests/test_the_parent_reads_the_bundle_from_fontconfig_s_cache_linux_e2e.py":
|
||||
(("windows",), "wrapper.e2e.fontconfig is linux_only: fontconfig exists only on Linux (DirectWrite opens a font from its path)"),
|
||||
"tests/test_webgl_draws_on_the_engine_s_own_gl_e2e.py::test_webgl_draws_on_the_engine_s_own_gl":
|
||||
(("windows",), "skips on Windows: the engine's own GL is Linux's"),
|
||||
"tests/test_webgl_draws_on_the_engine_s_own_gl_e2e.py::test_every_declared_extension_answers_as_on_windows":
|
||||
(("windows",), "skips on Windows: the engine's own GL is Linux's"),
|
||||
"tests/test_hidden_display_linux.py::test_hidden_display_stays_with_its_session":
|
||||
(("windows",), "skips on Windows: Xvfb is the Linux path; Windows hides on a desktop"),
|
||||
"tests/test_juggler_posix_pipe.py::test_the_posix_pipe_carries_messages_both_ways":
|
||||
(("windows",), "skips on Windows: the POSIX leg does not execute there, the pipe travels as inheritable HANDLEs"),
|
||||
"tests/test_screenshot_of_text_returns_linux_e2e.py::test_a_screenshot_of_a_page_with_text_returns":
|
||||
(("windows",), "skips on Windows: the Linux text path"),
|
||||
}
|
||||
#: Changed by hand, together with the list above: an exclusion is a test the candidate does not run, and it may not be added in silence.
|
||||
EXCLUDED_COUNT = 16
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=None)
|
||||
def _collected():
|
||||
"""Every node id the marker collects, parameters included (the files of the round after the publication are left out by the conftest)."""
|
||||
done = subprocess.run([sys.executable, "-m", "pytest", "--collect-only", "-q", "-p", "no:cacheprovider", "-o", "addopts=", "-m", MARKER, "tests"],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=300)
|
||||
assert done.returncode == 0, "the collection failed: " + done.stdout[-1500:] + done.stderr[-500:]
|
||||
return frozenset(line.strip() for line in done.stdout.splitlines() if "::" in line)
|
||||
|
||||
|
||||
def _rows():
|
||||
by_id = {r["id"]: r for r in json.loads(REQUIRED.read_text(encoding="utf-8"))}
|
||||
ids = [i for ids in PARTITION.values() for i in ids] + [CONTROL_A_ROW]
|
||||
missing = [i for i in ids if i not in by_id]
|
||||
assert not missing, "rows missing from ci/required-suites.json: %s" % missing
|
||||
return {i: by_id[i] for i in ids}
|
||||
|
||||
|
||||
def _file(node):
|
||||
return node.split("::", 1)[0]
|
||||
|
||||
|
||||
def _base(node):
|
||||
"""``file::test`` of a node id, without the parameters."""
|
||||
return node.split("[", 1)[0]
|
||||
|
||||
|
||||
def _covers(entry, node):
|
||||
return _file(node) == entry if "::" not in entry else _base(node) == entry
|
||||
|
||||
|
||||
def _excluded(node, system, excluded):
|
||||
return any(system in systems and _covers(entry, node) for entry, (systems, _why) in excluded.items())
|
||||
|
||||
|
||||
def accounting_problems(collected, rows, partition, control_a_row, control_a_file, excluded, excluded_count):
|
||||
"""-> why the partition is not whole (empty if it is). ``rows`` is {id: row of the list}."""
|
||||
out = []
|
||||
for rid, row in rows.items():
|
||||
entries = row["tests"]
|
||||
for entry in entries:
|
||||
if not (entry.startswith("tests/") and entry.split("::", 1)[0].endswith(".py")) or entry.count("::") > 1 or "[" in entry:
|
||||
out.append("%s: %r is not a file of tests/ or a `file::test` with no parameter" % (rid, entry))
|
||||
elif not any(_covers(entry, n) for n in collected):
|
||||
out.append("%s: %s has no test collected by %r (it is not there, or nothing in it runs)" % (rid, entry, MARKER))
|
||||
if list(entries) != sorted(entries) or len(set(entries)) != len(entries):
|
||||
out.append("%s: the entries are not sorted and unique" % rid)
|
||||
if len(excluded) != excluded_count:
|
||||
out.append("the exclusions are %d and the count says %d: change the count together with the list, and say why in the list" % (len(excluded), excluded_count))
|
||||
for entry, (systems, why) in sorted(excluded.items()):
|
||||
if not why.strip():
|
||||
out.append("%s is excluded with no reason" % entry)
|
||||
if not systems or not set(systems) <= set(partition):
|
||||
out.append("%s is excluded for %r, which are not systems of the partition" % (entry, systems))
|
||||
if not any(_covers(entry, n) for n in collected):
|
||||
out.append("%s is excluded and nothing collected by %r matches it: take it out of the list" % (entry, MARKER))
|
||||
for system, ids in partition.items():
|
||||
for node in sorted(collected):
|
||||
named = [rid for rid in ids if any(_covers(e, node) for e in rows[rid]["tests"])]
|
||||
if _excluded(node, system, excluded):
|
||||
if named:
|
||||
out.append("%s is excluded on %s and %s names it: a file entry holds it, so its tests go by name" % (node, system, ", ".join(named)))
|
||||
elif not named:
|
||||
out.append("%s has a test no row of %s names (%s): add it to a row, or to the exclusions with its reason" % (_file(node), system, _base(node)))
|
||||
elif len(named) > 1:
|
||||
out.append("%s is in more than one row of %s: %s" % (node, system, ", ".join(named)))
|
||||
for rid in ids:
|
||||
held = sum(1 for n in collected if not _excluded(n, system, excluded) and any(_covers(e, n) for e in rows[rid]["tests"]))
|
||||
if rows[rid]["min_tests"] != held:
|
||||
out.append("%s: min_tests is %s and the row covers %d collected test(s)" % (rid, rows[rid]["min_tests"], held))
|
||||
row = rows[control_a_row]
|
||||
if row["tests"] != [control_a_file]:
|
||||
out.append("%s must be exactly %s, not %s" % (control_a_row, control_a_file, row["tests"]))
|
||||
else:
|
||||
held = sum(1 for n in collected if _file(n) == control_a_file)
|
||||
if row["min_tests"] != held:
|
||||
out.append("%s: min_tests is %s and the file has %d collected test(s)" % (control_a_row, row["min_tests"], held))
|
||||
for system, ids in partition.items():
|
||||
if not any(control_a_file in rows[rid]["tests"] for rid in ids):
|
||||
out.append("%s is in no whole-suite row of %s: the Control+A row is its twin, not its place" % (control_a_file, system))
|
||||
return out
|
||||
|
||||
|
||||
def _state(**over):
|
||||
state = dict(collected=_collected(), rows=_rows(), partition=PARTITION, control_a_row=CONTROL_A_ROW, control_a_file=CONTROL_A_FILE,
|
||||
excluded=EXCLUDED, excluded_count=EXCLUDED_COUNT)
|
||||
state.update(over)
|
||||
return state
|
||||
|
||||
|
||||
def test_every_e2e_test_is_in_one_row_of_each_system_or_is_a_named_exclusion():
|
||||
assert accounting_problems(**_state()) == []
|
||||
|
||||
|
||||
def test_the_rows_of_the_suite_are_exact_e2e_rows_on_their_own_system():
|
||||
for system, ids in PARTITION.items():
|
||||
for rid in ids:
|
||||
row = _rows()[rid]
|
||||
assert row["os"] == [system] and row["marker"] == MARKER and row["exact"] is True and row["giro"] == "G2", rid
|
||||
row = _rows()[CONTROL_A_ROW]
|
||||
assert row["os"] == ["windows"] and row["marker"] == MARKER and row["exact"] is True
|
||||
|
||||
|
||||
# --- known-bad inputs ------------------------------------------------------------------------------------------------------------------------
|
||||
_A, _B, _C, _D = "tests/test_a.py", "tests/test_b.py", "tests/test_c.py", "tests/test_ctl.py"
|
||||
_NODES = {_A + "::test_one", _A + "::test_two[x]", _A + "::test_two[y]", _B + "::test_one", _B + "::test_skip", _C + "::test_one", _D + "::test_one",
|
||||
_D + "::test_two"}
|
||||
_EXCLUDED = {_B + "::test_skip": (("linux",), "skips on Linux"), _C: (("windows",), "a file of Linux")}
|
||||
_PARTITION = {"linux": ["l.1", "l.2"], "windows": ["w.1", "w.2"]}
|
||||
|
||||
|
||||
def _row(entries, n, system):
|
||||
return {"os": [system], "marker": "e2e", "exact": True, "giro": "G2", "min_tests": n, "tests": entries}
|
||||
|
||||
|
||||
def _rows_fake(**over):
|
||||
rows = {"l.1": _row([_A, _B + "::test_one", _D], 6, "linux"), "l.2": _row([_C], 1, "linux"),
|
||||
"w.1": _row([_A, _D], 5, "windows"), "w.2": _row([_B], 2, "windows"), "ctl": _row([_D], 2, "windows")}
|
||||
rows.update(over)
|
||||
return rows
|
||||
|
||||
|
||||
def _fake(**over):
|
||||
state = dict(collected=_NODES, rows=_rows_fake(), partition=_PARTITION, control_a_row="ctl", control_a_file=_D, excluded=_EXCLUDED, excluded_count=2)
|
||||
state.update(over)
|
||||
return state
|
||||
|
||||
|
||||
def test_the_fake_state_is_green():
|
||||
assert accounting_problems(**_fake()) == []
|
||||
|
||||
|
||||
def test_a_new_test_that_no_row_names_is_red():
|
||||
found = accounting_problems(**_fake(collected=_NODES | {"tests/test_new.py::test_x"}))
|
||||
assert len(found) == 2 and all("tests/test_new.py has a test no row of" in f for f in found), found
|
||||
|
||||
|
||||
def test_a_new_test_in_a_file_a_row_names_by_node_is_red():
|
||||
found = accounting_problems(**_fake(collected=_NODES | {_B + "::test_added"}))
|
||||
assert any("tests/test_b.py has a test no row of linux names (tests/test_b.py::test_added)" in f for f in found), found
|
||||
|
||||
|
||||
def test_a_test_in_two_rows_of_one_system_is_red():
|
||||
found = accounting_problems(**_fake(rows=_rows_fake(**{"l.2": _row([_C, _A], 4, "linux")})))
|
||||
assert any("is in more than one row of linux: l.1, l.2" in f for f in found), found
|
||||
|
||||
|
||||
def test_an_excluded_test_that_a_file_entry_holds_is_red():
|
||||
found = accounting_problems(**_fake(rows=_rows_fake(**{"l.1": _row([_A, _B, _D], 6, "linux")})))
|
||||
assert any("tests/test_b.py::test_skip is excluded on linux and l.1 names it" in f for f in found), found
|
||||
|
||||
|
||||
def test_a_file_excluded_for_one_system_only_is_still_run_by_the_other_and_refused_where_it_is_excluded():
|
||||
assert accounting_problems(**_fake()) == [] and _C in _EXCLUDED and _C in _rows_fake()["l.2"]["tests"]
|
||||
found = accounting_problems(**_fake(rows=_rows_fake(**{"w.1": _row([_A, _C, _D], 6, "windows")})))
|
||||
assert any("tests/test_c.py::test_one is excluded on windows and w.1 names it" in f for f in found), found
|
||||
|
||||
|
||||
def test_an_exclusion_added_without_the_count_or_without_a_reason_or_matching_nothing_is_red():
|
||||
more = dict(_EXCLUDED, **{_A + "::test_one": (("linux", "windows"), "because")})
|
||||
found = accounting_problems(**_fake(excluded=more))
|
||||
assert any("the count says 2" in f for f in found), found
|
||||
assert accounting_problems(**_fake(excluded=dict(_EXCLUDED, **{_C: (("windows",), " ")}))) != []
|
||||
found = accounting_problems(**_fake(excluded=dict(_EXCLUDED, **{"tests/test_gone.py": (("linux",), "gone")}), excluded_count=3))
|
||||
assert any("tests/test_gone.py is excluded and nothing collected" in f for f in found), found
|
||||
found = accounting_problems(**_fake(excluded=dict(_EXCLUDED, **{_C: (("macos",), "x")})))
|
||||
assert any("not systems of the partition" in f for f in found), found
|
||||
|
||||
|
||||
def test_a_row_that_names_a_file_with_no_collected_test_is_red():
|
||||
found = accounting_problems(**_fake(rows=_rows_fake(**{"l.2": _row([_C, "tests/test_gone.py"], 1, "linux")})))
|
||||
assert any("tests/test_gone.py has no test collected" in f for f in found), found
|
||||
found = accounting_problems(**_fake(rows=_rows_fake(**{"l.2": _row([_C, _A + "::test_nothing"], 1, "linux")})))
|
||||
assert any("test_nothing has no test collected" in f for f in found), found
|
||||
|
||||
|
||||
def test_a_parameter_a_folder_or_an_option_is_red():
|
||||
for entry in ("tests", "tests/test_a.py::test_two[x]", "--deselect=tests/test_a.py::test_one", "-k", "tests/test_a.py::T::test_one::deeper"):
|
||||
found = accounting_problems(**_fake(rows=_rows_fake(**{"l.2": _row([_C, entry], 1, "linux")})))
|
||||
assert any("is not a file of tests/" in f for f in found), (entry, found)
|
||||
|
||||
|
||||
def test_entries_that_are_not_sorted_or_are_repeated_are_red():
|
||||
found = accounting_problems(**_fake(rows=_rows_fake(**{"l.1": _row([_D, _A, _B + "::test_one"], 6, "linux")})))
|
||||
assert found == ["l.1: the entries are not sorted and unique"], found
|
||||
found = accounting_problems(**_fake(rows=_rows_fake(**{"l.1": _row([_A, _A, _B + "::test_one", _D], 6, "linux")})))
|
||||
assert any("not sorted and unique" in f for f in found), found
|
||||
|
||||
|
||||
def test_a_minimum_that_is_not_the_count_is_red():
|
||||
found = accounting_problems(**_fake(rows=_rows_fake(**{"w.2": _row([_B], 3, "windows")})))
|
||||
assert found == ["w.2: min_tests is 3 and the row covers 2 collected test(s)"], found
|
||||
found = accounting_problems(**_fake(rows=_rows_fake(**{"w.1": _row([_A, _D], 4, "windows")})))
|
||||
assert found == ["w.1: min_tests is 4 and the row covers 5 collected test(s)"], found
|
||||
|
||||
|
||||
def test_a_control_a_row_that_is_not_that_file_or_a_file_in_no_partition_row_is_red():
|
||||
found = accounting_problems(**_fake(rows=_rows_fake(ctl=_row([_A], 3, "windows"))))
|
||||
assert any("ctl must be exactly tests/test_ctl.py" in f for f in found), found
|
||||
found = accounting_problems(**_fake(rows=_rows_fake(ctl=_row([_D], 3, "windows"))))
|
||||
assert found == ["ctl: min_tests is 3 and the file has 2 collected test(s)"], found
|
||||
# the Control+A file in another row of Windows is as good as in the first: what is refused is a Windows partition that does not hold it
|
||||
rows = _rows_fake(**{"w.1": _row([_A], 3, "windows"), "w.2": _row([_B, _D], 4, "windows")})
|
||||
assert accounting_problems(**_fake(rows=rows)) == []
|
||||
rows = _rows_fake(**{"w.1": _row([_A], 3, "windows")})
|
||||
found = accounting_problems(**_fake(rows=rows))
|
||||
assert any("has a test no row of windows names" in f for f in found), found
|
||||
@@ -0,0 +1,51 @@
|
||||
"""The code a client evaluates in the page is not named "debugger eval code".
|
||||
|
||||
Juggler's `Runtime.evaluate` runs the client's script through the debugger
|
||||
(`Debugger.Object.executeInGlobal`), and SpiderMonkey names such a script
|
||||
"debugger eval code" and gives it the introduction type "debugger eval". A page
|
||||
reads the name from `new Error().stack` on a call it made inside an evaluation
|
||||
of the client, and no retail Firefox has a frame with that name. The engine's
|
||||
hook (js/src/debugger, `fingerprint/js-surface/eval-name`) gives the default
|
||||
name "eval code" and the type "eval"; a name given by the caller still wins.
|
||||
|
||||
Negative control: a script that names itself (`//# sourceURL=`) is read back
|
||||
with the name it gave, untouched, next to the one the engine gives to a script
|
||||
that names nothing, so the default is the only name that changed. (A filename
|
||||
passed to `executeInGlobal` by a caller is not reachable from a page; the
|
||||
display URL is the name a caller can give.) Runs the same on Linux and Windows.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
_CALLER_NAME = "caller-named-script.js"
|
||||
|
||||
|
||||
def _stacks(firefox_binary):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank")
|
||||
return {
|
||||
"expression": page.evaluate("new Error().stack"),
|
||||
"function": page.evaluate("() => new Error().stack"),
|
||||
"named": page.evaluate("new Error().stack\n//# sourceURL=%s" % _CALLER_NAME),
|
||||
}
|
||||
|
||||
|
||||
def test_the_evaluated_code_has_no_debugger_name(firefox_binary):
|
||||
stacks = _stacks(firefox_binary)
|
||||
for how in ("expression", "function"):
|
||||
stack = stacks[how]
|
||||
assert "debugger eval" not in stack, (how, stack)
|
||||
# What the engine gives instead: the name retail gives to evaluated code.
|
||||
assert "eval code" in stack, (how, stack)
|
||||
# Control: the name the caller gave is the one read, and it replaces the
|
||||
# default one, which is therefore the only name the hook changes.
|
||||
assert _CALLER_NAME in stacks["named"], stacks["named"]
|
||||
assert "debugger eval" not in stacks["named"], stacks["named"]
|
||||
assert "eval code" not in stacks["named"], stacks["named"]
|
||||
assert _CALLER_NAME not in stacks["expression"], stacks["expression"]
|
||||
@@ -0,0 +1,104 @@
|
||||
"""The families a page can detect are those of the bundle and nothing else; no font of the host is in the list (e2e, every OS, firefox-68).
|
||||
|
||||
What the engine fixes. A page learns which fonts a machine has by asking for a family by name and seeing whether the text changes: the width of a
|
||||
string through ``"<family>", <generic>`` against the width through the generic alone. The font list of the engine is the manifest the core hands it
|
||||
(``zoom.stealth.fonts.manifest``, the text of ``bundle-fonts.list``: the families of the Windows fonts the package ships, plus the Windows font
|
||||
substitutes) and NOTHING of the host: DirectWrite, fontconfig and the registry substitutes are never enumerated
|
||||
(``gfxPlatformFontList::mStealthBundleOnly``, always true on firefox-68; folder ``fingerprint/fonts/font-list`` of the series, with
|
||||
``fingerprint/fonts/bundle`` for the files). So the detectable set is the same on every machine, and it is not the machine's.
|
||||
|
||||
What the test reads. One page probes a list of names with the width method (three generics as baselines: a family is detected when the text is a
|
||||
different width through it than through ANY of the generics) and returns the detected ones:
|
||||
|
||||
* every family of the bundle manifest and every Windows font-substitute name of it (``A|`` rows): the names the engine may answer to;
|
||||
* every family name of the host that the bundle does not know: read from the font files of this machine (``tests/_font_names.py``: the
|
||||
``name`` table of each file of the system's font folders, minus every name of the manifest and of the bundle's own files). Nothing is typed:
|
||||
on Linux these are DejaVu, Liberation, Noto and whatever the image holds, on Windows the fonts of the runner that the bundle does not carry.
|
||||
|
||||
The assertions: the detected names are all names of the bundle (no host family is among them); the host has such families at all (a host with
|
||||
none would make the test say nothing, so it fails); twenty families of the bundle every Windows has (Arial, Times New Roman, Consolas, Segoe UI,
|
||||
...; the test first checks that the manifest lists them) ARE detected, which is the proof that the probe can detect an installed font.
|
||||
|
||||
The negative control, in the same test. The same page runs again with the engine not declared (``zoom.stealth.fpp.hw_seed`` = 0, the pref the core
|
||||
uses to tell the engine to stay stock). On firefox-68 bundle-only does not depend on the engine being declared (the member is set unconditionally),
|
||||
so the control reads the same set: the test asserts that the two detected sets are equal, and that no host family is detected with either. The day
|
||||
the engine gives the host's fonts to a page when it is not declared, or the detectable set moves with the declaration, this test is red.
|
||||
|
||||
Not covered here: a family that has no Latin glyph (the emoji, symbol and icon fonts) cannot be told by the width of a Latin string; the assertions
|
||||
are about the host names being absent and the standard Latin families present, not about the whole bundle being detected.
|
||||
|
||||
Run: pytest tests/test_the_font_list_is_the_bundle_e2e.py -m e2e -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
import _font_names as fn
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
#: Families every retail Windows has, with Latin glyphs: the test checks that the manifest lists each of them.
|
||||
CORE = ["Arial", "Calibri", "Cambria", "Candara", "Comic Sans MS", "Consolas", "Constantia", "Corbel", "Courier New", "Georgia", "Impact",
|
||||
"Lucida Console", "Lucida Sans Unicode", "Microsoft Sans Serif", "Palatino Linotype", "Segoe UI", "Tahoma", "Times New Roman",
|
||||
"Trebuchet MS", "Verdana"]
|
||||
|
||||
TEXT = "mmmmmmmmmmlliWWW0Oq@ Hamburgefonstiv 0123456789"
|
||||
|
||||
#: The page: which of the names change the width of TEXT against each of three generics.
|
||||
PROBE = """(args) => {
|
||||
const [names, text] = args;
|
||||
const span = document.createElement('span');
|
||||
span.style.cssText = 'position:absolute;left:-9999px;top:0;white-space:pre;font-size:48px;font-style:normal;font-weight:400;';
|
||||
span.textContent = text;
|
||||
document.body.appendChild(span);
|
||||
const width = (family) => { span.style.fontFamily = family; return span.getBoundingClientRect().width; };
|
||||
const generics = ['monospace', 'sans-serif', 'serif'];
|
||||
const base = generics.map(width);
|
||||
const detected = names.filter(name => generics.some((g, i) => width('"' + name + '", ' + g) !== base[i]));
|
||||
span.remove();
|
||||
return detected;
|
||||
}"""
|
||||
|
||||
|
||||
def _detected(firefox_binary, names, engine_declared):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
prefs = {} if engine_declared else {"zoom.stealth.fpp.hw_seed": 0}
|
||||
with InvisiblePlaywright(seed=21, binary_path=firefox_binary, headless=True, extra_prefs=prefs) as browser:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto("about:blank", timeout=30_000)
|
||||
return set(page.evaluate(PROBE, [names, TEXT]))
|
||||
|
||||
|
||||
def test_the_font_list_is_the_bundle_and_nothing_else(firefox_binary):
|
||||
manifest = fn.bundle_manifest()
|
||||
missing = [family for family in CORE if family not in manifest.families]
|
||||
assert not missing, "the manifest of the core does not list %r: the families this test expects the bundle to hold are not its families" % missing
|
||||
|
||||
known = fn.bundle_file_names(manifest, firefox_binary)
|
||||
host_only = fn.host_only_families(manifest, extra_known=known)
|
||||
assert host_only, ("the host has no font family the bundle does not know: there is no name here that only the host can answer to, "
|
||||
"so the test could not tell a list of the host's fonts from the bundle")
|
||||
|
||||
allowed = set(manifest.families) | set(manifest.aliases)
|
||||
names = list(manifest.families) + sorted(manifest.aliases) + host_only
|
||||
|
||||
for declared in (True, False):
|
||||
mode = "engine declared" if declared else "engine not declared (hw_seed 0)"
|
||||
detected = _detected(firefox_binary, names, declared)
|
||||
host_seen = sorted(detected & set(host_only))
|
||||
assert not host_seen, (
|
||||
"%s: the page detects %d family name(s) of the host that the bundle does not have: %r (of %d host-only names probed). The font list is "
|
||||
"not the bundle" % (mode, len(host_seen), host_seen, len(host_only)))
|
||||
outside = sorted(detected - allowed)
|
||||
assert not outside, "%s: the page detects %r, which are neither a family nor a substitute name of the bundle" % (mode, outside)
|
||||
not_found = [family for family in CORE if family not in detected]
|
||||
assert not not_found, (
|
||||
"%s: the page does not detect %r, standard Windows families of the bundle: the probe cannot see an installed font here (detected "
|
||||
"%d of %d bundle names)" % (mode, not_found, len(detected), len(manifest.families) + len(manifest.aliases)))
|
||||
if declared:
|
||||
with_engine = detected
|
||||
else:
|
||||
assert detected == with_engine, (
|
||||
"the detectable set differs between the engine declared and not declared: only with the engine %r, only without %r"
|
||||
% (sorted(with_engine - detected), sorted(detected - with_engine)))
|
||||
@@ -0,0 +1,428 @@
|
||||
"""The proxies of the tests carry only the lab's destinations: any other is refused and recorded, never forwarded.
|
||||
|
||||
The e2e tests run in the gate of the candidate, where no test may depend on a real service. A proxy of the tests that relayed a CONNECT or a datagram for
|
||||
real would carry the background requests of the browser behind it (a name of the vendor, a captive-portal check, a telemetry endpoint) to the internet, and
|
||||
a verdict would then depend on whether the runner reaches them. What this holds, on the helpers themselves (no browser):
|
||||
|
||||
* :func:`_socks_servers.is_lab_destination`: loopback, the documentation ranges, the addresses of this host's own interfaces and ``localhost`` are the lab's;
|
||||
a public address, a name of the internet and a public IPv6 address are not (an IPv4-mapped one is judged as the IPv4 address it carries);
|
||||
* the base :class:`_socks_servers.Gateway` (and with it ``Gateway(tcp_from_exit=True)``): a CONNECT to a public address or to a name is answered with reply 2
|
||||
and never opened upstream, a CONNECT to a loopback server is carried; a datagram of the UDP relay to a public address or a name is dropped, one to a lab
|
||||
address is sent; each refusal is recorded (time since the gateway started, address type, destination as received, port, protocol ``tcp`` or ``udp``);
|
||||
* ``Socks5TcpOnly`` and the SOCKS5 server of ``test_proxy_socks_auth_e2e.py`` (``_Socks5AuthRecorder``) do the same for CONNECT;
|
||||
* the record is written, always, when the gateway is closed, under ``$RUNNER_TEMP/invpw-evidence/<gateway>/`` (the folder the e2e jobs upload), once even
|
||||
if the gateway is closed twice; off a runner (no ``RUNNER_TEMP``) nothing is written;
|
||||
* the gateway of ``test_ipv6_literal_connect_e2e.py``, which narrows the rule to the listener it carries to, still carries the mapped destination and refuses
|
||||
a loopback server that is not the one mapped.
|
||||
|
||||
Known-bad inputs: a CONNECT to ``8.8.8.8:443`` (a public address), to ``detectportal.firefox.com:80`` (a name) and to a public IPv6 address; a datagram to
|
||||
``8.8.8.8:443`` and to a name; each must be refused and recorded, and nothing must be opened or sent for it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import socket
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
import _socks_servers as servers
|
||||
from _socks_servers import Socks5TcpOnly, coherent, is_lab_destination
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
PUBLIC_V4 = "8.8.8.8"
|
||||
PUBLIC_V6 = "2606:4700:4700::1111"
|
||||
NAME = "detectportal.firefox.com"
|
||||
|
||||
#: Address types of a SOCKS5 request (RFC 1928).
|
||||
V4, NAMED, V6 = 1, 3, 4
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_own_addresses(monkeypatch):
|
||||
"""The addresses of this machine's interfaces are not a fact of the test (a runner may have a public one): none, unless a test names them."""
|
||||
monkeypatch.setattr(servers, "_own_addresses", lambda: set())
|
||||
|
||||
|
||||
def _address(host: str, atyp: int) -> bytes:
|
||||
if atyp == V4:
|
||||
return b"\x01" + socket.inet_aton(host)
|
||||
if atyp == V6:
|
||||
return b"\x04" + socket.inet_pton(socket.AF_INET6, host)
|
||||
return b"\x03" + bytes([len(host)]) + host.encode()
|
||||
|
||||
|
||||
def _connect(port: int, host: str, dport: int, atyp: int, credentials=None):
|
||||
"""A SOCKS5 CONNECT to ``port`` of 127.0.0.1: the connected socket and the reply code."""
|
||||
s = socket.create_connection(("127.0.0.1", port), timeout=10)
|
||||
if credentials is None:
|
||||
s.sendall(b"\x05\x01\x00")
|
||||
assert s.recv(2) == b"\x05\x00"
|
||||
else:
|
||||
user, password = (c.encode() for c in credentials)
|
||||
s.sendall(b"\x05\x01\x02")
|
||||
assert s.recv(2) == b"\x05\x02"
|
||||
s.sendall(b"\x01" + bytes([len(user)]) + user + bytes([len(password)]) + password)
|
||||
assert s.recv(2) == b"\x01\x00"
|
||||
s.sendall(b"\x05\x01\x00" + _address(host, atyp) + struct.pack("!H", dport))
|
||||
reply = b""
|
||||
while len(reply) < 10:
|
||||
chunk = s.recv(10 - len(reply))
|
||||
if not chunk:
|
||||
break
|
||||
reply += chunk
|
||||
return s, (reply[1] if len(reply) > 1 else None)
|
||||
|
||||
|
||||
class _Echo:
|
||||
"""A TCP echo server on 127.0.0.1: the lab's server."""
|
||||
|
||||
def __init__(self):
|
||||
self._listener = socket.socket()
|
||||
self._listener.bind(("127.0.0.1", 0))
|
||||
self._listener.listen(8)
|
||||
self.port = self._listener.getsockname()[1]
|
||||
threading.Thread(target=self._serve, daemon=True).start()
|
||||
|
||||
def _serve(self):
|
||||
while True:
|
||||
try:
|
||||
conn, _ = self._listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self._echo, args=(conn,), daemon=True).start()
|
||||
|
||||
@staticmethod
|
||||
def _echo(conn):
|
||||
try:
|
||||
data = conn.recv(4096)
|
||||
conn.sendall(data)
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def close(self):
|
||||
self._listener.close()
|
||||
|
||||
|
||||
def _the_echo_is_carried(port: int, echo_port: int, credentials=None) -> None:
|
||||
s, code = _connect(port, "127.0.0.1", echo_port, V4, credentials)
|
||||
try:
|
||||
assert code == 0, "a CONNECT to a loopback server was refused (reply %s)" % code
|
||||
s.sendall(b"ping")
|
||||
assert s.recv(4) == b"ping"
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
|
||||
def _fields(record: dict) -> tuple:
|
||||
return record["atyp"], record["destination"], record["port"], record["protocol"]
|
||||
|
||||
|
||||
# -- what is the lab's -----------------------------------------------------------------------------------------------------
|
||||
@pytest.mark.parametrize("host", [
|
||||
"127.0.0.1", "127.9.9.9", "::1", "::ffff:127.0.0.1", "[::1]", "198.51.100.9", "198.51.100.5", "203.0.113.80", "203.0.113.7", "192.0.2.1",
|
||||
"2001:db8::1", "[2001:db8::1]", "localhost", "LOCALHOST", "localhost.", "page.localhost",
|
||||
])
|
||||
def test_these_are_the_labs(host):
|
||||
assert is_lab_destination(host), host
|
||||
|
||||
|
||||
@pytest.mark.parametrize("host", [
|
||||
PUBLIC_V4, "1.1.1.1", PUBLIC_V6, "::ffff:8.8.8.8", "10.9.8.7", "192.168.1.20", "fe80::1", NAME, "api.ipify.org", "stun.l.google.com",
|
||||
"example.com", "page.test", "localhost.example.com", "",
|
||||
])
|
||||
def test_these_are_not_the_labs(host):
|
||||
assert not is_lab_destination(host), host
|
||||
|
||||
|
||||
def test_an_address_of_an_interface_of_this_host_is_the_labs_and_no_other_private_one(monkeypatch):
|
||||
monkeypatch.setattr(servers, "_own_addresses", lambda: {"10.9.8.7", "fd00::7"})
|
||||
assert is_lab_destination("10.9.8.7") and is_lab_destination("fd00::7") and is_lab_destination("::ffff:10.9.8.7")
|
||||
assert not is_lab_destination("10.9.8.8") and not is_lab_destination("fd00::8")
|
||||
|
||||
|
||||
# -- the TCP side of the base gateway --------------------------------------------------------------------------------------
|
||||
@pytest.mark.parametrize("host, atyp", [(PUBLIC_V4, V4), (NAME, NAMED), (PUBLIC_V6, V6)], ids=["public_ipv4", "name", "public_ipv6"])
|
||||
def test_a_connect_to_a_public_destination_is_refused_recorded_and_never_opened(host, atyp):
|
||||
with coherent() as gateway:
|
||||
opened = []
|
||||
gateway._open_upstream = lambda target: opened.append(target) or pytest.fail("the gateway opened a connection to %s" % (target,))
|
||||
s, code = _connect(gateway.port, host, 443, atyp)
|
||||
s.close()
|
||||
assert code == 2, "the reply to a CONNECT outside the lab is 2 (not allowed): %s" % code
|
||||
assert opened == []
|
||||
assert len(gateway.guard.records) == 1
|
||||
record = gateway.guard.records[0]
|
||||
assert _fields(record) == (atyp, host, 443, "tcp"), record
|
||||
assert record["t"] >= 0
|
||||
assert gateway.guard.refused("tcp") == [(host, 443)] and gateway.guard.refused("udp") == []
|
||||
assert (host, 443) in gateway.connects, "the CONNECT is still listed: the test sees what the browser asked for"
|
||||
|
||||
|
||||
def test_a_connect_to_a_loopback_server_is_carried_and_leaves_no_refusal():
|
||||
echo = _Echo()
|
||||
try:
|
||||
with coherent() as gateway:
|
||||
_the_echo_is_carried(gateway.port, echo.port)
|
||||
assert gateway.guard.records == []
|
||||
finally:
|
||||
echo.close()
|
||||
|
||||
|
||||
def test_a_gateway_with_credentials_refuses_the_same_way():
|
||||
with coherent(user="alice", password="s3cret") as gateway:
|
||||
s, code = _connect(gateway.port, PUBLIC_V4, 80, V4, ("alice", "s3cret"))
|
||||
s.close()
|
||||
assert code == 2 and gateway.guard.refused("tcp") == [(PUBLIC_V4, 80)]
|
||||
|
||||
|
||||
def test_a_gateway_that_leaves_from_its_exit_refuses_a_public_connect_too():
|
||||
"""``Gateway(tcp_from_exit=True)``: the connection of the gateway would leave from ``exit_host``; to a public address it is never made."""
|
||||
with servers.Gateway(udp="refuse", tcp_exit="203.0.113.7", udp_exit="203.0.113.7", exit_host="127.0.0.2", tcp_from_exit=True) as gateway:
|
||||
opened = []
|
||||
gateway._open_upstream = lambda target: opened.append(target) or pytest.fail("the gateway opened a connection to %s" % (target,))
|
||||
s, code = _connect(gateway.port, PUBLIC_V4, 443, V4)
|
||||
s.close()
|
||||
assert code == 2 and opened == [] and gateway.guard.refused("tcp") == [(PUBLIC_V4, 443)]
|
||||
echo = _Echo()
|
||||
try:
|
||||
with servers.Gateway(udp="refuse", tcp_exit="203.0.113.7", udp_exit="203.0.113.7", exit_host="127.0.0.2", tcp_from_exit=True) as gateway:
|
||||
_the_echo_is_carried(gateway.port, echo.port)
|
||||
assert gateway.guard.records == []
|
||||
finally:
|
||||
echo.close()
|
||||
|
||||
|
||||
def test_the_questions_the_gateway_answers_itself_are_not_refusals():
|
||||
"""The exit question (``api.ipify.org:80``) and the page of ``WEB_NAME`` are the lab's own answers, given before the rule."""
|
||||
with coherent() as gateway:
|
||||
s, code = _connect(gateway.port, "api.ipify.org", 80, NAMED)
|
||||
try:
|
||||
assert code == 0
|
||||
s.sendall(b"GET / HTTP/1.1\r\nHost: api.ipify.org\r\n\r\n")
|
||||
assert gateway.tcp_exit.encode() in s.recv(4096)
|
||||
finally:
|
||||
s.close()
|
||||
s, code = _connect(gateway.port, servers.WEB_NAME, 80, NAMED)
|
||||
s.close()
|
||||
assert code == 0 and gateway.guard.records == []
|
||||
|
||||
|
||||
# -- the UDP side of the base gateway --------------------------------------------------------------------------------------
|
||||
def _associate(gateway):
|
||||
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 _datagram(host: str, port: int, atyp: int, payload: bytes) -> bytes:
|
||||
return b"\x00\x00\x00" + _address(host, atyp) + struct.pack("!H", port) + payload
|
||||
|
||||
|
||||
def test_a_datagram_to_a_public_destination_is_dropped_recorded_and_never_sent_and_one_to_a_lab_address_is_sent():
|
||||
from _waits import wait_until
|
||||
|
||||
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
server.bind(("127.0.0.1", 0))
|
||||
server.settimeout(10)
|
||||
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
client.bind(("127.0.0.1", 0))
|
||||
with coherent() as gateway:
|
||||
sent = []
|
||||
carry = gateway._later
|
||||
gateway._later = lambda fn, what="a datagram": (sent.append(what), carry(fn, what))
|
||||
control, relay = _associate(gateway)
|
||||
try:
|
||||
client.sendto(_datagram(PUBLIC_V4, 443, V4, b"quic"), relay)
|
||||
client.sendto(_datagram(NAME, 443, NAMED, b"quic"), relay)
|
||||
client.sendto(_datagram(PUBLIC_V6, 443, V6, b"quic"), relay)
|
||||
# the control: the same relay carries a datagram to a lab address (this one is read by the server below)
|
||||
client.sendto(_datagram("127.0.0.1", server.getsockname()[1], V4, b"lab"), relay)
|
||||
data, _peer = server.recvfrom(4096)
|
||||
assert data == b"lab"
|
||||
wait_until(lambda: len(gateway.datagrams) >= 4, 30, lambda: time.sleep(0.01))
|
||||
assert len(sent) == 1 and sent[0].startswith("the datagram to 127.0.0.1:"), "only the lab's datagram was sent: %s" % sent
|
||||
assert [_fields(r) for r in gateway.guard.records] == [
|
||||
(V4, PUBLIC_V4, 443, "udp"), (NAMED, NAME, 443, "udp"), (V6, PUBLIC_V6, 443, "udp")]
|
||||
assert gateway.guard.refused("tcp") == []
|
||||
assert {(h, p) for h, p, _d in gateway.datagrams} >= {(PUBLIC_V4, 443), (NAME, 443)}, "the datagrams read are still listed"
|
||||
assert gateway.send_errors == []
|
||||
finally:
|
||||
control.close()
|
||||
client.close()
|
||||
server.close()
|
||||
|
||||
|
||||
def test_the_documentation_addresses_and_the_fake_stun_are_the_labs_on_the_relay():
|
||||
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
client.bind(("127.0.0.1", 0))
|
||||
client.settimeout(10)
|
||||
with coherent() as gateway:
|
||||
control, relay = _associate(gateway)
|
||||
try:
|
||||
request = b"\x00\x01\x00\x00\x21\x12\xa4\x42" + b"txid-of-12by"
|
||||
for number in (servers.STUN_NUMBER, servers.MEASURE_NUMBER):
|
||||
client.sendto(_datagram(number, servers.STUN_PORT, V4, request), relay)
|
||||
answer, _peer = client.recvfrom(4096)
|
||||
assert answer[10:12] == b"\x01\x01"
|
||||
client.sendto(_datagram(servers.STUN_NAME, servers.STUN_PORT, NAMED, request), relay)
|
||||
answer, _peer = client.recvfrom(4096)
|
||||
assert answer[10:12] == b"\x01\x01"
|
||||
assert gateway.guard.records == []
|
||||
finally:
|
||||
control.close()
|
||||
client.close()
|
||||
|
||||
|
||||
def test_forward_only_to_only_narrows():
|
||||
"""A host the test lists that is not the lab's is not forwarded either: the list never reopens the rule."""
|
||||
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
client.bind(("127.0.0.1", 0))
|
||||
with coherent() as gateway:
|
||||
gateway.forward_only_to = {PUBLIC_V4}
|
||||
sent = []
|
||||
carry = gateway._later
|
||||
gateway._later = lambda fn, what="a datagram": (sent.append(what), carry(fn, what))
|
||||
control, relay = _associate(gateway)
|
||||
try:
|
||||
from _waits import wait_until
|
||||
|
||||
client.sendto(_datagram(PUBLIC_V4, 443, V4, b"quic"), relay)
|
||||
wait_until(lambda: gateway.guard.records, 30, lambda: time.sleep(0.01))
|
||||
assert sent == [] and gateway.guard.refused("udp") == [(PUBLIC_V4, 443)]
|
||||
finally:
|
||||
control.close()
|
||||
client.close()
|
||||
|
||||
|
||||
# -- the other proxies -----------------------------------------------------------------------------------------------------
|
||||
def test_the_tcp_only_proxy_refuses_a_public_connect_and_carries_a_loopback_one():
|
||||
echo = _Echo()
|
||||
proxy = Socks5TcpOnly()
|
||||
try:
|
||||
for host, atyp in ((PUBLIC_V4, V4), (NAME, NAMED), (PUBLIC_V6, V6)):
|
||||
s, code = _connect(proxy.port, host, 443, atyp)
|
||||
s.close()
|
||||
assert code == 2, (host, code)
|
||||
assert [_fields(r) for r in proxy.guard.records] == [(V4, PUBLIC_V4, 443, "tcp"), (NAMED, NAME, 443, "tcp"), (V6, PUBLIC_V6, 443, "tcp")]
|
||||
_the_echo_is_carried(proxy.port, echo.port)
|
||||
assert len(proxy.guard.records) == 3
|
||||
finally:
|
||||
proxy.close()
|
||||
echo.close()
|
||||
|
||||
|
||||
def test_the_proxy_that_asks_for_the_exit_still_fails_the_test_that_asked_the_world():
|
||||
"""The question of the exit keeps its own backstop (``asks_the_world``) ahead of the rule, so a proxy that forgot to declare its exit is a red with its name."""
|
||||
proxy = Socks5TcpOnly()
|
||||
try:
|
||||
s, code = _connect(proxy.port, "api.ipify.org", 443, NAMED)
|
||||
s.close()
|
||||
assert code == 2 and len(servers.nobody_asked_the_world()) == 1
|
||||
assert proxy.guard.records == [], "the question of the exit is the backstop's, not a destination the rule refused"
|
||||
finally:
|
||||
proxy.close()
|
||||
|
||||
|
||||
def test_the_socks5_server_with_authentication_refuses_a_public_connect_and_carries_a_loopback_one():
|
||||
from test_proxy_socks_auth_e2e import _USER, _PASS, _Socks5AuthRecorder
|
||||
|
||||
echo = _Echo()
|
||||
proxy = _Socks5AuthRecorder()
|
||||
try:
|
||||
s, code = _connect(proxy.port, PUBLIC_V4, 443, V4, (_USER, _PASS))
|
||||
s.close()
|
||||
assert code == 2
|
||||
s, code = _connect(proxy.port, NAME, 80, NAMED, (_USER, _PASS))
|
||||
s.close()
|
||||
assert code == 2
|
||||
assert [_fields(r) for r in proxy.guard.records] == [(V4, PUBLIC_V4, 443, "tcp"), (NAMED, NAME, 80, "tcp")]
|
||||
_the_echo_is_carried(proxy.port, echo.port, (_USER, _PASS))
|
||||
assert len(proxy.guard.records) == 2 and (_USER, _PASS) in proxy.seen_creds
|
||||
finally:
|
||||
proxy.close()
|
||||
echo.close()
|
||||
|
||||
|
||||
def test_the_doh_gateway_records_what_it_refuses_and_its_relay_is_the_labs_only():
|
||||
from _doh_servers import DohGateway, FakeDoh
|
||||
|
||||
with FakeDoh({}) as doh, DohGateway("gw", doh, udp="relay") as gateway:
|
||||
s, code = _connect(gateway.port, PUBLIC_V4, 443, V4)
|
||||
s.close()
|
||||
assert code == 2 and gateway.refused == [(PUBLIC_V4, 443)]
|
||||
assert [_fields(r) for r in gateway.guard.records] == [(V4, PUBLIC_V4, 443, "tcp")]
|
||||
|
||||
|
||||
def test_the_gateway_of_the_ipv6_literal_test_carries_only_what_it_maps():
|
||||
from test_ipv6_literal_connect_e2e import DOCUMENTATION, _GatewayToALocalListener, _Listener
|
||||
|
||||
with _Listener() as listener:
|
||||
gateway = _GatewayToALocalListener({(DOCUMENTATION, 80): ("127.0.0.1", listener.port)})
|
||||
try:
|
||||
s, code = _connect(gateway.port, DOCUMENTATION, 80, V6)
|
||||
try:
|
||||
assert code == 0, "the mapped destination was not carried"
|
||||
s.sendall(b"GET / HTTP/1.1\r\n\r\n")
|
||||
assert s.recv(4096).startswith(b"HTTP/1.1 200")
|
||||
finally:
|
||||
s.close()
|
||||
s, code = _connect(gateway.port, "127.0.0.1", listener.port ^ 1, V4) # loopback, but not the listener it maps to
|
||||
s.close()
|
||||
assert code == 2
|
||||
s, code = _connect(gateway.port, PUBLIC_V4, 443, V4)
|
||||
s.close()
|
||||
assert code == 2
|
||||
assert gateway.refused == [("127.0.0.1", listener.port ^ 1), (PUBLIC_V4, 443)]
|
||||
assert gateway.documentation_connects() == [(DOCUMENTATION, 80, V6)]
|
||||
assert [r["outcome"] for r in gateway.records] == [
|
||||
"carried to the listener of the lab", "refused", "refused"]
|
||||
finally:
|
||||
gateway.close()
|
||||
|
||||
|
||||
# -- the record ------------------------------------------------------------------------------------------------------------
|
||||
def test_the_record_is_written_when_the_gateway_is_closed_under_the_evidence_folder_and_once(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("RUNNER_TEMP", str(tmp_path))
|
||||
gateway = coherent()
|
||||
s, code = _connect(gateway.port, NAME, 80, NAMED)
|
||||
s.close()
|
||||
assert code == 2
|
||||
gateway.close()
|
||||
gateway.close()
|
||||
files = sorted((tmp_path / "invpw-evidence").rglob("*.json"))
|
||||
assert len(files) == 1, files
|
||||
assert files[0].parent.parent.name == "socks5-gateway" and files[0].name == "refused-destinations.json"
|
||||
written = json.loads(files[0].read_text(encoding="utf-8"))
|
||||
assert written["gateway"] == "socks5-gateway"
|
||||
assert [_fields(r) for r in written["refused"]] == [(NAMED, NAME, 80, "tcp")] and written["refused"][0]["t"] >= 0
|
||||
|
||||
|
||||
def test_a_gateway_that_refused_nothing_still_leaves_its_record(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("RUNNER_TEMP", str(tmp_path))
|
||||
proxy = Socks5TcpOnly()
|
||||
proxy.close()
|
||||
files = sorted((tmp_path / "invpw-evidence" / "socks5-tcp-only").rglob("refused-destinations.json"))
|
||||
assert len(files) == 1 and json.loads(files[0].read_text(encoding="utf-8"))["refused"] == []
|
||||
|
||||
|
||||
def test_off_a_runner_nothing_is_written(tmp_path, monkeypatch):
|
||||
monkeypatch.delenv("RUNNER_TEMP", raising=False)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
gateway = coherent()
|
||||
s, _code = _connect(gateway.port, NAME, 80, NAMED)
|
||||
s.close()
|
||||
gateway.close()
|
||||
assert list(tmp_path.rglob("*")) == []
|
||||
assert servers.LabGuard("x").write_evidence() is None
|
||||
@@ -0,0 +1,256 @@
|
||||
"""The launch counter is ONE plain GET to the address the engine carries, sent by the browser when it starts, before any page exists (firefox-68, Linux and Windows).
|
||||
|
||||
What it fixes, in the published engine (firefox-68), for the hooks of `platform/launch-counter` (`browser/components/BrowserGlue.sys.mjs`: the hook in
|
||||
`_beforeUIStartup`, which loads `StealthLaunchCounter.sys.mjs`): at start the parent process does `fetch(<counter address>, {method: "GET",
|
||||
credentials: "omit", cache: "no-store"})` once and swallows the errors. The counter is mandatory (no pref turns it off or moves it: the core refuses both)
|
||||
and it is part of the product, so a hook that is lost passes every test that never starts a browser and looks: the node test calls `fire()` directly. This
|
||||
is the test that starts the browser and counts what leaves.
|
||||
|
||||
How it observes a request to a host of the internet without a network. The browser is given an HTTP proxy of the test (the road of the browser's own
|
||||
requests: the counter is made by the parent, in no page). The proxy answers the `CONNECT` to the counter's host and terminates TLS with a leaf of a
|
||||
lab CA that the profile trusts (the CA is added to the profile with the engine's own xpcshell, `_lab_pki.add_ca_to_profile`), so it reads the GET itself:
|
||||
its method, its headers, its order. Every other request through the proxy is refused and recorded. Nothing leaves the machine. The address is read from the
|
||||
module the binary runs (`resource:///modules/StealthLaunchCounter.sys.mjs`, in the `browser/omni.ja` next to the executable): in core 68.80.0
|
||||
the core declares no counter address (no pref, no `USAGE_PING_URL`), the engine carries one constant, the same in every binary, and the test follows
|
||||
that constant in the binary under test, it does not copy it.
|
||||
|
||||
What the test asserts:
|
||||
* the GET arrives while NO page exists (the test waits for it before it opens a page, and the page server has received nothing at that moment);
|
||||
* it is a GET with no `Cookie`, `Authorization`, `Referer` or `Origin` (no credentials, nothing of a page) and it asks not to be cached (`Cache-Control:
|
||||
no-cache`, which is what `cache: "no-store"` sends);
|
||||
* once a page has been loaded and has made its own request to the same address, the proxy has seen exactly two GETs to it: the counter's and the page's.
|
||||
|
||||
Negative control: that page request. It goes through the same proxy to the same address, and the test tells it from the counter's by its `Referer`
|
||||
(a request of a page carries it, the counter's has none), so the count of two shows the proxy sees a page's request and that the counter's is not one
|
||||
of them, and a launch that sent the counter twice, or from the page, is red.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import itertools
|
||||
import re
|
||||
import socket
|
||||
import ssl
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import pytest
|
||||
|
||||
from invisible_core.jar import open_jar
|
||||
|
||||
from _lab_egress import LAB_EGRESS_IP
|
||||
from _lab_pki import LabCa, add_ca_to_profile
|
||||
from _servers import LocalServer
|
||||
from _socks_servers import declare_exit, forget_exit
|
||||
from _waits import wait_until
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
PAGE = b"<!doctype html><html><head><meta charset=utf-8><title>counter</title></head><body><p>page</p></body></html>"
|
||||
|
||||
|
||||
class Order:
|
||||
"""One order for what the two servers hear: the number of each request, across both."""
|
||||
|
||||
def __init__(self):
|
||||
self._numbers = itertools.count(1)
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def next(self):
|
||||
with self._lock:
|
||||
return next(self._numbers)
|
||||
|
||||
|
||||
class CounterProxy:
|
||||
"""An HTTP proxy on 127.0.0.1 that stands in for the counter's host: it terminates TLS for it and records the requests it reads there."""
|
||||
|
||||
def __init__(self, host, port, leaf, key, order):
|
||||
self.host, self.port, self.order = host, port, order
|
||||
self.gets = [] # every request read inside TLS for the counter's host, in order
|
||||
self.other = [] # every CONNECT or request for anything else: refused
|
||||
self.handshakes = []
|
||||
self._lock = threading.Lock()
|
||||
self._tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
self._tls.load_cert_chain(str(leaf), str(key))
|
||||
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))
|
||||
self._listener.listen(32)
|
||||
self.server = "http://127.0.0.1:%d" % self._listener.getsockname()[1]
|
||||
self._closed = False
|
||||
threading.Thread(target=self._accept, daemon=True).start()
|
||||
|
||||
def close(self):
|
||||
self._closed = True
|
||||
try:
|
||||
self._listener.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _accept(self):
|
||||
while not self._closed:
|
||||
try:
|
||||
conn, _ = self._listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self._handle, args=(conn,), daemon=True).start()
|
||||
|
||||
@staticmethod
|
||||
def _read_head(sock):
|
||||
data = b""
|
||||
while b"\r\n\r\n" not in data:
|
||||
chunk = sock.recv(65536)
|
||||
if not chunk:
|
||||
return None
|
||||
data += chunk
|
||||
return data.split(b"\r\n\r\n", 1)[0].decode("latin-1")
|
||||
|
||||
@staticmethod
|
||||
def _parse(head):
|
||||
lines = head.split("\r\n")
|
||||
method, target = lines[0].split(" ")[:2]
|
||||
headers = {}
|
||||
for line in lines[1:]:
|
||||
name, _, value = line.partition(":")
|
||||
headers[name.strip().lower()] = value.strip()
|
||||
return method, target, headers
|
||||
|
||||
def _handle(self, conn):
|
||||
try:
|
||||
conn.settimeout(30)
|
||||
head = self._read_head(conn)
|
||||
if head is None:
|
||||
return
|
||||
method, target, _headers = self._parse(head)
|
||||
if method == "CONNECT" and target == "%s:%d" % (self.host, self.port):
|
||||
conn.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
||||
self._serve_tls(conn)
|
||||
else:
|
||||
with self._lock:
|
||||
self.other.append("%s %s" % (method, target))
|
||||
conn.sendall(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
|
||||
except (OSError, ssl.SSLError, ValueError):
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
conn.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _serve_tls(self, conn):
|
||||
try:
|
||||
tls = self._tls.wrap_socket(conn, server_side=True)
|
||||
except (ssl.SSLError, OSError) as failure:
|
||||
with self._lock:
|
||||
self.handshakes.append("failed: %s" % failure)
|
||||
return
|
||||
with self._lock:
|
||||
self.handshakes.append("ok")
|
||||
head = self._read_head(tls)
|
||||
if head is None: # a speculative connection that never sends a request
|
||||
return
|
||||
method, target, headers = self._parse(head)
|
||||
with self._lock:
|
||||
self.gets.append({"order": self.order.next(), "method": method, "target": target, "headers": headers})
|
||||
body = b"ping\n"
|
||||
tls.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s" % (len(body), body))
|
||||
|
||||
def seen(self):
|
||||
with self._lock:
|
||||
return list(self.gets)
|
||||
|
||||
|
||||
class PageServer:
|
||||
"""The page of the test, on 127.0.0.1; records the order of every request it gets."""
|
||||
|
||||
def __init__(self, order):
|
||||
import http.server
|
||||
|
||||
self.requests = []
|
||||
requests = self.requests
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
timeout = 5
|
||||
|
||||
def do_GET(self):
|
||||
requests.append((order.next(), self.path))
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(PAGE)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(PAGE)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
self._server = LocalServer(("127.0.0.1", 0), Handler)
|
||||
self.url = "http://127.0.0.1:%d/" % self._server.server_address[1]
|
||||
threading.Thread(target=self._server.serve_forever, daemon=True).start()
|
||||
|
||||
def close(self):
|
||||
self._server.shutdown()
|
||||
self._server.server_close()
|
||||
|
||||
|
||||
def counter_address(firefox_binary):
|
||||
"""The address the engine's launch counter fetches, read from the module the browser runs (the one constant of
|
||||
`StealthLaunchCounter.sys.mjs`, inside `browser/omni.ja` beside the executable), with the core's jar reader."""
|
||||
omni = Path(firefox_binary).resolve().parent / "browser" / "omni.ja"
|
||||
# The core's own reader (`invisible_core.jar`): the omni.ja of a PGO build is Mozilla's optimized jar, which zipfile refuses.
|
||||
source = open_jar(omni).read("modules/StealthLaunchCounter.sys.mjs").decode("utf-8")
|
||||
found = re.findall(r'USAGE_PING_URL\s*=\s*"([^"]+)"', source)
|
||||
assert len(found) == 1, "the counter module of %s declares %d addresses: %s" % (omni, len(found), found)
|
||||
return found[0]
|
||||
|
||||
|
||||
def test_the_browser_sends_one_plain_get_to_the_counter_before_any_page(firefox_binary, tmp_path):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
USAGE_PING_URL = counter_address(firefox_binary)
|
||||
|
||||
counter = urlsplit(USAGE_PING_URL)
|
||||
assert counter.scheme == "https" and counter.hostname, USAGE_PING_URL
|
||||
port = counter.port or 443
|
||||
|
||||
order = Order()
|
||||
ca = LabCa(tmp_path)
|
||||
leaf, key = ca.leaf("counter", [counter.hostname], [], None)
|
||||
profile = tmp_path / "profile"
|
||||
for line in add_ca_to_profile(firefox_binary, profile, ca.ca_b64, tmp_path / "xpcshell"):
|
||||
print("LAB-CA %s" % line)
|
||||
proxy = CounterProxy(counter.hostname, port, leaf, key, order)
|
||||
pages = PageServer(order)
|
||||
stop = threading.Event()
|
||||
declare_exit(proxy.server, LAB_EGRESS_IP) # the proxy says where it leaves from: no request of the exit goes to the internet
|
||||
try:
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True, humanize=False,
|
||||
profile_dir=profile, proxy={"server": proxy.server}) as context:
|
||||
# Before any page: the counter arrives with no page of ours open, and the page server has heard nothing.
|
||||
arrived = wait_until(lambda: proxy.seen(), 120, lambda: stop.wait(0.25))
|
||||
at_that_moment = list(pages.requests)
|
||||
detail = ("handshakes %s; refused through the proxy: %s" % (proxy.handshakes[:6], proxy.other[:12]))
|
||||
assert arrived, "the browser sent no request to the counter's address %s after it started. %s" % (USAGE_PING_URL, detail)
|
||||
assert at_that_moment == [], "a page request had been made when the counter arrived: %s" % (at_that_moment,)
|
||||
first = proxy.seen()[0]
|
||||
|
||||
# The control: a page of ours makes its own request to the same address, through the same proxy.
|
||||
page = context.new_page()
|
||||
page.goto(pages.url, wait_until="load", timeout=60_000)
|
||||
page.evaluate("(u) => fetch(u, {mode: 'no-cors'}).then(() => 'done', () => 'failed')", USAGE_PING_URL)
|
||||
both = wait_until(lambda: len(proxy.seen()) >= 2, 60, lambda: stop.wait(0.25))
|
||||
gets = proxy.seen()
|
||||
finally:
|
||||
forget_exit(proxy.server)
|
||||
proxy.close()
|
||||
pages.close()
|
||||
|
||||
assert both, "the request of the page to the counter's address never reached the proxy: the sink would be blind to a second request. %s" % (detail,)
|
||||
assert len(gets) == 2, "expected the counter's GET and the page's, got %d: %s" % (len(gets), [(g["method"], g["target"]) for g in gets])
|
||||
assert gets[0] == first
|
||||
assert first["method"] == "GET" and first["target"] == counter.path + (("?" + counter.query) if counter.query else ""), first
|
||||
for forbidden in ("cookie", "authorization", "proxy-authorization", "referer", "origin"):
|
||||
assert forbidden not in first["headers"], "the counter's GET carries %s: %s" % (forbidden, first["headers"])
|
||||
assert "no-cache" in first["headers"].get("cache-control", "").lower(), first["headers"]
|
||||
# The page's own request is told apart by what only a page's request has.
|
||||
assert gets[1]["headers"].get("referer", "").startswith(pages.url[:-1]), gets[1]["headers"]
|
||||
@@ -1,7 +1,9 @@
|
||||
"""The helpers the e2e tests reach Marionette with, without a browser.
|
||||
|
||||
A browser's Marionette port is chosen per launch and never fixed: three e2e files shared 28431 and run on different xdist workers at
|
||||
once. And a connection that fails says what the engine says about its Marionette (e2e Windows part 2, run 43704738537: a refused
|
||||
A browser's Marionette port is chosen by the browser, never fixed and never freed for it to take: three e2e files shared 28431 and run on
|
||||
different xdist workers at once, and a port that was free when it was asked for can be taken by a neighbour before the browser binds it. The
|
||||
browser is launched with port 0 and the port it got is read from `<profile>/MarionetteActivePort`. And a connection that fails says what
|
||||
the engine says about its Marionette (e2e Windows part 2, run 43704738537: a refused
|
||||
connection for 120 s and nothing else to read)."""
|
||||
import pathlib
|
||||
import re
|
||||
@@ -12,17 +14,27 @@ import webfont_probe
|
||||
TESTS = pathlib.Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def test_a_marionette_port_is_free_when_it_is_given():
|
||||
port = webfont_probe.marionette_port()
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
|
||||
probe.bind(("127.0.0.1", port))
|
||||
def test_the_port_a_browser_got_is_read_from_its_profile(tmp_path):
|
||||
(tmp_path / "MarionetteActivePort").write_text("43117" + chr(10), encoding="utf-8")
|
||||
assert webfont_probe.marionette_active_port(tmp_path, timeout=5) == 43117
|
||||
|
||||
|
||||
def test_a_profile_without_the_active_port_says_what_the_engine_says(tmp_path):
|
||||
try:
|
||||
webfont_probe.marionette_active_port(tmp_path, timeout=0)
|
||||
except OSError as failure:
|
||||
text = str(failure)
|
||||
else:
|
||||
raise AssertionError("a profile with no MarionetteActivePort gave a port")
|
||||
assert "never wrote MarionetteActivePort" in text, text
|
||||
assert "no engine process below this one" in text, text
|
||||
|
||||
|
||||
def test_no_test_gives_a_browser_a_fixed_marionette_port():
|
||||
fixed = []
|
||||
for path in TESTS.glob("*.py"):
|
||||
for n, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
|
||||
if re.search(r"""["']marionette\.port["']\s*:\s*\d""", line) or re.search(r"^MARIONETTE_PORT\s*=\s*\d", line):
|
||||
if re.search(r"""["']marionette\.port["']\s*:\s*[1-9]""", line) or re.search(r"^MARIONETTE_PORT\s*=\s*\d", line):
|
||||
fixed.append("%s:%d" % (path.name, n))
|
||||
assert not fixed, "a fixed Marionette port: %s" % fixed
|
||||
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
"""The telemetry ping sent at shutdown is sent by the engine's own background task, `firefox --backgroundtask pingsender` (firefox-68, Linux and Windows).
|
||||
|
||||
What it fixes, in the published engine (firefox-68), for the hooks of `stillborn/telemetry` (`toolkit/components/telemetry/app/TelemetrySend.sys.mjs`,
|
||||
`pings/BackgroundTask_pingsender.sys.mjs`, the own files `StealthPingsender.sys.mjs` and `StealthPingsenderRoute.sys.mjs`): the shutdown ping
|
||||
never goes through `pingsender[.exe]` (a separate program that takes its road from the host: WinINet's proxy settings on Windows, libcurl's
|
||||
environment on Linux) but through the engine itself, with necko, by the road of the session. A server that receives a ping sees who sent it: the
|
||||
background task is the one whose request says `User-Agent: pingsender/2.0`. The program of the host says another one, and a ping that
|
||||
left from the host's own address says where the browser is. The server of telemetry is a pref (`toolkit.telemetry.server`), so the test points it at a
|
||||
server of its own on 127.0.0.1: nothing leaves the machine.
|
||||
|
||||
The address the test gives the session is `http://localhost:<port>`, and that is part of what the engine does: the background task keeps the allowlist the
|
||||
standalone pingsender had (`ALLOWED_ENDPOINTS` in `BackgroundTask_pingsender.sys.mjs`: `localhost` and `incoming.telemetry.mozilla.org`), so a ping addressed to
|
||||
any other host, `127.0.0.1` included, is refused by the task before a request is made and the ping stays on disk.
|
||||
|
||||
What the test does. A session (seed 42, no proxy; the road of the session is decided by the launch) with the telemetry server pref at the fake endpoint
|
||||
is opened and closed. The session ENDS (`_session_end.EndingPlaywright`: the reaper has finished, so the sender is finished or ended), then the test
|
||||
reads what the endpoint received.
|
||||
|
||||
The grace is the product's own (invisible-core, `juggler/_profile.SENDER_GRACE`, 10 s), not one of the test. `Connection.close` returns when the browser
|
||||
has exited (the sender is left running: `process.outlives_the_browser`) and starts the launch's reaper, `process.Reaper(tree, grace=SENDER_GRACE)`; from
|
||||
there the reaper waits up to the grace for the tree to empty by itself, then ends what is left (the process group: SIGTERM, SIGKILL 5 s later; on
|
||||
Windows the launch's job) and removes the session's profile. A sender still running at the end of the grace is killed and its ping is lost with the
|
||||
profile: a user's close does the same. The sender is started by the browser during its own shutdown, so the grace counts what is left of its run
|
||||
after the browser has gone (measured by the core: 0.6 s on Linux, 1.0 s on Windows). So the ping is asserted where the product puts it: on the
|
||||
endpoint when the session has ended, with no wait of the test after it. The endpoint records a request before it answers, and the sender ends only
|
||||
after the answer, so a ping that the sender delivered is on the record by then.
|
||||
|
||||
What it asserts:
|
||||
* at least one request reached the endpoint with `User-Agent: pingsender/2.0`, a POST to a path of the telemetry protocol (`/submit/telemetry/...`),
|
||||
with a body;
|
||||
* a second endpoint that the session was NOT pointed at received nothing (the pref is the address, there is no other).
|
||||
|
||||
Negative controls, each a session that must send nothing with that user agent: (1) the same session with `datareporting.healthreport.uploadEnabled`
|
||||
false (the switch retail Firefox has for it); (2) the same session pointed at an endpoint whose host is `127.0.0.1`, which the task's allowlist refuses.
|
||||
The test therefore fails when the ping leaves by another program (its user agent differs), when the session sends none, and when the allowlist stops
|
||||
refusing a host that is not on it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import http.server
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
|
||||
from _session_end import EndingPlaywright
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
SERVER = "toolkit.telemetry.server"
|
||||
UPLOAD = "datareporting.healthreport.uploadEnabled"
|
||||
BACKGROUND_TASK_AGENT = "pingsender/2.0"
|
||||
|
||||
|
||||
class Endpoint:
|
||||
"""A telemetry endpoint on 127.0.0.1 (a port the OS gives) that records every request and answers 200."""
|
||||
|
||||
def __init__(self, host="localhost"):
|
||||
self.requests = []
|
||||
outer = self
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
timeout = 10
|
||||
|
||||
def _record(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
body = self.rfile.read(length) if length else b""
|
||||
outer.requests.append({"method": self.command, "path": self.path, "agent": self.headers.get("User-Agent"),
|
||||
"bytes": len(body)})
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
|
||||
do_POST = do_PUT = do_GET = _record
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
self._server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
self._server.daemon_threads = True
|
||||
threading.Thread(target=self._server.serve_forever, daemon=True).start()
|
||||
self.url = "http://%s:%d" % (host, self._server.server_address[1])
|
||||
|
||||
def by_agent(self, agent):
|
||||
return [r for r in self.requests if r["agent"] == agent]
|
||||
|
||||
def close(self):
|
||||
self._server.shutdown()
|
||||
self._server.server_close()
|
||||
|
||||
|
||||
def session(binary, endpoint, extra_prefs=None):
|
||||
"""One session pointed at ``endpoint``, opened and closed; it has ended (the sender included) when this returns."""
|
||||
prefs = {SERVER: endpoint.url}
|
||||
prefs.update(extra_prefs or {})
|
||||
with EndingPlaywright(seed=42, binary_path=binary, headless=True, humanize=False, locale="en-US",
|
||||
timezone="America/New_York", extra_prefs=prefs) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank", timeout=60_000)
|
||||
|
||||
|
||||
def test_the_shutdown_ping_is_sent_by_the_background_task_and_not_by_the_host_program(firefox_binary):
|
||||
endpoint, elsewhere = Endpoint(), Endpoint()
|
||||
try:
|
||||
session(firefox_binary, endpoint)
|
||||
# The session has ended: the sender has finished within the product's grace, or the reaper killed it and its ping is lost. Nothing is
|
||||
# waited for after this point.
|
||||
pings = endpoint.by_agent(BACKGROUND_TASK_AGENT)
|
||||
seen = [(r["method"], r["path"][:60], r["agent"], r["bytes"]) for r in endpoint.requests]
|
||||
assert pings, ("no request with `User-Agent: %s` had reached the endpoint when the session ended: the background task did not deliver "
|
||||
"the shutdown ping within the core's grace (`SENDER_GRACE`, after which the reaper kills it); what the endpoint received: %s"
|
||||
% (BACKGROUND_TASK_AGENT, seen))
|
||||
assert all(r["method"] == "POST" and r["path"].startswith("/submit/telemetry/") and r["bytes"] > 0 for r in pings), pings
|
||||
assert elsewhere.requests == [], "an endpoint the session was not pointed at received %s" % (elsewhere.requests,)
|
||||
|
||||
# Control 1: with the upload switched off no ping leaves, so the request above is the product's and not the endpoint's own noise.
|
||||
control = Endpoint()
|
||||
try:
|
||||
session(firefox_binary, control, extra_prefs={UPLOAD: False})
|
||||
assert control.by_agent(BACKGROUND_TASK_AGENT) == [], (
|
||||
"a session with the upload switched off still sent a ping: %s" % (control.requests,))
|
||||
finally:
|
||||
control.close()
|
||||
|
||||
# Control 2: the same session, same upload switch, the endpoint named by an address that is not on the task's allowlist: the task refuses it.
|
||||
refused = Endpoint(host="127.0.0.1")
|
||||
try:
|
||||
session(firefox_binary, refused)
|
||||
assert refused.requests == [], (
|
||||
"a ping addressed to a host that is not on the background task's allowlist reached the endpoint: %s" % (refused.requests,))
|
||||
finally:
|
||||
refused.close()
|
||||
finally:
|
||||
endpoint.close()
|
||||
elsewhere.close()
|
||||
@@ -46,3 +46,57 @@ def test_the_voices_are_retail_windows_in_its_order_and_none_is_the_default(
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank")
|
||||
assert page.evaluate(READ) == RETAIL
|
||||
|
||||
|
||||
# --- voiceURI: the retail form, and what an empty declaration falls to ------
|
||||
# Retail Windows Firefox's SAPI backend names a voice `urn:moz-tts:sapi:<name>?<lang>`;
|
||||
# the engine builds that string from the declared list (the hook of
|
||||
# dom/media/webspeech/synth: StealthSpeechVoices, StealthSpeechVoice). With the
|
||||
# engine off (`zoom.stealth.fpp.hw_seed` 0: an active engine refuses an empty
|
||||
# declaration) the engine does not answer: Firefox's own path reads the host's
|
||||
# registry (Windows) or speech-dispatcher (Linux).
|
||||
|
||||
READ_URIS = """() => speechSynthesis.getVoices().map(v => [v.name, v.voiceURI])"""
|
||||
|
||||
#: A voice no host has: the declaration, not a coincidence of the machine.
|
||||
_ONLY = "Zaphod Quux - English (United States)"
|
||||
|
||||
|
||||
def _uris(firefox_binary, extra_prefs):
|
||||
"""The voices a page reads: asked until the list is not empty (the engine's
|
||||
answer is there at once; the host's comes when the host's service has loaded
|
||||
and may be empty, so the deadline is the end of the wait, not a failure)."""
|
||||
from _waits import wait_until
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=firefox_binary, headless=True,
|
||||
locale="en-US", timezone="America/New_York",
|
||||
extra_prefs=extra_prefs) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank")
|
||||
|
||||
def pump():
|
||||
page.wait_for_timeout(100) # the events of a sync client are delivered while it calls the browser
|
||||
|
||||
wait_until(lambda: page.evaluate(READ_URIS), 30, pump)
|
||||
return page.evaluate(READ_URIS)
|
||||
|
||||
|
||||
def test_the_voice_uri_is_the_retail_form_and_an_empty_list_falls_to_the_registry(
|
||||
firefox_binary):
|
||||
declared = _uris(firefox_binary, None)
|
||||
assert declared == [[name, "urn:moz-tts:sapi:%s?en-US" % name] for name, *_ in RETAIL], declared
|
||||
assert not any(uri.startswith("stealth") for _n, uri in declared), declared
|
||||
|
||||
# The declaration is what answers: a one-voice list is the whole answer.
|
||||
one = _uris(firefox_binary, {"zoom.stealth.voices.list": "%s|en-US|0|1" % _ONLY})
|
||||
assert one == [[_ONLY, "urn:moz-tts:sapi:%s?en-US" % _ONLY]], one
|
||||
|
||||
# Negative control: the same launch with the engine off (stock Firefox) is not
|
||||
# answered by the engine. Whatever the host's registry (Windows) or speech-dispatcher
|
||||
# (Linux) lists, it is not the declared voice, and no URI is of the engine's
|
||||
# internal `stealth` form.
|
||||
empty = _uris(firefox_binary, {"zoom.stealth.fpp.hw_seed": 0})
|
||||
assert all(name != _ONLY for name, _uri in empty), empty
|
||||
assert not any(uri.startswith("stealth") for _n, uri in empty), empty
|
||||
assert empty != one, (empty, one)
|
||||
@@ -0,0 +1,361 @@
|
||||
"""A WebGL context tells the page what the session DECLARES, never what the host's GL says.
|
||||
|
||||
Characterises, on the published engine (firefox-68), the hooks of the series folder
|
||||
``fingerprint/webgl/parameters`` in ``dom/canvas`` (``StealthWebGLParams.cpp`` and the hooks in
|
||||
``ClientWebGLContext.cpp``, ``WebGLContextValidate.cpp``): the numeric ``getParameter`` answers
|
||||
(``zoom.stealth.webgl.int_params`` / ``int2_params`` / ``float_params``), the renderer and the
|
||||
vendor strings (``zoom.stealth.webgl.renderer`` / ``vendor``), ``getShaderPrecisionFormat``
|
||||
(``zoom.stealth.webgl.shader_precisions``), the extension list the page reads
|
||||
(``zoom.stealth.webgl.extensions`` / ``zoom.stealth.webgl2.extensions``) and the stencil masks a
|
||||
fresh context starts with. A page reads every one of them with a handful of lines, and they are
|
||||
the biggest part of a WebGL fingerprint, so a value that came from the host's GPU or driver (a
|
||||
Mesa llvmpipe on a Linux runner, a WARP adapter on a Windows one) is a value that tells the
|
||||
machine apart from the Windows the session claims to be.
|
||||
|
||||
Each test declares a value no runner has (a ``MAX_TEXTURE_SIZE`` of 12345, a precision of
|
||||
7:11:13, a Radeon HD 5850, an extension list in a deliberately wrong order) and reads it back
|
||||
where a page reads it. The negative control is in the same test: the same page, the same
|
||||
engine, with the declaration of that value empty, reads the host's own answer, and the test
|
||||
asserts the two DIFFER, so it fails if the declaration is not what the page reads.
|
||||
|
||||
The renderer and the vendor have no empty control: an engine that is on refuses to start
|
||||
without them (the declaration gate), and an engine that is off draws on the host's GL, which a
|
||||
runner without a GPU may not give at all. The control there is the session's own persona (the
|
||||
product default), which the page must NOT read once the declaration says otherwise.
|
||||
|
||||
The stencil masks have no pref at all: the engine starts them at all ones, as ANGLE does, where
|
||||
the driver's own start is the stencil bits (Mesa: 255). The control is the same read after the
|
||||
page writes 255 itself, which proves the read is live and that 255 is what the masks were
|
||||
before the engine.
|
||||
|
||||
The test reads the engine through ``extra_prefs`` (applied last by the core), RFP stays off.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
SEED = 4246
|
||||
|
||||
#: gl.INVALID_ENUM
|
||||
INVALID_ENUM = 1280
|
||||
|
||||
# -- numeric parameters ----------------------------------------------------------------------
|
||||
|
||||
#: A value no runner has for each (the host's are 16384 / 2048 / 32767 on a GL or ANGLE).
|
||||
DECLARED_INT = "3379|12345,34024|23456,34076|9001,32883|4321,35071|777"
|
||||
DECLARED_INT2 = "3386|12345:23456"
|
||||
DECLARED_FLOAT = "33901|1:7777,33902|3:5"
|
||||
EMPTY_NUMERIC = {
|
||||
"zoom.stealth.webgl.int_params": "",
|
||||
"zoom.stealth.webgl.int2_params": "",
|
||||
"zoom.stealth.webgl.float_params": "",
|
||||
}
|
||||
DECLARED_NUMERIC = {
|
||||
"zoom.stealth.webgl.int_params": DECLARED_INT,
|
||||
"zoom.stealth.webgl.int2_params": DECLARED_INT2,
|
||||
"zoom.stealth.webgl.float_params": DECLARED_FLOAT,
|
||||
}
|
||||
|
||||
NUMERIC_JS = """() => {
|
||||
const NAMES = {
|
||||
MAX_TEXTURE_SIZE: 0x0D33, MAX_RENDERBUFFER_SIZE: 0x84E8, MAX_CUBE_MAP_TEXTURE_SIZE: 0x851C,
|
||||
MAX_VIEWPORT_DIMS: 0x0D3A, ALIASED_POINT_SIZE_RANGE: 0x846D, ALIASED_LINE_WIDTH_RANGE: 0x846E,
|
||||
MAX_3D_TEXTURE_SIZE: 0x8073, MAX_ARRAY_TEXTURE_LAYERS: 0x88FF,
|
||||
};
|
||||
const out = {};
|
||||
for (const kind of ["webgl", "webgl2"]) {
|
||||
const gl = document.createElement("canvas").getContext(kind);
|
||||
if (!gl) { out[kind] = null; continue; }
|
||||
gl.getError();
|
||||
const r = {};
|
||||
for (const [name, pname] of Object.entries(NAMES)) {
|
||||
const v = gl.getParameter(pname);
|
||||
const error = gl.getError();
|
||||
const view = v !== null && ArrayBuffer.isView(v);
|
||||
r[name] = {value: view ? Array.from(v) : v,
|
||||
type: v === null ? "null" : (view ? v.constructor.name : typeof v), error};
|
||||
}
|
||||
out[kind] = r;
|
||||
}
|
||||
return out;
|
||||
}"""
|
||||
|
||||
# -- renderer and vendor ---------------------------------------------------------------------
|
||||
|
||||
#: A device no runner has. ``SanitizeRenderer`` keeps the device of this Direct3D string as it
|
||||
#: is (a "Radeon HD 5850" is its own bucket) and rewrites what comes after the suffix, so the
|
||||
#: page reads this prefix whether the string is sanitized or not.
|
||||
RENDERER = "ANGLE (AMD, Radeon HD 5850 Direct3D11 vs_5_0 ps_5_0, D3D11)"
|
||||
RENDERER_READ_PREFIX = "ANGLE (AMD, Radeon HD 5850 Direct3D11 vs_5_0 ps_5_0"
|
||||
VENDOR = "Google Inc. (AMD)"
|
||||
|
||||
RENDERER_JS = """() => {
|
||||
const out = {};
|
||||
for (const kind of ["webgl", "webgl2"]) {
|
||||
const gl = document.createElement("canvas").getContext(kind);
|
||||
if (!gl) { out[kind] = null; continue; }
|
||||
gl.getError();
|
||||
// UNMASKED_RENDERER_WEBGL before the extension is enabled: Mozilla's own error.
|
||||
const before = gl.getParameter(0x9246);
|
||||
const before_error = gl.getError();
|
||||
const ext = gl.getExtension("WEBGL_debug_renderer_info");
|
||||
out[kind] = {
|
||||
renderer: gl.getParameter(gl.RENDERER),
|
||||
vendor: gl.getParameter(gl.VENDOR),
|
||||
unmasked_before_extension: before,
|
||||
unmasked_before_extension_error: before_error,
|
||||
has_extension: !!ext,
|
||||
unmasked_renderer: ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : null,
|
||||
unmasked_vendor: ext ? gl.getParameter(ext.UNMASKED_VENDOR_WEBGL) : null,
|
||||
error: gl.getError(),
|
||||
};
|
||||
}
|
||||
return out;
|
||||
}"""
|
||||
|
||||
# -- shader precision ------------------------------------------------------------------------
|
||||
|
||||
#: VERTEX_SHADER*LOW_FLOAT -> 7:11:13 and FRAGMENT_SHADER*HIGH_INT -> 3:5:2. No GPU has either.
|
||||
DECLARED_PRECISION = "35633*36336|7:11:13,35632*36341|3:5:2"
|
||||
|
||||
PRECISION_JS = """() => {
|
||||
const out = {};
|
||||
for (const kind of ["webgl", "webgl2"]) {
|
||||
const gl = document.createElement("canvas").getContext(kind);
|
||||
if (!gl) { out[kind] = null; continue; }
|
||||
gl.getError();
|
||||
const read = (shader, precision) => {
|
||||
const f = gl.getShaderPrecisionFormat(shader, precision);
|
||||
const error = gl.getError();
|
||||
return {format: f === null ? null : [f.rangeMin, f.rangeMax, f.precision], error};
|
||||
};
|
||||
out[kind] = {
|
||||
vertex_low_float: read(gl.VERTEX_SHADER, gl.LOW_FLOAT),
|
||||
fragment_high_int: read(gl.FRAGMENT_SHADER, gl.HIGH_INT),
|
||||
vertex_high_float: read(gl.VERTEX_SHADER, gl.HIGH_FLOAT),
|
||||
bad_precision_type: read(gl.VERTEX_SHADER, 0x1234),
|
||||
bad_shader_type: read(gl.TEXTURE_2D, gl.LOW_FLOAT),
|
||||
};
|
||||
}
|
||||
return out;
|
||||
}"""
|
||||
|
||||
# -- extension list --------------------------------------------------------------------------
|
||||
|
||||
#: ``WebGLExtensionID`` of ``dom/canvas/WebGLTypes.h``, in declaration order (``MOZ_debug`` is
|
||||
#: never listed to a page): the one order a page ever reads, the retail one.
|
||||
ENUM_ORDER = [
|
||||
"ANGLE_instanced_arrays", "EXT_blend_minmax", "EXT_clip_control", "EXT_color_buffer_float",
|
||||
"EXT_color_buffer_half_float", "EXT_depth_clamp", "EXT_disjoint_timer_query", "EXT_float_blend",
|
||||
"EXT_frag_depth", "EXT_polygon_offset_clamp", "EXT_shader_texture_lod", "EXT_sRGB",
|
||||
"EXT_texture_compression_bptc", "EXT_texture_compression_rgtc",
|
||||
"EXT_texture_filter_anisotropic", "EXT_texture_mirror_clamp_to_edge", "EXT_texture_norm16",
|
||||
"OES_draw_buffers_indexed", "OES_element_index_uint", "OES_fbo_render_mipmap",
|
||||
"OES_standard_derivatives", "OES_texture_float", "OES_texture_float_linear",
|
||||
"OES_texture_half_float", "OES_texture_half_float_linear", "OES_vertex_array_object",
|
||||
"OVR_multiview2", "WEBGL_color_buffer_float", "WEBGL_compressed_texture_astc",
|
||||
"WEBGL_compressed_texture_etc", "WEBGL_compressed_texture_etc1",
|
||||
"WEBGL_compressed_texture_pvrtc", "WEBGL_compressed_texture_s3tc",
|
||||
"WEBGL_compressed_texture_s3tc_srgb", "WEBGL_debug_renderer_info", "WEBGL_debug_shaders",
|
||||
"WEBGL_depth_texture", "WEBGL_draw_buffers", "WEBGL_explicit_present", "WEBGL_lose_context",
|
||||
"WEBGL_provoking_vertex",
|
||||
]
|
||||
|
||||
#: Declared in an order that is NOT the enum's: the page must read them in the enum's.
|
||||
DECLARED_EXTENSIONS_1 = ["WEBGL_lose_context", "OES_texture_float", "EXT_blend_minmax",
|
||||
"OES_vertex_array_object", "ANGLE_instanced_arrays"]
|
||||
DECLARED_EXTENSIONS_2 = ["WEBGL_lose_context", "EXT_texture_filter_anisotropic",
|
||||
"EXT_color_buffer_float", "OES_texture_float_linear"]
|
||||
|
||||
EXTENSIONS_JS = """() => {
|
||||
const out = {};
|
||||
for (const kind of ["webgl", "webgl2"]) {
|
||||
const gl = document.createElement("canvas").getContext(kind);
|
||||
if (!gl) { out[kind] = null; continue; }
|
||||
out[kind] = {list: gl.getSupportedExtensions(),
|
||||
depth_texture: gl.getExtension("WEBGL_depth_texture") === null ? null : "object"};
|
||||
}
|
||||
return out;
|
||||
}"""
|
||||
|
||||
# -- stencil masks ---------------------------------------------------------------------------
|
||||
|
||||
STENCIL_JS = """() => {
|
||||
const PNAMES = {STENCIL_VALUE_MASK: 0x0B93, STENCIL_WRITEMASK: 0x0B98,
|
||||
STENCIL_BACK_VALUE_MASK: 0x8CA4, STENCIL_BACK_WRITEMASK: 0x8CA5};
|
||||
const read = gl => {
|
||||
const r = {};
|
||||
for (const [name, pname] of Object.entries(PNAMES)) r[name] = gl.getParameter(pname);
|
||||
return r;
|
||||
};
|
||||
const out = {};
|
||||
for (const kind of ["webgl", "webgl2"]) {
|
||||
for (const stencil of [false, true]) {
|
||||
const key = kind + (stencil ? "+stencil" : "");
|
||||
const gl = document.createElement("canvas").getContext(kind, {stencil});
|
||||
if (!gl) { out[key] = null; continue; }
|
||||
const fresh = read(gl);
|
||||
// The control: the page writes 255 itself and reads it back.
|
||||
gl.stencilMask(255);
|
||||
gl.stencilMaskSeparate(gl.BACK, 255);
|
||||
gl.stencilFunc(gl.ALWAYS, 0, 255);
|
||||
gl.stencilFuncSeparate(gl.BACK, gl.ALWAYS, 0, 255);
|
||||
out[key] = {fresh, written: read(gl)};
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}"""
|
||||
|
||||
|
||||
def _read(firefox_binary, prefs, js):
|
||||
"""One short-lived product session with ``prefs`` overlaid, and what the page answers to ``js``."""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=SEED, binary_path=firefox_binary, headless=True,
|
||||
extra_prefs=dict(prefs)) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank")
|
||||
return page.evaluate(js)
|
||||
|
||||
|
||||
def _contexts(got, label):
|
||||
for kind in ("webgl", "webgl2"):
|
||||
assert got[kind] is not None, "%s: no %s context at all" % (label, kind)
|
||||
|
||||
|
||||
def test_declared_numeric_parameters_replace_the_hosts_and_webgl2_only_names_stay_null_on_webgl1(
|
||||
firefox_binary):
|
||||
declared = _read(firefox_binary, DECLARED_NUMERIC, NUMERIC_JS)
|
||||
control = _read(firefox_binary, EMPTY_NUMERIC, NUMERIC_JS)
|
||||
_contexts(declared, "declared")
|
||||
_contexts(control, "control")
|
||||
|
||||
want = {
|
||||
"MAX_TEXTURE_SIZE": (12345, "number"),
|
||||
"MAX_RENDERBUFFER_SIZE": (23456, "number"),
|
||||
"MAX_CUBE_MAP_TEXTURE_SIZE": (9001, "number"),
|
||||
"MAX_VIEWPORT_DIMS": ([12345, 23456], "Int32Array"),
|
||||
"ALIASED_POINT_SIZE_RANGE": ([1, 7777], "Float32Array"),
|
||||
"ALIASED_LINE_WIDTH_RANGE": ([3, 5], "Float32Array"),
|
||||
}
|
||||
want_webgl2_only = {"MAX_3D_TEXTURE_SIZE": 4321, "MAX_ARRAY_TEXTURE_LAYERS": 777}
|
||||
|
||||
for kind in ("webgl", "webgl2"):
|
||||
for name, (value, type_) in want.items():
|
||||
got = declared[kind][name]
|
||||
assert got == {"value": value, "type": type_, "error": 0}, (kind, name, got)
|
||||
# The control: the same page with the declaration empty reads the host's answer.
|
||||
assert control[kind][name]["value"] != value, (
|
||||
"%s %s: the host's own answer is the declared one, so this test cannot tell "
|
||||
"the declaration from the host: %r" % (kind, name, control[kind][name]))
|
||||
assert control[kind][name]["error"] == 0, (kind, name, control[kind][name])
|
||||
|
||||
# WebGL 2 only: the declared number is read on a WebGL 2 context ...
|
||||
for name, value in want_webgl2_only.items():
|
||||
got = declared["webgl2"][name]
|
||||
assert got == {"value": value, "type": "number", "error": 0}, (name, got)
|
||||
assert control["webgl2"][name]["value"] != value, (name, control["webgl2"][name])
|
||||
# ... and on a WebGL 1 context the name does not exist: null and INVALID_ENUM, declared
|
||||
# or not (the declaration cannot make a name appear that the context does not have).
|
||||
for label, run in (("declared", declared), ("control", control)):
|
||||
got = run["webgl"][name]
|
||||
assert got == {"value": None, "type": "null", "error": INVALID_ENUM}, (
|
||||
label, name, got)
|
||||
|
||||
|
||||
def test_declared_renderer_and_vendor_are_read_in_every_form(firefox_binary):
|
||||
declared = _read(firefox_binary, {"zoom.stealth.webgl.renderer": RENDERER,
|
||||
"zoom.stealth.webgl.vendor": VENDOR}, RENDERER_JS)
|
||||
# The control: the session's own persona, the product default (the declaration gate refuses
|
||||
# an empty pair on a running engine).
|
||||
control = _read(firefox_binary, {}, RENDERER_JS)
|
||||
_contexts(declared, "declared")
|
||||
_contexts(control, "control")
|
||||
|
||||
for kind in ("webgl", "webgl2"):
|
||||
got = declared[kind]
|
||||
# Every form of the renderer: the masked constant, and the unmasked one through the
|
||||
# extension the page enables.
|
||||
assert got["renderer"].startswith(RENDERER_READ_PREFIX), (kind, got)
|
||||
assert got["has_extension"], (kind, got)
|
||||
assert got["unmasked_renderer"].startswith(RENDERER_READ_PREFIX), (kind, got)
|
||||
assert got["unmasked_vendor"] == VENDOR, (kind, got)
|
||||
# The masked vendor is Firefox's own constant, whatever is declared.
|
||||
assert got["vendor"] == "Mozilla", (kind, got)
|
||||
# Without the extension the unmasked constants are not a thing: Mozilla's error.
|
||||
assert got["unmasked_before_extension"] is None, (kind, got)
|
||||
assert got["unmasked_before_extension_error"] == INVALID_ENUM, (kind, got)
|
||||
assert got["error"] == 0, (kind, got)
|
||||
|
||||
base = control[kind]
|
||||
assert base["has_extension"], (kind, base)
|
||||
assert not base["renderer"].startswith(RENDERER_READ_PREFIX), (kind, base)
|
||||
assert not base["unmasked_renderer"].startswith(RENDERER_READ_PREFIX), (kind, base)
|
||||
assert base["unmasked_vendor"] != VENDOR, (kind, base)
|
||||
assert base["vendor"] == "Mozilla", (kind, base)
|
||||
assert base["unmasked_before_extension"] is None, (kind, base)
|
||||
assert base["unmasked_before_extension_error"] == INVALID_ENUM, (kind, base)
|
||||
|
||||
|
||||
def test_declared_shader_precision_replaces_the_hosts_and_a_bad_pair_still_errors(
|
||||
firefox_binary):
|
||||
declared = _read(firefox_binary,
|
||||
{"zoom.stealth.webgl.shader_precisions": DECLARED_PRECISION}, PRECISION_JS)
|
||||
control = _read(firefox_binary, {"zoom.stealth.webgl.shader_precisions": ""}, PRECISION_JS)
|
||||
_contexts(declared, "declared")
|
||||
_contexts(control, "control")
|
||||
|
||||
for kind in ("webgl", "webgl2"):
|
||||
got, base = declared[kind], control[kind]
|
||||
assert got["vertex_low_float"] == {"format": [7, 11, 13], "error": 0}, (kind, got)
|
||||
assert got["fragment_high_int"] == {"format": [3, 5, 2], "error": 0}, (kind, got)
|
||||
# The control: with the declaration empty the page reads the host's formats.
|
||||
assert base["vertex_low_float"]["format"] not in (None, [7, 11, 13]), (kind, base)
|
||||
assert base["fragment_high_int"]["format"] not in (None, [3, 5, 2]), (kind, base)
|
||||
assert base["vertex_low_float"]["error"] == 0, (kind, base)
|
||||
# A pair nothing declares is the host's, untouched by the declarations next to it.
|
||||
assert got["vertex_high_float"] == base["vertex_high_float"], (kind, got, base)
|
||||
assert got["vertex_high_float"]["format"] is not None, (kind, got)
|
||||
# A bad pair is Mozilla's error with or without a declaration in the pref.
|
||||
for name in ("bad_precision_type", "bad_shader_type"):
|
||||
for label, run in (("declared", got), ("control", base)):
|
||||
assert run[name] == {"format": None, "error": INVALID_ENUM}, (kind, label, name, run)
|
||||
|
||||
|
||||
def test_the_declared_extension_list_is_read_in_firefoxs_order(firefox_binary):
|
||||
declared = _read(firefox_binary, {
|
||||
"zoom.stealth.webgl.extensions": ",".join(DECLARED_EXTENSIONS_1),
|
||||
"zoom.stealth.webgl2.extensions": ",".join(DECLARED_EXTENSIONS_2),
|
||||
}, EXTENSIONS_JS)
|
||||
control = _read(firefox_binary, {"zoom.stealth.webgl.extensions": "",
|
||||
"zoom.stealth.webgl2.extensions": ""}, EXTENSIONS_JS)
|
||||
_contexts(declared, "declared")
|
||||
_contexts(control, "control")
|
||||
|
||||
for kind, names in (("webgl", DECLARED_EXTENSIONS_1), ("webgl2", DECLARED_EXTENSIONS_2)):
|
||||
assert names != sorted(names, key=ENUM_ORDER.index), "the declared order must be wrong"
|
||||
want = [e for e in ENUM_ORDER if e in names]
|
||||
assert declared[kind]["list"] == want, (kind, declared[kind]["list"])
|
||||
# The control: with the declaration empty the page reads the host's own list.
|
||||
assert control[kind]["list"] != want, (kind, control[kind]["list"])
|
||||
assert control[kind]["list"], (kind, "the host list is empty")
|
||||
# Only what is declared is served: the host has WEBGL_depth_texture, the declaration lacks it.
|
||||
assert declared["webgl"]["depth_texture"] is None, declared["webgl"]
|
||||
|
||||
|
||||
def test_the_stencil_masks_start_at_all_ones(firefox_binary):
|
||||
got = _read(firefox_binary, {}, STENCIL_JS)
|
||||
all_ones = 4294967295
|
||||
names = ("STENCIL_VALUE_MASK", "STENCIL_WRITEMASK",
|
||||
"STENCIL_BACK_VALUE_MASK", "STENCIL_BACK_WRITEMASK")
|
||||
for key in ("webgl", "webgl+stencil", "webgl2", "webgl2+stencil"):
|
||||
run = got[key]
|
||||
assert run is not None, "%s: no context at all" % key
|
||||
# A fresh context, on any OS: all ones, as ANGLE starts them.
|
||||
assert run["fresh"] == {n: all_ones for n in names}, (key, run["fresh"])
|
||||
# The control: what the masks were before the engine on a driver GL is the stencil
|
||||
# bits (255 on Mesa), and a page that writes 255 reads 255 back, so the read is live and
|
||||
# all ones is not a constant of the page's reading.
|
||||
assert run["written"] == {n: 255 for n in names}, (key, run["written"])
|
||||
@@ -22,16 +22,35 @@ The clear colours are v/255 for integer v, so the expected byte is exactly v
|
||||
whatever the GPU's rounding: a k/64 colour lands on 127.5 at k=32, where two
|
||||
correct drivers may disagree.
|
||||
|
||||
Three more tests characterise the roads by which a page reads a WebGL canvas (the
|
||||
engine's WebGL readback hooks: ClientWebGLContext.cpp and StealthWebGLReadback.h
|
||||
of the fingerprint/canvas/noise-projection folder). Each reads with the engine on
|
||||
(zoom.stealth.fpp.hw_seed > 0) and, as the negative control in the same test, with the
|
||||
canvas noise declared off (zoom.stealth.canvas.substitute_pixels false, the engine still
|
||||
on: the bytes as drawn), and asserts the two differ, or no noise reached
|
||||
the road the test compares:
|
||||
|
||||
* readPixels into a PIXEL_PACK_BUFFER (WebGL2), read back with getBufferSubData,
|
||||
gives the bytes of readPixels into an array.
|
||||
* A frame of canvas.captureStream() has the bytes of toDataURL of the same canvas.
|
||||
* readPixels of a rectangle partly outside the framebuffer, and one with
|
||||
PACK_SKIP_PIXELS / PACK_SKIP_ROWS / PACK_ROW_LENGTH, change only the bytes the
|
||||
read wrote: the rest of the page's array stays what the page passed in, and the
|
||||
bytes written are those of a plain read of the same pixels.
|
||||
|
||||
Kept in its own file: it launches its own short-lived browsers, so it must not
|
||||
run alongside another module's shared browser (the Playwright sync API cannot
|
||||
nest). Run: pytest tests/test_webgl_noise_active.py -m e2e -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import hashlib
|
||||
|
||||
import pytest
|
||||
|
||||
from _page_bytes import unfiltered
|
||||
from _waits import wait_until
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
_GRADIENT_JS = """() => {
|
||||
@@ -118,3 +137,265 @@ def test_a_flat_clear_reads_back_exactly_as_cleared(firefox_binary, seed):
|
||||
"%d of 4096 cleared pixels do not read back as cleared (column, row, "
|
||||
"cleared, read): %s. A clear is the same bytes on every GPU, so noise "
|
||||
"on it is a tell" % (len(moved), moved[:5]))
|
||||
|
||||
|
||||
#: A hw_seed no runner has by accident (the engine is on when it is positive). The control of the tests below keeps the engine ON, with the
|
||||
#: same declared GPU, and declares only the canvas noise off (``zoom.stealth.canvas.substitute_pixels`` false): a launch with hw_seed 0 would
|
||||
#: change the declared GPU too, and a Windows runner without the engine has no WebGL2 at all, so the comparison would say nothing.
|
||||
_ENGINE_ON = 12345
|
||||
_ENGINE_OFF = 0 # "the noise is off": the engine stays on (see _page)
|
||||
|
||||
#: Draws what the tests below read: a triangle with per-vertex colours and antialiased edges on a white clear,
|
||||
#: the render of _GRADIENT_JS, where a device varies and so where the noise lands. ``scene(canvas, kind, attrs, alpha)``
|
||||
#: returns the context, drawn and finished, or null when there is no such context.
|
||||
_SCENE_JS = """
|
||||
const scene = (c, kind, attrs, alpha) => {
|
||||
const gl = c.getContext(kind, attrs);
|
||||
if (!gl) return null;
|
||||
const vs = gl.createShader(gl.VERTEX_SHADER);
|
||||
gl.shaderSource(vs, 'attribute vec2 p; attribute vec3 c; varying vec3 v;'
|
||||
+ ' void main(){v=c;gl_Position=vec4(p,0.,1.);}');
|
||||
gl.compileShader(vs);
|
||||
const fs = gl.createShader(gl.FRAGMENT_SHADER);
|
||||
gl.shaderSource(fs, 'precision mediump float; varying vec3 v; void main(){gl_FragColor=vec4(v,'
|
||||
+ alpha.toFixed(8) + ');}');
|
||||
gl.compileShader(fs);
|
||||
const pr = gl.createProgram(); gl.attachShader(pr, vs); gl.attachShader(pr, fs);
|
||||
gl.linkProgram(pr); gl.useProgram(pr);
|
||||
const b = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, b);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(
|
||||
[-0.9, -0.8, 1, 0, 0, 0.85, -0.6, 0, 1, 0, 0.1, 0.9, 0, 0, 1]), gl.STATIC_DRAW);
|
||||
const pl = gl.getAttribLocation(pr, 'p'), cl = gl.getAttribLocation(pr, 'c');
|
||||
gl.enableVertexAttribArray(pl); gl.vertexAttribPointer(pl, 2, gl.FLOAT, false, 20, 0);
|
||||
gl.enableVertexAttribArray(cl); gl.vertexAttribPointer(cl, 3, gl.FLOAT, false, 20, 8);
|
||||
gl.clearColor(1, 1, 1, alpha); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 3);
|
||||
gl.finish();
|
||||
return gl;
|
||||
};
|
||||
"""
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _page(firefox_binary, hw_seed: int):
|
||||
"""One short-lived browser at a blank page, the engine always on: with the noise on (hw_seed > 0) or with only the canvas noise
|
||||
declared off (``_ENGINE_OFF``: ``zoom.stealth.canvas.substitute_pixels`` false, the bytes as drawn by the same declared GPU)."""
|
||||
prefs = {"zoom.stealth.fpp.hw_seed": _ENGINE_ON}
|
||||
if hw_seed == _ENGINE_OFF:
|
||||
prefs["zoom.stealth.canvas.substitute_pixels"] = False
|
||||
with InvisiblePlaywright(
|
||||
seed=7, binary_path=firefox_binary, headless=True,
|
||||
extra_prefs=prefs,
|
||||
) as b:
|
||||
p = b.new_context().new_page()
|
||||
p.goto("about:blank", timeout=30_000)
|
||||
yield p
|
||||
|
||||
|
||||
def _differing(a, b) -> int:
|
||||
"""How many bytes of two equally long sequences differ."""
|
||||
assert len(a) == len(b), (len(a), len(b))
|
||||
return sum(1 for x, y in zip(a, b) if x != y)
|
||||
|
||||
|
||||
_PBO_JS = "() => {" + _SCENE_JS + """
|
||||
const W = 128, H = 128, OFFSET = 16;
|
||||
const c = document.createElement('canvas'); c.width = W; c.height = H;
|
||||
const gl = scene(c, 'webgl2', {preserveDrawingBuffer: true, antialias: true}, 1);
|
||||
if (!gl) return null;
|
||||
while (gl.getError()) {}
|
||||
const into = new Uint8Array(W * H * 4);
|
||||
gl.readPixels(0, 0, W, H, gl.RGBA, gl.UNSIGNED_BYTE, into);
|
||||
const pbo = gl.createBuffer();
|
||||
gl.bindBuffer(gl.PIXEL_PACK_BUFFER, pbo);
|
||||
gl.bufferData(gl.PIXEL_PACK_BUFFER, OFFSET + W * H * 4, gl.STREAM_READ);
|
||||
gl.readPixels(0, 0, W, H, gl.RGBA, gl.UNSIGNED_BYTE, OFFSET);
|
||||
const error = gl.getError();
|
||||
const back = new Uint8Array(OFFSET + W * H * 4);
|
||||
gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, back);
|
||||
gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
|
||||
return {error, into: Array.from(into), pbo: Array.from(back.subarray(OFFSET)),
|
||||
head: Array.from(back.subarray(0, OFFSET))};
|
||||
}"""
|
||||
|
||||
|
||||
def _pbo(firefox_binary, hw_seed: int):
|
||||
with _page(firefox_binary, hw_seed) as p:
|
||||
got = p.evaluate(_PBO_JS)
|
||||
assert got is not None, "webgl2 is unavailable: readPixels into a PIXEL_PACK_BUFFER cannot be read"
|
||||
assert got["error"] == 0, "readPixels into a PIXEL_PACK_BUFFER raised 0x%x" % got["error"]
|
||||
assert got["head"] == [0] * 16, "the 16 bytes before the offset of the read were written: %r" % got["head"]
|
||||
return bytes(got["into"]), bytes(got["pbo"])
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_readpixels_into_a_pixel_pack_buffer_reads_as_into_an_array(firefox_binary):
|
||||
"""The two roads a page reads WebGL2 pixels by give the same bytes, with the engine on and off.
|
||||
|
||||
With the engine on the PIXEL_PACK_BUFFER road (the host writes the buffer, the engine rewrites it with the noise
|
||||
row by row) must give what readPixels into an array gives. With the engine off both are the bytes as drawn, and
|
||||
the array differs from the engine-on array: the noise reaches the page on the array road, so the equality above is
|
||||
not two untouched reads."""
|
||||
on_array, on_pbo = _pbo(firefox_binary, _ENGINE_ON)
|
||||
off_array, off_pbo = _pbo(firefox_binary, _ENGINE_OFF)
|
||||
assert off_pbo == off_array, (
|
||||
"engine off: %d of %d bytes of the buffer read differ from the array read of the same render"
|
||||
% (_differing(off_pbo, off_array), len(off_array)))
|
||||
assert _differing(on_array, off_array), (
|
||||
"the array read is the same with the engine on and off: no noise reaches readPixels, so the comparison "
|
||||
"of the two roads says nothing")
|
||||
assert on_pbo == on_array, (
|
||||
"engine on: %d of %d bytes read from a PIXEL_PACK_BUFFER differ from readPixels into an array; "
|
||||
"off, the buffer differs from the array by %d bytes"
|
||||
% (_differing(on_pbo, on_array), len(on_array), _differing(off_pbo, off_array)))
|
||||
|
||||
|
||||
_CAPTURE_START_JS = "() => {" + _SCENE_JS + """
|
||||
const c = document.createElement('canvas'); c.width = 64; c.height = 64;
|
||||
const gl = scene(c, 'webgl', {preserveDrawingBuffer: true, antialias: true}, 1);
|
||||
if (!gl) return false;
|
||||
window.__png = c.toDataURL();
|
||||
const stream = c.captureStream();
|
||||
const v = document.createElement('video');
|
||||
v.muted = true; v.autoplay = true; v.srcObject = stream;
|
||||
document.body.appendChild(v);
|
||||
window.__video = v; window.__track = stream.getVideoTracks()[0]; window.__frame = null;
|
||||
v.play().catch(() => {});
|
||||
return true;
|
||||
}"""
|
||||
|
||||
#: One look at the video: when it holds a frame with something on it, copy it through a 2D canvas (which reads as
|
||||
#: drawn) and say so; otherwise ask the track for a frame again.
|
||||
_CAPTURE_POLL_JS = """() => {
|
||||
if (window.__frame) return true;
|
||||
const v = window.__video;
|
||||
if (v.readyState >= 2 && v.videoWidth === 64 && v.videoHeight === 64) {
|
||||
const c = document.createElement('canvas'); c.width = 64; c.height = 64;
|
||||
const x = c.getContext('2d'); x.drawImage(v, 0, 0);
|
||||
const d = x.getImageData(0, 0, 64, 64).data;
|
||||
if (d.some(b => b !== 0)) { window.__frame = Array.from(d); return true; }
|
||||
}
|
||||
window.__track.requestFrame();
|
||||
return false;
|
||||
}"""
|
||||
|
||||
|
||||
def _capture(firefox_binary, hw_seed: int):
|
||||
"""(a frame of canvas.captureStream() as 64x64 RGBA bytes, the pixels of toDataURL of the same canvas)."""
|
||||
import base64
|
||||
with _page(firefox_binary, hw_seed) as p:
|
||||
assert p.evaluate(_CAPTURE_START_JS), "webgl is unavailable: captureStream of a WebGL canvas cannot be read"
|
||||
got = wait_until(lambda: p.evaluate(_CAPTURE_POLL_JS), 60, lambda: p.wait_for_timeout(100))
|
||||
assert got, "the video of canvas.captureStream() never held a frame with something on it"
|
||||
frame, url = p.evaluate("() => [window.__frame, window.__png]")
|
||||
png = unfiltered(base64.b64decode(url.split(",", 1)[1]))
|
||||
assert (png["w"], png["h"], png["channels"]) == (64, 64, 4), png
|
||||
return bytes(frame), png["data"]
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_a_capturestream_frame_reads_as_todataurl(firefox_binary):
|
||||
"""A frame a page takes from canvas.captureStream() has the bytes toDataURL of the same canvas has.
|
||||
|
||||
captureStream is the one reader of the async snapshot, and a road of its own: the engine must apply the noise
|
||||
there too, once. With the engine off the frame is the render as drawn and still equals toDataURL; with it on
|
||||
the frame differs from the one of the engine off (the noise reaches this road) and equals toDataURL."""
|
||||
on_frame, on_url = _capture(firefox_binary, _ENGINE_ON)
|
||||
off_frame, off_url = _capture(firefox_binary, _ENGINE_OFF)
|
||||
assert off_frame == off_url, (
|
||||
"engine off: %d of %d bytes of a captureStream frame differ from toDataURL of the same canvas"
|
||||
% (_differing(off_frame, off_url), len(off_url)))
|
||||
assert _differing(on_url, off_url), (
|
||||
"toDataURL is the same with the engine on and off: no noise reaches the page, so comparing the two "
|
||||
"roads says nothing")
|
||||
assert _differing(on_frame, off_frame), (
|
||||
"a captureStream frame is the same with the engine on and off: the noise does not reach captureStream")
|
||||
assert on_frame == on_url, (
|
||||
"engine on: %d of %d bytes of a captureStream frame differ from toDataURL of the same canvas"
|
||||
% (_differing(on_frame, on_url), len(on_url)))
|
||||
|
||||
|
||||
_PARTIAL_JS = "() => {" + _SCENE_JS + """
|
||||
const W = 128, H = 128;
|
||||
const c = document.createElement('canvas'); c.width = W; c.height = H;
|
||||
const gl = scene(c, 'webgl2', {preserveDrawingBuffer: true, antialias: true}, 1);
|
||||
if (!gl) return null;
|
||||
while (gl.getError()) {}
|
||||
const errors = [];
|
||||
const filled = n => { const a = new Uint8Array(n); for (let i = 0; i < n; i++) a[i] = 1 + (i * 7) % 251; return a; };
|
||||
const full = new Uint8Array(W * H * 4);
|
||||
gl.readPixels(0, 0, W, H, gl.RGBA, gl.UNSIGNED_BYTE, full);
|
||||
errors.push(gl.getError());
|
||||
// A rectangle that starts 16 pixels left of and below the framebuffer: its first 16 columns and rows are outside.
|
||||
const part = filled(96 * 96 * 4), partPassed = part.slice();
|
||||
gl.readPixels(-16, -16, 96, 96, gl.RGBA, gl.UNSIGNED_BYTE, part);
|
||||
errors.push(gl.getError());
|
||||
// The same pixels as a plain read, put 5 pixels right and 3 rows down in rows of 80 pixels.
|
||||
gl.pixelStorei(gl.PACK_ROW_LENGTH, 80);
|
||||
gl.pixelStorei(gl.PACK_SKIP_PIXELS, 5);
|
||||
gl.pixelStorei(gl.PACK_SKIP_ROWS, 3);
|
||||
const skip = filled((3 + 64) * 80 * 4), skipPassed = skip.slice();
|
||||
gl.readPixels(0, 0, 64, 64, gl.RGBA, gl.UNSIGNED_BYTE, skip);
|
||||
errors.push(gl.getError());
|
||||
gl.pixelStorei(gl.PACK_ROW_LENGTH, 0);
|
||||
gl.pixelStorei(gl.PACK_SKIP_PIXELS, 0);
|
||||
gl.pixelStorei(gl.PACK_SKIP_ROWS, 0);
|
||||
return {errors, full: Array.from(full), part: Array.from(part), partPassed: Array.from(partPassed),
|
||||
skip: Array.from(skip), skipPassed: Array.from(skipPassed)};
|
||||
}"""
|
||||
|
||||
|
||||
def _partial(firefox_binary, hw_seed: int):
|
||||
"""Reads of one render: the whole framebuffer, a rectangle partly outside it, and a packed read. Returns the
|
||||
bytes of the whole read and the pixels of the other two that are not where they should be (empty when none)."""
|
||||
with _page(firefox_binary, hw_seed) as p:
|
||||
got = p.evaluate(_PARTIAL_JS)
|
||||
assert got is not None, "webgl2 is unavailable: readPixels with PACK_SKIP_* cannot be read"
|
||||
assert got["errors"] == [0, 0, 0], "readPixels raised %r" % got["errors"]
|
||||
full = got["full"]
|
||||
pixel = lambda arr, i: tuple(arr[4 * i:4 * i + 4])
|
||||
problems = []
|
||||
# The rectangle at (-16, -16), 96x96: request pixel (c, r) is framebuffer pixel (c - 16, r - 16); written when
|
||||
# that is inside the 128x128 framebuffer, that is for c, r in [16, 96).
|
||||
for r in range(96):
|
||||
for c in range(96):
|
||||
i = r * 96 + c
|
||||
if c >= 16 and r >= 16:
|
||||
want, what = pixel(full, (r - 16) * 128 + (c - 16)), "a plain read"
|
||||
else:
|
||||
want, what = pixel(got["partPassed"], i), "what the page passed in"
|
||||
if pixel(got["part"], i) != want:
|
||||
problems.append(("rectangle", (c, r), pixel(got["part"], i), want, what))
|
||||
# 64x64 at (0, 0) with skip 5 / 3 and rows of 80: request pixel (c, r) is at column c + 5 of row r + 3.
|
||||
for row in range(3 + 64):
|
||||
for col in range(80):
|
||||
i = row * 80 + col
|
||||
c, r = col - 5, row - 3
|
||||
if 0 <= c < 64 and 0 <= r < 64:
|
||||
want, what = pixel(full, r * 128 + c), "a plain read"
|
||||
else:
|
||||
want, what = pixel(got["skipPassed"], i), "what the page passed in"
|
||||
if pixel(got["skip"], i) != want:
|
||||
problems.append(("packed", (c, r), pixel(got["skip"], i), want, what))
|
||||
return bytes(full), problems
|
||||
|
||||
|
||||
@pytest.mark.e2e
|
||||
def test_readpixels_of_a_partial_rectangle_projects_only_what_was_written(firefox_binary):
|
||||
"""readPixels changes the bytes it wrote and no other, and writes what a plain read of those pixels gives.
|
||||
|
||||
Two reads of one render: a 96x96 rectangle that starts 16 pixels outside the framebuffer (only its inside part
|
||||
is written), and a 64x64 read with PACK_ROW_LENGTH 80, PACK_SKIP_PIXELS 5 and PACK_SKIP_ROWS 3. The bytes the
|
||||
read did not write must be what the page passed in, and the ones it wrote those of a plain read of the same
|
||||
framebuffer pixels (noised, with the engine on). Engine off, the same holds with the bytes as drawn; and the
|
||||
plain read differs from the engine-on one, so the noise is in what is compared."""
|
||||
on_full, on_problems = _partial(firefox_binary, _ENGINE_ON)
|
||||
off_full, off_problems = _partial(firefox_binary, _ENGINE_OFF)
|
||||
assert not off_problems, "engine off: %d pixels are not where they should be (read, pixel, got, want, from): %s" % (
|
||||
len(off_problems), off_problems[:5])
|
||||
assert _differing(on_full, off_full), (
|
||||
"the plain read is the same with the engine on and off: no noise reaches readPixels, so the comparison "
|
||||
"says nothing")
|
||||
assert not on_problems, (
|
||||
"engine on: %d pixels are not where they should be (read, pixel, got, want, from): %s. A pixel outside "
|
||||
"the rectangle that was written must stay what the page passed in, and one inside it must be what a "
|
||||
"plain read of the same pixel gives" % (len(on_problems), on_problems[:5]))
|
||||
@@ -0,0 +1,106 @@
|
||||
"""``getTranslatedShaderSource`` answers in the DECLARED shader language, not the host's.
|
||||
|
||||
Characterises, on the published engine (firefox-68), the hooks of the series folder
|
||||
``fingerprint/webgl/shader-language`` in ``dom/canvas`` (``StealthWebGLShaderLanguage.cpp``;
|
||||
hooks in ``WebGLShader.cpp``, ``WebGLShaderValidator.cpp``, ``WebGLContext.cpp``): with
|
||||
``zoom.stealth.webgl.shader_output_language`` set to ``essl`` the page that asks
|
||||
``WEBGL_debug_shaders`` for the translated source of a shader reads ANGLE's translation to ESSL,
|
||||
the language a Windows Firefox (ANGLE, a GLES context) always answers in; the driver keeps
|
||||
receiving its own.
|
||||
|
||||
Why a page reads it: the session declares a Windows ANGLE renderer, and on a host whose GL
|
||||
context is not GLES (Linux through GLX) the same translator emits desktop GLSL, so the page
|
||||
would read ``#version 450`` from a browser whose RENDERER says ANGLE: a contradiction inside
|
||||
one page, with no need to know the OS.
|
||||
|
||||
The negative control is in the same test: the same engine, the same shaders, with the
|
||||
declaration empty. It is adapted to the OS, as the engine is. On Linux the host's language is
|
||||
desktop GLSL, so the declared and the undeclared sources DIFFER (the WebGL 2 shaders lose their
|
||||
``#version 300 es`` line). On Windows the context already goes through ANGLE and is already
|
||||
ESSL, so the two are EQUAL (and the declared one is the Windows one). On both, the driver still
|
||||
compiles and links the shader: the page sees one language, the pixels do not move.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
SEED = 4246
|
||||
|
||||
TRANSLATE_JS = """() => {
|
||||
const VS1 = 'attribute vec2 p; void main(){ gl_Position = vec4(p, 0.0, 1.0); }';
|
||||
const FS1 = 'precision mediump float; void main(){ gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); }';
|
||||
const VS2 = '#version 300 es\\nin vec2 p;\\nvoid main(){ gl_Position = vec4(p, 0.0, 1.0); }';
|
||||
const FS2 = '#version 300 es\\nprecision mediump float;\\nout vec4 o;\\n'
|
||||
+ 'void main(){ o = vec4(1.0, 0.0, 0.0, 1.0); }';
|
||||
const out = {};
|
||||
for (const [kind, vs, fs] of [["webgl", VS1, FS1], ["webgl2", VS2, FS2]]) {
|
||||
const gl = document.createElement("canvas").getContext(kind);
|
||||
if (!gl) { out[kind] = null; continue; }
|
||||
const dbg = gl.getExtension("WEBGL_debug_shaders");
|
||||
const v = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(v, vs); gl.compileShader(v);
|
||||
const f = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(f, fs); gl.compileShader(f);
|
||||
const prog = gl.createProgram(); gl.attachShader(prog, v); gl.attachShader(prog, f);
|
||||
gl.linkProgram(prog);
|
||||
out[kind] = {
|
||||
has_extension: !!dbg,
|
||||
vertex: dbg ? dbg.getTranslatedShaderSource(v) : null,
|
||||
fragment: dbg ? dbg.getTranslatedShaderSource(f) : null,
|
||||
compiled: gl.getShaderParameter(v, gl.COMPILE_STATUS) && gl.getShaderParameter(f, gl.COMPILE_STATUS),
|
||||
linked: gl.getProgramParameter(prog, gl.LINK_STATUS),
|
||||
};
|
||||
}
|
||||
return out;
|
||||
}"""
|
||||
|
||||
|
||||
def _read(firefox_binary, language):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(
|
||||
seed=SEED, binary_path=firefox_binary, headless=True,
|
||||
extra_prefs={"zoom.stealth.webgl.shader_output_language": language}) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("about:blank")
|
||||
return page.evaluate(TRANSLATE_JS)
|
||||
|
||||
|
||||
def test_get_translated_shader_source_is_in_the_declared_language_and_the_driver_still_compiles(
|
||||
firefox_binary):
|
||||
declared = _read(firefox_binary, "essl")
|
||||
control = _read(firefox_binary, "")
|
||||
|
||||
for kind in ("webgl", "webgl2"):
|
||||
for label, run in (("declared", declared), ("control", control)):
|
||||
got = run[kind]
|
||||
assert got is not None, "%s: no %s context at all" % (label, kind)
|
||||
assert got["has_extension"], (label, kind)
|
||||
# The driver is not touched by what the page is shown: it compiles and links.
|
||||
assert got["compiled"] is True and got["linked"] is True, (label, kind, got)
|
||||
assert got["vertex"] and got["fragment"], (label, kind, got)
|
||||
|
||||
# Declared: ESSL, on every OS. A WebGL 1 shader has no #version line in ESSL 1.00 and a
|
||||
# WebGL 2 one keeps its "#version 300 es".
|
||||
assert "#version" not in declared["webgl"]["vertex"], declared["webgl"]
|
||||
assert "#version" not in declared["webgl"]["fragment"], declared["webgl"]
|
||||
assert declared["webgl2"]["vertex"].lstrip().startswith("#version 300 es"), declared["webgl2"]
|
||||
assert declared["webgl2"]["fragment"].lstrip().startswith("#version 300 es"), declared["webgl2"]
|
||||
|
||||
if sys.platform.startswith("linux"):
|
||||
# The host's context is desktop GL: without the declaration the page reads desktop GLSL.
|
||||
# The declaration is what makes the two differ (as a pair of stages: a one-line vertex
|
||||
# shader may translate to the same text in both languages).
|
||||
for kind in ("webgl", "webgl2"):
|
||||
assert (control[kind]["vertex"], control[kind]["fragment"]) != (
|
||||
declared[kind]["vertex"], declared[kind]["fragment"]), (kind, control[kind])
|
||||
assert not control["webgl2"]["vertex"].lstrip().startswith("#version 300 es"), control["webgl2"]
|
||||
assert not control["webgl2"]["fragment"].lstrip().startswith("#version 300 es"), control["webgl2"]
|
||||
else:
|
||||
# Windows (ANGLE, a GLES context): the host's language is already ESSL, nothing to
|
||||
# translate twice, and the declaration changes nothing.
|
||||
for kind in ("webgl", "webgl2"):
|
||||
for stage in ("vertex", "fragment"):
|
||||
assert control[kind][stage] == declared[kind][stage], (kind, stage, control[kind])
|
||||
@@ -0,0 +1,141 @@
|
||||
"""The WebGPU adapter a page sees is the one the core declares, never the host's (firefox-68, Linux and Windows).
|
||||
|
||||
Hooks of `fingerprint/webgpu/adapter-declaration` (`dom/webgpu/Adapter.cpp`, `Instance.cpp`, `StealthWebGPUDeclaration.cpp`, `WebGPUParent.cpp`): while the
|
||||
engine is active (`zoom.stealth.fpp.hw_seed` > 0) the features, the limits and `isFallbackAdapter` of `navigator.gpu.requestAdapter()` come from the
|
||||
prefs `zoom.stealth.webgpu.features`, `zoom.stealth.webgpu.limits` and `zoom.stealth.webgpu.adapter` (the core declares 12 features and 35 limits of
|
||||
retail Firefox's Direct3D 12 backend for every persona, and the engine adds `core-features-and-limits` itself); `isFallbackAdapter` is true only for an
|
||||
adapter asked for with `forceFallbackAdapter`; `RequestDevice` is clamped to the real adapter, so a page that asks for the declared maxima gets a device;
|
||||
and a declared GPU without Direct3D 12 (`zoom.stealth.webgpu.adapter` = `none`) makes `requestAdapter()` resolve null. A page reads all of it with no
|
||||
permission (a secure context: the page is served from 127.0.0.1). The adapter of the host is a Vulkan driver on Linux (our own, bundled) and WARP or a
|
||||
GPU on Windows, and its features and limits differ from retail's.
|
||||
|
||||
Nothing is skipped: a runner with no adapter is a red test (the engine must give one: the bundled Vulkan on Linux, WARP on Windows).
|
||||
|
||||
Negative controls: in the first test the same read with the engine off (`hw_seed` 0) does not give the declared adapter (the host's, or null); in the second
|
||||
the same call with the declared adapter `d3d12` gives an adapter where `none` gives null (the pref is what decides), and an unknown `featureLevel` gives
|
||||
null on both.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
HW_SEED = "zoom.stealth.fpp.hw_seed"
|
||||
ADAPTER = "zoom.stealth.webgpu.adapter"
|
||||
PAGE = "/from-network"
|
||||
|
||||
#: The adapter as a page reads it: its features, its limits, `info.isFallbackAdapter`, whether a device at the declared maxima resolves, and the adapter
|
||||
#: asked for with `forceFallbackAdapter`. null when the page gets no adapter.
|
||||
READ_ADAPTER = """async () => {
|
||||
if (!navigator.gpu) return {gpu: false};
|
||||
const describe = async (adapter) => {
|
||||
if (!adapter) return null;
|
||||
const limits = {};
|
||||
for (const name in adapter.limits) limits[name] = adapter.limits[name];
|
||||
return {features: [...adapter.features].sort(), limits, fallback: adapter.info.isFallbackAdapter};
|
||||
};
|
||||
const adapter = await navigator.gpu.requestAdapter();
|
||||
const out = {gpu: true, adapter: await describe(adapter)};
|
||||
if (adapter) {
|
||||
const maxima = ['maxBufferSize', 'maxStorageBufferBindingSize', 'maxTextureDimension2D', 'maxBindGroups',
|
||||
'maxComputeWorkgroupStorageSize'];
|
||||
const required = {};
|
||||
for (const name of maxima) required[name] = adapter.limits[name];
|
||||
try {
|
||||
const device = await adapter.requestDevice({requiredLimits: required});
|
||||
const got = {};
|
||||
for (const name of maxima) got[name] = device.limits[name];
|
||||
out.device = {asked: required, got};
|
||||
} catch (e) {
|
||||
out.device = {error: String(e)};
|
||||
}
|
||||
}
|
||||
out.forced = await describe(await navigator.gpu.requestAdapter({forceFallbackAdapter: true}));
|
||||
return out;
|
||||
}"""
|
||||
|
||||
READ_NO_ADAPTER = """async () => {
|
||||
if (!navigator.gpu) return {gpu: false};
|
||||
const answer = async (options) => (await navigator.gpu.requestAdapter(options)) === null ? null : 'adapter';
|
||||
return {
|
||||
gpu: true,
|
||||
plain: await answer(),
|
||||
unknown_level: await answer({featureLevel: 'no-such-level'}),
|
||||
xr: await answer({xrCompatible: true}),
|
||||
};
|
||||
}"""
|
||||
|
||||
|
||||
def read(binary, url, expression, extra_prefs=None):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=binary, headless=True, humanize=False, locale="en-US",
|
||||
timezone="America/New_York", extra_prefs=extra_prefs) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(url, timeout=60_000)
|
||||
# The expression runs in the PAGE's realm, as a script of the page would: `page.evaluate` runs in the caller's world, where Firefox
|
||||
# cannot wrap the iterator of `adapter.features` (a set-like): "Xray wrapping of iterators not supported". The answer is written as
|
||||
# JSON into the DOM and the test waits on that condition.
|
||||
page.add_script_tag(content=(
|
||||
"(async () => { let out; try { out = await (%s)(); } catch (e) { out = {scriptError: String(e)}; }"
|
||||
" document.documentElement.setAttribute('data-read', JSON.stringify(out)); })();" % expression))
|
||||
page.wait_for_function("() => document.documentElement.hasAttribute('data-read')", timeout=60_000)
|
||||
answer = json.loads(page.evaluate("() => document.documentElement.getAttribute('data-read')"))
|
||||
assert not (isinstance(answer, dict) and "scriptError" in answer), answer
|
||||
return answer
|
||||
|
||||
|
||||
def declared():
|
||||
"""What the core declares, read from the core (the one place that holds it)."""
|
||||
from invisible_core.prefs import _WIN_WEBGPU_FEATURES, _WIN_WEBGPU_LIMITS
|
||||
|
||||
features = sorted(_WIN_WEBGPU_FEATURES.split(chr(10)) + ["core-features-and-limits"])
|
||||
limits = {name: int(value) for name, value in (line.split("=") for line in _WIN_WEBGPU_LIMITS.split(chr(10)))}
|
||||
return features, limits
|
||||
|
||||
|
||||
def test_the_page_sees_the_declared_adapter_e2e(firefox_binary, fixture_server):
|
||||
url = fixture_server + PAGE
|
||||
features, limits = declared()
|
||||
assert len(limits) == 35, len(limits)
|
||||
|
||||
on = read(firefox_binary, url, READ_ADAPTER)
|
||||
assert on["gpu"] is True, "navigator.gpu is missing: %r" % (on,)
|
||||
adapter = on["adapter"]
|
||||
assert adapter is not None, "requestAdapter() gave no adapter with the engine on: the engine must give one on every runner"
|
||||
assert adapter["features"] == features, adapter["features"]
|
||||
differing = {k: (adapter["limits"].get(k), limits.get(k)) for k in set(limits) | set(adapter["limits"])
|
||||
if adapter["limits"].get(k) != limits.get(k)}
|
||||
assert adapter["limits"] == limits, differing
|
||||
assert adapter["fallback"] is False
|
||||
# RequestDevice at the declared maxima resolves, and the device holds what was asked.
|
||||
assert on["device"].get("error") is None and on["device"]["asked"] == on["device"]["got"], on["device"]
|
||||
# An adapter asked for with forceFallbackAdapter is the fallback one, with the same declared features and limits.
|
||||
forced = on["forced"]
|
||||
assert forced is not None, "requestAdapter({forceFallbackAdapter: true}) gave no adapter"
|
||||
assert forced["fallback"] is True
|
||||
assert forced["features"] == features and forced["limits"] == limits
|
||||
|
||||
# Control: with the engine off the page does not read the declaration (the host's adapter, or none).
|
||||
off = read(firefox_binary, url, READ_ADAPTER, extra_prefs={HW_SEED: 0})
|
||||
assert off["gpu"] is True, off
|
||||
assert off["adapter"] != adapter, "the engine off answered the declared adapter: %r" % (off["adapter"],)
|
||||
|
||||
|
||||
def test_a_gpu_without_d3d12_has_no_adapter_e2e(firefox_binary, fixture_server):
|
||||
url = fixture_server + PAGE
|
||||
none = read(firefox_binary, url, READ_NO_ADAPTER, extra_prefs={ADAPTER: "none"})
|
||||
assert none["gpu"] is True, none
|
||||
# A declared GPU without Direct3D 12: requestAdapter resolves null, with or without options.
|
||||
assert none["plain"] is None and none["xr"] is None and none["unknown_level"] is None, none
|
||||
|
||||
# Control: the same call with the declared adapter `d3d12` answers an adapter (also with xrCompatible, which warns and goes on), and an
|
||||
# unknown featureLevel answers null as it does for stock.
|
||||
d3d12 = read(firefox_binary, url, READ_NO_ADAPTER, extra_prefs={ADAPTER: "d3d12"})
|
||||
assert d3d12["plain"] == "adapter", d3d12
|
||||
assert d3d12["xr"] == "adapter", d3d12
|
||||
assert d3d12["unknown_level"] is None, d3d12
|
||||
assert d3d12["plain"] != none["plain"]
|
||||
@@ -0,0 +1,119 @@
|
||||
"""A WebGPU canvas is read noised through ``toDataURL`` and ``toBlob`` (e2e, every OS; written on firefox-68, which the engine of the series must keep).
|
||||
|
||||
The engine applies its canvas noise (``gfx::StealthProjectPixels``) when a page reads a WebGL or WebGPU canvas, never a 2D one. The WebGPU canvas has
|
||||
two roads that are its own, ``CanvasContext::GetImageBuffer`` (``toDataURL``) and ``CanvasContext::GetInputStream`` (``toBlob``), and in each the
|
||||
snapshot Mozilla takes goes through ``CanvasUtils::StealthProjectWebGPUSnapshot`` (``fingerprint/canvas/noise-projection``: dom/webgpu/CanvasContext.cpp).
|
||||
A page that reads a WebGPU canvas with either method reads the noised pixels, and the same ones with both.
|
||||
|
||||
The page draws the scene of ``tests/_canvas_readers.py`` (ten triangles with random vertex colours over a white clear) with a render pipeline of
|
||||
WGSL into a canvas configured ``opaque``, and reads it. The control is in the same test: a second launch with the canvas noise declared off
|
||||
(``zoom.stealth.canvas.substitute_pixels`` false, every other declaration the same). The test asks that
|
||||
|
||||
* ``toDataURL`` and ``toBlob`` read the same pixels with the noise on, and the same with it off;
|
||||
* the two launches differ (the noise is there), and only in the low bit of R, G and B (nothing else is written).
|
||||
|
||||
NO SKIP: the core declares a GPU, so ``navigator.gpu.requestAdapter()`` answers an adapter on every runner. A page that gets ``null`` is a result
|
||||
of this test (the declaration did not reach WebGPU, or the runner has no way to give one), not a reason to leave it unrun.
|
||||
|
||||
The frame of a WebGPU canvas reaches the readers after the submit, in the page's own time: the test reads again, with a deadline, until the PNG
|
||||
holds the opaque scene (the middle pixel has alpha 255; a canvas not yet presented reads transparent). The pixels it keeps are those of the read
|
||||
that saw the scene.
|
||||
|
||||
Run: pytest tests/test_webgpu_canvas_readback_is_noised_e2e.py -m e2e -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
import _canvas_readers as cr
|
||||
from _waits import wait_until
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
PAGE_JS = r"""
|
||||
const WGSL = `
|
||||
struct VOut { @builtin(position) pos : vec4<f32>, @location(0) color : vec3<f32> };
|
||||
@vertex fn vs(@location(0) p : vec2<f32>, @location(1) c : vec3<f32>) -> VOut {
|
||||
var o : VOut; o.pos = vec4<f32>(p, 0.0, 1.0); o.color = c; return o;
|
||||
}
|
||||
@fragment fn fs(@location(0) color : vec3<f32>) -> @location(0) vec4<f32> { return vec4<f32>(color, 1.0); }`;
|
||||
|
||||
async function gpuStart() {
|
||||
if (!navigator.gpu) return {state: 'navigator.gpu is missing'};
|
||||
const adapter = await navigator.gpu.requestAdapter();
|
||||
if (!adapter) return {state: 'requestAdapter() answered null'};
|
||||
const device = await adapter.requestDevice();
|
||||
const canvas = document.createElement('canvas'); canvas.width = W; canvas.height = H;
|
||||
document.body.appendChild(canvas);
|
||||
const context = canvas.getContext('webgpu');
|
||||
if (!context) return {state: 'getContext("webgpu") answered null'};
|
||||
const format = navigator.gpu.getPreferredCanvasFormat();
|
||||
context.configure({device, format, alphaMode: 'opaque'});
|
||||
const data = new Float32Array(starVertices());
|
||||
const vertices = device.createBuffer({size: data.byteLength, usage: GPUBufferUsage.VERTEX, mappedAtCreation: true});
|
||||
new Float32Array(vertices.getMappedRange()).set(data);
|
||||
vertices.unmap();
|
||||
const module = device.createShaderModule({code: WGSL});
|
||||
const pipeline = device.createRenderPipeline({
|
||||
layout: 'auto',
|
||||
vertex: {module, entryPoint: 'vs', buffers: [{arrayStride: 20, attributes: [
|
||||
{shaderLocation: 0, offset: 0, format: 'float32x2'}, {shaderLocation: 1, offset: 8, format: 'float32x3'}]}]},
|
||||
fragment: {module, entryPoint: 'fs', targets: [{format}]},
|
||||
primitive: {topology: 'triangle-list'},
|
||||
});
|
||||
const encoder = device.createCommandEncoder();
|
||||
const pass = encoder.beginRenderPass({colorAttachments: [{
|
||||
view: context.getCurrentTexture().createView(), clearValue: {r: 1, g: 1, b: 1, a: 1}, loadOp: 'clear', storeOp: 'store'}]});
|
||||
pass.setPipeline(pipeline); pass.setVertexBuffer(0, vertices); pass.draw(30); pass.end();
|
||||
device.queue.submit([encoder.finish()]);
|
||||
await device.queue.onSubmittedWorkDone();
|
||||
window.GPU_CANVAS = canvas;
|
||||
return {state: 'drawn', format};
|
||||
}
|
||||
|
||||
async function gpuRead() {
|
||||
const canvas = window.GPU_CANVAS;
|
||||
return {'toDataURL.png': canvas.toDataURL('image/png').split(',')[1],
|
||||
'toBlob.png': await blobB64(await new Promise(r => canvas.toBlob(r, 'image/png')))};
|
||||
}
|
||||
"""
|
||||
|
||||
HTML = cr.page_html(PAGE_JS)
|
||||
MIDDLE_ALPHA = ((cr.SIZE // 2) * cr.SIZE + cr.SIZE // 2) * 4 + 3
|
||||
|
||||
|
||||
def _draw_and_read(firefox_binary, noised):
|
||||
"""The two PNGs of the WebGPU canvas, decoded, read again until they hold the scene."""
|
||||
with cr.launched(firefox_binary, HTML, noised=noised) as page:
|
||||
started = cr.run(page, "gpuStart()")
|
||||
assert started["state"] == "drawn", (
|
||||
"the page could not draw with WebGPU: %s. The core declares a GPU, so requestAdapter() must answer one on every runner" % started["state"])
|
||||
seen = {}
|
||||
|
||||
def holds_the_scene():
|
||||
seen.clear()
|
||||
seen.update(cr.decode(page.evaluate("() => gpuRead()")))
|
||||
return all(pixels[MIDDLE_ALPHA] == 255 for pixels in seen.values())
|
||||
|
||||
assert wait_until(holds_the_scene, 120, lambda: page.wait_for_timeout(200)), (
|
||||
"the WebGPU canvas never read as the opaque scene it was drawn with: the middle pixel's alpha is %r through toDataURL and toBlob"
|
||||
% {name: pixels[MIDDLE_ALPHA] for name, pixels in seen.items()})
|
||||
return dict(seen), started["format"]
|
||||
|
||||
|
||||
@pytest.mark.timeout(300, method="thread")
|
||||
def test_a_webgpu_canvas_reads_noised_through_todataurl_and_toblob(firefox_binary):
|
||||
on, format_on = _draw_and_read(firefox_binary, True)
|
||||
off, format_off = _draw_and_read(firefox_binary, False)
|
||||
assert format_on == format_off, "the two launches draw into canvases of different formats (%s, %s)" % (format_on, format_off)
|
||||
|
||||
cr.assert_agree("WebGPU canvas, noise on", on, "toDataURL.png")
|
||||
cr.assert_agree("WebGPU canvas, noise declared off", off, "toDataURL.png")
|
||||
n = cr.differing_pixels(on["toDataURL.png"], off["toDataURL.png"])
|
||||
assert n > 0, (
|
||||
"the WebGPU canvas reads byte for byte the same with the canvas noise declared on and off: toDataURL and toBlob read the pixels "
|
||||
"as drawn, so the page's readback of a WebGPU canvas is not noised")
|
||||
beyond = cr.only_the_low_bit_of_rgb(on["toDataURL.png"], off["toDataURL.png"])
|
||||
assert not beyond, (
|
||||
"%d pixels of the noised WebGPU read differ from the plain one by more than the low bit of R, G and B (first: %r); the noise writes "
|
||||
"nothing else" % (len(beyond), beyond[:5]))
|
||||
@@ -0,0 +1,46 @@
|
||||
"""`GPUDevice.prototype.importExternalTexture` exists on every operating system (firefox-68, Linux and Windows).
|
||||
|
||||
Hooks of `fingerprint/webgpu/adapter-declaration` (`modules/libpref/init/StaticPrefList.yaml`: `dom.webgpu.external-texture.enabled` is true on every OS;
|
||||
`gfx/thebes/gfxPlatform.cpp`: the force-disable for a system that is not Windows or macOS is off) and of `fingerprint/webgpu/external-texture-vulkan` (the
|
||||
Vulkan backend has external textures, so the API is real on Linux): upstream Firefox has the interface on Windows and macOS only, so a page could tell
|
||||
a Linux engine from a Windows one by `typeof GPUDevice.prototype.importExternalTexture`. The method is `[Func=ExternalTexturePrefEnabled]`: present
|
||||
when the pref (read once, at start) is true. A page reads it with no permission.
|
||||
|
||||
Negative control: the same read with the pref `dom.webgpu.external-texture.enabled` false (the stock value on Linux) has no such method.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
PREF = "dom.webgpu.external-texture.enabled"
|
||||
PAGE = "/from-network"
|
||||
|
||||
READ = """() => ({
|
||||
interface: typeof GPUDevice,
|
||||
method: typeof GPUDevice === 'undefined' ? 'no GPUDevice' : typeof GPUDevice.prototype.importExternalTexture,
|
||||
})"""
|
||||
|
||||
|
||||
def read(binary, url, extra_prefs=None):
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
with InvisiblePlaywright(seed=42, binary_path=binary, headless=True, humanize=False, locale="en-US",
|
||||
timezone="America/New_York", extra_prefs=extra_prefs) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(url, timeout=60_000)
|
||||
return page.evaluate(READ)
|
||||
|
||||
|
||||
def test_importexternaltexture_exists_on_every_os_e2e(firefox_binary, fixture_server):
|
||||
url = fixture_server + PAGE
|
||||
on = read(firefox_binary, url)
|
||||
assert on["interface"] == "function", on
|
||||
assert on["method"] == "function", on
|
||||
|
||||
# Control: the pref false takes the method away, so the read above depends on the declaration and not on the page.
|
||||
off = read(firefox_binary, url, extra_prefs={PREF: False})
|
||||
assert off["interface"] == "function", off
|
||||
assert off["method"] == "undefined", off
|
||||
assert off["method"] != on["method"]
|
||||
@@ -13,12 +13,24 @@ The control, in the same test: the two prefs true. The same two sessions, the sa
|
||||
proves nothing (a window that was never covered is visible too); it runs first, so a runner on which two windows do not cover each other is red here and not a
|
||||
green that means nothing.
|
||||
|
||||
Two sessions are launched on one display and both are headed: the Linux e2e runs under ``xvfb-run`` (no window manager, so the second window is mapped over the
|
||||
first), Windows uses the interactive desktop of the runner (the second maximized window is created on top of the first and the tracker, when on, calculates
|
||||
the cover). A page reads it from ``document.visibilityState`` and the ``visibilitychange`` event.
|
||||
Two sessions are launched on one display and both are headed. Linux: the e2e runs under ``xvfb-run`` (no window manager, so the second window is mapped over
|
||||
the first and X tells the first one it is fully obscured). Windows: opening the second window is not enough. ``WinWindowOcclusionTracker`` marks a root window
|
||||
``OCCLUDED`` only when the windows ABOVE it in the Z-order already cover its rectangle (``widget/windows/WinWindowOcclusionTracker.cpp``,
|
||||
``ProcessComputeNativeWindowOcclusionStatusCallback``: ``it->second = (mUnoccludedDesktopRegion == currUnoccludedDestkop) ? OCCLUDED : VISIBLE``); the second
|
||||
window lands above the first only when the system lets its process take the foreground (``nsWindow::Show``: ``::ShowWindow(mWnd, SW_SHOWNORMAL)``, an
|
||||
activation the system's foreground rules may refuse to a process the foreground one did not start); and a later move of another process's window is heard only
|
||||
once that process was seen with a visible window (``RegisterEventHookForProcess``). So on Windows the test puts the covering in place itself, as a user who drags
|
||||
one window over the other: the first window goes right under the second one, inside its rectangle as the tracker reads it (a maximized window counts as its
|
||||
monitor's work area), in one ``SetWindowPos`` with ``SWP_NOACTIVATE``. That move of the first window is the tracker's own signal (``EVENT_OBJECT_LOCATIONCHANGE``
|
||||
of its process), and before waiting the test checks what the tracker checks: the second window visible, not minimized, not cloaked, not layered-transparent,
|
||||
not a popup, above the first, and the first window inside it. A red says which of these did not hold.
|
||||
|
||||
A page reads it from ``document.visibilityState`` and the ``visibilitychange`` event.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from _window_sessions import in_a_thread_of_its_own, launch, wait_for_condition
|
||||
@@ -38,15 +50,191 @@ STATE = "() => document.visibilityState"
|
||||
CHANGES = "() => window.__visibility"
|
||||
#: Two painted frames: the page's own process has handled what the window system told it before this returns.
|
||||
TWO_FRAMES = "() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(done)))"
|
||||
#: Names the page, so that on Windows its top-level window is found by its title.
|
||||
NAME = "(name) => { document.title = name; return document.title; }"
|
||||
COVERED_TITLE, COVER_TITLE = "occlusion-covered-window", "occlusion-covering-window"
|
||||
|
||||
#: How far inside the covering window's rectangle the covered one is put, in device pixels.
|
||||
INSET = 32
|
||||
|
||||
|
||||
def opens_the_covering_window(second):
|
||||
"""Runs in the second session's own thread: opens a window on the display and waits for two painted frames."""
|
||||
"""Runs in the second session's own thread: opens a window on the display, names it, and waits for two painted frames."""
|
||||
cover = second.new_page()
|
||||
cover.goto("about:blank")
|
||||
cover.evaluate(NAME, COVER_TITLE)
|
||||
cover.evaluate(TWO_FRAMES)
|
||||
|
||||
|
||||
class Win32:
|
||||
"""The user32/dwmapi calls that find the two windows and put one under the other, with the rules ``WinWindowOcclusionTracker`` reads them by."""
|
||||
|
||||
SWP_NOACTIVATE = 0x0010
|
||||
GW_HWNDPREV = 3
|
||||
SW_MAXIMIZE = 3
|
||||
MONITOR_DEFAULTTONEAREST = 2
|
||||
DWMWA_CLOAKED = 14
|
||||
GWL_STYLE, GWL_EXSTYLE = -16, -20
|
||||
WS_POPUP = 0x80000000
|
||||
WS_EX_TRANSPARENT, WS_EX_TOOLWINDOW, WS_EX_LAYERED = 0x20, 0x80, 0x80000
|
||||
LWA_COLORKEY, LWA_ALPHA = 0x1, 0x2
|
||||
COMPLEXREGION = 3
|
||||
|
||||
def __init__(self) -> None:
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
self.ctypes, self.wintypes = ctypes, wintypes
|
||||
self.user32 = ctypes.WinDLL("user32", use_last_error=True)
|
||||
self.gdi32 = ctypes.WinDLL("gdi32")
|
||||
self.dwmapi = ctypes.WinDLL("dwmapi")
|
||||
u = self.user32
|
||||
u.GetWindow.restype, u.GetWindow.argtypes = wintypes.HWND, (wintypes.HWND, wintypes.UINT)
|
||||
u.GetForegroundWindow.restype = wintypes.HWND
|
||||
u.GetWindowLongW.restype, u.GetWindowLongW.argtypes = wintypes.LONG, (wintypes.HWND, ctypes.c_int)
|
||||
u.MonitorFromWindow.restype, u.MonitorFromWindow.argtypes = wintypes.HANDLE, (wintypes.HWND, wintypes.DWORD)
|
||||
u.SetWindowPos.argtypes = (wintypes.HWND, wintypes.HWND, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, wintypes.UINT)
|
||||
u.GetWindowRgn.argtypes = (wintypes.HWND, wintypes.HANDLE)
|
||||
self.gdi32.CreateRectRgn.restype = wintypes.HANDLE
|
||||
self.gdi32.DeleteObject.argtypes = (wintypes.HANDLE,)
|
||||
self.dwmapi.DwmGetWindowAttribute.argtypes = (wintypes.HWND, wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD)
|
||||
self.ENUM = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
|
||||
|
||||
class MONITORINFO(ctypes.Structure):
|
||||
_fields_ = [("cbSize", wintypes.DWORD), ("rcMonitor", wintypes.RECT), ("rcWork", wintypes.RECT), ("dwFlags", wintypes.DWORD)]
|
||||
|
||||
class WINDOWPLACEMENT(ctypes.Structure):
|
||||
_fields_ = [("length", wintypes.UINT), ("flags", wintypes.UINT), ("showCmd", wintypes.UINT), ("ptMinPosition", wintypes.POINT),
|
||||
("ptMaxPosition", wintypes.POINT), ("rcNormalPosition", wintypes.RECT)]
|
||||
|
||||
self.MONITORINFO, self.WINDOWPLACEMENT = MONITORINFO, WINDOWPLACEMENT
|
||||
|
||||
def window_titled(self, title):
|
||||
"""The one visible top-level Firefox window whose title starts with ``title``, or None (none, or more than one)."""
|
||||
ctypes = self.ctypes
|
||||
found = []
|
||||
|
||||
def each(hwnd, _):
|
||||
name, text = ctypes.create_unicode_buffer(256), ctypes.create_unicode_buffer(512)
|
||||
self.user32.GetClassNameW(hwnd, name, 256)
|
||||
self.user32.GetWindowTextW(hwnd, text, 512)
|
||||
if name.value.startswith("MozillaWindowClass") and text.value.startswith(title) and self.user32.IsWindowVisible(hwnd):
|
||||
found.append(hwnd)
|
||||
return True
|
||||
|
||||
self.user32.EnumWindows(self.ENUM(each), 0)
|
||||
return found[0] if len(found) == 1 else None
|
||||
|
||||
def rect(self, hwnd):
|
||||
r = self.wintypes.RECT()
|
||||
self.user32.GetWindowRect(hwnd, self.ctypes.byref(r))
|
||||
return (r.left, r.top, r.right, r.bottom)
|
||||
|
||||
def work_area(self, hwnd):
|
||||
info = self.MONITORINFO()
|
||||
info.cbSize = self.ctypes.sizeof(info)
|
||||
self.user32.GetMonitorInfoW(self.user32.MonitorFromWindow(hwnd, self.MONITOR_DEFAULTTONEAREST), self.ctypes.byref(info))
|
||||
w = info.rcWork
|
||||
return (w.left, w.top, w.right, w.bottom)
|
||||
|
||||
def maximized(self, hwnd):
|
||||
placement = self.WINDOWPLACEMENT()
|
||||
placement.length = self.ctypes.sizeof(placement)
|
||||
self.user32.GetWindowPlacement(hwnd, self.ctypes.byref(placement))
|
||||
return placement.showCmd == self.SW_MAXIMIZE
|
||||
|
||||
def tracker_rect(self, hwnd):
|
||||
"""The rectangle ``IsWindowVisibleAndFullyOpaque`` gives the window: ``GetWindowRect``, fitted to the work area when it is maximized."""
|
||||
left, top, right, bottom = self.rect(hwnd)
|
||||
if not self.maximized(hwnd):
|
||||
return (left, top, right, bottom)
|
||||
wl, wt, wr, wb = self.work_area(hwnd)
|
||||
width, height = min(wr - wl, right - left), min(wb - wt, bottom - top)
|
||||
x = wl if left < wl else min(wr, left + width) - width
|
||||
y = wt if top < wt else min(wb, top + height) - height
|
||||
return (x, y, x + width, y + height)
|
||||
|
||||
def why_it_cannot_cover(self, hwnd):
|
||||
"""What ``IsWindowVisibleAndFullyOpaque`` refuses the window for, in its order; '' when the window can cover others."""
|
||||
user32, ctypes = self.user32, self.ctypes
|
||||
if not user32.IsWindow(hwnd) or not user32.IsWindowVisible(hwnd):
|
||||
return "not visible"
|
||||
if user32.IsIconic(hwnd):
|
||||
return "minimized"
|
||||
ex = user32.GetWindowLongW(hwnd, self.GWL_EXSTYLE) & 0xFFFFFFFF
|
||||
if ex & self.WS_EX_TRANSPARENT:
|
||||
return "WS_EX_TRANSPARENT"
|
||||
if ex & self.WS_EX_TOOLWINDOW:
|
||||
return "WS_EX_TOOLWINDOW"
|
||||
if ex & self.WS_EX_LAYERED:
|
||||
alpha, flags = ctypes.c_ubyte(), self.wintypes.DWORD()
|
||||
if not user32.GetLayeredWindowAttributes(hwnd, None, ctypes.byref(alpha), ctypes.byref(flags)):
|
||||
return "layered without attributes"
|
||||
if (flags.value & self.LWA_ALPHA and alpha.value < 255) or flags.value & self.LWA_COLORKEY:
|
||||
return "layered and not opaque"
|
||||
region = self.gdi32.CreateRectRgn(0, 0, 0, 0)
|
||||
kind = user32.GetWindowRgn(hwnd, region)
|
||||
self.gdi32.DeleteObject(region)
|
||||
if kind == self.COMPLEXREGION:
|
||||
return "complex window region"
|
||||
cloaked = self.wintypes.DWORD()
|
||||
self.dwmapi.DwmGetWindowAttribute(hwnd, self.DWMWA_CLOAKED, ctypes.byref(cloaked), ctypes.sizeof(cloaked))
|
||||
if cloaked.value:
|
||||
return "cloaked"
|
||||
left, top, right, bottom = self.rect(hwnd)
|
||||
if right <= left or bottom <= top:
|
||||
return "empty rectangle"
|
||||
if user32.GetWindowLongW(hwnd, self.GWL_STYLE) & 0xFFFFFFFF & self.WS_POPUP:
|
||||
return "WS_POPUP"
|
||||
return ""
|
||||
|
||||
def above(self, upper, lower):
|
||||
"""Whether ``upper`` comes before ``lower`` in the Z-order, the order ``EnumWindows`` walks (top first)."""
|
||||
hwnd = self.user32.GetWindow(lower, self.GW_HWNDPREV)
|
||||
while hwnd:
|
||||
if hwnd == upper:
|
||||
return True
|
||||
hwnd = self.user32.GetWindow(hwnd, self.GW_HWNDPREV)
|
||||
return False
|
||||
|
||||
def put_under(self, covered, cover):
|
||||
"""Moves ``covered`` right under ``cover`` in the Z-order, inside ``cover``'s rectangle and its work area, activating nothing."""
|
||||
cl, ct, cr, cb = self.tracker_rect(cover)
|
||||
wl, wt, wr, wb = self.work_area(cover)
|
||||
left, top, right, bottom = max(cl, wl) + INSET, max(ct, wt) + INSET, min(cr, wr) - INSET, min(cb, wb) - INSET
|
||||
assert right - left > 2 * INSET and bottom - top > 2 * INSET, "no room inside the covering window %r (work area %r)" % (
|
||||
(cl, ct, cr, cb), (wl, wt, wr, wb))
|
||||
moved = self.user32.SetWindowPos(covered, cover, left, top, right - left, bottom - top, self.SWP_NOACTIVATE)
|
||||
assert moved, "SetWindowPos of the covered window failed (WinError %d)" % self.ctypes.get_last_error()
|
||||
|
||||
def coverage(self, covered, cover):
|
||||
"""What the tracker's calculation depends on, for the two windows; ``ok`` when the second one covers the first."""
|
||||
inner, outer = self.tracker_rect(covered), self.tracker_rect(cover)
|
||||
inside = outer[0] <= inner[0] and outer[1] <= inner[1] and inner[2] <= outer[2] and inner[3] <= outer[3]
|
||||
refused = self.why_it_cannot_cover(cover)
|
||||
above = self.above(cover, covered)
|
||||
return {"ok": inside and above and not refused, "covered": inner, "cover": outer, "inside": inside, "cover above": above,
|
||||
"cover refused for": refused or None, "covered maximized": self.maximized(covered),
|
||||
"foreground is the cover": self.user32.GetForegroundWindow() == cover}
|
||||
|
||||
|
||||
def covers_on_windows(covered):
|
||||
"""Windows only: finds the two windows, puts the covered one under the covering one, and checks the covering as the tracker reads it."""
|
||||
win = Win32()
|
||||
found = {}
|
||||
for title in (COVERED_TITLE, COVER_TITLE):
|
||||
seen = wait_for_condition(covered, lambda title=title: win.window_titled(title), lambda hwnd: hwnd is not None,
|
||||
"no single visible top-level window is titled %r" % title)
|
||||
found[title] = seen.history[-1][1]
|
||||
first, cover = found[COVERED_TITLE], found[COVER_TITLE]
|
||||
wait_for_condition(covered, lambda: win.why_it_cannot_cover(cover), lambda why: why == "",
|
||||
"the covering window is not one the tracker counts as covering")
|
||||
win.put_under(first, cover)
|
||||
seen = wait_for_condition(covered, lambda: win.coverage(first, cover), lambda state: state["ok"],
|
||||
"the second window does not cover the first one as the tracker reads them")
|
||||
return seen.history[-1][1]
|
||||
|
||||
|
||||
def second_window_over_the_first(firefox_binary, tracking):
|
||||
"""(state, changes) of the first session's page after a second session's window is up over it.
|
||||
|
||||
@@ -55,11 +243,13 @@ def second_window_over_the_first(firefox_binary, tracking):
|
||||
with launch(firefox_binary, extra_prefs=extra) as first, in_a_thread_of_its_own(firefox_binary) as second:
|
||||
covered = first.new_page()
|
||||
covered.goto("about:blank")
|
||||
covered.evaluate(NAME, COVERED_TITLE)
|
||||
assert covered.evaluate(WATCH) == "visible", "the page was not visible before anything covered it"
|
||||
second.run(opens_the_covering_window)
|
||||
windows = covers_on_windows(covered) if sys.platform == "win32" else None
|
||||
if tracking:
|
||||
wait_for_condition(covered, lambda: covered.evaluate(STATE), lambda state: state == "hidden",
|
||||
"a window that another one covers never turned hidden with occlusion tracking enabled")
|
||||
"a window that another one covers never turned hidden with occlusion tracking enabled (windows: %r)" % (windows,))
|
||||
else:
|
||||
covered.evaluate(TWO_FRAMES)
|
||||
return covered.evaluate(STATE), covered.evaluate(CHANGES)
|
||||
|
||||
@@ -6,6 +6,10 @@ started by the New Tab page), so a test that compared two counts of processes re
|
||||
under test (test_same_site_other_port_stays_in_process, red in 14 of 30 runs of the e2e suite). The names below are
|
||||
the ones measured on firefox-62 (Linux), with command lines as /proc gives them.
|
||||
"""
|
||||
import calendar
|
||||
import pathlib
|
||||
import time
|
||||
|
||||
import _processes
|
||||
import pytest
|
||||
|
||||
@@ -86,3 +90,106 @@ def test_a_process_of_another_firefox_is_not_counted():
|
||||
|
||||
def test_a_process_that_is_not_a_tab_is_not_counted():
|
||||
assert _processes.site_pids([_Proc(1, "http://a.test^u", kind="gpu")], A) == set()
|
||||
|
||||
|
||||
# --- The type a process was given is read for the process INSTANCE, not for the pid alone ---------------------------
|
||||
#
|
||||
# Where the system names no process (Windows) the e2e tests that look at sites read the engine's own log (`Setting
|
||||
# remoteType of process <pid> to <type>`, in the parent's file and in one `base.child-N` file per child). A plain
|
||||
# `{pid: last type}` read the files in the order of their names (child-10 before child-2), and the system gives the
|
||||
# number of an ended process to a later one, so a process of another kind with the pid of a dead site process was read
|
||||
# as that site and a wait for "no process of the site is left" never became true. The lines carry their time (`MOZ_LOG`
|
||||
# with `timestamp`): they are ordered by it, and a process takes only the types logged at or after its own creation.
|
||||
|
||||
T0 = calendar.timegm((2026, 11, 22, 10, 0, 0))
|
||||
|
||||
|
||||
def _line(seconds, pid, remote_type, kind="Setting remoteType of process {pid} to {type}"):
|
||||
stamp = T0 + seconds
|
||||
whole = int(stamp)
|
||||
micro = int(round((stamp - whole) * 1e6))
|
||||
text = "%04d-%02d-%02d %02d:%02d:%02d.%06d UTC - [Child %d: Main Thread]: D/Process " % (
|
||||
*time.gmtime(whole)[:6], micro, pid)
|
||||
return text + kind.format(pid=pid, type=remote_type) + "\n"
|
||||
|
||||
|
||||
def _changed(seconds, pid, remote_type):
|
||||
return _line(seconds, pid, remote_type, "Changing remoteType of process {pid} from prealloc to {type}")
|
||||
|
||||
|
||||
def _logs(tmp_path, files):
|
||||
base = tmp_path / "engine.log"
|
||||
for suffix, lines in files.items():
|
||||
pathlib.Path(str(base) + suffix).write_text("".join(lines), encoding="utf-8")
|
||||
return base
|
||||
|
||||
|
||||
class _LoggedProc:
|
||||
def __init__(self, pid, created):
|
||||
self.pid, self._created = pid, created
|
||||
|
||||
def create_time(self):
|
||||
return T0 + self._created
|
||||
|
||||
def exe(self):
|
||||
return "C:/engine/firefox.exe"
|
||||
|
||||
def name(self):
|
||||
return "firefox.exe"
|
||||
|
||||
def cmdline(self):
|
||||
return ["C:/engine/firefox.exe", "-contentproc", "-isForBrowser", str(self.pid), "tab"]
|
||||
|
||||
|
||||
def test_the_lines_of_a_pid_are_read_in_the_order_they_were_logged_not_in_the_order_of_the_file_names(tmp_path):
|
||||
"""child-2 holds the first line of pid 40 (a spare process), child-10 the last (its site): sorted by name child-10
|
||||
comes first and the spare type would win."""
|
||||
base = _logs(tmp_path, {
|
||||
".child-2": [_line(1, 40, "prealloc")],
|
||||
".child-10": [_changed(2, 40, "webIsolated=http://a.test^userContextId=1")],
|
||||
})
|
||||
types = _processes.remote_types(base)
|
||||
assert [t for _stamp, t in types[40]] == ["prealloc", "webIsolated=http://a.test^userContextId=1"]
|
||||
assert _processes.type_of_process(types, 40, T0) == "webIsolated=http://a.test^userContextId=1"
|
||||
|
||||
|
||||
def test_the_child_files_are_ordered_by_their_number():
|
||||
names = [pathlib.Path("e.log" + s) for s in (".child-10", ".child-2", "", ".child-1")]
|
||||
assert [p.name for p in sorted(names, key=_processes._natural)] == ["e.log", "e.log.child-1", "e.log.child-2", "e.log.child-10"]
|
||||
|
||||
|
||||
def test_a_pid_reused_by_a_later_process_does_not_inherit_the_type_of_the_old_one(tmp_path):
|
||||
"""The known-bad case: pid 40 hosted a.test and ended; the system gave 40 to a process that has not logged its type
|
||||
yet. It is not a.test's, and `none_hosted` waits could never be true."""
|
||||
base = _logs(tmp_path, {".child-3": [_line(1, 40, "webIsolated=http://a.test^userContextId=1")]})
|
||||
types = _processes.remote_types(base)
|
||||
assert _processes.type_of_process(types, 40, T0 + 1 - 0.5) == "webIsolated=http://a.test^userContextId=1" # the old one
|
||||
assert _processes.type_of_process(types, 40, T0 + 30) == "" # born 29 s after the old type was logged
|
||||
old, reused = _LoggedProc(40, 0.5), _LoggedProc(40, 30)
|
||||
assert _processes.site_pids_by_type([old], A, types) == {40}
|
||||
assert _processes.site_pids_by_type([reused], A, types) == set()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("early_file, late_file", [(".child-9", ".child-10"), (".child-10", ".child-2")])
|
||||
def test_a_reused_pid_takes_the_type_of_its_own_process_whichever_file_holds_it(tmp_path, early_file, late_file):
|
||||
"""pid 40 was a.test (early), then the system gave 40 to a process of b.test (late): the process alive now, born
|
||||
late, is b.test's, whatever the order of the files (the second case reads the late line before the early one)."""
|
||||
base = _logs(tmp_path, {
|
||||
early_file: [_line(1, 40, "webIsolated=http://a.test^userContextId=1")],
|
||||
late_file: [_line(20, 40, "webIsolated=http://b.test^userContextId=1")],
|
||||
})
|
||||
types = _processes.remote_types(base)
|
||||
now = _LoggedProc(40, 19.5)
|
||||
assert _processes.site_pids_by_type([now], B, types) == {40}
|
||||
assert _processes.site_pids_by_type([now], A, types) == set()
|
||||
|
||||
|
||||
def test_a_process_born_just_before_its_first_line_is_stamped_still_has_it():
|
||||
types = {7: [(T0 + 10, "webIsolated=http://a.test^userContextId=1")]}
|
||||
assert _processes.type_of_process(types, 7, T0 + 10 + _processes.BIRTH_SLACK / 2) != ""
|
||||
assert _processes.type_of_process(types, 7, T0 + 10 + _processes.BIRTH_SLACK * 4) == ""
|
||||
|
||||
|
||||
def test_a_process_with_no_log_line_has_no_type(tmp_path):
|
||||
base = _logs(tmp_path, {".child-1": [_line(1, 5, "web")]})
|
||||
assert _processes.type_of_process(_processes.remote_types(base), 99, T0) == ""
|
||||
+47
-12
@@ -26,16 +26,52 @@ from unittest import mock
|
||||
|
||||
|
||||
|
||||
def marionette_port() -> int:
|
||||
"""A port for ONE browser's Marionette, free when it is asked for.
|
||||
def marionette_active_port(profile: Optional[Path] = None, timeout: float = 120.0) -> int:
|
||||
"""The port ONE browser's Marionette got, read from the browser itself: launch it with ``"marionette.port": 0`` and ask here.
|
||||
|
||||
⛔ NEVER A FIXED PORT. Three e2e files used 28431 and xdist runs them on different workers at once: the second browser could
|
||||
not bind it while the first held it, its Marionette never listened, and once the first closed every connection was refused
|
||||
(ConnectionRefusedError 10061 for 120 s, e2e Windows part 2, run 43704738537: the font test on gw2 while the iframe-crash test
|
||||
held the port on gw1). The OS picks the port; it is released just before the browser binds it."""
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
|
||||
probe.bind(("127.0.0.1", 0))
|
||||
return probe.getsockname()[1]
|
||||
⛔ NEVER A FIXED PORT, AND NEVER A PORT FREED FOR THE BROWSER TO TAKE. Three e2e files used 28431 and xdist runs them on different
|
||||
workers at once: the second browser could not bind it while the first held it, its Marionette never listened, and once the first
|
||||
closed every connection was refused (ConnectionRefusedError 10061 for 120 s, e2e Windows part 2, run 43704738537: the font test on
|
||||
gw2 while the iframe-crash test held the port on gw1). A port that was free when it was asked for and released just before the
|
||||
browser binds it has the same race with a neighbour that binds first. With port 0 the browser binds first and the OS chooses; the
|
||||
engine writes `<profile>/MarionetteActivePort` once Marionette listens, and this is what reads it.
|
||||
|
||||
`profile` is the profile directory of the browser; None finds it in the command line (`-profile`) of the engine process below this
|
||||
one (a test runs one browser). It waits on the condition "the file holds a port", up to `timeout`."""
|
||||
import re
|
||||
|
||||
end = time.time() + timeout
|
||||
while True:
|
||||
folder = profile if profile is not None else _profile_of_the_engine()
|
||||
if folder is not None:
|
||||
try:
|
||||
found = re.search(r"\d+", (Path(folder) / "MarionetteActivePort").read_text(encoding="utf-8", errors="replace"))
|
||||
except OSError:
|
||||
found = None
|
||||
if found is not None and int(found.group()) > 0:
|
||||
return int(found.group())
|
||||
if time.time() > end:
|
||||
raise OSError("Marionette never wrote MarionetteActivePort in %.0f s (profile %s). %s"
|
||||
% (timeout, folder if folder is not None else "not found", marionette_diagnosis(0)))
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def _profile_of_the_engine() -> Optional[Path]:
|
||||
"""The `-profile` of the parent process of the engine below this process, or None while it is not there."""
|
||||
import psutil
|
||||
|
||||
try:
|
||||
below = psutil.Process().children(recursive=True)
|
||||
except psutil.Error:
|
||||
return None
|
||||
for proc in below:
|
||||
try:
|
||||
cmd = proc.cmdline()
|
||||
if _runs_firefox(proc) and "-contentproc" not in cmd and "-profile" in cmd:
|
||||
return Path(cmd[cmd.index("-profile") + 1])
|
||||
except (psutil.Error, OSError, ValueError, IndexError):
|
||||
continue
|
||||
return None
|
||||
|
||||
FONTS_REPORTER = "explicit/gfx/webrender/resource-cache/fonts"
|
||||
|
||||
@@ -246,16 +282,15 @@ def run(binary: str, contexts: int = 20, open_at_once: int = 3) -> Dict[str, flo
|
||||
folder = tempfile.mkdtemp(prefix="webfont_probe_")
|
||||
result: Dict[str, float] = {"contexts": contexts}
|
||||
marionette = None
|
||||
port = marionette_port()
|
||||
try:
|
||||
# the engine reads the variable from the environment it inherits (the launcher takes none): set for this launch only, undone after it
|
||||
with mock.patch.dict(os.environ, {"MOZ_REMOTE_ALLOW_SYSTEM_ACCESS": "1"}), InvisiblePlaywright(
|
||||
binary_path=binary, headless=True, humanize=False, extra_args=["-marionette"],
|
||||
extra_prefs={"marionette.port": port}) as browser:
|
||||
extra_prefs={"marionette.port": 0}) as browser:
|
||||
keep = browser.new_context()
|
||||
keep_page = keep.new_page()
|
||||
keep_page.goto(root + "/blank.html")
|
||||
marionette = _Marionette(port)
|
||||
marionette = _Marionette(marionette_active_port())
|
||||
marionette.call("WebDriver:NewSession", {"capabilities": {"alwaysMatch": {}}})
|
||||
marionette.call("WebDriver:SetTimeouts", {"script": 240000})
|
||||
result["before_mb"] = fonts_mb(marionette, folder, "before")
|
||||
|
||||
Reference in new issue
Block a user