Files
archived-camoufox/python/tests/test_config_schema.py
T
Jake WriterandClaude Opus 5.5 0c98d2b734 Look up each spoof by the document's own context, and make the OS, popups and startup prefs per-context or loud
- One helper, RoverfoxStorageManager::UserContextId(), reads the user
  context from a principal, node or window. Every per-context lookup used
  the browsing context instead, which a document from
  createHTMLDocument() or DOMParser does not have, so a canvas there read
  context 0, which held whichever context set its values last: a page
  could see two GPUs (#839) or another context's font list. The setters
  no longer copy their values into context 0.
- UNMASKED_RENDERER_WEBGL and UNMASKED_VENDOR_WEBGL apply stock's
  fingerprinting-protection checks before the spoofed value, as RENDERER
  does, so the two never disagree.
- system-ui, the CSS2 system fonts and WebRTC's fabricated port use the
  context's own OS (NavigatorManager::GetSpoofedOS), not the launch's, so
  a macOS context of a Windows launch no longer resolves Segoe UI.
- CamoufoxWindow sizes only windows the driver opens; a page's popup keeps
  the size it asked for.
- camoufox.cfg applies CAMOU_PREFS through the default branch and quits
  with the reason on stderr when a pref cannot be applied, instead of
  starting without it.
- Delete commented-out prefs; shorten the setter-seal comments into a
  tribal rule; mark the unread navigator.buildID key removed.
- Refresh five patches that only applied with fuzz; the patched tree is
  byte-identical.
- Guards: webgl-renderer-pair covers data and DOMParser documents, two
  contexts and the unmasked vendor; new context-os-system-font and
  popup-window-size; startup-prefs covers the loader's failures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 13:39:02 -06:00

168 lines
6.2 KiB
Python

"""
Guard: every config key the browser reads must be declared in the schema.
Regression guard for the `media:spoof_codecs` gap in PR #562. The C++ side read
the key via MaskConfig::GetBool("media:spoof_codecs"), but nothing ever added it
to browser/settings/properties.json, and validate_config() drops any key it does not
recognise -- printing "Skipping unknown patch media:spoof_codecs" and moving on.
The documented usage,
AsyncCamoufox(config={"media:spoof_codecs": True})
therefore did nothing at all: the key never reached the browser, so the feature
could not be switched on through the supported path.
This is the read-but-undeclared direction of a mistake the project has made
before in the other direction -- canvas:seed (#721) and navigator.maxTouchPoints
(#696) were both declared in the schema while nothing consumed them. A patch and
a schema entry are two halves of one change; this test fails the build when only
one half lands.
Run with:
cd python && python -m pytest tests/test_config_schema.py -v
"""
import json
import re
from pathlib import Path
import pytest
REPO = Path(__file__).resolve().parents[2]
PROPERTIES = REPO / "browser" / "settings" / "properties.json"
# MaskConfig::GetBool("k") / GetString("k") / GetUint32("k") / HasKey("k") ...
MASKCONFIG_READ = re.compile(r'MaskConfig::(?:Get|Has)\w*\(\s*"([^"]+)"')
# Declared keys the browser never reads, each with the reason it is declared
# anyway. Everything else in properties.json must be read by a patch or by
# Juggler: a key nothing reads does nothing, silently.
NOT_READ_BY_THE_BROWSER = {
"locale:script": "the launcher joins it with locale:language/region into the UI locale",
"navigator.doNotTrack": "the launcher applies it as privacy.donottrackheader.enabled (#760)",
}
# How Juggler and the patches name a key: a quoted string literal.
QUOTED = '"{key}"', "'{key}'"
def _sources():
for pattern in ("browser/patches/**/*.patch", "browser/additions/**/*"):
for path in REPO.glob(pattern):
if path.is_file():
yield path
def _declared_keys() -> set:
"""Live keys: an entry marked "removed" is kept only for older libraries."""
return {
entry["property"]
for entry in json.loads(PROPERTIES.read_text())
if "removed" not in entry
}
def _removed_keys() -> set:
return {
entry["property"]
for entry in json.loads(PROPERTIES.read_text())
if "removed" in entry
}
def _keys_read() -> dict:
"""Map config key -> sorted list of files that read it."""
found: dict = {}
for path in _sources():
try:
text = path.read_text(errors="ignore")
except OSError:
continue
for match in MASKCONFIG_READ.finditer(text):
found.setdefault(match.group(1), set()).add(
str(path.relative_to(REPO))
)
return {k: sorted(v) for k, v in found.items()}
def test_properties_json_is_wellformed():
entries = json.loads(PROPERTIES.read_text())
assert entries, "browser/settings/properties.json is empty"
for entry in entries:
assert "property" in entry and "type" in entry, f"malformed entry: {entry}"
def test_every_key_the_browser_reads_is_declared():
declared = _declared_keys()
read = _keys_read()
assert read, "found no MaskConfig reads -- the scanner regexp has gone stale"
undeclared = {
key: files
for key, files in read.items()
if key not in declared
}
if undeclared:
lines = [
"config keys are read by the browser but missing from "
"browser/settings/properties.json,",
"so validate_config() silently drops them and the feature cannot be "
"enabled through the Python API:",
"",
]
for key, files in sorted(undeclared.items()):
lines.append(f" {key}")
for f in files:
lines.append(f" read in {f}")
pytest.fail("\n".join(lines))
def test_every_declared_key_is_read_by_the_browser():
"""The other direction: canvas:seed (#721) was declared, generated by both
launchers and sent on every launch for three releases after the patch that
read it was removed (#528)."""
text = "".join(path.read_text(errors="ignore") for path in _sources())
unread = sorted(
key
for key in _declared_keys()
if key not in NOT_READ_BY_THE_BROWSER
and not any(form.format(key=key) in text for form in QUOTED)
)
assert not unread, (
"browser/settings/properties.json declares keys that no patch or Juggler file "
f"reads, so setting them does nothing: {unread}. Mark them \"removed\" "
"(never delete an entry: older libraries reject undeclared keys, #835), "
"or add them to NOT_READ_BY_THE_BROWSER with the reason they are declared."
)
def test_removed_keys_are_really_unread():
"""A key marked removed that the browser reads again is a live key, and the
launchers would drop it before it reached the browser."""
text = "".join(path.read_text(errors="ignore") for path in _sources())
read = sorted(
key for key in _removed_keys()
if any(form.format(key=key) in text for form in QUOTED)
)
assert not read, f"marked removed in browser/settings/properties.json but read by the browser: {read}"
def test_keys_not_read_by_the_browser_are_really_unread():
"""An exemption must lapse once the browser starts reading the key."""
text = "".join(path.read_text(errors="ignore") for path in _sources())
now_read = [
key for key in NOT_READ_BY_THE_BROWSER
if any(form.format(key=key) in text for form in QUOTED)
]
assert not now_read, f"remove from NOT_READ_BY_THE_BROWSER, the browser reads them now: {now_read}"
@pytest.mark.parametrize("key", ["media:spoof_codecs"])
def test_known_previously_missing_keys_stay_declared(key):
"""Pin the specific keys this guard was written for, so a schema edit that
drops one fails loudly here rather than only in the general scan above."""
assert key in _declared_keys(), (
f"{key} is read by the browser but is not declared in "
f"browser/settings/properties.json -- see PR #562"
)