Files
archived-camoufox/python/tests/test_launch_environment.py
T
Jake WriterandClaude Opus 5.5 e90abccee6 Firefox 159: stock parity for a driven browser (#997)
* Firefox 159: stock parity for a driven browser

A page driven through Camoufox should read like stock Firefox in a
person's hands. This brings the Firefox 159 port up to that.

Stock defaults
- Remote Settings, Safe Browsing, region detection, Push, connectivity
  checks and the new tab keep Firefox's defaults; Nimbus is tied to
  Normandy so the new tab starts without it.
- No policies.json: any policy file puts Firefox in enterprise mode,
  which a page can see (DNS over HTTPS stands down).
- Firefox's 100% release rollouts are default prefs; stock's search
  engines are back.
- WebGL, devicePixelRatio and worker getters cost what stock's do; Linux
  builds use --enable-stdcxx-compat, as Mozilla's do.

Juggler
- Driver code defines no interfaces on the page's window, isolated and
  main-world evaluates included.
- Input arrives as a person's: click hold, hover dwell and double-click
  gap; fill() and insert_text() type key by key; the wheel turns notches;
  moves coalesce per frame; drags behave as a GTK drag session. Input
  waits for Firefox's user-input gate.
- Focus, Fission and bfcache stay Firefox's unless a driver needs them.
- Screenshots and document.fonts.ready leave the page alone.

Humanize
- One engine per channel (mouse, keyboard, scroll) behind one seam in
  Juggler, a seed for repeatable input, and custom(fn) engines run in the
  caller's process (Python). The build lists its engines in
  humanize-engines.json.

Network
- A SOCKS5 proxy with a username and password works for the launch and
  per context.
- The User-Agent header follows the context's identity.
- WebRTC UDP goes through a SOCKS5 proxy's UDP ASSOCIATE relay
  (webrtc-socks5-udp.patch), so a page's STUN server sees the exit and the
  srflx is real. Nothing goes around the proxy: a page with no HTTP-loaded
  document behind it counts as proxied, a proxy that carries no UDP gets
  none, and a relay address inside the proxy's own NAT is replaced by the
  proxy's public one.

Identity
- Bundled fonts and speech voices follow the drawn identity.
- The window holds the identity's size and position through startup, and
  on a virtual display a window outside the root is neither occluded nor
  refused focus.

CI runs every new guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BLGoGNeymhNcr3EAQX5hJE

* Paste inserted text; draw input delays from one normal helper

fill() and keyboard.insert_text() typed the text key by key, a quarter of a
second per character, which ran past Playwright's timeouts and is not how a
person enters a whole string. They now paste: the paste shortcut (Ctrl+V,
Cmd+V for a Mac platform) goes down, Firefox's own paste runs with the text
through nsIEditor.pasteTransferable (a trusted paste event with the text as
clipboardData, then beforeinput/input insertFromPaste), and the shortcut
comes up. The shortcut's keypress, where Firefox would read the system
clipboard, is cancelled in the system group, which content cannot observe;
the system clipboard is never used. A page that cancels the paste or the
shortcut gets nothing, and the call fails saying so.

input/HumanDelay.js holds normalDelay(mean, sd, min, max), the one draw for
the delays between a person's input events: the click hold (normal around
110 ms, SD 30, never under 50 ms, with no ceiling), the double-click gap,
the hover dwell, the paste key's hold, and the Shift and paste modifiers'
lead and trail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BLGoGNeymhNcr3EAQX5hJE

* Fix driven input and headless parity

* Headless with a display uses that display's GL

A headless probe that failed to load EGL still recorded TEST_TYPE EGL, so Firefox refused GLX and every headless WebGL context died. Probe EGL only when there is no display, and only claim it when that probe initialized. Move spacing starts when the move is sent, so a steps path stays a 125 Hz mouse instead of one move per frame.

* Fix focus, humanize-off, and WebRTC proxy parity

- A stock identity mirror adds no humanize keys when humanize is off.
- Keep the real focus and run the upstream focus tests.
- Add the per-context WebRTC proxy flag; do not fabricate a srflx behind a proxy.
- Refresh the Python/TypeScript parity tests, skiplist and docs.
- Install Mesa DRI so the software WebGL guards can run.

* Fix TypeScript humanize float encoding

Encode humanize option values as PyFloat so a duration serializes as 1.0, matching Python, and apply Biome's import formatting.

* Close a relay overflow, stop inventing srflx, and fix driven input gaps

WebRTC:
- A SOCKS5 relay read larger than the caller's buffer overran the stack
  buffer. A page-named STUN server could send one. Drop the datagram.
- Remove the fabricated srflx candidate; a srflx now only comes from a
  STUN answer, and the guards run against a server that answers.
- Juggler records each proxy it sets, so a caller's own
  new_context(proxy=...) cannot gather around it. This replaces the
  launcher's webrtc:proxied key and its page-visible setter.
- Headless GL probes use the surfaceless platform without launcher plumbing.

Input:
- A wheel without a scroll engine takes the activation slot per notch, so
  a long scroll no longer stalls input in every other context.
- Paste and fill work inside an iframe.
- Python fill honours the caller's timeout.

TypeScript humanize matches Python: off, seeds, duplicate options and the
scroll warning.

Guards with a missing prerequisite fail rather than pass. Add
navigation-preconnect-proxied. Move the tweened click test to a skiplist
pattern entry, since whether it passes depends on machine speed.

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

* Check the tweened click entry with its guard, not the audit

Whether test_click_with_tweened_mouse_movement passes depends on machine
speed: 0 of 20 runs on all cores here, 3 of 15 on two, and it passed on CI.
The audit cannot demand a failure from it, and a pattern entry would leave
its reason unchecked. A skiplist entry's checked_by now names the patch
guard that checks the reason, here driven-move-coalescing.

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

* Ask the display-less GL probe for a pbuffer config

Mesa's surfaceless platform has only pbuffer configs. The probe asked for
the default window surface type, so eglChooseConfig matched nothing and
eglCreateContext got an uninitialized config. With no GPU, a display-less
headless launch then had an empty gfxInfo: no WebGL and no WebRTC H264.

A host where NVIDIA's EGL answers first never reaches Mesa here, so the
guards only failed on machines without a GPU.

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

* Open about:blank for a driver and run first-page init scripts after PageAgent

A headed persistent launch opened about:home once the start page prefs went
back to stock. browser.startup.page now becomes 0 only when a driver attaches,
so a browser nobody drives keeps Firefox's start page.

Init scripts on a page's initial document ran before PageAgent existed, so
their binding calls and console messages had no listener and were lost. They
now run after PageAgent has reported the page's execution contexts.

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

* Warm up the crash growth test past Firefox 159's timed startup work

The parent holds up to 400 MB more for a while at fixed times after launch, in
stock Firefox 159 as well. Two RSS readings taken across one of those peaks
read as growth or shrinkage, and pushed the test over its limit with no leak.
Warm up by time instead of by context count. The metric and limit are unchanged.

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

* Close WebRTC paths around a proxy, stop background traffic, fix driven input

WebRTC behind a proxy no longer shows the host's address: ICE uses the proxy's
SOCKS5 UDP relay when it has one, and UDP is dropped otherwise. A page on the
bypass list behind a forced proxy is blocked on UDP and ICE TCP. A proxy hanging
up straight after CONNECT no longer crashes the parent process.

Remote Settings stops polling, with the page-visible lists bundled as a snapshot
pinned by scripts/remote_settings.py, and Push connects on demand.

fill clicks an unfocused text field and types when a page blocks paste. Click
throughput across contexts is restored. The TypeScript launcher gains custom
humanize engines and driver defaults, in step with Python, and caps WebGL2
MAX_UNIFORM_BLOCK_SIZE at Firefox 159's 64 KiB.

docs/input-dispatch.md records a person's wheel on macOS, which is one line a
notch where the driven wheel sends three.

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

* Leave the humanize engine system for its own pull request

Per-channel engines, seeded streams, custom() and the keyboard and
scroll-into-view plans are a separate feature. humanize keeps main's meaning
here: a human cursor move, on or off, with an optional duration cap, planned by
CursorTrajectory.js and paced by Pacer.js. The five per-channel config keys were
declared on this branch, so they stay declared as removed.

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

* Warn, not raise, on a browser that cannot read voices:speechd

A new package has to launch an older build (#835, and the install gate launches
the last release). A Linux identity there reports no voices, so it warns and the
warning cannot be silenced.

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

* Give a macOS identity macOS's wheel

A person's notched mouse on macOS sends one line for a slow notch, with no native
tick, and accelerates a faster turn from there. Driven input sent Linux's three
ticked lines. A macOS identity now sends lines at 16 px each, starting at one and
growing, and stock's per-OS system scroll override follows the identity.

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

* Install the tracking lists where a clean build's reader looks

A relative wildcard keeps its directory under recursive make and drops it under
faster make. The clean build nested the attachments one directory too deep, so
the classifier had no tables. An incremental objdir hid this with old links.

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

* Make two guards deterministic: the wheel's OS and a dropped relay

A launch without `os` draws one, and a macOS draw now gets macOS's wheel, so the
guards asserting three notches failed by the draw. They assert Linux's now.

The browser flushes queued datagrams when UDP ASSOCIATE is granted, so a relay
closed just after the grant could forward one, and the STUN server heard the
proxy's own relay port as if it had gone around the proxy. It closes first now.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-07 17:51:40 +00:00

654 lines
27 KiB
Python

"""Regression tests for per-launch environment isolation."""
import copy
import json
import os
import pytest
from camoufox import utils
@pytest.fixture
def isolated_launch_dependencies(monkeypatch):
"""Keep launch_options focused on environment assembly, without a browser."""
monkeypatch.setattr(utils, "add_default_addons", lambda *args, **kwargs: None)
monkeypatch.setattr(utils, "generate_fingerprint", lambda *args, **kwargs: object())
monkeypatch.setattr(utils, "from_fpgen", lambda *args, **kwargs: {})
monkeypatch.setattr(utils, "get_screen_cons", lambda *args, **kwargs: None)
monkeypatch.setattr(utils, "_generate_random_font_subset", lambda *args, **kwargs: [])
monkeypatch.setattr(utils, "draw_voice_config", lambda *args, **kwargs: {"voices": []})
monkeypatch.setattr(utils, "fix_navigator_arch", lambda *args: None)
monkeypatch.setattr(utils, "follow_baseline_protection", lambda *args: None)
monkeypatch.setattr(utils, "clamp_window_dimensions", lambda *args: None)
monkeypatch.setattr(utils, "set_media_devices_defaults", lambda *args: None)
monkeypatch.setattr(utils, "installed_verstr", lambda: "152.0.4-beta.28")
monkeypatch.setattr(utils, "validate_config", lambda *args, **kwargs: None)
monkeypatch.setattr(utils, "get_env_vars", lambda *args, **kwargs: {})
monkeypatch.setattr(utils, "launch_path", lambda: "/test/camoufox")
def _launch_with_virtual_display(**kwargs):
return utils.launch_options(
virtual_display=":4242",
headless=True,
block_webgl=True,
i_know_what_im_doing=True,
**kwargs,
)
def test_virtual_display_does_not_mutate_process_environment(
monkeypatch, isolated_launch_dependencies
):
monkeypatch.delenv("DISPLAY", raising=False)
monkeypatch.setenv("GDK_BACKEND", "wayland")
monkeypatch.setenv("WAYLAND_DISPLAY", "wayland-0")
monkeypatch.setenv("MOZ_ENABLE_WAYLAND", "1")
keys = ("DISPLAY", "GDK_BACKEND", "WAYLAND_DISPLAY", "MOZ_ENABLE_WAYLAND")
before = {key: os.environ.get(key) for key in keys}
options = _launch_with_virtual_display()
assert {key: os.environ.get(key) for key in keys} == before
assert options["env"]["DISPLAY"] == ":4242"
assert options["env"]["GDK_BACKEND"] == "x11"
assert "WAYLAND_DISPLAY" not in options["env"]
assert options["env"]["MOZ_ENABLE_WAYLAND"] == "0"
def test_virtual_display_does_not_mutate_caller_environment(
isolated_launch_dependencies,
):
caller_env = {
"UNCHANGED": "value",
"GDK_BACKEND": "wayland",
"WAYLAND_DISPLAY": "wayland-0",
"MOZ_ENABLE_WAYLAND": "1",
}
before = caller_env.copy()
options = _launch_with_virtual_display(env=caller_env)
assert caller_env == before
assert options["env"]["UNCHANGED"] == "value"
assert options["env"]["DISPLAY"] == ":4242"
assert options["env"]["GDK_BACKEND"] == "x11"
assert "WAYLAND_DISPLAY" not in options["env"]
assert options["env"]["MOZ_ENABLE_WAYLAND"] == "0"
def test_launch_does_not_mutate_caller_inputs(monkeypatch, isolated_launch_dependencies):
"""A caller's mappings, reused for a second launch, must not carry the first
launch's identity in. The first launch's webGl:vendor left in a reused config
read as a GPU the caller named, so the second launch covered its canvas."""
monkeypatch.setattr(utils, "add_default_addons", lambda addons, *_: addons.append("/default-addon"))
monkeypatch.setattr(utils, "confirm_paths", lambda paths: None)
inputs = {
"config": {"navigator.userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:152.0) Gecko/20100101 Firefox/152.0"},
"firefox_user_prefs": {"caller.pref": 1},
"args": ["-caller-arg"],
"addons": ["/caller-addon"],
}
before = copy.deepcopy(inputs)
options = utils.launch_options(block_webgl=True, i_know_what_im_doing=True, **inputs)
assert inputs == before
assert options["firefox_user_prefs"]["caller.pref"] == 1
class TestFontFallbackAsyncPref:
"""Per-character font fallback must not skip families whose
charmap is not loaded yet.
Gecko's GlobalFontFallback walks the shared font list for a family covering
the character; in a content process with async fallback on it hits the
`!family.IsFullyInitialized()` branch, schedules a cmap load and SKIPS the
family, so the first measurement of a character only one bundled family
provides returns the primary family's .notdef. Linux takes that path for
every fallback (UseCmapsDuringSystemFallback), so the font-hijacker change
that restored this on macOS cannot reach it there.
macOS must NOT get the pref: it uses the CoreText fallback, and forcing the
synchronous scan changed the face picked for U+1E9E in Futura (stock 21.733
-> 27.267), measured on a real Mac mini.
"""
PREF = "gfx.font_rendering.fallback.async"
def _prefs_for(self, ua, isolated):
return utils.launch_options(
config={"navigator.userAgent": ua},
i_know_what_im_doing=True,
)["firefox_user_prefs"]
def test_linux_disables_async_font_fallback(self, isolated_launch_dependencies):
prefs = self._prefs_for("Mozilla/5.0 (X11; Linux x86_64; rv:152.0) Gecko/20100101 Firefox/152.0", None)
assert prefs[self.PREF] is False
def test_macos_keeps_async_font_fallback(self, isolated_launch_dependencies):
prefs = self._prefs_for(
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:152.0) Gecko/20100101 Firefox/152.0", None
)
assert self.PREF not in prefs
def test_windows_keeps_async_font_fallback(self, isolated_launch_dependencies):
prefs = self._prefs_for(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:152.0) Gecko/20100101 Firefox/152.0", None
)
assert self.PREF not in prefs
def test_caller_pref_wins(self, isolated_launch_dependencies):
prefs = utils.launch_options(
config={"navigator.userAgent": "Mozilla/5.0 (X11; Linux x86_64; rv:152.0) Gecko/20100101 Firefox/152.0"},
firefox_user_prefs={"gfx.font_rendering.fallback.async": True},
i_know_what_im_doing=True,
)["firefox_user_prefs"]
assert prefs[self.PREF] is True
class TestUiLocaleFollowsIntlLocale:
"""The packaged browser locale must follow the spoofed Intl locale.
With locale="fr-FR" and the browser left on en-US, Intl formatting went
French while input.validationMessage and XML parse errors stayed English --
a mix no real Firefox produces. Packages now bake in the language packs;
intl.locale.requested selects one, and must always be set because an empty
value would follow the host OS locale.
"""
PREF = "intl.locale.requested"
UA = "Mozilla/5.0 (X11; Linux x86_64; rv:152.0) Gecko/20100101 Firefox/152.0"
def _prefs(self, **kwargs):
return utils.launch_options(
config={"navigator.userAgent": self.UA, **kwargs.pop("config", {})},
i_know_what_im_doing=True,
**kwargs,
)["firefox_user_prefs"]
def test_default_identity_pins_en_us(self, isolated_launch_dependencies):
assert self._prefs()[self.PREF] == "en-US"
def test_spoofed_locale_selects_matching_ui_locale(self, isolated_launch_dependencies):
# handle_locale adds the likely script; Gecko's filtering negotiation
# treats a packaged "fr" as a range, so fr-Latn-FR still selects fr.
assert self._prefs(locale="fr-FR")[self.PREF] == "fr-Latn-FR"
assert self._prefs(locale="pt-BR")[self.PREF] == "pt-Latn-BR"
def test_first_of_several_locales_wins(self, isolated_launch_dependencies):
assert self._prefs(locale="de-DE, en-US")[self.PREF] == "de-Latn-DE"
def test_geoip_style_config_locale_is_used(self, isolated_launch_dependencies):
config = {"locale:language": "ja", "locale:region": "JP"}
assert self._prefs(config=config)[self.PREF] == "ja-JP"
def test_script_subtag_is_kept(self, isolated_launch_dependencies):
config = {"locale:language": "zh", "locale:script": "Hant", "locale:region": "TW"}
assert self._prefs(config=config)[self.PREF] == "zh-Hant-TW"
def test_caller_pref_wins(self, isolated_launch_dependencies):
prefs = self._prefs(locale="fr-FR", firefox_user_prefs={self.PREF: "de"})
assert prefs[self.PREF] == "de"
class TestToggleSettingsAreWrittenBothWays:
"""Fresh profiles omit off toggles; persistent profiles clear old values."""
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:152.0) Gecko/20100101 Firefox/152.0"
TOGGLES = [
("block_webrtc", "media.peerconnection.enabled", True, False),
("block_images", "permissions.default.image", 1, 2),
("disable_coop", "browser.tabs.remote.useCrossOriginOpenerPolicy", True, False),
]
def _prefs(self, **kwargs):
return utils.launch_options(
config={"navigator.userAgent": self.UA}, i_know_what_im_doing=True, **kwargs
)["firefox_user_prefs"]
@pytest.mark.parametrize("flag, pref, stock, toggled", TOGGLES)
def test_off_writes_nothing_as_stock_does(self, isolated_launch_dependencies, flag, pref, stock, toggled):
assert pref not in self._prefs()
@pytest.mark.parametrize("flag, pref, stock, toggled", TOGGLES)
def test_off_clears_a_value_an_earlier_launch_left(self, isolated_launch_dependencies, tmp_path,
flag, pref, stock, toggled):
(tmp_path / "prefs.js").write_text(f'user_pref("{pref}", {json.dumps(toggled)});\n')
assert utils.saved_pref(str(tmp_path), pref) == toggled
prefs = {}
utils.set_toggle_pref(prefs, pref, False, stock, toggled, str(tmp_path))
assert prefs == {pref: stock}
(tmp_path / "prefs.js").write_text(f'user_pref("{pref}", {json.dumps(stock)});\n')
prefs = {}
utils.set_toggle_pref(prefs, pref, False, stock, toggled, str(tmp_path))
assert prefs == {}
@pytest.mark.parametrize("flag, pref, stock, toggled", TOGGLES)
def test_on_writes_the_toggled_value(self, isolated_launch_dependencies, flag, pref, stock, toggled):
assert self._prefs(**{flag: True})[pref] == toggled
@pytest.mark.parametrize("flag, pref, stock, toggled", TOGGLES)
def test_caller_pref_wins(self, isolated_launch_dependencies, flag, pref, stock, toggled):
assert self._prefs(firefox_user_prefs={pref: toggled})[pref] == toggled
class TestGeoipIPv6:
"""Without a proxy, sites reach this host over IPv6 when it has an address.
network.dns.disableIPv6 used to be set for every IPv4 geoip address, which
broke IPv6-only sites (daijro/camoufox#849) while IPv6 literals still
connected. IPv6 is now kept when the host's address geolocates where the
identity does; otherwise network:ipv4Only makes the browser behave as on an
IPv4-only network.
"""
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:152.0) Gecko/20100101 Firefox/152.0"
IPV4 = "203.0.113.7"
HERE = {"timezone": "America/Chicago", "locale:region": "US"}
PLACES = {
IPV4: HERE,
"2001:db8::1": HERE,
"2001:db8::2": {"timezone": "Europe/Berlin", "locale:region": "DE"},
}
def _launch(self, monkeypatch, host_ipv6, **kwargs):
class Location:
def __init__(self, config):
self.config = config
def as_config(self):
return dict(self.config)
def geolocate(ip, **kwargs):
if ip not in self.PLACES:
raise utils.UnknownIPLocation(ip)
return Location(self.PLACES[ip])
sent = {}
monkeypatch.setattr(utils, "geoip_allowed", lambda: None)
monkeypatch.setattr(utils, "get_geolocation", geolocate)
monkeypatch.setattr(utils, "public_ipv6", host_ipv6 if callable(host_ipv6) else lambda: host_ipv6)
monkeypatch.setattr(utils, "get_env_vars", lambda config, *args, **kwargs: sent.update(config) or {})
prefs = utils.launch_options(
config={"navigator.userAgent": self.UA}, **kwargs
)["firefox_user_prefs"]
assert "network.dns.disableIPv6" not in prefs
return sent
def test_ipv6_in_the_same_place_is_kept(self, monkeypatch, isolated_launch_dependencies):
sent = self._launch(monkeypatch, "2001:db8::1", geoip=self.IPV4)
assert "network:ipv4Only" not in sent
assert sent["webrtc:ipv4"] == self.IPV4
def test_no_ipv6_route_is_an_ipv4_only_network(self, monkeypatch, isolated_launch_dependencies):
sent = self._launch(monkeypatch, None, geoip=self.IPV4)
assert sent["network:ipv4Only"] is True
@pytest.mark.parametrize("host_ipv6", ["2001:db8::2", "2001:db8::3"], ids=["elsewhere", "unknown"])
def test_ipv6_that_disagrees_is_dropped_with_a_warning(
self, monkeypatch, isolated_launch_dependencies, host_ipv6
):
with pytest.warns(utils.LeakWarning, match="IPv6 address geolocates somewhere other"):
sent = self._launch(monkeypatch, host_ipv6, geoip=self.IPV4)
assert sent["network:ipv4Only"] is True
def test_proxy_leaves_ipv6_alone(self, monkeypatch, isolated_launch_dependencies):
def no_lookup():
raise AssertionError("the host's IPv6 address is not what a proxied site sees")
sent = self._launch(
monkeypatch, no_lookup, geoip=self.IPV4, proxy={"server": "http://127.0.0.1:3128"}
)
assert "network:ipv4Only" not in sent
def test_ipv6_identity_leaves_ipv6_alone(self, monkeypatch, isolated_launch_dependencies):
sent = self._launch(monkeypatch, None, geoip="2001:db8::1")
assert "network:ipv4Only" not in sent
assert sent["webrtc:ipv6"] == "2001:db8::1"
class TestPrefsReachStartup:
"""Launcher prefs must be readable by camoufox.cfg at startup.
Playwright's non-persistent launch writes no user.js, so firefox_user_prefs
only arrived via juggler after startup; intl.locale.requested lost the race
against Gecko's pre-created string bundles on Windows.
"""
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:152.0) Gecko/20100101 Firefox/152.0"
def test_prefs_are_passed_as_env(self, isolated_launch_dependencies):
import orjson
opts = utils.launch_options(config={"navigator.userAgent": self.UA}, locale="fr-FR", i_know_what_im_doing=True)
chunks = sorted((k for k in opts["env"] if k.startswith("CAMOU_PREFS_")), key=lambda k: int(k.rsplit("_", 1)[1]))
assert chunks and chunks[0] == "CAMOU_PREFS_1"
prefs = orjson.loads("".join(opts["env"][k] for k in chunks))
assert prefs == opts["firefox_user_prefs"]
assert prefs["intl.locale.requested"] == "fr-Latn-FR"
def test_large_prefs_are_chunked_in_order(self, monkeypatch):
import orjson
monkeypatch.setattr(utils, "OS_NAME", "win")
prefs = {f"camoufox.test.pref{i}": "x" * 50 for i in range(200)}
env = utils.get_pref_env_vars(prefs)
assert len(env) > 1 and all(len(v) <= 2047 for v in env.values())
joined = "".join(env[f"CAMOU_PREFS_{i}"] for i in range(1, len(env) + 1))
assert orjson.loads(joined) == prefs
def test_no_prefs_no_env(self):
assert utils.get_pref_env_vars({}) == {}
class TestWindowsScrollbarsFollowVersion:
"""Windows 11 draws overlay scrollbars by default (stock 152.0.4 on Win11: 0 px),
Windows 10 classic 17 px ones; the identity's font draw decides the version."""
PREF = "ui.useOverlayScrollbars"
WIN_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:152.0) Gecko/20100101 Firefox/152.0"
def _prefs(self, fonts, ua=None):
return utils.launch_options(
config={"navigator.userAgent": ua or self.WIN_UA, "fonts": fonts},
i_know_what_im_doing=True,
)["firefox_user_prefs"]
def test_windows_11_fonts_get_overlay(self, isolated_launch_dependencies):
assert self._prefs(["Arial", "Segoe UI Variable Text"])[self.PREF] == 1
def test_windows_10_fonts_get_classic(self, isolated_launch_dependencies):
assert self._prefs(["Arial", "Segoe UI", "Calibri"])[self.PREF] == 0
def test_other_oses_overlay(self, isolated_launch_dependencies):
ua = "Mozilla/5.0 (X11; Linux x86_64; rv:152.0) Gecko/20100101 Firefox/152.0"
assert self._prefs(["DejaVu Sans"], ua=ua)[self.PREF] == 1
class TestNativeWindowsVariantFonts:
"""A native Windows identity claims the Win11 font variant iff the host has it."""
def test_native_windows_11_host_claims_variant(self, monkeypatch):
from camoufox import fingerprints as fp
monkeypatch.setattr(fp, "_host_has_variant_fonts", lambda target_os: True)
fonts = fp._generate_random_font_subset("windows", seed=1, native=True)
assert fp.WINDOWS_11_MARKER_FONTS <= set(fonts)
def test_native_windows_10_host_does_not(self, monkeypatch):
from camoufox import fingerprints as fp
monkeypatch.setattr(fp, "_host_has_variant_fonts", lambda target_os: False)
fonts = fp._generate_random_font_subset("windows", seed=1, native=True)
assert not (fp.WINDOWS_11_MARKER_FONTS & set(fonts))
def test_non_windows_hosts_never_report_variant(self):
from camoufox import fingerprints as fp
assert fp._host_has_variant_fonts("linux") is False
assert fp._host_has_variant_fonts("macos") is False
class _Usage:
"""shutil.disk_usage's namedtuple, with only `total` filled in."""
def __init__(self, total):
self.total = total
self.used = 0
self.free = total
class TestStorageQuotaFollowsHostDisk:
"""The storage quota a page reads must be the host's, not a constant.
Gecko derives navigator.storage.estimate().quota from the disk: the
temporary-storage limit is GetDiskCapacity() / 2 and the group limit a page
reads is min(that / 5, 10 GiB). camoufox.cfg used to pin the limit to
52428800 KB -- 50 GiB, which is exactly nsRFPService::GetSpoofedStorageLimit()
and reports 10 GiB on every host whatever its disk holds.
Deriving it from the host keeps the shape Gecko produces (a 100 GB+ disk
reports the 10 GiB cap, a smaller one reports capacity / 10) while ignoring
the disk Playwright's throwaway profile happens to land on -- a tmpfs /tmp
is a RAM-sized volume no real profile lives on.
"""
PREF = "dom.quotaManager.temporaryStorage.fixedLimit"
UA = "Mozilla/5.0 (X11; Linux x86_64; rv:152.0) Gecko/20100101 Firefox/152.0"
def _prefs(self, **kwargs):
return utils.launch_options(
config={"navigator.userAgent": self.UA},
i_know_what_im_doing=True,
**kwargs,
)["firefox_user_prefs"]
def test_limit_is_half_the_host_disk(self, monkeypatch, isolated_launch_dependencies):
# 512 GiB, the way a filesystem reports it: a multiple of the block size.
capacity = 512 * 1024**3
monkeypatch.setattr(utils.shutil, "disk_usage", lambda _p: _Usage(capacity))
assert self._prefs()[self.PREF] == capacity // 2 // 1024
def test_small_disk_reports_less_than_the_cap(
self, monkeypatch, isolated_launch_dependencies
):
# A 40 GB VPS: stock reports 4 GB, not the 10 GiB cap. The old pin
# claimed 10 GiB here, which that machine's own Firefox never says.
capacity = 40 * 1000**3
monkeypatch.setattr(utils.shutil, "disk_usage", lambda _p: _Usage(capacity))
limit_kb = self._prefs()[self.PREF]
group_limit = min(limit_kb * 1024 // 5, 10 * 1024**3)
assert group_limit == capacity // 2 // 5
assert group_limit < 10 * 1024**3
def test_multi_terabyte_disk_stays_in_int32(
self, monkeypatch, isolated_launch_dependencies
):
monkeypatch.setattr(utils.shutil, "disk_usage", lambda _p: _Usage(16 * 1024**4))
limit_kb = self._prefs()[self.PREF]
assert limit_kb <= 2**31 - 1
# Still above 50 GiB, so the page reads the same 10 GiB cap stock does.
assert limit_kb * 1024 // 5 >= 10 * 1024**3
def test_unreadable_disk_leaves_gecko_to_measure(
self, monkeypatch, isolated_launch_dependencies
):
def _raise(_p):
raise OSError("no such device")
monkeypatch.setattr(utils.shutil, "disk_usage", _raise)
assert self.PREF not in self._prefs()
def test_caller_pref_wins(self, monkeypatch, isolated_launch_dependencies):
monkeypatch.setattr(utils.shutil, "disk_usage", lambda _p: _Usage(512 * 1024**3))
prefs = self._prefs(firefox_user_prefs={self.PREF: 1234})
assert prefs[self.PREF] == 1234
class TestStockMediaDefaults:
"""The host's own media features, not Playwright's emulated ones.
Playwright emulates four media features on every context whether or not the
caller asked: colorScheme "light", and no-preference values for
reducedMotion / forcedColors / contrast. The page then reads those whatever
the machine is set to -- measured 2026-09-18, headed on an Xvfb with
GTK_THEME=Adwaita:dark: stock Firefox reported
`(prefers-color-scheme: dark)`, camoufox reported light.
"no-override" is Playwright's opt-out: no emulation is sent and the browser
answers from the host.
"""
def test_defaults_are_no_override(self):
assert utils.STOCK_MEDIA_DEFAULTS == {
"color_scheme": "no-override",
"reduced_motion": "no-override",
"forced_colors": "no-override",
"contrast": "no-override",
}
def test_new_page_and_new_context_get_them(self):
class FakeBrowser:
def __init__(self):
self.calls = []
def new_page(self, **kwargs):
self.calls.append(("new_page", kwargs))
def new_context(self, **kwargs):
self.calls.append(("new_context", kwargs))
browser = FakeBrowser()
utils.attach_stock_media_defaults(browser)
browser.new_page()
browser.new_context()
for _, kwargs in browser.calls:
assert kwargs["color_scheme"] == "no-override"
assert kwargs["reduced_motion"] == "no-override"
assert kwargs["forced_colors"] == "no-override"
assert kwargs["contrast"] == "no-override"
def test_caller_value_wins(self):
class FakeBrowser:
def __init__(self):
self.kwargs = None
def new_context(self, **kwargs):
self.kwargs = kwargs
browser = FakeBrowser()
utils.attach_stock_media_defaults(browser)
browser.new_context(color_scheme="dark", forced_colors="active")
assert browser.kwargs["color_scheme"] == "dark"
assert browser.kwargs["forced_colors"] == "active"
# the ones the caller left alone still follow the host
assert browser.kwargs["reduced_motion"] == "no-override"
class TestScreenshotCaret:
"""A screenshot of a page Camoufox launched defaults to caret="initial":
Playwright's caret hiding writes the page's style attributes, and Firefox's
capture never paints the caret anyway."""
class Owner:
def __init__(self, parent=None):
self._parent = parent
@staticmethod
def shot(owner, **kwargs):
import asyncio
from camoufox import driver_defaults
async def original(self, **kw):
return kw
return asyncio.run(driver_defaults._with_caret_default(original)(owner, **kwargs))
def test_pages_under_a_camoufox_launch_keep_the_caret(self):
from camoufox import driver_defaults
browser = driver_defaults.mark(self.Owner())
handle = self.Owner(self.Owner(self.Owner(self.Owner(browser)))) # handle, frame, page, context
assert self.shot(handle, caret=None)["caret"] == "initial"
assert self.shot(handle)["caret"] == "initial"
def test_the_callers_caret_wins(self):
from camoufox import driver_defaults
page = self.Owner(driver_defaults.mark(self.Owner()))
assert self.shot(page, caret="hide")["caret"] == "hide"
def test_other_browsers_are_left_alone(self):
assert self.shot(self.Owner(self.Owner()), caret=None)["caret"] is None
def test_fill_clicks_a_text_field_without_focus_first(self):
import asyncio
from camoufox import driver_defaults
clicks = []
evaluates = []
class Field:
def __init__(self, needs_click, lands):
self.needs_click = needs_click
self.lands = lands
self.first = self
async def evaluate(self, expression, timeout=None):
evaluates.append(timeout)
return self.needs_click if expression == driver_defaults.FILL_NEEDS_CLICK else self.lands
async def scroll_into_view_if_needed(self, timeout=None):
pass
async def click(self, **kwargs):
clicks.append(kwargs)
async def original(self, selector, **kwargs):
return selector
browser = driver_defaults.mark(self.Owner())
for needs_click, lands in ((True, True), (False, True), (True, False)):
frame = self.Owner(browser)
frame.locator = lambda selector, field=Field(needs_click, lands): field
assert asyncio.run(driver_defaults._frame_fill_clicks_first(original)(frame, "#f", timeout=5)) == "#f"
assert clicks == [{"timeout": 5, "force": None}] # a covered field fills as it would have
assert set(evaluates) == {5} # a missing field fails within the caller's timeout
def test_installs_once_on_page_and_element_handle(self):
from playwright._impl._element_handle import ElementHandle
from playwright._impl._page import Page
from camoufox import driver_defaults
driver_defaults.mark(self.Owner())
driver_defaults.mark(self.Owner())
for cls in (Page, ElementHandle):
assert getattr(cls.screenshot, "_camoufox_driver_defaults", False)
assert not getattr(cls.screenshot.__wrapped__, "_camoufox_driver_defaults", False)
def test_fill_wraps_frame_fill_on_playwright_without_frame__fill(self, monkeypatch):
# Playwright before 1.54 has no Frame._fill; launching must not fail there.
from playwright._impl import _frame
from camoufox import driver_defaults
class OldFrame:
async def fill(self, selector, value, **kwargs):
return value
monkeypatch.setattr(_frame, "Frame", OldFrame)
driver_defaults.mark(self.Owner())
assert getattr(OldFrame.fill, "_camoufox_driver_defaults", False)
assert not hasattr(OldFrame, "_fill")
class TestDesktopOnlyWarning:
"""Camoufox has only desktop identities and Juggler never enters Responsive
Design Mode, so is_mobile on new_page()/new_context() gets a LeakWarning."""
class FakeBrowser:
def new_page(self, **kwargs):
return kwargs
def new_context(self, **kwargs):
return kwargs
def test_is_mobile_warns(self):
from camoufox._warnings import LeakWarning
browser = utils.attach_desktop_only_warning(self.FakeBrowser())
for create in (browser.new_page, browser.new_context):
with pytest.warns(LeakWarning, match="built for desktops"):
assert create(is_mobile=True) == {"is_mobile": True}
def test_a_desktop_context_does_not(self):
import warnings
browser = utils.attach_desktop_only_warning(self.FakeBrowser())
with warnings.catch_warnings():
warnings.simplefilter("error")
browser.new_context(viewport={"width": 800, "height": 600}, is_mobile=False)
browser.new_page()