ci: the page A/B oracle reads a poisoned host and every realm a page can make, and holds both to the declared identity
The comparison of two engines on one machine lets through a value both read from it. The page oracle's leg now runs on a machine given values the engine must never read, and the dumps are held to what the persona declares: * scripts/ci_poison_host.py: apply, verify and undo per system. Windows: the zone of Lima (tzutil), the ja-JP culture and user language list, the dark scheme (HKCU AppsUseLightTheme and SystemUsesLightTheme), a per-user canary font. Linux: TZ, LANG, GTK_THEME, a user-installed canary font, and a null PulseAudio sink at 96000 Hz with 6 channels as the default. The canary is generated, byte for byte the same every time (no third-party font). Every PowerShell forces the invariant culture first, and the state it keeps is text read before any change. `control` is the negative control: Playwright's own Firefox on the same runner must read the offsets of Lima, the dark scheme, the canary's width and, on Linux, the 96000 Hz sink, or it is a broken control. The dumps' findings are the host's values against what the identity declares (the core's prefs of the seed and the retail reference). * host_gate_page.html: the ab.poison probe (one block between two markers, which the control evaluates too). * scripts/host_gate/ab and ci_host_gate.py: an extra visit of seeds 0 and 63 in a launch of ja-JP and in a context of de-DE and America/Lima: the top window, a cross-site iframe, a srcdoc iframe, a worker, a shared worker, a service worker answering a navigation, an audio worklet, OffscreenCanvas, canvas and WebGL hashes in each, window.open with and without features, the Accept-Language the server saw per kind of request, and a re-read after back/forward. Leaves are under ab. (skipped by the retail comparison like diag., compared by the A/B). Seed 63 is the control of seed 0: it must differ on at least AB_CONTROL_MIN leaves. * the page oracle's test checks that the ab visit read, that the control held, and on a poisoned host that the poison is in force, that stock Firefox read it and that neither engine did.
This commit is contained in:
1 parent
6ff74cd2a0
commit
91b576aed2
18 files changed
+1870
-12
No files matched your search
@@ -14,8 +14,8 @@
|
||||
{"id": "wrapper.e2e.fakeweb", "giro": "G2", "os": ["linux", "windows"], "min_tests": 4, "exact": true, "tests": ["tests/test_fakeweb_p2_e2e.py", "tests/test_fakeweb_p4_e2e.py"], "marker": "e2e", "needs_root": false, "note": "The fake web, offline: our browser on the hard pages (profile P2: a reused routed page reaches networkidle every time, also under a load of three other browsers; the other site is another process) and on the 17-step journey of a person (profile P4), each judged against what stock Firefox does, as tests/fakeweb/pages.json declares it. 4 = 3 + 1. Stock itself is held to that declaration, and compared with ours step by step, by scripts/run_fakeweb.py in .github/workflows/fakeweb.yml. Needs the candidate binary (STEALTHFOX_E2E_BINARY)."},
|
||||
{"id": "wrapper.e2e.fontconfig", "giro": "G2", "os": ["linux"], "min_tests": 2, "exact": true, "tests": ["tests/test_the_parent_reads_the_bundle_from_fontconfig_s_cache_linux_e2e.py"], "marker": "e2e", "needs_root": false, "linux_only": "Fontconfig exists only on Linux: the parent of the engine shows <GRE>/fonts to it (FcConfigAppFontAddDir) to rebuild a font from a path and a face index. On Windows DirectWrite opens the file from its path, with no folder to scan and no cache to read, so this test has no Windows counterpart.", "note": "2 = (1) the stand-in that runs the engine under strace stays in the engine's place, as the core launches it (the leader of a process group of its own): a fake engine with a child, no browser; the process the launcher holds lives as long as the fake engine, and the group killed holds strace and the child (the stand-in that exec'd setsid forked and exited 0 at once: candidate 44161687675); (2) the warm launch of the parent reads the bundle from fontconfig's cache and does not scan it again (from firefox-66, engine_at_least). Two launches under strace with the same XDG_CACHE_HOME of the test, the first cold and the second warm: the cold parent opens every font file of <GRE>/fonts (the folder as the disk lists it) before any page and fontconfig writes its cache; the warm parent does not open every one of them, and it opens a *.cache-* file of fontconfig (a few files are opened to be used, so the verdict asks about the whole folder, as a scan does). Scan and drawing are told apart by position: only what the parent opens before the first page counts (the opens that draw are written as after_startup). Evidence in RUNNER_TEMP/invpw-evidence/fontconfig-cache: the interval and the number of opens of the bundle, the names of the files of the bundle each launch opened before the first page, the size of the cache file, the VmRSS of the parent after about:blank and after a page with every family, and a third launch with gfx.bundled-fonts.activate=0 (the behaviour before), which is evidence only. Needs strace on the runner: without it both are red, not skipped. No threshold."},
|
||||
{"id": "wrapper.unit.compositing", "giro": "G1", "os": ["linux", "windows"], "min_tests": 30, "exact": true, "tests": ["tests/test_the_page_bytes_reference_compares_decoded_pixels.py"], "marker": "unit", "needs_root": false, "note": "The helpers of wrapper.e2e.compositing on known inputs, no browser: the PNG compared on decoded pixels (another deBG chunk and compression are the same, one pixel is not, every scanline filter), the comparison with a reference (changed, missing and extra keys named, the entry to record), the type of an engine process, an engine process known by its executable and not by the name it gives itself (Linux), and the CPU of a window, and the shape of the committed Windows reference, and the box cut out of a screenshot (its pixels, a box outside the picture refused, written as a PNG and read back, two boxes told apart by a pixel that is named, the pixels that are not grey)."},
|
||||
{"id": "wrapper.unit.all.linux", "giro": "G1", "os": ["linux"], "min_tests": 2636, "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_ab_host.py", "tests/test_ab_network.py", "tests/test_ab_oracle.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_persona_cover.py", "tests/test_pin.py", "tests/test_pin_dicts_are_valid.py", "tests/test_pinning_doc.py", "tests/test_pointer_serLine truncated
|
||||
{"id": "wrapper.unit.all.windows", "giro": "G1", "os": ["windows"], "min_tests": 2637, "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_ab_host.py", "tests/test_ab_network.py", "tests/test_ab_oracle.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_persona_cover.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_adoptLine truncated
|
||||
{"id": "wrapper.unit.all.linux", "giro": "G1", "os": ["linux"], "min_tests": 2636, "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_ab_host.py", "tests/test_ab_network.py", "tests/test_ab_oracle.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_host_gate_ab.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_poison_host.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_persona_cover.py", "tests/test_pin.py", "tests/test_pin_dicts_arLine truncated
|
||||
{"id": "wrapper.unit.all.windows", "giro": "G1", "os": ["windows"], "min_tests": 2637, "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_ab_host.py", "tests/test_ab_network.py", "tests/test_ab_oracle.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_host_gate_ab.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_poison_host.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_persona_cover.py", "tests/test_pin.py", "tests/test_pin_dicts_are_valid.py", "tests/test_pinningLine 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.ab_oracle", "giro": "G2", "os": ["linux", "windows"], "min_tests": 1, "exact": true, "tests": ["tests/test_ab_oracle_e2e.py"], "marker": "e2e", "needs_root": false, "note": "Same seed, same bytes: the engine published as firefox-68 against the candidate, on one machine, with the same core and wrapper, after the control: the published engine against ITSELF (the A/A; a difference is a broken control, exit 2, and the A/B is not run). On a pull request (no candidate: INVPW_BINARY_PATH is the published engine, no INVISIBLE_SEAL_FILE) the A/A is the whole test, on the first two seeds of the candidate set (all five when the pull request changes a file of this oracle: the step of e2e.yml that runs scripts/ci_ab_pr_seeds.py exports AB_ORACLE_PR_SEEDS), and saves both dumps and the diff under $AB_ORACLE_OUT or $RUNNER_TEMP/invpw-evidence/ab-oracle. scripts/ci_ab_oracle.py runs the host gate's dump (scripts/ci_host_gate.py dump: the persona seeds of ci/persona-seeds.json, each at its own DPR with nothing pinned, the whole page of scripts/host_gate; the `candidate` set of 5 seeds that reach every webgl renderer and every DPR, or with AB_ORACLE_SEED_SET=final and AB_ORACLE_SHARD=i/n the 20 seeds that reach every value of every dimension split over n jobs) twice, once with the firefox-68 binary (the release's seal.json, then the core's own download.ensure_binary under that seal: the archive's sha256 is checked against the seal) and once with the candidate binary of the leg under its own seal, and compares every leaf of every visit: the only differences allowed are the `noise` entries of scripts/host_gate/exceptions.json and the diag. keys; anything else is red with the leaf, the two values and the seed; fewer leaves than the host gate's reference holds (16439 per visit; a DPR the reference does not record is held to the least of those it does) is red. The files (dump-68.json, dump-68-again.json, diff-a-a.json and, with a candidate, dump-candidate.json and diff.json) are the artifact ab-oracle-<os> of the leg. 1 = the one test; the comparator's own cases (51, the A/A's among them) are in tests/test_ab_oracle.py, the persona seeds' (15) in tests/test_persona_cover.py, in the rows of the whole unit suite. Needs the engine's binary (INVPW_BINARY_PATH) and, for the A/B, the candidate's seal (INVISIBLE_SEAL_FILE) and the network (the release assets of firefox-68). The engine of the candidate must accept the core of the leg and the 68 engine must accept it too: a core that declares something the published engine refuses is a red of this suite, not of the engine."},
|
||||
{"id": "wrapper.e2e.ab_network", "giro": "G2", "os": ["linux", "windows"], "min_tests": 1, "exact": true, "tests": ["tests/test_ab_network_e2e.py"], "marker": "e2e", "needs_root": false, "note": "Network A/B oracle: the P4 journey, HTTPS h1/h2 (ClientHello, h2 frames, header order), HTTP/3 (transport parameters, H3 SETTINGS), WebRTC through the coherent SOCKS5 lab gateway, DNS through the fake DoH, and an idle launch; transcripts compared leaf by leaf, direct connections red on either side. A/A first (the published engine twice: a difference is a broken control; ci/ab-network-volatile.json holds the leaves the A/A proved volatile, and may only shrink), then the published engine against the candidate. Without a candidate (a PR's e2e) the A/A alone, on the first seed (all five when the pull request changes a file of this oracle: AB_NETWORK_PR_SEEDS), in jobs of its own in e2e.yml on Linux and on Windows (the shared e2e jobs leave this file out)."},
|
||||
|
||||
@@ -15,6 +15,10 @@ seed runs at its OWN DPR (nothing is pinned):
|
||||
the archive against the seal and the engine against the seal);
|
||||
2. with the candidate binary the gate already holds, under its own seal.
|
||||
|
||||
The dump also reads what the host gate's retail comparison leaves alone, the ab. leaves (ci_host_gate.is_ab): ab.poison on every seed (zone, language, colour scheme, a
|
||||
canary font and the audio context, which scripts/ci_poison_host.py holds to the declared identity on a poisoned host) and, on seeds 0 and 63, the extra visit of every realm and
|
||||
window a page can make (--ab; ci_host_gate.ab_visit). They are compared like every other leaf; the diag. ones are not.
|
||||
|
||||
Then every leaf of every visit is compared. Everything must be equal. The only
|
||||
differences allowed are the `noise` entries of host_gate/exceptions.json (values that
|
||||
differ between two launches of one engine) and keys under the diag. prefix (what the
|
||||
@@ -341,7 +345,7 @@ def run_dump(binary: str, seal: Path | None, leg: str, out: Path, visits: list |
|
||||
if visits is not None:
|
||||
if relaunch_visits(visits):
|
||||
cmd += ["--relaunch-seed", str(RELAUNCH_SEED)]
|
||||
cmd += ["--no-pin"] + [a for dpr, seed in visits for a in ("--visit", "%d:%s" % (seed, dpr))]
|
||||
cmd += ["--no-pin", "--ab"] + [a for dpr, seed in visits for a in ("--visit", "%d:%s" % (seed, dpr))]
|
||||
with tempfile.TemporaryDirectory(prefix="ab-oracle-cache-") as cache:
|
||||
return subprocess.run(cmd, env=own_cache_env(env, cache), timeout=DUMP_TIMEOUT_S).returncode
|
||||
|
||||
|
||||
@@ -28,7 +28,8 @@ ROOT = Path(__file__).resolve().parent.parent
|
||||
SHARED = ("scripts/ci_ab_oracle.py", "scripts/ci_ab_pr_seeds.py", "scripts/persona_cover.py", "ci/persona-seeds.json")
|
||||
#: variable -> (oracle, seeds by default on a pull request that does not touch it, the files of the oracle: exact paths or fnmatch patterns).
|
||||
ORACLES = {
|
||||
"AB_ORACLE_PR_SEEDS": ("page", 2, SHARED + ("scripts/ci_host_gate.py", "scripts/host_gate/*", "tests/test_ab_oracle*")),
|
||||
"AB_ORACLE_PR_SEEDS": ("page", 2, SHARED + ("scripts/ci_host_gate.py", "scripts/ci_poison_host.py", "scripts/host_gate/*", "tests/test_ab_oracle*", "tests/test_ci_host_gate*",
|
||||
"tests/test_ci_poison_host.py")),
|
||||
"AB_NETWORK_PR_SEEDS": ("network", 1, SHARED + ("scripts/ci_ab_network.py", "ci/ab-network-volatile.json", "tests/test_ab_network*")),
|
||||
"AB_HOST_PR_SEEDS": ("host", 2, SHARED + ("scripts/ci_ab_host.py", "tests/_strace_stand_in.py", "ci/ab-host-expected.json", "tests/test_ab_host*")),
|
||||
}
|
||||
|
||||
+184
-5
@@ -41,6 +41,10 @@ legitimately differ on them and the retail reference does not record them.
|
||||
compare() skips them by name; dump() prints them into the job log, so a run
|
||||
tells why without its artifacts being downloaded.
|
||||
|
||||
Values under the ab. prefix are read for the A/B oracle: what a page reads of values a host may hold and the engine must never read
|
||||
(ab.poison, with scripts/ci_poison_host.py) and, on the oracle's visits of seeds 0 and 63, the surfaces of every realm and window a page
|
||||
can make (ab_visit). compare() skips them by name, as it skips diag.: the A/B compares them between the two engines.
|
||||
|
||||
Values under the state. prefix are the window in the states a page can drive
|
||||
it to: state.normal, state.fullscreen (entered through a real click, a user
|
||||
gesture) and state.after_fullscreen. The dump measures them after the page is
|
||||
@@ -71,6 +75,7 @@ import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from typing import Callable, NamedTuple
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
HERE = Path(__file__).resolve().parent / "host_gate"
|
||||
PAGE = HERE / "host_gate_page.html"
|
||||
@@ -105,6 +110,16 @@ def is_diag(key: str) -> bool:
|
||||
return key.startswith(DIAG)
|
||||
|
||||
|
||||
#: Keys under this prefix are read for the A/B oracle (scripts/ci_ab_oracle.py compares them between two engines on one machine). The host gate
|
||||
#: does not hold them to either of its properties: the retail reference does not record them, and they are made on the oracle's machine
|
||||
#: (a poisoned host, a launch in another locale), not on the gate's.
|
||||
AB = "ab."
|
||||
|
||||
|
||||
def is_ab(key: str) -> bool:
|
||||
return key.startswith(AB)
|
||||
|
||||
|
||||
def diag_lines(items: dict, before: dict | None = None) -> list:
|
||||
"""The diag. leaves of one visit as 'key = value' lines; with before (an
|
||||
earlier visit's diag leaves), only the keys whose value changed."""
|
||||
@@ -440,11 +455,12 @@ def second_launch(options: dict, port: int, dpr: float, timeout_ms: int, read=No
|
||||
|
||||
|
||||
def dump(firefox: str, leg: str, out: Path, reference: Path, timeout_ms: int = 180_000,
|
||||
visits: list | None = None, pin_dpr: bool = True, relaunch_seeds: tuple = ()) -> int:
|
||||
visits: list | None = None, pin_dpr: bool = True, relaunch_seeds: tuple = (), ab: bool = False) -> int:
|
||||
"""`visits` is [(dpr, seed)] (default: every seed of SEEDS at every DPR of DPRS, the DPR pinned). With pin_dpr
|
||||
False the DPR is not pinned: it is the one the seed's persona has, and `dpr` of a visit only names the file and
|
||||
the page's query. A seed of `relaunch_seeds` is visited once more, launched twice on one profile folder, and the
|
||||
items of that second launch are added to the visit under RELAUNCH (the visit's own items stay those of a fresh profile)."""
|
||||
items of that second launch are added to the visit under RELAUNCH (the visit's own items stay those of a fresh profile).
|
||||
With `ab`, the seeds of AB_SEEDS also get the extra visit of the A/B oracle (ab_visit): its leaves join the visit's items."""
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), _Page)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
@@ -465,6 +481,8 @@ def dump(firefox: str, leg: str, out: Path, reference: Path, timeout_ms: int = 1
|
||||
return 2
|
||||
result["items"].update(relaunch_items(again["items"]))
|
||||
print("second launch of seed %d on a reused profile: %d items" % (seed, len(again["items"])))
|
||||
if ab and seed in AB_SEEDS:
|
||||
result["items"].update(ab_visit(firefox, seed, zone, dpr if pin_dpr else None))
|
||||
path = out / ("%s_dpr%s_seed%d.json" % (leg, dpr, seed))
|
||||
path.write_text(json.dumps({"leg": leg, "dpr": dpr, "seed": seed, "result": result}),
|
||||
encoding="utf-8")
|
||||
@@ -483,6 +501,165 @@ def dump(firefox: str, leg: str, out: Path, reference: Path, timeout_ms: int = 1
|
||||
return 0
|
||||
|
||||
|
||||
# -
|
||||
# The A/B oracle's extra visit: every realm and every kind of window a page can make, in a launch of another locale and in a context of yet
|
||||
# another, on seeds 0 and 63. Its leaves are under ab. (see is_ab): scripts/ci_ab_oracle.py compares them between the two engines. It is a
|
||||
# separate launch per seed, with its own server and its own functions: nothing here changes how the visits above are made.
|
||||
#
|
||||
# Seed 63 is the CONTROL of seed 0: an identity that is not seed 0's must read other values, so the same block on both must differ on at least
|
||||
# AB_CONTROL_MIN ab. leaves (ab_control). A block that answered the same for two identities would pass an engine that ignores the identity.
|
||||
|
||||
AB_DIR = HERE / "ab"
|
||||
AB_SEEDS = (0, 63)
|
||||
AB_LAUNCH_LOCALE = "ja-JP"
|
||||
#: (name of the context, what the context is made with). The first is the launch's own default context (locale ja-JP); the second overrides
|
||||
#: both the language and the zone.
|
||||
AB_CONTEXTS = (("launch", {}), ("context", {"locale": "de-DE", "timezone_id": "America/Lima"}))
|
||||
AB_BUDGET_MS = 240_000
|
||||
#: How many ab. leaves seed 63 must differ from seed 0 on. PROVISIONAL, from the core's prefs and not from a run: the two personas differ in their core
|
||||
#: count (12 and 32), their GPU, their screen and their DPR, so hardwareConcurrency alone differs in every realm that must have read (top, cross-site
|
||||
#: iframe, srcdoc iframe, worker, in each of the 2 contexts: 8 leaves) and the page-read GPU, the screen and the canvas leaves come on top of them.
|
||||
#: The first run on GitHub prints the measured count (ab_control's line in the oracle's log, and ab-control.json): this number then moves to a safe
|
||||
#: fraction of it, written here with the run it came from.
|
||||
AB_CONTROL_MIN = 8
|
||||
AB_CONTROL_NAMESPACES = tuple("%s%s." % (AB, name) for name, _ in AB_CONTEXTS)
|
||||
|
||||
_AB_TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8"}
|
||||
#: A one-pixel GIF: what /ab/probe answers to a fetch and to an image alike.
|
||||
_GIF = base64.b64decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")
|
||||
|
||||
|
||||
class _AbSite(BaseHTTPRequestHandler):
|
||||
"""The site of the ab visit: the files of scripts/host_gate/ab, /ab/probe (a pixel) and /ab/seen (the Accept-Language the server saw,
|
||||
per context, by kind of request: `<Sec-Fetch-Dest>:<path>` -> the sorted distinct values)."""
|
||||
|
||||
def _send(self, status, content_type, body):
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self):
|
||||
url = urlsplit(self.path)
|
||||
ctx = (parse_qs(url.query).get("ctx") or [""])[0]
|
||||
if url.path == "/ab/seen":
|
||||
with self.server.ab_lock:
|
||||
seen = {k: sorted(v) for k, v in self.server.ab_seen.get(ctx, {}).items()}
|
||||
return self._send(200, "application/json", json.dumps(seen, sort_keys=True).encode())
|
||||
if url.path.startswith("/ab/"):
|
||||
with self.server.ab_lock:
|
||||
kind = "%s:%s" % (self.headers.get("Sec-Fetch-Dest") or "none", url.path)
|
||||
self.server.ab_seen.setdefault(ctx, {}).setdefault(kind, set()).add(self.headers.get("Accept-Language") or "<none>")
|
||||
if url.path.startswith("/ab/probe"):
|
||||
return self._send(200, "image/gif", _GIF)
|
||||
name = url.path[len("/ab/"):] if url.path.startswith("/ab/") else ""
|
||||
path = AB_DIR / name
|
||||
if not name or "/" in name or "\\" in name or path.suffix not in _AB_TYPES or not path.is_file():
|
||||
return self._send(404, "text/plain", b"not found")
|
||||
return self._send(200, _AB_TYPES[path.suffix], path.read_bytes())
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def ab_options(firefox: str, seed: int, dpr: float | None, zone: str) -> dict:
|
||||
"""The launch of the ab visit: the host gate's own, in ja-JP."""
|
||||
options = {"seed": seed, "binary_path": firefox, "headless": True, "show_cursor": False,
|
||||
"locale": AB_LAUNCH_LOCALE, "timezone": zone}
|
||||
if dpr is not None:
|
||||
options["pin"] = {"screen.dpr": dpr}
|
||||
return options
|
||||
|
||||
|
||||
def ab_items(context: str, result, back) -> dict:
|
||||
"""The items of one context of the ab visit: what the page recorded (ab.<context>.<step>...), what a page that came back from the history reads
|
||||
again (ab.<context>.bfcache: whether it was restored from the back/forward cache is the engine's, not the identity's, and goes to diag.)."""
|
||||
body = dict(result) if isinstance(result, dict) else {"result": result}
|
||||
body["bfcache"] = back.get("data") if isinstance(back, dict) else back
|
||||
return {AB + context: body, DIAG + AB + context: {"bfcache_persisted": back.get("persisted") if isinstance(back, dict) else None}}
|
||||
|
||||
|
||||
def ab_visit(firefox: str, seed: int, zone: str, dpr: float | None = None, timeout_ms: int = AB_BUDGET_MS) -> dict:
|
||||
"""Launch `firefox` with the seed in ja-JP, and read the ab site in its default context and in a context of de-DE and America/Lima;
|
||||
returns {key: value} to add to the visit's items."""
|
||||
from invisible_playwright import InvisiblePlaywright
|
||||
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), _AbSite)
|
||||
server.ab_seen, server.ab_lock = {}, threading.Lock()
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
base = "http://127.0.0.1:%d/ab/" % server.server_address[1]
|
||||
items = {}
|
||||
try:
|
||||
with InvisiblePlaywright(**ab_options(firefox, seed, dpr, zone)) as browser:
|
||||
for name, options in AB_CONTEXTS:
|
||||
context = browser.new_context(**options)
|
||||
try:
|
||||
page = context.new_page()
|
||||
page.goto(base + "surfaces.html?ctx=" + name, timeout=timeout_ms)
|
||||
page.wait_for_function("document.title === 'ab-done'", timeout=timeout_ms)
|
||||
result = page.evaluate("window.__abResult")
|
||||
# away and back: the page that comes back reads again (pageshow), restored from the cache or loaded anew
|
||||
page.goto(base + "leave.html?ctx=" + name, timeout=timeout_ms)
|
||||
page.go_back(timeout=timeout_ms)
|
||||
page.wait_for_function("window.__abBf && window.__abBf.n >= 2", timeout=timeout_ms)
|
||||
back = page.evaluate("window.__abBf")
|
||||
finally:
|
||||
context.close()
|
||||
items.update(ab_items(name, result, back))
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
return items
|
||||
|
||||
|
||||
def ab_control(items_by_seed: dict, seeds: tuple = AB_SEEDS, minimum: int | None = None) -> dict:
|
||||
"""The control of the ab visit: on how many leaves of the ab visit seeds[1] differs from seeds[0]. `items_by_seed` maps a seed to its items.
|
||||
Returns {"status": "ok"|"too_few"|"not_visited", "differing", "compared", "minimum", "line"}; not_visited (a run that did not visit both,
|
||||
the pull request's two seeds) is said, and the caller decides whether that is allowed."""
|
||||
minimum = AB_CONTROL_MIN if minimum is None else minimum
|
||||
a, b = seeds
|
||||
mine = {}
|
||||
for seed in seeds:
|
||||
items = items_by_seed.get(seed)
|
||||
mine[seed] = None if items is None else {k: v for k, v in leaves(items).items() if k.startswith(AB_CONTROL_NAMESPACES)}
|
||||
if not mine[a] or not mine[b]:
|
||||
missing = [s for s in seeds if not mine[s]]
|
||||
return {"status": "not_visited", "differing": None, "compared": None, "minimum": minimum,
|
||||
"line": "ab control: seed %s has no ab. leaves in this run" % " and ".join(map(str, missing))}
|
||||
keys = sorted(set(mine[a]) | set(mine[b]))
|
||||
differing = [k for k in keys if mine[a].get(k, "<missing>") != mine[b].get(k, "<missing>")]
|
||||
status = "ok" if len(differing) >= minimum else "too_few"
|
||||
return {"status": status, "differing": len(differing), "compared": len(keys), "minimum": minimum, "sample": differing[:12],
|
||||
"line": "ab control: seed %d differs from seed %d on %d of %d ab. leaves (at least %d are required)%s"
|
||||
% (b, a, len(differing), len(keys), minimum, "" if status == "ok" else ": an identity that is not seed %d's read the same" % a)}
|
||||
|
||||
|
||||
#: The steps of the ab visit that must have read something in every context: a realm that answers `timeout` or an error says the page did not
|
||||
#: read, and an A/B of two such answers compares nothing. The others (the service worker, the audio worklet, the popups) may be missing on a
|
||||
#: host that has none of it; what they answered is compared like any leaf.
|
||||
AB_REQUIRED_STEPS = ("top", "iframe_cross", "iframe_srcdoc", "worker", "accept_language")
|
||||
|
||||
|
||||
def ab_coverage(items_by_seed: dict, seeds: tuple = AB_SEEDS) -> list:
|
||||
"""What is missing from the ab visit of the seeds of this run that have one: [problem]. A seed of `seeds` that the run visited without an
|
||||
ab visit, a context without its leaves, and a required step that did not read a dict are problems."""
|
||||
problems = []
|
||||
for seed in seeds:
|
||||
items = items_by_seed.get(seed)
|
||||
if items is None:
|
||||
continue
|
||||
for name, _ in AB_CONTEXTS:
|
||||
body = items.get(AB + name)
|
||||
if not isinstance(body, dict):
|
||||
problems.append("seed %d: no %s%s leaves (the ab visit did not run, or the page recorded none)" % (seed, AB, name))
|
||||
continue
|
||||
for step in AB_REQUIRED_STEPS:
|
||||
if not isinstance(body.get(step), dict):
|
||||
problems.append("seed %d %s%s.%s: %s" % (seed, AB, name, step, json.dumps(body.get(step))[:160]))
|
||||
return problems
|
||||
|
||||
|
||||
# -
|
||||
# Compare: every leg, every visit, against each other and against retail.
|
||||
|
||||
@@ -547,7 +724,7 @@ def compare(dumps: Path, reference: Path, exceptions: dict, notes: list | None =
|
||||
for path in sorted(dumps.glob("*.json")):
|
||||
d = json.loads(path.read_text(encoding="utf-8"))
|
||||
items = d["result"]["items"]
|
||||
visits[(d["leg"], d["dpr"], d["seed"])] = {k: v for k, v in leaves(items).items() if not is_diag(k)}
|
||||
visits[(d["leg"], d["dpr"], d["seed"])] = {k: v for k, v in leaves(items).items() if not is_diag(k) and not is_ab(k)}
|
||||
# the invariants: every leg, every visit, every state; no exception and no reference applies
|
||||
failures += invariant_lines("%s dpr %s seed %d" % (d["leg"], d["dpr"], d["seed"]), items)
|
||||
if not visits:
|
||||
@@ -559,7 +736,7 @@ def compare(dumps: Path, reference: Path, exceptions: dict, notes: list | None =
|
||||
items = reference_items(reference, dpr)
|
||||
if items is None:
|
||||
return ["no retail reference for dpr %s in %s" % (dpr, reference)]
|
||||
refs[dpr] = {k: v for k, v in leaves(items).items() if not is_diag(k)}
|
||||
refs[dpr] = {k: v for k, v in leaves(items).items() if not is_diag(k) and not is_ab(k)}
|
||||
pending[dpr] = tuple(p for p in REFERENCE_PENDING if not any(k.startswith(p) for k in refs[dpr]))
|
||||
for p in pending[dpr]:
|
||||
if notes is not None:
|
||||
@@ -641,6 +818,8 @@ def main(argv=None) -> int:
|
||||
d.add_argument("--reference", type=Path, default=REFERENCE)
|
||||
d.add_argument("--visit", action="append", metavar="SEED:DPR",
|
||||
help="visit this seed (repeatable; default: the host gate's own seeds at its own DPRs)")
|
||||
d.add_argument("--ab", action="store_true",
|
||||
help="the seeds of AB_SEEDS also get the A/B oracle's extra visit (ab. leaves)")
|
||||
d.add_argument("--no-pin", action="store_true",
|
||||
help="do not pin the DPR: the seed's persona has its own (the DPR of --visit only names the file)")
|
||||
d.add_argument("--relaunch-seed", action="append", type=int, default=[], metavar="SEED",
|
||||
@@ -654,7 +833,7 @@ def main(argv=None) -> int:
|
||||
if args.visit:
|
||||
visits = [(float(dpr), int(seed)) for seed, dpr in (v.split(":", 1) for v in args.visit)]
|
||||
return dump(args.firefox, args.leg, args.out, args.reference, visits=visits, pin_dpr=not args.no_pin,
|
||||
relaunch_seeds=tuple(args.relaunch_seed))
|
||||
relaunch_seeds=tuple(args.relaunch_seed), ab=args.ab)
|
||||
notes = []
|
||||
failures = compare(args.dumps, args.reference, load_exceptions(), notes)
|
||||
for n in notes:
|
||||
|
||||
@@ -0,0 +1,600 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The poisoned host of the page A/B oracle.
|
||||
|
||||
The page oracle compares two engines on one machine, so a value both read from that machine passes the comparison. This puts values on the
|
||||
machine that the engine must never read, for the run of the page oracle only (the job of that leg: the host oracle's parsers read
|
||||
tracerpt and strace output and are not in it), and proves that they are there with a NEGATIVE CONTROL: Playwright's own Firefox on the
|
||||
same runner reads them. The engine's dumps are then held to the identity the core declares, never to the poison.
|
||||
|
||||
poison where Firefox reads it what the engine declares instead
|
||||
time zone Lima (UTC-5, no DST): Windows `tzutil`, Linux `TZ` the zone of the host gate's reference (Asia/Bangkok), by the launch
|
||||
language ja-JP: Windows `Set-Culture` and the user language list, en-US, by the launch
|
||||
Linux `LANG`
|
||||
colour scheme dark: Windows AppsUseLightTheme=0, Linux `GTK_THEME` the scheme of the seed's persona (dark for 40% of them)
|
||||
fonts a user-installed CANARY font, family `ZZHostCanary`: no such family: a user font is not the declared machine's
|
||||
Windows per-user fonts, Linux ~/.local/share/fonts
|
||||
audio (Linux) a null sink at 96000 Hz and 6 channels, the default sink the persona's sample rate (44100 or 48000) and channel count
|
||||
|
||||
The canary is generated here, byte for byte the same every time (`canary_font()`: a TrueType font of three glyphs, written from the
|
||||
specification, no third-party font and so no licence): every letter and digit is a box 1.5 em wide, so a page that reads the family
|
||||
measures a text far wider than any fallback. Its sha256 is CANARY_SHA256 and the tests hold the two together.
|
||||
|
||||
python ci_poison_host.py apply [--state FILE] [--no-audio] put the poison on this machine (and verify it); writes the undo state
|
||||
python ci_poison_host.py verify [--expect-env] the poison is in force (--expect-env: this process also inherited the variables)
|
||||
python ci_poison_host.py undo --state FILE put back what apply found
|
||||
python ci_poison_host.py control --out FILE the negative control: stock Firefox of Playwright reads the poison, or exit 2 (broken control)
|
||||
python ci_poison_host.py font --out FILE write the canary font
|
||||
|
||||
Windows warning. `Set-Culture` changes the number and date formats of every process started after it. Every PowerShell this script runs
|
||||
starts by forcing the invariant culture on its own thread, and the state it keeps is text it read before the change: nothing here
|
||||
parses a formatted number or a date. The poison belongs to the page oracle's job and `undo` runs before that job's judge.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
PAGE = HERE / "host_gate" / "host_gate_page.html"
|
||||
|
||||
FAMILY = "ZZHostCanary"
|
||||
FONT_FILE = FAMILY + ".ttf"
|
||||
#: Where Firefox must read Lima from, in the two spellings: the Windows id and the IANA name (the offsets are what a page tells apart).
|
||||
WINDOWS_ZONE, IANA_ZONE = "SA Pacific Standard Time", "America/Lima"
|
||||
LIMA_OFFSETS = [300, 300]
|
||||
CULTURE, LINUX_LANG = "ja-JP", "ja_JP.UTF-8"
|
||||
GTK_THEME = "Adwaita:dark"
|
||||
SINK, SINK_RATE, SINK_CHANNELS = "hostcanary", 96000, 6
|
||||
SINK_MAP = "front-left,front-right,front-center,lfe,rear-left,rear-right"
|
||||
#: The variables a Linux poison puts in the environment of the later steps ($GITHUB_ENV), and the one that says it is on.
|
||||
LINUX_ENV = {"TZ": IANA_ZONE, "LANG": LINUX_LANG, "LANGUAGE": "ja", "GTK_THEME": GTK_THEME}
|
||||
SWITCH = "AB_ORACLE_POISON"
|
||||
#: The variable that names the file `apply` wrote its undo state to.
|
||||
STATE_SWITCH = "AB_ORACLE_POISON_STATE"
|
||||
THEME_KEY = r"HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"
|
||||
FONTS_KEY = r"HKCU:\Software\Microsoft\Windows NT\CurrentVersion\Fonts"
|
||||
FONT_VALUE = FAMILY + " (TrueType)"
|
||||
|
||||
Run = Callable[[list], tuple]
|
||||
|
||||
|
||||
# -
|
||||
# The canary font.
|
||||
|
||||
def _checksum(data: bytes) -> int:
|
||||
data += b"\0" * (-len(data) % 4)
|
||||
return sum(struct.unpack(">%dI" % (len(data) // 4), data)) & 0xFFFFFFFF
|
||||
|
||||
|
||||
def _pad(data: bytes) -> bytes:
|
||||
return data + b"\0" * (-len(data) % 4)
|
||||
|
||||
|
||||
def canary_font() -> bytes:
|
||||
"""A TrueType font, family ZZHostCanary, of three glyphs: .notdef and every character of U+0021..U+007E are boxes, U+0020 is blank.
|
||||
The advance of a box is 1500 units of 1000 per em, the space's 500. Deterministic: no clock, no randomness."""
|
||||
upem, box_advance, space_advance = 1000, 1500, 500
|
||||
box = struct.pack(">hhhhh", 1, 100, 0, 1400, 700) + struct.pack(">H", 3) + struct.pack(">H", 0) + bytes([1, 1, 1, 1]) \
|
||||
+ struct.pack(">4h", 100, 0, 1300, 0) + struct.pack(">4h", 0, 700, 0, -700)
|
||||
glyf = _pad(box) + _pad(box) # .notdef and the box: the same drawing
|
||||
loca = struct.pack(">4I", 0, len(_pad(box)), 2 * len(_pad(box)), 2 * len(_pad(box))) # .notdef, box, space (empty)
|
||||
hmtx = struct.pack(">HhHhHh", box_advance, 100, box_advance, 100, space_advance, 0)
|
||||
head = struct.pack(">IIIIHHqqhhhhHHhhh", 0x00010000, 0x00010000, 0, 0x5F0F3CF5, 0x000B, upem,
|
||||
3_700_000_000, 3_700_000_000, 0, 0, 1400, 700, 0, 8, 2, 1, 0)
|
||||
hhea = struct.pack(">IhhhHhhhhhhhhhhhH", 0x00010000, 800, -200, 0, box_advance, 100, 100, 1400, 1, 0, 0, 0, 0, 0, 0, 0, 3)
|
||||
maxp = struct.pack(">IHHHHHHHHHHHHHH", 0x00010000, 3, 4, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0)
|
||||
os2 = struct.pack(">HhHHH11h", 4, 1500, 400, 5, 0, 650, 600, 0, 75, 650, 600, 0, 350, 50, 250, 0)
|
||||
os2 += bytes(10) + struct.pack(">IIII", 1, 0, 0, 0) + b"NONE"
|
||||
os2 += struct.pack(">HHHhhhHHII", 0x40, 0x20, 0x7E, 800, -200, 0, 800, 200, 1, 0) + struct.pack(">hhHHH", 500, 700, 0, 0x20, 1)
|
||||
post = struct.pack(">IIhhIIIII", 0x00030000, 0, -100, 50, 0, 0, 0, 0, 0)
|
||||
# cmap: format 4, one segment per character (a constant glyph needs no glyph-index array)
|
||||
chars = [(0x20, 2)] + [(c, 1) for c in range(0x21, 0x7F)]
|
||||
ends = [c for c, _ in chars] + [0xFFFF]
|
||||
deltas = [(g - c) & 0xFFFF for c, g in chars] + [1]
|
||||
seg = len(ends)
|
||||
sub = (struct.pack(">HHHHHHH", 4, 16 + 8 * seg, 0, seg * 2, 128, 6, 2 * seg - 128)
|
||||
+ struct.pack(">%dH" % seg, *ends) + struct.pack(">H", 0) + struct.pack(">%dH" % seg, *ends)
|
||||
+ struct.pack(">%dH" % seg, *deltas) + struct.pack(">%dH" % seg, *([0] * seg)))
|
||||
cmap = struct.pack(">HHHHI", 0, 1, 3, 1, 12) + sub
|
||||
names = {1: FAMILY, 2: "Regular", 3: FAMILY + "-Regular-1.000", 4: FAMILY + " Regular", 5: "Version 1.000", 6: FAMILY + "-Regular"}
|
||||
strings, records = b"", b""
|
||||
for nid in sorted(names):
|
||||
text = names[nid].encode("utf-16-be")
|
||||
records += struct.pack(">HHHHHH", 3, 1, 0x409, nid, len(text), len(strings))
|
||||
strings += text
|
||||
name = struct.pack(">HHH", 0, len(names), 6 + 12 * len(names)) + records + strings
|
||||
tables = {b"OS/2": os2, b"cmap": cmap, b"glyf": glyf, b"head": head, b"hhea": hhea, b"hmtx": hmtx,
|
||||
b"loca": loca, b"maxp": maxp, b"name": name, b"post": post}
|
||||
n = len(tables)
|
||||
out = struct.pack(">IHHHH", 0x00010000, n, 128, 3, n * 16 - 128)
|
||||
offset = 12 + 16 * n
|
||||
body = b""
|
||||
for tag in sorted(tables):
|
||||
data = tables[tag]
|
||||
out += struct.pack(">4sIII", tag, _checksum(data), offset + len(body), len(data))
|
||||
body += _pad(data)
|
||||
font = bytearray(out + body)
|
||||
head_at = offset + sum(len(_pad(tables[t])) for t in sorted(tables) if t < b"head") + 8
|
||||
struct.pack_into(">I", font, head_at, (0xB1B0AFBA - _checksum(bytes(font))) & 0xFFFFFFFF)
|
||||
return bytes(font)
|
||||
|
||||
|
||||
#: The sha256 of canary_font(): a font that changed is a different poison, said here and held by a test.
|
||||
CANARY_SHA256 = "fc1a766e6253f2791fb422f241db7e14a9793a8975ebd867c13e1257110e4045"
|
||||
|
||||
|
||||
def canary_sha256() -> str:
|
||||
return hashlib.sha256(canary_font()).hexdigest()
|
||||
|
||||
|
||||
def read_tables(font: bytes) -> dict:
|
||||
"""{tag: bytes} of an sfnt, after checking the directory's checksums and the whole-file checksum (head.checkSumAdjustment)."""
|
||||
n = struct.unpack_from(">H", font, 4)[0]
|
||||
tables = {}
|
||||
for i in range(n):
|
||||
tag, csum, off, length = struct.unpack_from(">4sIII", font, 12 + 16 * i)
|
||||
data = font[off:off + length]
|
||||
if tag != b"head" and _checksum(data) != csum:
|
||||
raise ValueError("table %r: bad checksum" % tag)
|
||||
tables[tag.decode("latin-1")] = data
|
||||
if _checksum(font) != 0xB1B0AFBA:
|
||||
raise ValueError("the whole-file checksum is not the one head.checkSumAdjustment makes")
|
||||
return tables
|
||||
|
||||
|
||||
# -
|
||||
# What the page reads: the probe lives in the page (host_gate_page.html, between the two markers) and the control evaluates the same text.
|
||||
|
||||
PROBE_BEGIN, PROBE_END = "// ab.poison:begin", "// ab.poison:end"
|
||||
|
||||
|
||||
def probe_source(page: Path = PAGE) -> str:
|
||||
"""The probe function of the page, `const abPoisonProbe = async () => {...};`, exactly as the page runs it."""
|
||||
text = page.read_text(encoding="utf-8")
|
||||
if text.count(PROBE_BEGIN) != 1 or text.count(PROBE_END) != 1 or text.index(PROBE_BEGIN) > text.index(PROBE_END):
|
||||
raise SystemExit("%s must hold the probe between one %r and one %r" % (page.name, PROBE_BEGIN, PROBE_END))
|
||||
return text.split(PROBE_BEGIN, 1)[1].split(PROBE_END, 1)[0]
|
||||
|
||||
|
||||
# -
|
||||
# The engine under the poison: what its dumps must say instead.
|
||||
|
||||
def declared(seed: int, reference=None, dpr: float = 1.0) -> dict:
|
||||
"""What the identity of `seed` declares for each poisoned value: from the core's prefs of the seed (the dark scheme, the audio chain) and
|
||||
from the retail reference of the host gate (the zone and the language the launch declares, the strings they make)."""
|
||||
import ci_host_gate as gate
|
||||
import persona_cover as personas
|
||||
|
||||
prefs = {k: json.loads(v) for k, v in personas.seed_features(seed)[1].items()}
|
||||
intl = gate.reference_items(reference or gate.REFERENCE, dpr)["surface.intl"]
|
||||
return {"timezone": intl["DateTimeFormat"]["timeZone"], "offsets": intl["offsets"], "locale": intl["DateTimeFormat"]["locale"],
|
||||
"language": intl["languages"][0], "date_full": intl["strings"][4], "number": intl["strings"][3],
|
||||
"dark": bool(prefs["ui.systemUsesDarkTheme"]),
|
||||
"sample_rate": prefs[personas.P + "audio.sample_rate"], "max_channels": prefs[personas.P + "audio.max_channel_count"]}
|
||||
|
||||
|
||||
def findings(probe, want: dict) -> list:
|
||||
"""What an engine's `ab.poison` leaves say about the host, against `want` (declared()): every line is a value that is the machine's
|
||||
(or that is not what the persona declares), empty when the page read none of the poison. A page that dumped no probe is a finding too:
|
||||
it would pass anything."""
|
||||
if not isinstance(probe, dict) or not probe:
|
||||
return ["the dump has no ab.poison leaves: the page did not read the poison, so nothing was checked"]
|
||||
out = []
|
||||
|
||||
def expect(key, value, what):
|
||||
if probe.get(key) != value:
|
||||
out.append("%s: the page read %s, the identity declares %s" % (what, json.dumps(probe.get(key)), json.dumps(value)))
|
||||
|
||||
expect("timezone", want["timezone"], "time zone")
|
||||
expect("offsets", want["offsets"], "UTC offsets of January and July")
|
||||
if probe.get("offsets") == LIMA_OFFSETS and want["offsets"] != LIMA_OFFSETS:
|
||||
out.append("time zone: the offsets are the host's Lima (UTC-5, no DST)")
|
||||
expect("language", want["language"], "navigator.language")
|
||||
expect("intl_locale", want["locale"], "the default Intl locale")
|
||||
expect("date_full", want["date_full"], "a full date")
|
||||
expect("number", want["number"], "a formatted number")
|
||||
expect("dark", want["dark"], "prefers-color-scheme dark")
|
||||
canary = probe.get("canary")
|
||||
if not isinstance(canary, dict) or "present" not in canary:
|
||||
out.append("canary font: the probe did not measure it")
|
||||
elif canary["present"]:
|
||||
out.append("canary font: a page measures the user-installed family %s (its text is %s wide, a fallback's %s)"
|
||||
% (FAMILY, json.dumps(canary.get("with")), json.dumps(canary.get("without"))))
|
||||
audio = probe.get("audio")
|
||||
if not isinstance(audio, dict):
|
||||
out.append("audio: the probe did not read the audio context: %s" % json.dumps(audio))
|
||||
else:
|
||||
if audio.get("sampleRate") != want["sample_rate"]:
|
||||
out.append("audio: sampleRate %s, the persona declares %s" % (audio.get("sampleRate"), want["sample_rate"]))
|
||||
if audio.get("maxChannelCount") != want["max_channels"]:
|
||||
out.append("audio: maxChannelCount %s, the persona declares %s" % (audio.get("maxChannelCount"), want["max_channels"]))
|
||||
return out
|
||||
|
||||
|
||||
def dump_findings(dump: dict, wants: Callable = declared) -> list:
|
||||
"""findings() of every visit of a packed dump (ci_ab_oracle.pack), as 'seed N dprD: line'."""
|
||||
out = []
|
||||
for visit in dump.get("visits", []):
|
||||
probe = visit["items"].get("ab.poison")
|
||||
out += ["seed %d dpr %s: %s" % (visit["seed"], visit["dpr"], line) for line in findings(probe, wants(visit["seed"]))]
|
||||
return out
|
||||
|
||||
|
||||
# -
|
||||
# The negative control: what stock Firefox must read on the poisoned runner.
|
||||
|
||||
#: Each requirement of the control, with what it means. Language is reported and not required: Playwright's Firefox is an en-US build, which
|
||||
#: takes its language from its own locale, not from the machine; the control prints what it read, and the requirement is one line away
|
||||
#: (REQUIRED) once a run has shown that stock reads it.
|
||||
REQUIRED = ("timezone", "dark", "canary", "audio")
|
||||
|
||||
|
||||
def control_failures(probe, system: str) -> list:
|
||||
"""[(requirement, message)] of what stock Firefox did NOT read of the poison. `system` is 'linux' or 'windows' (audio is Linux's)."""
|
||||
if not isinstance(probe, dict):
|
||||
return [("probe", "the probe returned %s" % json.dumps(probe))]
|
||||
out = []
|
||||
if probe.get("offsets") != LIMA_OFFSETS:
|
||||
out.append(("timezone", "stock Firefox read the offsets %s, not Lima's %s" % (json.dumps(probe.get("offsets")), LIMA_OFFSETS)))
|
||||
if probe.get("dark") is not True:
|
||||
out.append(("dark", "stock Firefox read prefers-color-scheme dark = %s" % json.dumps(probe.get("dark"))))
|
||||
canary = probe.get("canary")
|
||||
if not isinstance(canary, dict) or canary.get("present") is not True:
|
||||
out.append(("canary", "stock Firefox did not measure the user-installed family %s: %s" % (FAMILY, json.dumps(canary))))
|
||||
if system == "linux":
|
||||
audio = probe.get("audio")
|
||||
if not isinstance(audio, dict) or audio.get("sampleRate") != SINK_RATE:
|
||||
out.append(("audio", "stock Firefox read the audio %s, not the null sink's %d Hz" % (json.dumps(audio), SINK_RATE)))
|
||||
return [(name, message) for name, message in out if name in REQUIRED]
|
||||
|
||||
|
||||
def language_reads(probe) -> dict:
|
||||
"""What stock read of the language, for the log: the leaves and whether any of them is Japanese."""
|
||||
keys = ("language", "languages", "intl_locale", "date_full", "number")
|
||||
reads = {k: probe.get(k) for k in keys} if isinstance(probe, dict) else {}
|
||||
text = json.dumps(reads, ensure_ascii=False)
|
||||
return {"reads": reads, "japanese": bool(re.search(r'"ja\b|"ja-|[-ヿ一-鿿]', text))}
|
||||
|
||||
|
||||
def system_name() -> str:
|
||||
return "windows" if sys.platform == "win32" else "linux"
|
||||
|
||||
|
||||
def control(out: Path, headless: bool = False) -> int:
|
||||
"""Launch Playwright's own Firefox (headed: a headless Firefox has no theme to read) on this runner, read the probe, write `out`.
|
||||
0 when it read the poison, 2 BROKEN CONTROL (the poison is not in force or the control cannot see it)."""
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
probe = None
|
||||
error = None
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.firefox.launch(headless=headless, firefox_user_prefs={"intl.regional_prefs.use_os_locales": True})
|
||||
try:
|
||||
page = browser.new_context().new_page()
|
||||
page.goto("about:blank")
|
||||
probe = page.evaluate("(async () => {%s; return await abPoisonProbe(); })()" % probe_source())
|
||||
finally:
|
||||
browser.close()
|
||||
except Exception as e: # noqa: BLE001 - a control that could not run is a broken control, with the reason
|
||||
error = "%s: %s" % (type(e).__name__, str(e)[:500])
|
||||
failures = [("run", error)] if error else control_failures(probe, system_name())
|
||||
report = {"format": "poison-control/1", "system": system_name(), "probe": probe, "language": language_reads(probe),
|
||||
"failures": [{"requirement": n, "message": m} for n, m in failures], "verdict": "green" if not failures else "broken"}
|
||||
out.write_text(json.dumps(report, sort_keys=True, indent=1, ensure_ascii=False), encoding="utf-8")
|
||||
print("stock Firefox read: %s" % json.dumps(probe, sort_keys=True, ensure_ascii=False))
|
||||
print("language, informational: %s" % json.dumps(report["language"], sort_keys=True, ensure_ascii=False))
|
||||
for name, message in failures:
|
||||
print("BROKEN CONTROL (%s): %s" % (name, message))
|
||||
print("POISON CONTROL %s" % ("OK" if not failures else "BROKEN"))
|
||||
return 0 if not failures else 2
|
||||
|
||||
|
||||
# -
|
||||
# Putting the poison on a machine, and taking it off.
|
||||
|
||||
def _run(cmd: list) -> tuple:
|
||||
try:
|
||||
done = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=180)
|
||||
except (OSError, subprocess.SubprocessError) as e: # the program is not on this machine, or did not answer
|
||||
return 127, "%s: %s" % (type(e).__name__, e)
|
||||
return done.returncode, (done.stdout or "") + (done.stderr if done.returncode else "")
|
||||
|
||||
|
||||
#: Every PowerShell of this script: the invariant culture on its own thread first (the culture of the machine is what the poison changes).
|
||||
PS_PRELUDE = ("[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::InvariantCulture; "
|
||||
"$ErrorActionPreference = 'Stop'; ")
|
||||
|
||||
|
||||
def ps(script: str) -> list:
|
||||
return ["powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", PS_PRELUDE + script]
|
||||
|
||||
|
||||
def _ok(run: Run, cmd: list, what: str) -> str:
|
||||
rc, text = run(cmd)
|
||||
if rc != 0:
|
||||
raise SystemExit("the poison could not %s (exit %s): %s" % (what, rc, text.strip()[:400]))
|
||||
return text.strip()
|
||||
|
||||
|
||||
def _try(run: Run, cmd: list) -> str:
|
||||
rc, text = run(cmd)
|
||||
return text.strip() if rc == 0 else ""
|
||||
|
||||
|
||||
def font_path_windows(env=None) -> Path:
|
||||
return Path((env or os.environ)["LOCALAPPDATA"]) / "Microsoft" / "Windows" / "Fonts" / FONT_FILE
|
||||
|
||||
|
||||
def font_dir_linux(env=None) -> Path:
|
||||
env = env or os.environ
|
||||
base = env.get("XDG_DATA_HOME") or str(Path(env.get("HOME") or Path.home()) / ".local" / "share")
|
||||
return Path(base) / "fonts"
|
||||
|
||||
|
||||
def _reg_get(name: str) -> list:
|
||||
return ps("$v = (Get-ItemProperty -Path '%s' -Name %s -ErrorAction SilentlyContinue).%s; if ($null -ne $v) { $v }" % (THEME_KEY, name, name))
|
||||
|
||||
|
||||
def _reg_set(name: str, value) -> list:
|
||||
if value in ("", None):
|
||||
return ps("Remove-ItemProperty -Path '%s' -Name %s -ErrorAction SilentlyContinue" % (THEME_KEY, name))
|
||||
return ps("New-ItemProperty -Path '%s' -Name %s -Value %s -PropertyType DWord -Force | Out-Null" % (THEME_KEY, name, int(value)))
|
||||
|
||||
|
||||
def apply_windows(run: Run = _run, font_dir: Path | None = None) -> dict:
|
||||
"""Put the poison on this Windows machine; returns the state `undo_windows` needs (what was there before, as text read before any change)."""
|
||||
font = font_path_windows() if font_dir is None else Path(font_dir) / FONT_FILE
|
||||
state = {"system": "windows", "font": str(font),
|
||||
"timezone": _ok(run, ["tzutil", "/g"], "read the time zone"),
|
||||
"culture": _ok(run, ps("(Get-Culture).Name"), "read the culture"),
|
||||
"languages": _ok(run, ps("(Get-WinUserLanguageList | ForEach-Object { $_.LanguageTag }) -join ','"), "read the user languages"),
|
||||
"theme": {n: _try(run, _reg_get(n)) for n in ("AppsUseLightTheme", "SystemUsesLightTheme")}}
|
||||
_ok(run, ["tzutil", "/s", WINDOWS_ZONE], "set the time zone")
|
||||
_ok(run, ps("Set-Culture -CultureInfo '%s'" % CULTURE), "set the culture")
|
||||
_ok(run, ps("Set-WinUserLanguageList -LanguageList '%s' -Force" % CULTURE), "set the user language list")
|
||||
for name in state["theme"]:
|
||||
_ok(run, _reg_set(name, 0), "set " + name)
|
||||
font.parent.mkdir(parents=True, exist_ok=True)
|
||||
font.write_bytes(canary_font())
|
||||
_ok(run, ps("New-ItemProperty -Path '%s' -Name '%s' -Value '%s' -PropertyType String -Force | Out-Null" % (FONTS_KEY, FONT_VALUE, font)),
|
||||
"register the canary font")
|
||||
_announce_font(str(font))
|
||||
return state
|
||||
|
||||
|
||||
def _announce_font(path: str) -> None:
|
||||
"""Tell the running session about the font (AddFontResourceW and WM_FONTCHANGE); a process started later reads the registry anyway."""
|
||||
try:
|
||||
import ctypes
|
||||
|
||||
ctypes.windll.gdi32.AddFontResourceW(path)
|
||||
ctypes.windll.user32.SendMessageTimeoutW(0xFFFF, 0x001D, 0, 0, 2, 1000, None)
|
||||
except Exception: # noqa: BLE001 - best effort: the registry entry is what a new process reads
|
||||
pass
|
||||
|
||||
|
||||
def _forget_font(path: str) -> None:
|
||||
try:
|
||||
import ctypes
|
||||
|
||||
ctypes.windll.gdi32.RemoveFontResourceW(path)
|
||||
except Exception: # noqa: BLE001 - best effort, as the announcement
|
||||
pass
|
||||
|
||||
|
||||
def undo_windows(state: dict, run: Run = _run) -> None:
|
||||
font = Path(state["font"])
|
||||
_try(run, ps("Remove-ItemProperty -Path '%s' -Name '%s' -ErrorAction SilentlyContinue" % (FONTS_KEY, FONT_VALUE)))
|
||||
_forget_font(str(font))
|
||||
try:
|
||||
font.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
for name, value in state["theme"].items():
|
||||
_try(run, _reg_set(name, value))
|
||||
if state.get("languages"):
|
||||
_try(run, ps("Set-WinUserLanguageList -LanguageList %s -Force" % ",".join("'%s'" % t for t in state["languages"].split(","))))
|
||||
if state.get("culture"):
|
||||
_try(run, ps("Set-Culture -CultureInfo '%s'" % state["culture"]))
|
||||
if state.get("timezone"):
|
||||
_try(run, ["tzutil", "/s", state["timezone"]])
|
||||
|
||||
|
||||
def verify_windows(run: Run = _run, state: dict | None = None) -> list:
|
||||
problems = []
|
||||
font = Path(state["font"]) if state else font_path_windows()
|
||||
tz = _try(run, ["tzutil", "/g"])
|
||||
if tz != WINDOWS_ZONE:
|
||||
problems.append("time zone is %r, not %r" % (tz, WINDOWS_ZONE))
|
||||
culture = _try(run, ps("(Get-Culture).Name"))
|
||||
if culture != CULTURE:
|
||||
problems.append("culture is %r, not %r" % (culture, CULTURE))
|
||||
langs = _try(run, ps("(Get-WinUserLanguageList | ForEach-Object { $_.LanguageTag }) -join ','")).split(",")
|
||||
if langs[0] != CULTURE:
|
||||
problems.append("the first user language is %r, not %r" % (langs[0], CULTURE))
|
||||
for name in ("AppsUseLightTheme", "SystemUsesLightTheme"):
|
||||
value = _try(run, _reg_get(name))
|
||||
if value != "0":
|
||||
problems.append("%s is %r, not 0 (dark)" % (name, value))
|
||||
registered = _try(run, ps("(Get-ItemProperty -Path '%s' -Name '%s' -ErrorAction SilentlyContinue).'%s'" % (FONTS_KEY, FONT_VALUE, FONT_VALUE)))
|
||||
if os.path.normcase(registered) != os.path.normcase(str(font)):
|
||||
problems.append("the canary font is registered at %r, not %r" % (registered, str(font)))
|
||||
problems += _font_file_problems(font)
|
||||
return problems
|
||||
|
||||
|
||||
def _font_file_problems(font: Path) -> list:
|
||||
if not font.is_file():
|
||||
return ["the canary font file %s is missing" % font.name]
|
||||
if hashlib.sha256(font.read_bytes()).hexdigest() != CANARY_SHA256:
|
||||
return ["the canary font file is not the canary (sha256 differs from %s)" % CANARY_SHA256]
|
||||
return []
|
||||
|
||||
|
||||
def _sudo(cmd: list) -> list:
|
||||
return cmd if getattr(os, "geteuid", lambda: 0)() == 0 else ["sudo", "-n"] + cmd
|
||||
|
||||
|
||||
def _sink_server(info: str) -> str:
|
||||
m = re.search(r"^Server String:\s*(\S+)", info, re.M)
|
||||
return m.group(1) if m else ""
|
||||
|
||||
|
||||
def apply_linux(run: Run = _run, font_dir: Path | None = None, audio: bool = True) -> dict:
|
||||
"""Put the poison on this Linux machine; returns the state `undo_linux` needs. The environment part is for the later steps of the job
|
||||
(state["env"], appended to $GITHUB_ENV by `apply`)."""
|
||||
fonts = font_dir_linux() if font_dir is None else Path(font_dir)
|
||||
state = {"system": "linux", "font": str(fonts / FONT_FILE), "env": dict(LINUX_ENV),
|
||||
"before_env": {k: os.environ.get(k, "") for k in list(LINUX_ENV) + ["PULSE_SERVER"]}, "module": ""}
|
||||
if "ja_jp.utf8" not in _try(run, ["locale", "-a"]).lower().replace("-", ""):
|
||||
_ok(run, _sudo(["locale-gen", LINUX_LANG]), "generate the %s locale" % LINUX_LANG)
|
||||
fonts.mkdir(parents=True, exist_ok=True)
|
||||
(fonts / FONT_FILE).write_bytes(canary_font())
|
||||
_ok(run, ["fc-cache", "-f", str(fonts)], "refresh the font cache")
|
||||
if audio:
|
||||
_try(run, ["pulseaudio", "--daemonize=yes", "--exit-idle-time=-1", "--disallow-exit"])
|
||||
module = _ok(run, ["pactl", "load-module", "module-null-sink", "sink_name=" + SINK, "rate=%d" % SINK_RATE,
|
||||
"channels=%d" % SINK_CHANNELS, "channel_map=" + SINK_MAP, "sink_properties=device.description=" + SINK],
|
||||
"load the null sink")
|
||||
state["module"] = module
|
||||
_ok(run, ["pactl", "set-default-sink", SINK], "make the null sink the default")
|
||||
server = _sink_server(_try(run, ["pactl", "info"]))
|
||||
if server:
|
||||
state["env"]["PULSE_SERVER"] = server if "://" in server or ":" in server.split("/")[0] else "unix:" + server
|
||||
return state
|
||||
|
||||
|
||||
def undo_linux(state: dict, run: Run = _run) -> None:
|
||||
if state.get("module"):
|
||||
_try(run, ["pactl", "unload-module", state["module"]])
|
||||
_try(run, ["pulseaudio", "--kill"])
|
||||
font = Path(state["font"])
|
||||
try:
|
||||
font.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
_try(run, ["fc-cache", "-f", str(font.parent)])
|
||||
|
||||
|
||||
def verify_linux(run: Run = _run, state: dict | None = None, expect_env: bool = False, audio: bool = True, env=None) -> list:
|
||||
problems = []
|
||||
font = Path(state["font"]) if state else font_dir_linux() / FONT_FILE
|
||||
if "ja_jp.utf8" not in _try(run, ["locale", "-a"]).lower().replace("-", ""):
|
||||
problems.append("the %s locale is not installed" % LINUX_LANG)
|
||||
problems += _font_file_problems(font)
|
||||
if FAMILY not in _try(run, ["fc-list", ":", "family"]):
|
||||
problems.append("fontconfig does not list the family %s" % FAMILY)
|
||||
if audio:
|
||||
sinks = _try(run, ["pactl", "list", "short", "sinks"])
|
||||
line = next((ln for ln in sinks.splitlines() if SINK in ln), "")
|
||||
if "%dch %dHz" % (SINK_CHANNELS, SINK_RATE) not in line:
|
||||
problems.append("the null sink %s is not %d channels at %d Hz: %r" % (SINK, SINK_CHANNELS, SINK_RATE, line))
|
||||
if SINK not in _try(run, ["pactl", "get-default-sink"]):
|
||||
problems.append("the null sink is not the default sink")
|
||||
if expect_env:
|
||||
e = os.environ if env is None else env
|
||||
problems += ["%s is %r in this process, not %r" % (k, e.get(k), v) for k, v in LINUX_ENV.items() if e.get(k) != v]
|
||||
if audio and not e.get("PULSE_SERVER"):
|
||||
problems.append("PULSE_SERVER is not set in this process: Firefox would not find the null sink's server")
|
||||
return problems
|
||||
|
||||
|
||||
def verify_here(expect_env: bool = False, run: Run = _run) -> list:
|
||||
"""Is the poison in force on this machine, for a process that wants to know (the page oracle's test): what apply wrote in the state file
|
||||
named by AB_ORACLE_POISON_STATE tells where the font is and whether there is a null sink."""
|
||||
state_file = os.environ.get(STATE_SWITCH)
|
||||
state = json.loads(Path(state_file).read_text(encoding="utf-8")) if state_file and Path(state_file).is_file() else None
|
||||
if system_name() == "windows":
|
||||
return verify_windows(run, state)
|
||||
return verify_linux(run, state, expect_env, audio=bool(state and state.get("audio")))
|
||||
|
||||
|
||||
def github_env_lines(env: dict) -> str:
|
||||
return "".join("%s=%s\n" % (k, v) for k, v in env.items())
|
||||
|
||||
|
||||
def apply(state_file: Path | None, audio: bool = True, run: Run = _run) -> int:
|
||||
system = system_name()
|
||||
state = apply_windows(run) if system == "windows" else apply_linux(run, audio=audio)
|
||||
state["audio"] = audio and system == "linux"
|
||||
if state_file:
|
||||
state_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
state_file.write_text(json.dumps(state, sort_keys=True, indent=1), encoding="utf-8")
|
||||
problems = verify_windows(run, state) if system == "windows" else verify_linux(run, state, audio=state["audio"])
|
||||
for p in problems:
|
||||
print("POISON NOT IN FORCE: " + p)
|
||||
if problems:
|
||||
return 2
|
||||
target = os.environ.get("GITHUB_ENV")
|
||||
env = dict(state.get("env", {}), **{SWITCH: "1"})
|
||||
if state_file:
|
||||
env[STATE_SWITCH] = str(state_file.resolve())
|
||||
if target:
|
||||
with open(target, "a", encoding="utf-8", newline="\n") as f:
|
||||
f.write(github_env_lines(env))
|
||||
print("the host is poisoned (%s): %s" % (system, json.dumps({k: v for k, v in state.items() if k not in ("before_env",)}, sort_keys=True)))
|
||||
return 0
|
||||
|
||||
|
||||
def undo(state_file: Path, run: Run = _run) -> int:
|
||||
state = json.loads(state_file.read_text(encoding="utf-8"))
|
||||
if state["system"] == "windows":
|
||||
undo_windows(state, run)
|
||||
else:
|
||||
undo_linux(state, run)
|
||||
target = os.environ.get("GITHUB_ENV")
|
||||
if target: # the later steps of the job read what it was
|
||||
with open(target, "a", encoding="utf-8", newline="\n") as f:
|
||||
f.write(github_env_lines(dict(state["before_env"], **{SWITCH: "", STATE_SWITCH: ""})))
|
||||
print("the poison is taken off (%s)" % state["system"])
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
a = sub.add_parser("apply")
|
||||
a.add_argument("--state", type=Path)
|
||||
a.add_argument("--no-audio", action="store_true", help="Linux: no null audio sink")
|
||||
v = sub.add_parser("verify")
|
||||
v.add_argument("--state", type=Path)
|
||||
v.add_argument("--expect-env", action="store_true")
|
||||
v.add_argument("--no-audio", action="store_true")
|
||||
u = sub.add_parser("undo")
|
||||
u.add_argument("--state", type=Path, required=True)
|
||||
c = sub.add_parser("control")
|
||||
c.add_argument("--out", type=Path, required=True)
|
||||
c.add_argument("--headless", action="store_true")
|
||||
f = sub.add_parser("font")
|
||||
f.add_argument("--out", type=Path, required=True)
|
||||
args = ap.parse_args(argv)
|
||||
if args.cmd == "apply":
|
||||
return apply(args.state, audio=not args.no_audio)
|
||||
if args.cmd == "undo":
|
||||
return undo(args.state)
|
||||
if args.cmd == "control":
|
||||
return control(args.out, args.headless)
|
||||
if args.cmd == "font":
|
||||
args.out.write_bytes(canary_font())
|
||||
print(canary_sha256())
|
||||
return 0
|
||||
state = json.loads(args.state.read_text(encoding="utf-8")) if args.state else None
|
||||
system = system_name()
|
||||
problems = verify_windows(_run, state) if system == "windows" else verify_linux(_run, state, args.expect_env, not args.no_audio)
|
||||
for p in problems:
|
||||
print("POISON NOT IN FORCE: " + p)
|
||||
return 2 if problems else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,4 @@
|
||||
<!doctype html>
|
||||
<meta charset=utf-8>
|
||||
<title>not controlled</title>
|
||||
<p>The service worker did not answer this navigation.</p>
|
||||
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<meta charset=utf-8>
|
||||
<title>frame</title>
|
||||
<script>
|
||||
document.write('<script src="/ab/realm.js' + location.search + '"><\/script>');
|
||||
</script>
|
||||
<script>
|
||||
(async () => {
|
||||
const q = new URLSearchParams(location.search);
|
||||
const data = await abRealm();
|
||||
data.host = location.hostname;
|
||||
parent.postMessage({id: q.get('id'), data}, '*');
|
||||
})();
|
||||
</script>
|
||||
@@ -0,0 +1,4 @@
|
||||
<!doctype html>
|
||||
<meta charset=utf-8>
|
||||
<title>leave</title>
|
||||
<p>The page of the back and forward step.</p>
|
||||
@@ -0,0 +1,16 @@
|
||||
<!doctype html>
|
||||
<meta charset=utf-8>
|
||||
<title>opened</title>
|
||||
<script>
|
||||
document.write('<script src="/ab/realm.js' + location.search + '"><\/script>');
|
||||
</script>
|
||||
<script>
|
||||
(async () => {
|
||||
const q = new URLSearchParams(location.search);
|
||||
const data = await abRealm();
|
||||
const bar = n => { try { return window[n].visible; } catch (e) { return 'ERR'; } };
|
||||
data.geometry = {innerWidth, innerHeight, outerWidth, outerHeight, screenX, screenY, screen: [screen.width, screen.height, screen.availWidth, screen.availHeight],
|
||||
bars: ['menubar', 'toolbar', 'locationbar', 'statusbar', 'scrollbars', 'personalbar'].map(bar), hasOpener: !!window.opener, name: window.name};
|
||||
try { opener.postMessage({id: q.get('id'), data}, '*'); } catch (e) {}
|
||||
})();
|
||||
</script>
|
||||
@@ -0,0 +1,84 @@
|
||||
// The surface subset one realm reads: the same text is loaded by the page, a cross-site iframe, a srcdoc iframe, a worker, a shared worker, a
|
||||
// service worker and an audio worklet, so that a value the engine declares for one realm and forgets for another shows as a difference.
|
||||
// Everything here is a plain read of what the realm exposes; a realm that lacks an API says 'absent'.
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const errs = e => 'ERR ' + ((e && e.name) || '') + ': ' + ((e && e.message) || String(e));
|
||||
const bytesHash = u8 => {
|
||||
let a = 0x811c9dc5, b = 0xdeadbeef;
|
||||
for (let i = 0; i < u8.length; i++) { a = Math.imul(a ^ u8[i], 0x01000193) >>> 0; b = Math.imul(b ^ u8[i], 0x5bd1e995) >>> 0; b ^= b >>> 13; }
|
||||
return u8.length + ':' + a.toString(16) + b.toString(16);
|
||||
};
|
||||
const textHash = s => { const u = new Uint8Array(s.length); for (let i = 0; i < s.length; i++) u[i] = s.charCodeAt(i) & 255; return bytesHash(u); };
|
||||
const TEXT = 'Hamburgefonstiv 0123 ZZ';
|
||||
const draw = g => {
|
||||
g.fillStyle = '#fff'; g.fillRect(0, 0, 160, 40); g.fillStyle = '#036'; g.font = '16px sans-serif'; g.fillText(TEXT, 4, 16);
|
||||
g.font = '14px serif'; g.fillText('\u65e5\u672c\u8a9e Stra\u00dfe', 4, 34);
|
||||
};
|
||||
const measure = g => ['sans-serif', 'serif', 'monospace', 'ZZHostCanary, sans-serif'].map(f => { g.font = '16px ' + f; return g.measureText(TEXT).width; });
|
||||
const scene = c => {
|
||||
const gl = c.getContext('webgl');
|
||||
if (!gl) return 'no webgl';
|
||||
const sh = (type, src) => { const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s); return s; };
|
||||
const p = gl.createProgram();
|
||||
gl.attachShader(p, sh(gl.VERTEX_SHADER, 'attribute vec2 a;void main(){gl_Position=vec4(a,0.,1.);}'));
|
||||
gl.attachShader(p, sh(gl.FRAGMENT_SHADER, 'precision mediump float;void main(){gl_FragColor=vec4(.9,.3,.1,1.);}'));
|
||||
gl.linkProgram(p); gl.useProgram(p);
|
||||
const buf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buf);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-0.8, -0.8, 0.8, -0.8, 0, 0.8]), gl.STATIC_DRAW);
|
||||
const a = gl.getAttribLocation(p, 'a'); gl.enableVertexAttribArray(a); gl.vertexAttribPointer(a, 2, gl.FLOAT, false, 0, 0);
|
||||
gl.viewport(0, 0, 32, 32); gl.clearColor(0.2, 0.4, 0.6, 1); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 3);
|
||||
const px = new Uint8Array(32 * 32 * 4); gl.readPixels(0, 0, 32, 32, gl.RGBA, gl.UNSIGNED_BYTE, px);
|
||||
const dbg = gl.getExtension('WEBGL_debug_renderer_info');
|
||||
return {pixels: bytesHash(px), vendor: gl.getParameter(gl.VENDOR), renderer: gl.getParameter(gl.RENDERER),
|
||||
unmasked: dbg ? [gl.getParameter(dbg.UNMASKED_VENDOR_WEBGL), gl.getParameter(dbg.UNMASKED_RENDERER_WEBGL)] : 'absent'};
|
||||
};
|
||||
|
||||
// What needs no await: the only part an audio worklet can read.
|
||||
const readSync = () => {
|
||||
const o = {};
|
||||
const t = (k, f) => { try { o[k] = f(); } catch (e) { o[k] = errs(e); } };
|
||||
const nav = root.navigator;
|
||||
if (nav) {
|
||||
t('language', () => nav.language); t('languages', () => Array.from(nav.languages)); t('platform', () => nav.platform);
|
||||
t('hardwareConcurrency', () => nav.hardwareConcurrency); t('userAgent', () => nav.userAgent);
|
||||
} else { o.navigator = 'absent'; }
|
||||
t('intl', () => { const r = new Intl.DateTimeFormat().resolvedOptions(); return [r.locale, r.timeZone, r.calendar, r.numberingSystem]; });
|
||||
const d = new Date(Date.UTC(2026, 0, 15, 12)), s = new Date(Date.UTC(2026, 6, 15, 12));
|
||||
t('dates', () => [d.toString(), s.toString(), d.toLocaleString(), d.toLocaleDateString(undefined, {dateStyle: 'full'}), (1234567.891).toLocaleString(),
|
||||
d.getTimezoneOffset(), s.getTimezoneOffset()]);
|
||||
t('sampleRate', () => typeof root.sampleRate === 'number' ? root.sampleRate : 'absent');
|
||||
return o;
|
||||
};
|
||||
|
||||
const read = async () => {
|
||||
const o = readSync();
|
||||
const ta = async (k, f) => { try { o[k] = await f(); } catch (e) { o[k] = errs(e); } };
|
||||
if (root.document && root.document.createElement) {
|
||||
await ta('canvas', async () => {
|
||||
const c = root.document.createElement('canvas'); c.width = 160; c.height = 40; const g = c.getContext('2d'); draw(g);
|
||||
return {toDataURL: textHash(c.toDataURL()), measure: measure(g)};
|
||||
});
|
||||
await ta('webgl', async () => { const c = root.document.createElement('canvas'); c.width = 32; c.height = 32; return scene(c); });
|
||||
} else { o.canvas = 'absent'; }
|
||||
if (typeof root.OffscreenCanvas === 'function') {
|
||||
await ta('offscreen', async () => {
|
||||
const c = new root.OffscreenCanvas(160, 40), g = c.getContext('2d'); draw(g);
|
||||
const m = measure(g), blob = await c.convertToBlob();
|
||||
return {measure: m, png: bytesHash(new Uint8Array(await blob.arrayBuffer()))};
|
||||
});
|
||||
await ta('offscreen_webgl', async () => scene(new root.OffscreenCanvas(32, 32)));
|
||||
} else { o.offscreen = 'absent'; }
|
||||
return o;
|
||||
};
|
||||
|
||||
root.abRealm = read;
|
||||
root.abRealmSync = readSync;
|
||||
// An audio worklet runs this file as a module: its processor reports what the worklet's own realm reads, when it is created.
|
||||
if (typeof root.registerProcessor === 'function' && typeof root.AudioWorkletProcessor === 'function') {
|
||||
root.registerProcessor('ab-probe', class extends root.AudioWorkletProcessor {
|
||||
constructor() { super(); this.port.postMessage(readSync()); }
|
||||
process() { return false; }
|
||||
});
|
||||
}
|
||||
})(typeof globalThis !== 'undefined' ? globalThis : self);
|
||||
@@ -0,0 +1,5 @@
|
||||
importScripts('/ab/realm.js' + location.search);
|
||||
onconnect = e => {
|
||||
const port = e.ports[0];
|
||||
port.onmessage = async () => { port.postMessage(await abRealm()); };
|
||||
};
|
||||
@@ -0,0 +1,89 @@
|
||||
<!doctype html>
|
||||
<meta charset=utf-8>
|
||||
<title>ab</title>
|
||||
<body>
|
||||
<script>
|
||||
// The A/B oracle's visit of the surfaces a plain read of the top window does not reach: every realm and every kind of window a page can make
|
||||
// reads the same subset (realm.js), and the server says which Accept-Language it saw for each kind of request. The page is served from
|
||||
// http://127.0.0.1 (a secure context: service workers and the audio worklet need one); `?ctx=` names the context it runs in.
|
||||
// What it records goes to window.__abResult; the title says when it is done. A step that does not answer says 'timeout: <step>' after its own
|
||||
// budget, never silence, so that the two engines of an A/B compare the same leaves.
|
||||
document.write('<script src="/ab/realm.js' + location.search + '"><\/script>');
|
||||
</script>
|
||||
<script>
|
||||
(async () => {
|
||||
const Q = new URLSearchParams(location.search), CTX = Q.get('ctx') || 'none', ID = '?ctx=' + encodeURIComponent(CTX);
|
||||
const errs = e => 'ERR ' + ((e && e.name) || '') + ': ' + ((e && e.message) || String(e));
|
||||
const within = (p, ms, what) => Promise.race([p, new Promise(res => setTimeout(() => res('timeout: ' + what), ms))]);
|
||||
const step = async (R, k, f, ms = 15000) => { try { R[k] = await within(Promise.resolve().then(f), ms, k); } catch (e) { R[k] = errs(e); } };
|
||||
const waiting = {};
|
||||
addEventListener('message', e => { const m = e.data; if (m && typeof m.id === 'string' && waiting[m.id]) { waiting[m.id](Object.assign({origin: e.origin}, m.data)); delete waiting[m.id]; } });
|
||||
const popups = [];
|
||||
const pop = (id, name, features) => new Promise(res => {
|
||||
waiting[id] = res;
|
||||
const url = '/ab/opened.html' + ID + '&id=' + id;
|
||||
const w = features === undefined ? window.open(url, name) : window.open(url, name, features);
|
||||
if (w) popups.push(w); else res('blocked');
|
||||
});
|
||||
|
||||
addEventListener('pageshow', async e => {
|
||||
let n = 1;
|
||||
try { n = (Number(sessionStorage.getItem('abPs')) || 0) + 1; sessionStorage.setItem('abPs', String(n)); } catch (x) {}
|
||||
let data; try { data = JSON.parse(JSON.stringify(await abRealm())); } catch (x) { data = errs(x); }
|
||||
window.__abBf = {n, persisted: e.persisted, data};
|
||||
});
|
||||
|
||||
let done = false;
|
||||
try { done = sessionStorage.getItem('abDone') === '1'; } catch (x) {}
|
||||
if (done) { document.title = 'ab-done'; return; }
|
||||
|
||||
const R = {};
|
||||
await step(R, 'top', () => abRealm());
|
||||
await step(R, 'iframe_cross', () => new Promise(res => {
|
||||
waiting.cross = res;
|
||||
const f = document.createElement('iframe'); f.src = 'http://localhost:' + location.port + '/ab/frame.html' + ID + '&id=cross'; document.body.appendChild(f); }));
|
||||
await step(R, 'iframe_srcdoc', () => new Promise((res, rej) => {
|
||||
const f = document.createElement('iframe');
|
||||
f.srcdoc = '<!doctype html><script src="/ab/realm.js' + ID + '"><\/script>';
|
||||
f.onload = async () => { try { res(await f.contentWindow.abRealm()); } catch (e) { rej(e); } };
|
||||
document.body.appendChild(f); }));
|
||||
await step(R, 'worker', () => new Promise((res, rej) => {
|
||||
const w = new Worker('/ab/worker.js' + ID); w.onmessage = e => { res(e.data); w.terminate(); }; w.onerror = () => { rej(new Error('worker error')); w.terminate(); }; w.postMessage('go'); }));
|
||||
await step(R, 'shared_worker', () => new Promise((res, rej) => {
|
||||
const w = new SharedWorker('/ab/shared.js' + ID); w.port.onmessage = e => res(e.data); w.onerror = () => rej(new Error('shared worker error')); w.port.postMessage('go'); }));
|
||||
await step(R, 'service_worker', async () => {
|
||||
if (!navigator.serviceWorker) return 'absent';
|
||||
const reg = await navigator.serviceWorker.register('/ab/sw.js' + ID, {scope: '/ab/'});
|
||||
try {
|
||||
await navigator.serviceWorker.ready;
|
||||
const f = document.createElement('iframe'), loaded = new Promise(r => { f.onload = r; });
|
||||
f.src = '/ab/controlled.html' + ID; document.body.appendChild(f); await loaded;
|
||||
const el = f.contentDocument.getElementById('sw');
|
||||
return el ? JSON.parse(el.textContent) : 'the worker did not answer the navigation';
|
||||
} finally { try { await reg.unregister(); } catch (e) {} }
|
||||
}, 20000);
|
||||
await step(R, 'audio_worklet', async () => {
|
||||
const ac = new AudioContext();
|
||||
try {
|
||||
await ac.audioWorklet.addModule('/ab/realm.js' + ID);
|
||||
const node = new AudioWorkletNode(ac, 'ab-probe');
|
||||
const got = new Promise(res => { node.port.onmessage = e => res(e.data); });
|
||||
ac.resume().catch(() => {});
|
||||
return await got;
|
||||
} finally { try { await ac.close(); } catch (e) {} }
|
||||
}, 8000);
|
||||
await step(R, 'popup_plain', () => pop('plain', 'abPlain'));
|
||||
await step(R, 'popup_features', () => pop('features', 'abFeatures', 'popup,width=500,height=420,left=40,top=30'));
|
||||
for (const w of popups) { try { w.close(); } catch (e) {} }
|
||||
// two more kinds of request, so that the server has seen a fetch and an image next to the documents, scripts and workers
|
||||
await step(R, 'requests', async () => {
|
||||
await fetch('/ab/probe' + ID + '&k=fetch');
|
||||
await new Promise(res => { const i = new Image(); i.onload = i.onerror = res; i.src = '/ab/probe' + ID + '&k=image'; });
|
||||
return 'made'; }, 5000);
|
||||
await step(R, 'accept_language', async () => (await fetch('/ab/seen' + ID)).json(), 5000);
|
||||
|
||||
window.__abResult = JSON.parse(JSON.stringify(R));
|
||||
try { sessionStorage.setItem('abDone', '1'); } catch (e) {}
|
||||
document.title = 'ab-done';
|
||||
})();
|
||||
</script>
|
||||
@@ -0,0 +1,17 @@
|
||||
// A service worker that answers one navigation itself: the page it builds carries what the worker's own realm reads and the headers the
|
||||
// worker saw on the request, so a controlled navigation is read through the worker, not around it.
|
||||
importScripts('/ab/realm.js' + location.search);
|
||||
self.addEventListener('install', () => self.skipWaiting());
|
||||
self.addEventListener('activate', e => e.waitUntil(self.clients.claim()));
|
||||
self.addEventListener('fetch', e => {
|
||||
const u = new URL(e.request.url);
|
||||
if (u.pathname !== '/ab/controlled.html') return;
|
||||
e.respondWith((async () => {
|
||||
const data = await abRealm();
|
||||
data.request = {acceptLanguage: e.request.headers.get('accept-language'), mode: e.request.mode, destination: e.request.destination};
|
||||
try { data.own_fetch = (await fetch('/ab/probe' + u.search)).status; } catch (x) { data.own_fetch = 'ERR ' + ((x && x.name) || ''); }
|
||||
const json = JSON.stringify(data).replace(/</g, '\\u003c');
|
||||
return new Response('<!doctype html><meta charset=utf-8><title>controlled</title><script type="application/json" id="sw">' + json + '</script>',
|
||||
{headers: {'Content-Type': 'text/html; charset=utf-8'}});
|
||||
})());
|
||||
});
|
||||
@@ -0,0 +1,2 @@
|
||||
importScripts('/ab/realm.js' + location.search);
|
||||
onmessage = async () => { postMessage(await abRealm()); };
|
||||
@@ -281,6 +281,37 @@ await safe('surface.branding', () => Promise.all(['chrome://branding/locale/bran
|
||||
noise('history_length', history.length);
|
||||
noise('main_loop_ms', await new Promise(r => { const t = performance.now(); setTimeout(() => r(Math.round(performance.now() - t)), 20); }));
|
||||
|
||||
// ================================================================= AB (read by the A/B oracle only, never by the retail comparison)
|
||||
// ab.poison: what the page reads of values a host may hold and the engine must never read: the zone, the language, the colour scheme, a
|
||||
// user-installed canary font (scripts/ci_poison_host.py puts them on the oracle's runner and holds the engine's dumps to the declared identity).
|
||||
// The probe between the two markers is self-contained: the negative control evaluates the same text in Playwright's own Firefox.
|
||||
// ab.poison:begin
|
||||
const abPoisonProbe = async () => {
|
||||
const o = {}, f = (k, g) => { try { o[k] = g(); } catch (e) { o[k] = 'ERR ' + ((e && e.name) || ''); } };
|
||||
const jan = new Date(Date.UTC(2026, 0, 15, 12)), jul = new Date(Date.UTC(2026, 6, 15, 12));
|
||||
f('timezone', () => Intl.DateTimeFormat().resolvedOptions().timeZone);
|
||||
f('offsets', () => [jan.getTimezoneOffset(), jul.getTimezoneOffset()]);
|
||||
f('language', () => navigator.language);
|
||||
f('languages', () => Array.from(navigator.languages));
|
||||
f('intl_locale', () => Intl.DateTimeFormat().resolvedOptions().locale);
|
||||
f('date_full', () => jan.toLocaleDateString(undefined, {dateStyle: 'full'}));
|
||||
f('number', () => (1234567.891).toLocaleString());
|
||||
f('dark', () => matchMedia('(prefers-color-scheme: dark)').matches);
|
||||
// document.fonts.check answers true for a family nobody has (the specification: nothing to load), so it is recorded and the WIDTH decides
|
||||
f('canary_check', () => document.fonts.check('12px ZZHostCanary'));
|
||||
f('canary', () => {
|
||||
const box = document.createElement('div'); box.style.cssText = 'position:absolute;left:-9999px;top:0;visibility:hidden;white-space:nowrap';
|
||||
document.documentElement.appendChild(box);
|
||||
const width = fam => { const e = document.createElement('span'); e.style.cssText = 'font:12px ' + fam; e.textContent = 'mmmmmmmmmmmm'; box.appendChild(e); const w = e.getBoundingClientRect().width; e.remove(); return w; };
|
||||
const out = {with: [width('ZZHostCanary, monospace'), width('ZZHostCanary, serif')], without: [width('monospace'), width('serif')]};
|
||||
box.remove(); out.present = out.with[0] !== out.without[0] || out.with[1] !== out.without[1]; return out; });
|
||||
try { const c = new AudioContext(); o.audio = {sampleRate: c.sampleRate, maxChannelCount: c.destination.maxChannelCount}; try { c.close(); } catch (e) {} }
|
||||
catch (e) { o.audio = 'ERR ' + ((e && e.name) || ''); }
|
||||
return o;
|
||||
};
|
||||
// ab.poison:end
|
||||
await safe('ab.poison', abPoisonProbe);
|
||||
|
||||
// ================================================================= DIAG (information, never compared)
|
||||
// diag.*: why this host's WebGL is what it is (no WebGL2, no MSAA). Last, so its extra contexts
|
||||
// cannot disturb anything measured above; each is lost again once read.
|
||||
|
||||
@@ -14,6 +14,12 @@ DPR. Like the network and host oracles, it has two modes, told by whether there
|
||||
The only differences either comparison lets through are the `noise` entries of scripts/host_gate/exceptions.json and the diag. keys. The verdict is the pytest result; the files (dump-68.json,
|
||||
dump-68-again.json, diff-a-a.json and, with a candidate, dump-candidate.json and diff.json) and the log are the evidence.
|
||||
|
||||
Two more things the comparison cannot say are held here (`_check_ab_visit_and_poison`). The oracle's dumps carry the ab. leaves (scripts/ci_host_gate.py): the poison probe of the page on every
|
||||
seed and, on seeds 0 and 63, the extra visit of every realm and window a page can make; seed 63 must differ from seed 0 on at least AB_CONTROL_MIN of them (the count is in ab-control.json and the log).
|
||||
On the gate's leg the host is POISONED (scripts/ci_poison_host.py: another zone, language, colour scheme, a user-installed canary font and, on Linux, a null audio sink at 96000 Hz with 6 channels;
|
||||
AB_ORACLE_POISON=1): the poison is in force, Playwright's own Firefox read it (poison-control.json, written by the leg's step before this test; not read: BROKEN CONTROL), and neither engine read any of
|
||||
it (the dumps say what the persona declares).
|
||||
|
||||
Not skipped on a machine without a candidate: a skipped test is a red one in the judge, and an oracle that did not run says nothing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -31,6 +37,8 @@ pytestmark = pytest.mark.e2e
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SCRIPT = ROOT / "scripts" / "ci_ab_oracle.py"
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
import ci_host_gate as gate # noqa: E402
|
||||
import ci_poison_host as poison # noqa: E402
|
||||
from ci_ab_pr_seeds import pr_seed_count # noqa: E402
|
||||
import ci_ab_oracle as ab # noqa: E402
|
||||
|
||||
@@ -73,6 +81,40 @@ BUDGET_S = budget_s(*plan())
|
||||
TIMEOUT_S = BUDGET_S
|
||||
|
||||
|
||||
def _items_by_seed(path: Path) -> dict:
|
||||
return {v["seed"]: v["items"] for v in json.loads(path.read_text(encoding="utf-8"))["visits"]}
|
||||
|
||||
|
||||
def _check_ab_visit_and_poison(out: Path, candidate: bool) -> None:
|
||||
"""What the oracle's comparison cannot say. The ab visit ran where it was due and read something (a page that dumped nothing would pass
|
||||
any A/B), and seed 63 reads other values than seed 0 (the control of the ab leaves; the measured count goes to ab-control.json and the log).
|
||||
On a poisoned host (the gate's leg: AB_ORACLE_POISON=1) the poison is in force, the negative control of stock Firefox read it, and neither
|
||||
engine read any of it: its dumps hold the identity the core declares."""
|
||||
published = out / "dump-68.json"
|
||||
dumps = [("the published engine", published)] + ([("the candidate", out / "dump-candidate.json")] if candidate else [])
|
||||
problems = []
|
||||
for name, path in dumps:
|
||||
problems += ["%s: %s" % (name, line) for line in gate.ab_coverage(_items_by_seed(path))]
|
||||
assert not problems, "the ab visit did not read:\n" + "\n".join(problems)
|
||||
control = gate.ab_control(_items_by_seed(published))
|
||||
(out / "ab-control.json").write_text(json.dumps(control, sort_keys=True), encoding="utf-8")
|
||||
with open(out / "oracle.log", "a", encoding="utf-8") as log:
|
||||
log.write(control["line"] + "\n")
|
||||
assert control["status"] != "too_few", control["line"] + " (the sample: %s)" % control.get("sample")
|
||||
if os.environ.get(poison.SWITCH) != "1":
|
||||
return
|
||||
not_in_force = poison.verify_here(expect_env=True)
|
||||
assert not not_in_force, "the host is not poisoned, the oracle ran on a clean machine:\n" + "\n".join(not_in_force)
|
||||
control_file = out / "poison-control.json"
|
||||
assert control_file.is_file(), "BROKEN CONTROL: stock Firefox did not read the poison on this runner (no poison-control.json)"
|
||||
verdict = json.loads(control_file.read_text(encoding="utf-8"))
|
||||
assert verdict.get("verdict") == "green", "BROKEN CONTROL: " + json.dumps(verdict.get("failures"))
|
||||
read = []
|
||||
for name, path in dumps:
|
||||
read += ["%s: %s" % (name, line) for line in poison.dump_findings(json.loads(path.read_text(encoding="utf-8")))]
|
||||
assert not read, "the engine read the poisoned host:\n" + "\n".join(read)
|
||||
|
||||
|
||||
def _out(tmp_path: Path) -> Path:
|
||||
explicit = os.environ.get("AB_ORACLE_OUT")
|
||||
if explicit:
|
||||
@@ -113,11 +155,12 @@ def test_the_published_engine_repeats_itself_and_the_candidate_gives_the_same_by
|
||||
assert control["verdict"] == "green" and control["differences"] == [] and control["problems"] == [] and len(control["compared"]) == len(control["visits"]) >= 1
|
||||
assert len(control["visits"]) == len(visits), "every seed of the shard is visited: %s" % control["visits"]
|
||||
assert sorted(control["relaunch"]) == sorted(ab.visit_name(*key) for key in ab.relaunch_visits(visits)), "seed 0 is launched twice on one profile, whichever shard has it"
|
||||
names = sorted(p.name for p in out.glob("*.json"))
|
||||
_check_ab_visit_and_poison(out, candidate)
|
||||
names = sorted(p.name for p in out.glob("*.json") if not p.name.startswith("poison-"))
|
||||
if candidate:
|
||||
diff = json.loads((out / "diff.json").read_text(encoding="utf-8"))
|
||||
assert diff["verdict"] == "green" and diff["differences"] == [] and diff["problems"] == []
|
||||
assert len(diff["visits"]) >= 1 and len(diff["compared"]) == len(diff["visits"]), "every visit asked for is compared: %s" % diff["visits"]
|
||||
assert names == ["diff-a-a.json", "diff.json", "dump-68-again.json", "dump-68.json", "dump-candidate.json"]
|
||||
assert names == ["ab-control.json", "diff-a-a.json", "diff.json", "dump-68-again.json", "dump-68.json", "dump-candidate.json"]
|
||||
else:
|
||||
assert names == ["diff-a-a.json", "dump-68-again.json", "dump-68.json"]
|
||||
assert names == ["ab-control.json", "diff-a-a.json", "dump-68-again.json", "dump-68.json"]
|
||||
@@ -0,0 +1,361 @@
|
||||
"""The ab. leaves of the host gate (scripts/ci_host_gate.py): the poison probe of the page and the A/B oracle's extra visit of seeds 0 and 63.
|
||||
|
||||
No browser. The site of the visit is served by a real loopback server and asked with plain HTTP requests, the way the browser asks it; the page's
|
||||
JavaScript is held by what it must contain and by the files it names. What the comparison does with the leaves is shown on synthetic dumps.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from http.server import ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
import ci_ab_oracle as oracle # noqa: E402
|
||||
import ci_host_gate as gate # noqa: E402
|
||||
import test_ci_host_gate as host_gate_tests # noqa: E402
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
AB = ROOT / "scripts" / "host_gate" / "ab"
|
||||
|
||||
|
||||
# -
|
||||
# The prefix: read by the A/B, skipped by the retail comparison.
|
||||
|
||||
def test_the_ab_prefix_is_skipped_by_the_retail_comparison_like_diag(tmp_path):
|
||||
items = lambda leg, seed: {"surface.gpu.limits": 8, "ab.poison": {"timezone": leg}, "ab.launch": {"top": {"language": "ja-JP", "seed": seed}}}
|
||||
assert host_gate_tests.run(tmp_path, items, {"surface.gpu.limits": 8}) == []
|
||||
|
||||
|
||||
def test_only_the_ab_prefix_is_skipped(tmp_path):
|
||||
items = lambda leg, seed: {"abc.value": leg}
|
||||
failures = host_gate_tests.run(tmp_path, items, {"abc.value": "win-x86_64"})
|
||||
assert any(f.startswith("host abc.value") for f in failures)
|
||||
|
||||
|
||||
def test_the_ab_oracle_compares_the_ab_leaves_which_the_diag_ones_are_left_out():
|
||||
assert gate.is_ab("ab.launch.top.language") and not gate.is_ab("diag.ab.launch")
|
||||
both = {"ab.launch": {"top": {"language": "ja-JP"}}, "diag.ab.launch": {"bfcache_persisted": True}}
|
||||
assert set(oracle.comparable(both)) == {"ab.launch.top.language"}
|
||||
published, candidate = {(1.0, 0): both}, {(1.0, 0): {"ab.launch": {"top": {"language": "en-US"}}}}
|
||||
report = oracle.compare_visits(published, candidate, [], min_leaves={1.0: 1}, expected=((1.0, 0),))
|
||||
assert report["verdict"] == "red" and report["differences"][0]["leaf"] == "ab.launch.top.language"
|
||||
|
||||
|
||||
def test_the_oracle_asks_the_dump_for_the_ab_visit():
|
||||
source = (ROOT / "scripts" / "ci_ab_oracle.py").read_text(encoding="utf-8")
|
||||
assert '"--no-pin", "--ab"' in source
|
||||
|
||||
|
||||
def test_the_dump_adds_the_ab_visit_to_the_seeds_that_have_one(monkeypatch):
|
||||
seen = []
|
||||
monkeypatch.setattr(gate, "dump", lambda *a, **k: seen.append(k) or 0)
|
||||
assert gate.main(["dump", "ff", "--leg", "linux-x86_64", "--out", "o", "--visit", "0:1.0", "--ab"]) == 0
|
||||
assert seen[0]["ab"] is True and seen[0]["visits"] == [(1.0, 0)]
|
||||
gate.main(["dump", "ff", "--leg", "linux-x86_64", "--out", "o"])
|
||||
assert seen[1]["ab"] is False
|
||||
|
||||
|
||||
# -
|
||||
# The launch of the visit.
|
||||
|
||||
def test_the_ab_visit_launches_in_japanese_and_pins_a_dpr_only_when_asked():
|
||||
options = gate.ab_options("ff", 0, None, "Asia/Bangkok")
|
||||
assert options["locale"] == "ja-JP" and options["seed"] == 0 and options["timezone"] == "Asia/Bangkok" and "pin" not in options
|
||||
assert gate.ab_options("ff", 63, 1.5, "Asia/Bangkok")["pin"] == {"screen.dpr": 1.5}
|
||||
|
||||
|
||||
def test_the_second_context_of_the_visit_overrides_language_and_zone():
|
||||
assert dict(gate.AB_CONTEXTS)["launch"] == {}
|
||||
assert dict(gate.AB_CONTEXTS)["context"] == {"locale": "de-DE", "timezone_id": "America/Lima"}
|
||||
assert gate.AB_SEEDS == (0, 63)
|
||||
|
||||
|
||||
def test_a_visit_keeps_what_the_back_navigation_read_and_puts_whether_it_was_cached_in_diag():
|
||||
items = gate.ab_items("launch", {"top": {"language": "ja-JP"}}, {"n": 2, "persisted": True, "data": {"language": "ja-JP"}})
|
||||
assert items["ab.launch"] == {"top": {"language": "ja-JP"}, "bfcache": {"language": "ja-JP"}}
|
||||
assert items["diag.ab.launch"] == {"bfcache_persisted": True}
|
||||
|
||||
|
||||
# -
|
||||
# The site.
|
||||
|
||||
@pytest.fixture()
|
||||
def site():
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), gate._AbSite)
|
||||
server.ab_seen, server.ab_lock = {}, threading.Lock()
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
yield "http://127.0.0.1:%d" % server.server_address[1]
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def get(url, **headers):
|
||||
try:
|
||||
with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=10) as r:
|
||||
return r.status, r.headers.get("Content-Type"), r.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.headers.get("Content-Type"), e.read()
|
||||
|
||||
|
||||
def test_every_file_of_the_visit_is_served_with_its_type(site):
|
||||
for path in sorted(AB.iterdir()):
|
||||
status, kind, body = get("%s/ab/%s?ctx=launch" % (site, path.name))
|
||||
assert status == 200 and body == path.read_bytes(), path.name
|
||||
assert kind.startswith("text/html" if path.suffix == ".html" else "text/javascript"), path.name
|
||||
|
||||
|
||||
def test_what_is_not_a_file_of_the_visit_is_not_served(site):
|
||||
for url in ("/ab/", "/ab/missing.js", "/ab/..%2Fci_host_gate.py", "/ab/%2e%2e/ci_host_gate.py", "/ab/realm.js.map", "/ab/notes.txt", "/etc/passwd", "/ab"):
|
||||
assert get(site + url)[0] == 404, url
|
||||
|
||||
|
||||
def test_the_server_says_which_accept_language_it_saw_for_each_kind_of_request(site):
|
||||
get(site + "/ab/surfaces.html?ctx=launch", **{"Accept-Language": "ja-JP,ja;q=0.9", "Sec-Fetch-Dest": "document"})
|
||||
get(site + "/ab/frame.html?ctx=launch&id=cross", **{"Accept-Language": "ja-JP,ja;q=0.9", "Sec-Fetch-Dest": "iframe"})
|
||||
get(site + "/ab/realm.js?ctx=launch", **{"Accept-Language": "ja-JP,ja;q=0.9", "Sec-Fetch-Dest": "script"})
|
||||
get(site + "/ab/probe?ctx=launch&k=fetch", **{"Accept-Language": "ja-JP", "Sec-Fetch-Dest": "empty"})
|
||||
get(site + "/ab/realm.js?ctx=context", **{"Accept-Language": "de-DE", "Sec-Fetch-Dest": "script"})
|
||||
get(site + "/ab/leave.html?ctx=launch")
|
||||
status, kind, body = get(site + "/ab/seen?ctx=launch")
|
||||
seen = json.loads(body)
|
||||
assert status == 200 and kind == "application/json"
|
||||
assert seen == {"document:/ab/surfaces.html": ["ja-JP,ja;q=0.9"], "iframe:/ab/frame.html": ["ja-JP,ja;q=0.9"], "script:/ab/realm.js": ["ja-JP,ja;q=0.9"],
|
||||
"empty:/ab/probe": ["ja-JP"], "none:/ab/leave.html": ["<none>"]}
|
||||
assert json.loads(get(site + "/ab/seen?ctx=context")[2]) == {"script:/ab/realm.js": ["de-DE"]}
|
||||
assert json.loads(get(site + "/ab/seen?ctx=nobody")[2]) == {}
|
||||
|
||||
|
||||
def test_asking_what_the_server_saw_is_not_itself_something_it_saw(site):
|
||||
get(site + "/ab/seen?ctx=launch", **{"Accept-Language": "x", "Sec-Fetch-Dest": "empty"})
|
||||
assert json.loads(get(site + "/ab/seen?ctx=launch")[2]) == {}
|
||||
|
||||
|
||||
def test_two_values_of_one_kind_are_both_told(site):
|
||||
get(site + "/ab/realm.js?ctx=launch", **{"Accept-Language": "ja", "Sec-Fetch-Dest": "script"})
|
||||
get(site + "/ab/realm.js?ctx=launch", **{"Accept-Language": "en", "Sec-Fetch-Dest": "script"})
|
||||
assert json.loads(get(site + "/ab/seen?ctx=launch")[2]) == {"script:/ab/realm.js": ["en", "ja"]}
|
||||
|
||||
|
||||
# -
|
||||
# The page and the realms: what they must do, and that they name only files that exist.
|
||||
|
||||
def test_every_file_the_visit_names_exists():
|
||||
served = {p.name for p in AB.iterdir()}
|
||||
for path in AB.iterdir():
|
||||
text = path.read_text(encoding="utf-8")
|
||||
for name in re.findall(r"/ab/([A-Za-z]+\.(?:js|html))", text):
|
||||
assert name in served, "%s names /ab/%s" % (path.name, name)
|
||||
|
||||
|
||||
def test_the_page_reads_every_kind_of_realm_and_window_and_the_required_steps_are_among_them():
|
||||
page = (AB / "surfaces.html").read_text(encoding="utf-8")
|
||||
steps = re.findall(r"step\(R, '([a-z_]+)'", page)
|
||||
assert steps == ["top", "iframe_cross", "iframe_srcdoc", "worker", "shared_worker", "service_worker", "audio_worklet",
|
||||
"popup_plain", "popup_features", "requests", "accept_language"]
|
||||
assert set(gate.AB_REQUIRED_STEPS) <= set(steps)
|
||||
assert "'http://localhost:' + location.port" in page # a site that is not the page's
|
||||
assert "f.srcdoc" in page and "window.open(url, name)" in page and "window.open(url, name, features)" in page
|
||||
assert "'pageshow'" in page and "__abBf" in page and "document.title = 'ab-done'" in page
|
||||
assert "new SharedWorker" in page and "serviceWorker.register" in page and "audioWorklet.addModule" in page
|
||||
|
||||
|
||||
def test_the_driver_waits_for_what_the_page_sets():
|
||||
source = (ROOT / "scripts" / "ci_host_gate.py").read_text(encoding="utf-8")
|
||||
page = (AB / "surfaces.html").read_text(encoding="utf-8")
|
||||
for expression in ("document.title === 'ab-done'", "window.__abResult", "window.__abBf && window.__abBf.n >= 2", "window.__abBf"):
|
||||
assert expression in source, expression
|
||||
assert "window.__abResult =" in page and "window.__abBf = " in page
|
||||
|
||||
|
||||
def test_the_realm_reads_the_subset_and_an_audio_worklet_reports_through_its_processor():
|
||||
realm = (AB / "realm.js").read_text(encoding="utf-8")
|
||||
for name in ("language", "languages", "hardwareConcurrency", "intl", "dates", "sampleRate", "toDataURL", "measureText", "convertToBlob",
|
||||
"offscreen_webgl", "registerProcessor('ab-probe'"):
|
||||
assert name in realm, name
|
||||
assert "ab-probe" in (AB / "surfaces.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_a_controlled_navigation_is_answered_by_the_worker_not_by_the_server():
|
||||
worker = (AB / "sw.js").read_text(encoding="utf-8")
|
||||
assert "e.respondWith" in worker and "/ab/controlled.html" in worker and "accept-language" in worker
|
||||
assert "the worker did not answer the navigation" in (AB / "surfaces.html").read_text(encoding="utf-8")
|
||||
assert "not controlled" in (AB / "controlled.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# -
|
||||
# The control: another identity must read other values.
|
||||
|
||||
def visit(**steps):
|
||||
return {"ab.launch": dict({"top": {"hardwareConcurrency": 16, "language": "ja-JP"}}, **steps),
|
||||
"ab.context": {"top": {"hardwareConcurrency": 16, "language": "de-DE"}}}
|
||||
|
||||
|
||||
def test_the_control_counts_the_leaves_seed_63_reads_differently_from_seed_0():
|
||||
other = {"ab.launch": {"top": {"hardwareConcurrency": 8, "language": "ja-JP"}}, "ab.context": {"top": {"hardwareConcurrency": 8, "language": "de-DE"}}}
|
||||
result = gate.ab_control({0: visit(), 63: other}, minimum=2)
|
||||
assert result["status"] == "ok" and result["differing"] == 2 and result["compared"] == 4
|
||||
assert result["line"].startswith("ab control: seed 63 differs from seed 0 on 2 of 4 ab. leaves (at least 2 are required)")
|
||||
|
||||
|
||||
def test_two_identities_that_read_the_same_fail_the_control():
|
||||
result = gate.ab_control({0: visit(), 63: visit()}, minimum=1)
|
||||
assert result["status"] == "too_few" and result["differing"] == 0
|
||||
assert "an identity that is not seed 0's read the same" in result["line"]
|
||||
|
||||
|
||||
def test_the_control_counts_neither_the_poison_probe_nor_diag():
|
||||
a = dict(visit(), **{"ab.poison": {"offsets": [1]}, "diag.ab.launch": {"bfcache_persisted": True}})
|
||||
b = dict(visit(), **{"ab.poison": {"offsets": [2]}, "diag.ab.launch": {"bfcache_persisted": False}})
|
||||
assert gate.ab_control({0: a, 63: b}, minimum=1)["differing"] == 0
|
||||
|
||||
|
||||
def test_a_run_that_did_not_visit_both_seeds_says_so():
|
||||
result = gate.ab_control({0: visit()})
|
||||
assert result["status"] == "not_visited" and "seed 63 has no ab. leaves" in result["line"]
|
||||
assert gate.ab_control({0: {"surface.x": 1}, 63: visit()})["status"] == "not_visited"
|
||||
|
||||
|
||||
def test_the_minimum_is_written_and_provisional_until_a_run_measures_it():
|
||||
assert isinstance(gate.AB_CONTROL_MIN, int) and gate.AB_CONTROL_MIN >= 1
|
||||
source = (ROOT / "scripts" / "ci_host_gate.py").read_text(encoding="utf-8")
|
||||
assert "PROVISIONAL" in source
|
||||
|
||||
|
||||
# -
|
||||
# What a run must have read for its A/B to mean anything.
|
||||
|
||||
def full(ctx_steps=None):
|
||||
steps = {s: {"language": "x"} for s in gate.AB_REQUIRED_STEPS}
|
||||
steps.update(ctx_steps or {})
|
||||
return {"ab." + name: dict(steps) for name, _ in gate.AB_CONTEXTS}
|
||||
|
||||
|
||||
def test_a_visit_that_read_every_required_step_in_every_context_is_whole():
|
||||
assert gate.ab_coverage({0: full(), 63: full(), 2: {"surface.x": 1}}) == []
|
||||
|
||||
|
||||
def test_a_seed_of_the_ab_visit_without_its_leaves_is_a_problem_and_a_seed_not_visited_is_not():
|
||||
assert gate.ab_coverage({2: {"surface.x": 1}, 4: {}}) == []
|
||||
problems = gate.ab_coverage({0: {"surface.x": 1}})
|
||||
assert len(problems) == len(gate.AB_CONTEXTS) and all("seed 0: no ab." in p for p in problems)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("step", gate.AB_REQUIRED_STEPS)
|
||||
def test_a_required_step_that_timed_out_is_a_problem(step):
|
||||
problems = gate.ab_coverage({63: full({step: "timeout: " + step})})
|
||||
assert len(problems) == len(gate.AB_CONTEXTS) and all(step in p and "timeout" in p for p in problems)
|
||||
|
||||
|
||||
def test_the_steps_that_a_host_may_not_have_are_not_required():
|
||||
assert gate.ab_coverage({0: full({"service_worker": "absent", "audio_worklet": "timeout: audio_worklet", "popup_plain": "blocked"})}) == []
|
||||
|
||||
|
||||
# -
|
||||
# The visit and the dump, with a fake browser: the order of what is asked, and where the leaves go.
|
||||
|
||||
class _Page:
|
||||
def __init__(self, log):
|
||||
self.log = log
|
||||
self.mouse = self
|
||||
|
||||
def goto(self, url, timeout=None):
|
||||
self.log.append(("goto", url.split("/ab/")[-1] if "/ab/" in url else url, timeout))
|
||||
|
||||
def go_back(self, timeout=None):
|
||||
self.log.append(("back", timeout))
|
||||
|
||||
def wait_for_function(self, expression, timeout=None):
|
||||
self.log.append(("wait", expression, timeout))
|
||||
|
||||
def evaluate(self, expression):
|
||||
self.log.append(("evaluate", expression))
|
||||
if expression == "window.__abResult":
|
||||
return {"top": {"language": "ja-JP"}}
|
||||
if expression == "window.__abBf":
|
||||
return {"n": 2, "persisted": False, "data": {"language": "ja-JP"}}
|
||||
if expression == "window.__hostGate":
|
||||
return {"format": gate.FORMAT, "items": {"surface.x": 1}}
|
||||
raise RuntimeError("not asked by this fake")
|
||||
|
||||
def move(self, *a):
|
||||
pass
|
||||
|
||||
def click(self, *a):
|
||||
pass
|
||||
|
||||
|
||||
class _Context:
|
||||
def __init__(self, log, options):
|
||||
self.log, self.options = log, options
|
||||
|
||||
def new_page(self):
|
||||
return _Page(self.log)
|
||||
|
||||
def close(self):
|
||||
self.log.append(("context closed", self.options))
|
||||
|
||||
|
||||
class _Launch:
|
||||
def __init__(self, log, options):
|
||||
self.log, self.options = log, options
|
||||
|
||||
def __enter__(self):
|
||||
self.log.append(("launch", self.options))
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.log.append(("quit",))
|
||||
|
||||
def new_context(self, **options):
|
||||
self.log.append(("context", options))
|
||||
return _Context(self.log, options)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def fake_browser(monkeypatch):
|
||||
import types
|
||||
|
||||
log = []
|
||||
module = types.ModuleType("invisible_playwright")
|
||||
module.InvisiblePlaywright = lambda **options: _Launch(log, options)
|
||||
monkeypatch.setitem(sys.modules, "invisible_playwright", module)
|
||||
return log
|
||||
|
||||
|
||||
def test_the_ab_visit_reads_each_context_then_goes_away_and_back_and_closes_it(fake_browser):
|
||||
items = gate.ab_visit("ff", 0, "Asia/Bangkok", 1.5, timeout_ms=1234)
|
||||
assert set(items) == {"ab.launch", "diag.ab.launch", "ab.context", "diag.ab.context"}
|
||||
assert items["ab.launch"]["top"] == {"language": "ja-JP"} and items["ab.launch"]["bfcache"] == {"language": "ja-JP"}
|
||||
kinds = [e[0] for e in fake_browser]
|
||||
assert kinds[0] == "launch" and kinds[-1] == "quit" and kinds.count("context") == 2 and kinds.count("context closed") == 2
|
||||
assert fake_browser[0][1] == gate.ab_options("ff", 0, 1.5, "Asia/Bangkok")
|
||||
contexts = [e[1] for e in fake_browser if e[0] == "context"]
|
||||
assert contexts == [{}, {"locale": "de-DE", "timezone_id": "America/Lima"}]
|
||||
for name in ("launch", "context"):
|
||||
steps = [e for e in fake_browser if e[0] in ("goto", "back", "wait") and (e[0] != "goto" or ("ctx=" + name) in e[1])]
|
||||
assert [e[1] for e in steps if e[0] == "goto"] == ["surfaces.html?ctx=" + name, "leave.html?ctx=" + name]
|
||||
assert all(e[-1] == 1234 for e in fake_browser if e[0] in ("goto", "wait", "back"))
|
||||
waits = [e[1] for e in fake_browser if e[0] == "wait"]
|
||||
assert waits == ["document.title === 'ab-done'", "window.__abBf && window.__abBf.n >= 2"] * 2
|
||||
|
||||
|
||||
def test_the_dump_adds_the_ab_leaves_to_seeds_0_and_63_only_and_only_when_asked(fake_browser, monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(gate, "ab_visit", lambda firefox, seed, zone, dpr=None: {"ab.launch": {"seed": seed}})
|
||||
for ab, expected in ((True, {0: True, 2: False, 63: True}), (False, {0: False, 2: False, 63: False})):
|
||||
out = tmp_path / str(ab)
|
||||
assert gate.dump("ff", "linux-x86_64", out, gate.REFERENCE, visits=[(1.0, 0), (1.0, 2), (1.0, 63)], ab=ab) == 0
|
||||
for seed, has in expected.items():
|
||||
items = json.loads((out / ("linux-x86_64_dpr1.0_seed%d.json" % seed)).read_text(encoding="utf-8"))["result"]["items"]
|
||||
assert ("ab.launch" in items) is has, (ab, seed)
|
||||
if has:
|
||||
assert items["ab.launch"] == {"seed": seed}
|
||||
@@ -0,0 +1,404 @@
|
||||
"""The poisoned host of the page A/B oracle (scripts/ci_poison_host.py), no browser and nothing put on this machine.
|
||||
|
||||
What is held: the canary font is a valid, deterministic font (and is the one whose hash the script declares); the probe the page and the negative control
|
||||
share is one text; the findings say, for each poisoned value, that an engine that read it is caught, and that an engine that read the declared identity
|
||||
is not; the negative control fails when stock Firefox did not read the poison; and apply, verify and undo issue the commands of each system in an order
|
||||
that puts back what was found (a fake runner records them: nothing here touches the zone, the culture, the registry or the fonts of this machine).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
import ci_poison_host as poison # noqa: E402
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
WANT = {"timezone": "Asia/Bangkok", "offsets": [-420, -420], "locale": "en-US", "language": "en-US",
|
||||
"date_full": "Thursday, January 15, 2026", "number": "1,234,567.891", "dark": False, "sample_rate": 48000, "max_channels": 2}
|
||||
OURS = {"timezone": "Asia/Bangkok", "offsets": [-420, -420], "language": "en-US", "languages": ["en-US", "en"], "intl_locale": "en-US",
|
||||
"date_full": "Thursday, January 15, 2026", "number": "1,234,567.891", "dark": False, "canary_check": True,
|
||||
"canary": {"with": [100, 100], "without": [100, 100], "present": False}, "audio": {"sampleRate": 48000, "maxChannelCount": 2}}
|
||||
STOCK = {"timezone": "America/Bogota", "offsets": [300, 300], "language": "en-US", "languages": ["en-US", "en"], "intl_locale": "en-US",
|
||||
"dark": True, "canary_check": True, "canary": {"with": [180, 180], "without": [100, 100], "present": True},
|
||||
"audio": {"sampleRate": 96000, "maxChannelCount": 6}}
|
||||
|
||||
|
||||
# -
|
||||
# The canary font.
|
||||
|
||||
def test_the_canary_is_the_same_bytes_every_time_and_is_the_one_the_script_declares():
|
||||
assert poison.canary_font() == poison.canary_font()
|
||||
assert poison.canary_sha256() == poison.CANARY_SHA256
|
||||
|
||||
|
||||
def test_the_canary_is_a_well_formed_sfnt_of_a_family_with_wide_letters():
|
||||
font = poison.canary_font()
|
||||
tables = poison.read_tables(font) # raises on a bad table checksum or a bad whole-file checksum
|
||||
assert sorted(tables) == ["OS/2", "cmap", "glyf", "head", "hhea", "hmtx", "loca", "maxp", "name", "post"]
|
||||
assert struct.unpack_from(">I", font)[0] == 0x00010000
|
||||
units_per_em = struct.unpack_from(">H", tables["head"], 18)[0]
|
||||
number_of_glyphs = struct.unpack_from(">H", tables["maxp"], 4)[0]
|
||||
assert (units_per_em, number_of_glyphs) == (1000, 3)
|
||||
advances = struct.unpack(">HhHhHh", tables["hmtx"])[::2]
|
||||
assert advances == (1500, 1500, 500) # a box is 1.5 em wide: far from any fallback's letter
|
||||
# the family is in the name table, as UTF-16BE of platform 3
|
||||
count, offset = struct.unpack_from(">HH", tables["name"], 2)
|
||||
records = [struct.unpack_from(">HHHHHH", tables["name"], 6 + 12 * i) for i in range(count)]
|
||||
family = next(r for r in records if r[3] == 1)
|
||||
text = tables["name"][offset + family[5]:offset + family[5] + family[4]].decode("utf-16-be")
|
||||
assert text == poison.FAMILY == "ZZHostCanary"
|
||||
|
||||
|
||||
def test_the_canary_maps_every_printable_ascii_character_to_a_glyph():
|
||||
cmap = poison.read_tables(poison.canary_font())["cmap"]
|
||||
sub = struct.unpack_from(">I", cmap, 8)[0]
|
||||
seg2 = struct.unpack_from(">H", cmap, sub + 6)[0]
|
||||
segments = seg2 // 2
|
||||
ends = struct.unpack_from(">%dH" % segments, cmap, sub + 14)
|
||||
deltas = struct.unpack_from(">%dH" % segments, cmap, sub + 16 + 2 * segments * 2)
|
||||
glyph = {end: (end + delta) & 0xFFFF for end, delta in zip(ends, deltas)}
|
||||
assert {glyph[c] for c in range(0x21, 0x7F)} == {1}
|
||||
assert glyph[0x20] == 2
|
||||
assert ends[-1] == 0xFFFF
|
||||
|
||||
|
||||
# -
|
||||
# The probe, shared by the page and the control.
|
||||
|
||||
def test_the_probe_is_one_self_contained_block_of_the_page():
|
||||
source = poison.probe_source()
|
||||
assert source.count("const abPoisonProbe = async () =>") == 1
|
||||
for helper in ("put(", "safe(", "errs(", "plain(", "noise("):
|
||||
assert helper not in source, "the control evaluates the block alone: %s is the page's" % helper
|
||||
page = (ROOT / "scripts" / "host_gate" / "host_gate_page.html").read_text(encoding="utf-8")
|
||||
assert "await safe('ab.poison', abPoisonProbe);" in page
|
||||
|
||||
|
||||
def test_a_page_without_the_markers_is_refused(tmp_path):
|
||||
page = tmp_path / "page.html"
|
||||
page.write_text("<script>no markers</script>", encoding="utf-8")
|
||||
with pytest.raises(SystemExit):
|
||||
poison.probe_source(page)
|
||||
|
||||
|
||||
# -
|
||||
# What the engine must not read.
|
||||
|
||||
def test_an_engine_that_reads_the_declared_identity_has_no_finding():
|
||||
assert poison.findings(OURS, WANT) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change, says", [
|
||||
({"offsets": [300, 300]}, "Lima"),
|
||||
({"timezone": "America/Lima"}, "time zone"),
|
||||
({"language": "ja-JP"}, "navigator.language"),
|
||||
({"intl_locale": "ja-JP"}, "Intl locale"),
|
||||
({"date_full": "2026年1月15日木曜日"}, "full date"),
|
||||
({"dark": True}, "prefers-color-scheme"),
|
||||
({"canary": {"with": [180, 180], "without": [100, 100], "present": True}}, "ZZHostCanary"),
|
||||
({"audio": {"sampleRate": 96000, "maxChannelCount": 6}}, "sampleRate 96000"),
|
||||
({"audio": {"sampleRate": 48000, "maxChannelCount": 6}}, "maxChannelCount 6"),
|
||||
({"audio": "ERR NotSupportedError"}, "did not read the audio"),
|
||||
])
|
||||
def test_each_poisoned_value_is_caught_when_the_engine_reads_it(change, says):
|
||||
lines = poison.findings(dict(OURS, **change), WANT)
|
||||
assert lines and any(says in line for line in lines), lines
|
||||
|
||||
|
||||
def test_a_dump_without_the_probe_is_a_finding_not_a_pass():
|
||||
assert poison.findings(None, WANT) and poison.findings({}, WANT)
|
||||
assert "nothing was checked" in poison.findings({}, WANT)[0]
|
||||
|
||||
|
||||
def test_a_dark_host_is_invisible_on_a_persona_that_declares_dark_and_caught_on_one_that_does_not():
|
||||
# why the dark scheme is held against the SEED's declaration and not against 'light': 40% of the personas declare dark
|
||||
assert poison.findings(dict(OURS, dark=True), dict(WANT, dark=True)) == []
|
||||
assert poison.findings(dict(OURS, dark=True), dict(WANT, dark=False))
|
||||
|
||||
|
||||
def test_document_fonts_check_answering_true_is_not_a_finding_the_width_decides():
|
||||
# the specification: check() is true for a family nobody has
|
||||
assert OURS["canary_check"] is True and poison.findings(OURS, WANT) == []
|
||||
|
||||
|
||||
def test_a_dump_is_judged_visit_by_visit_with_the_declaration_of_its_seed():
|
||||
dump = {"visits": [{"seed": 0, "dpr": 1.0, "items": {"ab.poison": OURS}},
|
||||
{"seed": 63, "dpr": 1.25, "items": {"ab.poison": dict(OURS, dark=True)}}]}
|
||||
lines = poison.dump_findings(dump, wants=lambda seed: WANT)
|
||||
assert len(lines) == 1 and lines[0].startswith("seed 63 dpr 1.25: ")
|
||||
|
||||
|
||||
def test_the_declaration_of_a_seed_comes_from_the_core_and_the_reference():
|
||||
d0, d63 = poison.declared(0), poison.declared(63)
|
||||
assert set(d0) == set(WANT)
|
||||
assert d0["timezone"] == "Asia/Bangkok" and d0["offsets"] != poison.LIMA_OFFSETS
|
||||
assert d0["sample_rate"] in (44100, 48000) and d63["sample_rate"] in (44100, 48000)
|
||||
assert isinstance(d0["dark"], bool)
|
||||
|
||||
|
||||
# -
|
||||
# The negative control.
|
||||
|
||||
def test_stock_firefox_that_read_the_poison_is_a_sound_control():
|
||||
for system in ("linux", "windows"):
|
||||
assert poison.control_failures(STOCK, system) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change, requirement", [
|
||||
({"offsets": [-420, -420]}, "timezone"),
|
||||
({"dark": False}, "dark"),
|
||||
({"canary": {"with": [100, 100], "without": [100, 100], "present": False}}, "canary"),
|
||||
({"audio": {"sampleRate": 48000, "maxChannelCount": 2}}, "audio"),
|
||||
])
|
||||
def test_a_poison_that_stock_firefox_did_not_read_is_a_broken_control(change, requirement):
|
||||
failures = poison.control_failures(dict(STOCK, **change), "linux")
|
||||
assert [name for name, _ in failures] == [requirement]
|
||||
|
||||
|
||||
def test_the_audio_sink_is_linux_s_only():
|
||||
assert poison.control_failures(dict(STOCK, audio={"sampleRate": 48000, "maxChannelCount": 2}), "windows") == []
|
||||
|
||||
|
||||
def test_a_control_that_returned_nothing_is_broken():
|
||||
assert poison.control_failures(None, "linux")[0][0] == "probe"
|
||||
|
||||
|
||||
def test_the_language_is_reported_and_not_required_and_says_whether_stock_read_japanese():
|
||||
assert "language" not in poison.REQUIRED
|
||||
assert poison.language_reads(STOCK)["japanese"] is False
|
||||
assert poison.language_reads(dict(STOCK, language="ja-JP"))["japanese"] is True
|
||||
assert poison.language_reads(dict(STOCK, date_full="2026年1月15日"))["japanese"] is True
|
||||
|
||||
|
||||
# -
|
||||
# Windows: the commands, their order and the way back.
|
||||
|
||||
class Fake:
|
||||
"""A runner that records what it was asked and answers like a machine that has a zone, a culture, a language list and a theme."""
|
||||
|
||||
def __init__(self, answers=None):
|
||||
self.calls = []
|
||||
self.answers = {"tzutil /g": "Tokyo Standard Time", "(Get-Culture).Name": "en-US", "Get-WinUserLanguageList": "en-US,it-IT",
|
||||
"AppsUseLightTheme": "1", "SystemUsesLightTheme": "1"}
|
||||
self.answers.update(answers or {})
|
||||
|
||||
def __call__(self, cmd):
|
||||
self.calls.append(list(cmd))
|
||||
text = " ".join(cmd)
|
||||
for key, value in self.answers.items():
|
||||
if key in text:
|
||||
return 0, value
|
||||
return 0, ""
|
||||
|
||||
def text(self):
|
||||
return [" ".join(c) for c in self.calls]
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def no_session(monkeypatch):
|
||||
"""The two calls that tell the running Windows session about a font are not made from a test."""
|
||||
monkeypatch.setattr(poison, "_announce_font", lambda path: None)
|
||||
monkeypatch.setattr(poison, "_forget_font", lambda path: None)
|
||||
|
||||
|
||||
def test_windows_apply_reads_everything_before_it_changes_anything(tmp_path, no_session):
|
||||
fake = Fake()
|
||||
state = poison.apply_windows(fake, font_dir=tmp_path)
|
||||
lines = fake.text()
|
||||
first_change = next(i for i, line in enumerate(lines) if "tzutil /s" in line)
|
||||
assert all("Set-" not in line and "New-ItemProperty" not in line for line in lines[:first_change])
|
||||
assert state["timezone"] == "Tokyo Standard Time" and state["culture"] == "en-US" and state["languages"] == "en-US,it-IT"
|
||||
assert state["theme"] == {"AppsUseLightTheme": "1", "SystemUsesLightTheme": "1"}
|
||||
assert any("tzutil /s %s" % poison.WINDOWS_ZONE in line for line in lines)
|
||||
assert any("Set-Culture -CultureInfo 'ja-JP'" in line for line in lines)
|
||||
assert any("Set-WinUserLanguageList -LanguageList 'ja-JP' -Force" in line for line in lines)
|
||||
assert sum("-Name AppsUseLightTheme -Value 0" in line or "-Name SystemUsesLightTheme -Value 0" in line for line in lines) == 2
|
||||
assert (tmp_path / poison.FONT_FILE).read_bytes() == poison.canary_font()
|
||||
assert any(poison.FONT_VALUE in line and "-PropertyType String" in line for line in lines)
|
||||
|
||||
|
||||
def test_every_powershell_of_the_script_forces_the_invariant_culture_first(tmp_path, no_session):
|
||||
fake = Fake()
|
||||
poison.apply_windows(fake, font_dir=tmp_path)
|
||||
poison.verify_windows(fake, {"font": str(tmp_path / poison.FONT_FILE)})
|
||||
poison.undo_windows({"font": str(tmp_path / poison.FONT_FILE), "theme": {"AppsUseLightTheme": "1"}, "languages": "en-US", "culture": "en-US",
|
||||
"timezone": "Tokyo Standard Time"}, fake)
|
||||
shells = [c for c in fake.calls if c[0] == "powershell.exe"]
|
||||
assert shells
|
||||
for cmd in shells:
|
||||
assert "-NoProfile" in cmd and "-NonInteractive" in cmd
|
||||
script = cmd[-1]
|
||||
assert script.startswith("[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::InvariantCulture")
|
||||
|
||||
|
||||
def test_windows_undo_puts_back_what_was_found_and_removes_what_was_added(tmp_path, no_session):
|
||||
fake = Fake()
|
||||
state = poison.apply_windows(fake, font_dir=tmp_path)
|
||||
fake.calls.clear()
|
||||
poison.undo_windows(state, fake)
|
||||
lines = fake.text()
|
||||
assert not (tmp_path / poison.FONT_FILE).exists()
|
||||
assert any("Remove-ItemProperty" in line and poison.FONT_VALUE in line for line in lines)
|
||||
assert any("-Name AppsUseLightTheme -Value 1" in line for line in lines)
|
||||
assert any("Set-Culture -CultureInfo 'en-US'" in line for line in lines)
|
||||
assert any("Set-WinUserLanguageList -LanguageList 'en-US','it-IT' -Force" in line for line in lines)
|
||||
assert any(line.endswith("tzutil /s Tokyo Standard Time") for line in lines)
|
||||
|
||||
|
||||
def test_a_theme_value_that_was_not_there_is_removed_not_set_on_undo(tmp_path, no_session):
|
||||
fake = Fake({"AppsUseLightTheme": "", "SystemUsesLightTheme": ""})
|
||||
state = poison.apply_windows(fake, font_dir=tmp_path)
|
||||
assert state["theme"] == {"AppsUseLightTheme": "", "SystemUsesLightTheme": ""}
|
||||
fake.calls.clear()
|
||||
poison.undo_windows(state, fake)
|
||||
removed = [line for line in fake.text() if "Remove-ItemProperty" in line and "Personalize" in line]
|
||||
assert len(removed) == 2
|
||||
|
||||
|
||||
def test_windows_apply_that_a_command_refuses_stops_with_the_command_named(tmp_path, no_session):
|
||||
def refuse(cmd):
|
||||
return (1, "access denied") if cmd[:2] == ["tzutil", "/s"] else Fake()(cmd)
|
||||
|
||||
with pytest.raises(SystemExit) as stop:
|
||||
poison.apply_windows(refuse, font_dir=tmp_path)
|
||||
assert "set the time zone" in str(stop.value) and "access denied" in str(stop.value)
|
||||
|
||||
|
||||
def test_windows_verify_names_each_value_that_is_not_in_force(tmp_path):
|
||||
font = tmp_path / poison.FONT_FILE
|
||||
font.write_bytes(poison.canary_font())
|
||||
right = Fake({"tzutil /g": poison.WINDOWS_ZONE, "(Get-Culture).Name": "ja-JP", "Get-WinUserLanguageList": "ja-JP",
|
||||
"AppsUseLightTheme": "0", "SystemUsesLightTheme": "0", "Get-ItemProperty -Path 'HKCU:\\Software\\Microsoft\\Windows NT": str(font)})
|
||||
assert poison.verify_windows(right, {"font": str(font)}) == []
|
||||
wrong = Fake()
|
||||
problems = poison.verify_windows(wrong, {"font": str(font)})
|
||||
assert any("time zone" in p for p in problems) and any("culture" in p for p in problems) and any("AppsUseLightTheme" in p for p in problems)
|
||||
assert any("registered" in p for p in problems)
|
||||
font.write_bytes(b"not the canary")
|
||||
assert any("not the canary" in p for p in poison.verify_windows(right, {"font": str(font)}))
|
||||
|
||||
|
||||
# -
|
||||
# Linux.
|
||||
|
||||
def test_linux_apply_installs_the_locale_the_font_and_the_null_sink(tmp_path):
|
||||
answers = {"locale -a": "C\nPOSIX\nen_US.utf8", "load-module": "42", "pactl info": "Server String: /run/user/1001/pulse/native\n"}
|
||||
fake = Fake(answers)
|
||||
state = poison.apply_linux(fake, font_dir=tmp_path / "fonts")
|
||||
lines = fake.text()
|
||||
assert any(line.endswith("locale-gen ja_JP.UTF-8") for line in lines)
|
||||
assert (tmp_path / "fonts" / poison.FONT_FILE).read_bytes() == poison.canary_font()
|
||||
assert any(line.startswith("fc-cache -f") for line in lines)
|
||||
sink = next(line for line in lines if "module-null-sink" in line)
|
||||
assert "rate=96000" in sink and "channels=6" in sink and "sink_name=hostcanary" in sink
|
||||
assert any(line == "pactl set-default-sink hostcanary" for line in lines)
|
||||
assert state["module"] == "42"
|
||||
assert state["env"]["TZ"] == "America/Lima" and state["env"]["LANG"] == "ja_JP.UTF-8" and state["env"]["GTK_THEME"] == "Adwaita:dark"
|
||||
assert state["env"]["PULSE_SERVER"] == "unix:/run/user/1001/pulse/native"
|
||||
|
||||
|
||||
def test_linux_apply_without_audio_makes_no_sink_and_a_present_locale_is_not_generated_again(tmp_path):
|
||||
fake = Fake({"locale -a": "C\nja_JP.utf8"})
|
||||
state = poison.apply_linux(fake, font_dir=tmp_path, audio=False)
|
||||
lines = fake.text()
|
||||
assert not any("locale-gen" in line for line in lines) and not any("pactl" in line for line in lines)
|
||||
assert "PULSE_SERVER" not in state["env"] and state["module"] == ""
|
||||
|
||||
|
||||
def test_linux_undo_unloads_the_sink_and_removes_the_font(tmp_path):
|
||||
fake = Fake({"locale -a": "ja_JP.utf8", "load-module": "7"})
|
||||
state = poison.apply_linux(fake, font_dir=tmp_path)
|
||||
fake.calls.clear()
|
||||
poison.undo_linux(state, fake)
|
||||
lines = fake.text()
|
||||
assert "pactl unload-module 7" in lines
|
||||
assert not (tmp_path / poison.FONT_FILE).exists()
|
||||
|
||||
|
||||
def test_linux_verify_wants_the_sink_to_be_6_channels_at_96000_and_the_default(tmp_path):
|
||||
font = tmp_path / poison.FONT_FILE
|
||||
font.write_bytes(poison.canary_font())
|
||||
state = {"font": str(font)}
|
||||
good = Fake({"locale -a": "ja_JP.utf8", "fc-list": "ZZHostCanary", "list short sinks": "1\thostcanary\tmodule-null-sink.c\ts16le 6ch 96000Hz\tIDLE",
|
||||
"get-default-sink": "hostcanary"})
|
||||
assert poison.verify_linux(good, state) == []
|
||||
bad = Fake({"locale -a": "ja_JP.utf8", "fc-list": "ZZHostCanary", "list short sinks": "1\thostcanary\tmodule-null-sink.c\ts16le 2ch 44100Hz\tIDLE",
|
||||
"get-default-sink": "alsa_output"})
|
||||
problems = poison.verify_linux(bad, state)
|
||||
assert any("6 channels at 96000" in p for p in problems) and any("default sink" in p for p in problems)
|
||||
assert any("fontconfig" in p for p in poison.verify_linux(Fake({"locale -a": "ja_JP.utf8"}), state, audio=False))
|
||||
|
||||
|
||||
def test_linux_verify_of_the_environment_is_for_the_process_that_inherited_it(tmp_path):
|
||||
font = tmp_path / poison.FONT_FILE
|
||||
font.write_bytes(poison.canary_font())
|
||||
quiet = Fake({"locale -a": "ja_JP.utf8", "fc-list": "ZZHostCanary"})
|
||||
state = {"font": str(font)}
|
||||
assert poison.verify_linux(quiet, state, audio=False) == []
|
||||
problems = poison.verify_linux(quiet, state, expect_env=True, audio=False, env={"TZ": "UTC"})
|
||||
assert len(problems) == 4 and any("TZ" in p for p in problems)
|
||||
assert poison.verify_linux(quiet, state, expect_env=True, audio=False, env=dict(poison.LINUX_ENV)) == []
|
||||
|
||||
|
||||
# -
|
||||
# apply and undo, as the CLI runs them.
|
||||
|
||||
def test_apply_tells_the_later_steps_by_github_env_and_undo_gives_the_old_values_back(tmp_path, monkeypatch):
|
||||
target = tmp_path / "github_env"
|
||||
state_file = tmp_path / "state.json"
|
||||
monkeypatch.setenv("GITHUB_ENV", str(target))
|
||||
monkeypatch.setattr(poison, "system_name", lambda: "linux")
|
||||
monkeypatch.setattr(poison, "apply_linux", lambda run, audio=True: {"system": "linux", "font": str(tmp_path / "f.ttf"), "module": "",
|
||||
"env": {"TZ": "America/Lima"}, "before_env": {"TZ": "UTC"}})
|
||||
monkeypatch.setattr(poison, "verify_linux", lambda *a, **k: [])
|
||||
monkeypatch.setattr(poison, "undo_linux", lambda state, run: None)
|
||||
assert poison.apply(state_file, audio=False) == 0
|
||||
written = target.read_text(encoding="utf-8")
|
||||
assert "TZ=America/Lima\n" in written and "AB_ORACLE_POISON=1\n" in written
|
||||
assert "AB_ORACLE_POISON_STATE=%s\n" % state_file.resolve() in written
|
||||
assert json.loads(state_file.read_text(encoding="utf-8"))["system"] == "linux"
|
||||
target.write_text("", encoding="utf-8")
|
||||
assert poison.undo(state_file) == 0
|
||||
back = target.read_text(encoding="utf-8")
|
||||
assert "TZ=UTC\n" in back and "AB_ORACLE_POISON=\n" in back
|
||||
|
||||
|
||||
def test_a_poison_that_is_not_in_force_after_apply_is_exit_2_and_tells_nothing_to_the_later_steps(tmp_path, monkeypatch, capsys):
|
||||
target = tmp_path / "github_env"
|
||||
monkeypatch.setenv("GITHUB_ENV", str(target))
|
||||
monkeypatch.setattr(poison, "system_name", lambda: "linux")
|
||||
monkeypatch.setattr(poison, "apply_linux", lambda run, audio=True: {"system": "linux", "font": "f", "module": "", "env": {}, "before_env": {}})
|
||||
monkeypatch.setattr(poison, "verify_linux", lambda *a, **k: ["the null sink is not the default sink"])
|
||||
assert poison.apply(None) == 2
|
||||
assert "POISON NOT IN FORCE: the null sink" in capsys.readouterr().out
|
||||
assert not target.exists()
|
||||
|
||||
|
||||
def test_verify_here_reads_the_state_the_apply_wrote(tmp_path, monkeypatch):
|
||||
seen = {}
|
||||
monkeypatch.setattr(poison, "system_name", lambda: "linux")
|
||||
monkeypatch.setattr(poison, "verify_linux", lambda run, state, expect_env, audio: seen.update(state=state, env=expect_env, audio=audio) or [])
|
||||
state_file = tmp_path / "state.json"
|
||||
state_file.write_text(json.dumps({"font": "x", "audio": True}), encoding="utf-8")
|
||||
monkeypatch.setenv(poison.STATE_SWITCH, str(state_file))
|
||||
assert poison.verify_here(expect_env=True) == []
|
||||
assert seen == {"state": {"font": "x", "audio": True}, "env": True, "audio": True}
|
||||
|
||||
|
||||
# -
|
||||
# The words and paths a test or a message of the repository must not hold.
|
||||
|
||||
def test_the_new_files_name_no_machine_path_and_no_forbidden_word():
|
||||
banned = ["C:" + "\\Users", "/home/" + "runner", "camou" + "fox"]
|
||||
for path in [ROOT / "scripts" / "ci_poison_host.py", Path(__file__)] + sorted((ROOT / "scripts" / "host_gate" / "ab").iterdir()):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
for word in banned:
|
||||
assert word not in text, "%s holds %r" % (path.name, word)
|
||||
assert "\r" not in text, "%s is not LF" % path.name
|
||||
Reference in new issue
Block a user