Files
archived-camoufox/python/tests/test_identity_salt.py
T
76da8386a9 Audio renders as stock Firefox does: remove the audio noise and audio:seed (#927)
* Let a launch leave Web Audio output unmodified

The launchers seed Web Audio noise per identity so a returning identity
reproduces its audio hash. A caller who wanted stock audio output had to
pass audio:seed in config, and NewContext contexts still drew their own
seed.

audio_noise (default True, as before) set to False sends seed 0, which
audio-fingerprint-manager.patch reads as no noise, and NewBrowser
records it so NewContext gives its contexts seed 0 as well. An
audio:seed the caller sets wins either way. Python and TypeScript take
the option the same way, the launch goldens gain an audio_noise_false
scenario, and both package READMEs list it.

On v158.0-beta.40 an OfflineAudioContext probe renders the same with
audio_noise=False across launches, in the page and in a NewContext,
and matches a launch with audio:seed 0; default launches differ.

Split out of #890, without its gpu_passthrough option.

Co-Authored-By: coffeegrind123 <103264516+coffeegrind123@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Let a context turn its Web Audio noise off

A context without an audio seed of its own takes the launch's audio:seed,
so a per-context seed of 0 means "the launch's seed", not "no noise". On a
browser launched with noise, no context could render stock audio.

setAudioFingerprintNoise(false) stores that choice for the calling
context, and AudioFingerprintManager::GetSeed returns 0 for it whatever
the launch seed. The setter has its own gate and is sealed with the
others; the build tester and the setter-seal guard list it.

The context-audio-off guard renders an OfflineAudioContext with the
noise off at launch as the reference, then on a noised launch requires a
context that called the setter to match it, also after a navigation,
while a plain context and a NewContext context stay noised. It fails on
v158.0-beta.40, which has no such setter.

Both patches were regenerated from a tree of the files the series
touches, and the whole series applies to vanilla 158 without fuzz.

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

* Replace audio_noise with fingerprint_options

The launchers take one option for the noise Camoufox adds on top of an
identity, in Python and TypeScript alike:

    fingerprint_options={"audio": {"noise": False}}    # stock Web Audio
    fingerprint_options={"audio": {"seed": 1000433}}   # fixed audio seed
    fingerprint_options={"canvas": {"randomize": True}}

Without an audio entry the seed still follows the identity; without a
canvas entry randomization is still on for another OS or GPU. Any other
surface or key raises InvalidFingerprintOptions, naming the tribal rules
that keep canvas pixels and glyph spacing unnoised, as do a seed outside
1 to 2**32-1 and noise off together with a seed. fingerprint= stays the
fpgen identity.

canvas_noise= and config={"audio:seed": N} keep working with a
FutureWarning, as a deprecated GeoIP source does; either one together
with the matching fingerprint_options entry raises.

NewContext takes the audio entry per context. Without one a context
follows the browser, read from the audio:seed the launch sent, so
launch_options() and from_options launches behave the same: no noise if
the launch sent 0, otherwise a fresh seed of its own. A context never
takes the browser's seed, fixed or not, since two devices sharing an
audio hash are linked; a per-context seed reproduces a context instead.
A context with its noise off calls setAudioFingerprintNoise(false). On a
noised browser that needs a build with the setter: NewContext asks the
browser once, from an init script in a throwaway context, and raises on
an older build rather than leave the context noised. canvas in a context
raises: randomization belongs to the browser.

audio_noise, context_audio(browser) and _camoufox_audio_noise are gone.
The launch goldens replace audio_noise_false with audio and canvas
scenarios, the init-script golden gains a seed-0 case, and the READMEs,
AGENTS.md and docs/per-context-patches.md describe the option; repo
callers of canvas_noise use the new form.

On v158.0-beta.40, an OfflineAudioContext probe renders the same with
{"audio": {"noise": False}} in the page, in a NewContext and with
config audio:seed 0; default launches differ; seed 1000433 and a
context seed reproduce across launches; a context turning its noise off
on a noised browser raises.

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

* Audio renders as stock: remove the noise, the seed and fingerprint_options

Stock Firefox has one audio fingerprint per CPU architecture. 103 runs of
Firefox 152-158 on 12 CPUs gave 35.749972093850374 on every x86-64 machine
and 35.74996626004577 on every ARM64 one, whatever the OS, sound device,
sample rate or version. The per-identity noise put every Camoufox identity
on a value no real machine renders.

Browser: audio-fingerprint-manager.patch is gone, with
setAudioFingerprintSeed and setAudioFingerprintNoise; font-list-spoofing,
webrtc-ip-spoofing and window-setter-seal are regenerated without its
context (the series applies cleanly to vanilla 158). audio:seed is marked
removed in properties.json.

Library (py and ts): no seed is derived or drawn, and config or
config_overrides carrying audio:seed raise InvalidPropertyType pointing at
the new tribal rule. fingerprint_options, never released, is reverted;
canvas_noise stays as released.

Tests: tribal rule audio-is-not-noised with its test; the
audio-matches-stock guard replaces context-audio-off and
audio-frequency-noise, holding the fpjs buffer, AnalyserNode, biquad and
sine renders to the recorded stock values in several contexts and two
launches while sending the seed released libraries send. build-tester
counts the audio hash as must-match and fails its noise trap.

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

* A removed audio:seed warns and is dropped; the rule lists each machine

Passing audio:seed in config (or a NewContext config_overrides) no longer
raises. Both launchers drop the key and emit one FutureWarning from
warnings.yml (audio_seed_removed): the option was removed and audio is
rendered exactly as stock Firefox renders it. The caller's dict is left
as it was. Tests on both sides check the single warning and a normal
launch; the launch golden records the warning in order.

audio-is-not-noised now lists the evidence per machine and architecture,
including the Raspberry Pi 4 runs (106 runs: 45 ARM64, 61 x86-64), the
device swap, fpgen's share and what the noise produced.

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

---------

Co-authored-by: coffeegrind123 <103264516+coffeegrind123@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 01:33:25 +00:00

252 lines
10 KiB
Python

"""Per-identity draws: unrelated launches must not share them, a pinned identity must.
identity_seed() used to hash only the UA, platform, screen size and core count.
Those take a handful of values per OS, so over 500 launches the seed took 12-30
distinct values, and every install drew its fonts, voices, GPU, media devices and
canvas/audio noise seeds from that same short list.
"""
from contextlib import contextmanager
from unittest import mock
import orjson
import pytest
from camoufox import cpu_affinity, utils
from camoufox import fingerprints as fp
@contextmanager
def host():
with mock.patch.object(utils, "get_screen_cons", lambda headless: None), (
mock.patch.object(utils, "has_display", lambda env: False)
), mock.patch.object(utils, "installed_verstr", lambda: "150.0.2"), (
mock.patch.object(utils, "launch_path", lambda **kwargs: "/nonexistent/camoufox")
):
yield
def config_of(options):
env = options["env"]
chunks = sorted(
(int(k.rsplit("_", 1)[1]), v) for k, v in env.items() if k.startswith("CAMOU_CONFIG_")
)
return orjson.loads("".join(chunk for _, chunk in chunks))
def launch(**kwargs):
kwargs.setdefault("os", "linux")
kwargs.setdefault("headless", True)
kwargs.setdefault("i_know_what_im_doing", True)
with host():
return config_of(utils.launch_options(**kwargs))
DRAWN = ("fonts", "voices", "webGl:renderer")
def drawn(config):
return {k: orjson.dumps(config.get(k)) for k in DRAWN}
class TestUnpinnedLaunchesAreDistinct:
def test_same_presented_values_still_differ(self):
# The same UA/platform/screen/cores, i.e. what two users on the same
# common machine present, must not yield the same draws.
config = {"navigator.userAgent": "x", "navigator.platform": "Win32",
"screen.width": 1920, "screen.height": 1080, "navigator.hardwareConcurrency": 8}
seeds = {fp.identity_seed(config, fp.identity_salt()) for _ in range(200)}
assert len(seeds) == 200
class TestPinnedIdentityIsStable:
def test_fixed_fingerprint_reproduces_every_draw(self):
fingerprint = fp.generate_fingerprint(os="linux")
first = launch(fingerprint=fingerprint)
second = launch(fingerprint=fingerprint)
assert drawn(first) == drawn(second)
def test_fixed_preset_reproduces_every_draw(self):
preset = fp.get_random_preset(os="windows", ff_version="150")
assert preset, "no Windows presets bundled"
first = launch(os="windows", fingerprint_preset=preset)
second = launch(os="windows", fingerprint_preset=preset)
assert drawn(first) == drawn(second)
@pytest.mark.parametrize("os_name", ["windows", "macos", "linux"])
def test_every_bundled_preset_launches(self, os_name):
# The test above draws ONE preset at random, so a preset that cannot
# launch would show up as a flake rather than a failure. Every preset
# must launch with its own GPU and that GPU's recorded parameters.
presets = fp.load_presets("150")["presets"][os_name]
for i, preset in enumerate(presets):
config = launch(os=os_name, fingerprint_preset=preset)
assert config["webGl:renderer"] == preset["webgl"]["unmaskedRenderer"], (os_name, i)
assert config.get("webGl:parameters"), (os_name, i)
def test_salt_of_equal_objects_is_equal(self):
a = fp.generate_fingerprint(os="windows")
assert fp.identity_salt(a) == fp.identity_salt(a)
assert fp.identity_salt({"a": 1, "b": 2}) == fp.identity_salt({"b": 2, "a": 1})
def test_no_audio_seed_is_generated():
"""The browser renders audio as stock does: one value per CPU architecture
(ci/tribal-rules.yml: audio-is-not-noised). There is no seed to send."""
assert "audio:seed" not in launch()
for preset in (None, fp.get_random_preset(os="windows", ff_version="150")):
context = fp.generate_context_fingerprint(os="windows", preset=preset)
assert "audio:seed" not in context["config"]
assert "setAudioFingerprintSeed" not in context["init_script"]
def _removed_audio_warnings(record):
return [w for w in record if w.category is FutureWarning and "audio:seed" in str(w.message)]
def test_an_audio_seed_warns_once_and_is_dropped():
"""A caller's seed would do nothing on this browser and noise a released
one, so it is dropped, with one warning saying audio is rendered as stock."""
import warnings
with warnings.catch_warnings(record=True) as record:
warnings.simplefilter("always")
config = launch(config={"audio:seed": 9})
assert "audio:seed" not in config and config["fonts"]
[warning] = _removed_audio_warnings(record)
assert "rendered exactly as stock Firefox" in str(warning.message)
overrides = {"audio:seed": 7, "timezone": "Pacific/Chatham"}
with warnings.catch_warnings(record=True) as record:
warnings.simplefilter("always")
context = fp.generate_context_fingerprint(os="linux", config_overrides=overrides)
assert len(_removed_audio_warnings(record)) == 1
assert "audio:seed" not in context["config"]
assert context["config"]["timezone"] == "Pacific/Chatham"
assert overrides == {"audio:seed": 7, "timezone": "Pacific/Chatham"}, "the caller's dict was changed"
def test_no_canvas_seed_is_generated():
"""The browser adds no canvas noise (#528), and no patch reads canvas:seed
(#721). Generating one only sent the browser a value it ignored."""
assert "canvas:seed" not in launch()
context = fp.generate_context_fingerprint(os="linux")
assert "canvas:seed" not in context["config"]
assert "setCanvasSeed" not in context["init_script"]
class TestVoicesFollowLocale:
def test_windows_fr_identity_has_french_voices(self, monkeypatch):
for _ in range(5):
config = launch(os="windows", locale="fr-FR")
langs = {v["lang"] for v in config["voices"]}
assert "fr-FR" in langs, langs
class TestCoreCountFloor:
def test_small_pinnable_host_reports_table_floor(self, monkeypatch):
monkeypatch.setattr(cpu_affinity, "supported", lambda: True)
for host_cores in (1, 2, 3):
monkeypatch.setattr(fp, "host_cpu_count", lambda n=host_cores: n)
for drawn_cores in (1, 2, 3, 8):
c = {"navigator.hardwareConcurrency": drawn_cores}
fp.fix_hardware_concurrency(c)
assert c["navigator.hardwareConcurrency"] == 4, (host_cores, drawn_cores)
def test_unpinned_launch_reports_host(self, monkeypatch):
monkeypatch.setattr(cpu_affinity, "supported", lambda: True)
monkeypatch.setattr(fp, "host_cpu_count", lambda: 16)
c = {"navigator.hardwareConcurrency": 8}
fp.fix_hardware_concurrency(c, can_pin=False)
assert c["navigator.hardwareConcurrency"] == 16
def test_recorded_counts_are_in_the_table(self):
for n in (18, 22, 28, 32):
assert n in fp.PLAUSIBLE_CORE_COUNTS
class TestAffinityPick:
def test_adjacent_cores_from_a_random_start(self):
cores = list(range(16))
starts = set()
for _ in range(200):
picked = cpu_affinity._pick(cores, 4)
assert len(picked) == 4 and set(picked) <= set(cores)
ring = sorted(picked)
# adjacent modulo 16
assert any(all((s + i) % 16 in picked for i in range(4)) for s in ring)
starts.add(tuple(picked))
assert len(starts) > 4
class TestPrefsEnvIsAscii:
def test_non_ascii_pref_round_trips(self):
prefs = {"font.name.serif.ja": "游明朝", "intl.accept_languages": "fr-FR, fr"}
env = utils.get_pref_env_vars(prefs)
joined = "".join(env[f"CAMOU_PREFS_{i}"] for i in range(1, len(env) + 1))
assert joined.isascii()
assert orjson.loads(joined) == prefs
@pytest.mark.parametrize("off", [None, False])
def test_fingerprint_preset_off_never_draws_a_preset(off):
"""`fingerprint_preset=False` means off, the same as None. It used to be
checked with `is not None`, so False drew a random bundled preset."""
with mock.patch.object(utils, "get_random_preset", side_effect=AssertionError("preset drawn")):
launch(fingerprint_preset=off)
def test_no_glyph_spacing_seed_is_generated():
"""Glyph-spacing noise moved every measured text width off what the same
font gives on a real machine, so it was itself a fingerprint; the feature
is gone from the browser, and the launcher sends nothing for it."""
assert "fonts:spacing_seed" not in launch()
context = fp.generate_context_fingerprint(os="linux")
assert "fonts:spacing_seed" not in context["config"]
assert "setFontSpacingSeed" not in context["init_script"]
def test_config_overrides_reach_the_config_and_the_init_script():
context = fp.generate_context_fingerprint(
os="linux", config_overrides={"timezone": "Pacific/Chatham"}
)
assert context["config"]["timezone"] == "Pacific/Chatham"
assert "Pacific/Chatham" in context["init_script"]
def test_instant_animations_warn_that_they_are_detectable():
from camoufox._warnings import LeakWarning
with pytest.warns(LeakWarning, match="getComputedTiming"):
launch(config={"instantAnimations": True}, i_know_what_im_doing=False)
def test_is_mobile_warns_that_camoufox_is_desktop_only():
"""A persistent context takes its context options at launch."""
from camoufox._warnings import LeakWarning
with pytest.warns(LeakWarning, match="built for desktops"):
launch(is_mobile=True, i_know_what_im_doing=False)
def test_a_context_with_a_linux_ua_is_linux_throughout(monkeypatch):
"""fpgen's Linux pool now and then pairs the Linux UA with platform Win32 and
a Windows oscpu (~1.6% of NewContext Linux identities). launch_options()
fixed that and generate_context_fingerprint() did not -- and it reads the OS
for fonts and voices from the platform, so those came out Windows too."""
real = fp.generate_fingerprint
def mismatched(**kwargs):
drawn = real(**kwargs)
drawn["navigator"]["platform"] = "Win32"
drawn["navigator"]["oscpu"] = "Windows NT 10.0; Win64; x64"
return drawn
monkeypatch.setattr(fp, "generate_fingerprint", mismatched)
config = fp.generate_context_fingerprint(os="linux")["config"]
assert "Linux x86_64" in config["navigator.userAgent"]
assert config["navigator.platform"] == "Linux x86_64"
assert config["navigator.oscpu"] == "Linux x86_64"
assert "Segoe UI" not in config["fonts"]