Release 0.17.0 on firefox-31, where an authenticated HTTP proxy routes again (#210)

* go_back() is no longer expected to fail, and a test says what it must do

The xfail went on when the cause was unknown. It is known now: the engine goes
back perfectly well and Juggler had no bookkeeping for a document restored from
the back forward cache, so the client was never told the navigation had
committed. The remedy is in the engine.

The second test is the one that matters. Asserting that the URL changed would
pass against a browser that silently refetched the page, which is what every
other automation stack settles for and is not what going back means. It serves
the document once, counts what the server is asked for, and requires that going
back asks for nothing: a restored document, not a second download. Proven red
against a page served with Cache-Control: no-store before it was trusted.

* An authenticated HTTP proxy is a gate now, and the pinning page's examples run

Issue #206 reported that behind an authenticated HTTP proxy the browser started
without an error and the page came out of the host address, while the same
credentials over socks5 worked. The cause is in the engine. What is fixed here
is the reason nothing saw it: the two HTTP end-to-end arms of
test_proxy_reaches_the_browser.py launch with no credentials at all, the only
authenticated arm is SOCKS5 in test_proxy_socks_auth_e2e.py, and the single test
that puts http and credentials together asserts on a Python dict and never opens
a browser. The product had never once been driven out through an authenticated
HTTP proxy under test.

test_proxy_http_auth_e2e.py drives a real browser through a local HTTP proxy
that answers 407 until it is shown the right Proxy-Authorization. The assertions
are in the positive form, because "the proxy received something" is green on the
leak: a browser that connects directly leaves nothing on the proxy, so an empty
recorder and a healthy proxy are the same observation. What is asserted is that
the proxy routed the page's own request and that the page read this proxy
instance's own body, for a host RFC 2606 reserves to resolve nowhere. Measured
against two engines: red on the packaged firefox-30 with Page.goto:
NS_ERROR_UNKNOWN_HOST, which is the leak itself, and green on a local build
carrying the fix. Taking the password back out of the dict makes it red on the
fixed engine too, with NS_ERROR_PROXY_CONNECTION_REFUSED and the proxy's own
record showing it was offered the user with an empty password. The navigation
error is caught rather than left to propagate, because both known-bad engines
fail inside goto and an uncaught Gecko code says neither of those two opposite
things.

The pinning page's two GPU examples raised when copied. An RTX 4090 in the
opening block and an Iris Xe under "mimic a specific real device" name no
persona in the validated pool, so both ended in "names no validated GPU
persona". They are replaced with personas read off that exception, a GTX 980 and
an Intel HD Graphics, the second one mid_range so the class_tier written beside
it stays true. The paragraph on implausible pairings named the RTX 4090 too and
said the sampler picks the screen from the seed's own tier, which a GPU pin has
conditioned since 2026-09-15. It now says where such a pair can still be built,
by pinning both halves, and carries the measurement: over 200 seeds a low_end
persona draws a 4K screen zero times and mid_range draws one 23 times.

test_pinning_doc.py could see neither. It compared example keys against the
validator's table while the GPU refusal is on the value, so it was green on both
broken blocks; putting the Iris Xe string back confirms it, the new executing
test fails naming the string and the keys-only test still passes. The keys test
stays, as the cheaper half that names the offending key directly. And the
extraction only matched pin = {...}, so the opening block, which hands pin={...}
to the constructor as a keyword argument, was invisible: 2 examples found
before, 3 now. The count is a floor rather than a non-zero check, because with
two other examples on the page a non-zero check stayed green while a third of it
went unread. Removing the keyword arm again now fails with "found 2 pin
example(s) on the page, expected at least 3".

* Stage the changelog the ledger step rewrites, or the rewrite never happened

invisible-core's record step now realigns this version's changelog heading to
the upload date the index reports, which is the fix for a heading typed hours
before the upload it claims to describe. This is the repository that keeps a
changelog, so this is where that matters, and a file rewritten on the runner's
disk that nobody stages is a change that never happened.

Conditional for the same reason the release notes step below is: git add on a
missing path fails the step under bash -e.

* The context proxy gets the same gate, because the report measured both roads

Issue #206 listed the launch proxy and the context proxy as separate arms and
both leaked, which is what a cause living under both looks like. The fix is one
function, so this arm cannot fail for an engine reason while the other passes.
It can fail for a wiring reason: setBrowserProxy and setContextProxy are two
commands with two handlers and two stores, and the eager refusal that stops an
inexpressible proxy from becoming a silent direct connection is installed at two
call sites. Remove one and contexts go out in the clear while launches stay
proxied, which is the original bug on the road nothing was watching.

Known-bad on two real engines, both arms. Against the shipped firefox-30 both
fail with NS_ERROR_UNKNOWN_HOST and the proxy logs nothing at all, routed and
refused both empty, which is the browser resolving the name itself and leaving
directly. Against the engine that carries the fix, both pass in 12 seconds.

* Release 0.17.0 on firefox-31

The pinned engine moves to firefox-31 through invisible-core 31.23.0, and the
two fixes it carries are the reason to take it.

An authenticated HTTP or HTTPS proxy was accepted and then bypassed on every
engine from firefox-24 to firefox-30, with the page going out over the host's
own address and nothing raised anywhere. And go_back now reports the navigation
it performed, which it had been doing all along without telling the client.

Minor rather than patch: both are behaviour a caller can observe changing, and
the second removes an expected-failure marker that people have been coding
around.
This commit is contained in:
Federico authored and GitHub committed 2026-09-16 04:54:18 +02:00
1 parent 9833d053fa
commit 080b6ffdaa
7 files changed
+501 -44

No files matched your search

+12
View File
@@ -213,6 +213,18 @@ jobs:
git config user.name "feder-cr"
git config user.email "85809106+feder-cr@users.noreply.github.com"
git add PUBLISHED.json
# `record` also realigns this version's CHANGELOG heading to the upload
# date the index reports, and this is the repository that keeps a
# changelog, so this is where it matters. A file rewritten on the
# runner's disk that nobody stages is a change that never happened, and
# the whole point is that the date stops being written by hand: 0.16.2
# shipped dated a day ahead because the heading is typed at bump time,
# hours before the upload it claims to describe, in whatever timezone
# the author is in. Conditional to match the release notes step below,
# and because `git add` on a missing path fails under `bash -e`.
if [ -f CHANGELOG.md ]; then
git add CHANGELOG.md
fi
git commit -m "record $VERSION as published"
BRANCH="${{ github.event.repository.default_branch }}"
if git push origin "HEAD:refs/heads/$BRANCH"; then
+28
View File
@@ -6,6 +6,34 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
## [0.17.0] - 2026-09-16
### Fixed
- **An authenticated HTTP or HTTPS proxy routes the page again.** It was
accepted and then bypassed, silently, on every engine from firefox-24 to
firefox-30: the credentials went to the proxy endpoint, where Gecko
implements them for SOCKS only, so the call failed inside the channel filter
and the connection went out directly over the host's own address with
nothing raised anywhere. SOCKS was unaffected, which is why it lived through
seven releases. HTTP proxy auth answers the 407 challenge instead, and that
path was already wired. Reported from the outside, not caught here. There is
now an end to end test that drives a browser through an authenticated HTTP
proxy, on both the launch road and the context road, which is the case
nothing covered.
- **`go_back()` and `go_forward()` report the navigation they performed.** The
engine went back all along; Juggler had no bookkeeping for a document
restored from the back forward cache, so the client was never told the
navigation had committed. The test asserts that going back RESTORES the
document rather than fetching it again, because asserting on the URL alone
passes against a browser that silently refetches.
### Changed
- Pinned engine moves to **firefox-31**, via `invisible-core` 31.23.0.
- The pinning page's worked examples now run as written. Two of them named a
GPU the validated pool cannot present and raised when copied.
- The ledger step realigns this file's heading date to the date the index
reports, so a heading typed hours before the upload it describes cannot
disagree with the gate that checks it.
## [0.16.2] - 2026-09-15
### Changed
+3 -3
View File
@@ -18,7 +18,7 @@ from invisible_playwright import InvisiblePlaywright
with InvisiblePlaywright(
seed=42,
pin={
"gpu.renderer": "ANGLE (NVIDIA, NVIDIA GeForce RTX 4090 Direct3D11)",
"gpu.renderer": "ANGLE (NVIDIA, NVIDIA GeForce GTX 980 Direct3D11 vs_5_0 ps_5_0, D3D11)",
"gpu.vendor": "Google Inc. (NVIDIA)",
"screen.width": 2560,
"screen.height": 1440,
@@ -39,7 +39,7 @@ When you pin a field:
1. The pinned value is written directly, bypassing the sampler.
2. **Unpinned children are still sampled from their conditionals** - using the parent's original posterior, not the pinned value.
That last point is the subtle one: pinning breaks the conditional chain. If you pin `gpu.renderer` to an RTX 4090 string but leave `screen` unpinned, the sampler will pick `screen` from the seed-derived tier (which might be `low_end`), producing a physically implausible "RTX 4090 + 1366x768" pairing.
That last point is the subtle one, and `gpu.*` is the exception to it: a GPU pin selects a whole persona, so the class of the persona you picked conditions the screen, concurrency and storage still being drawn (see the `gpu.*` section below). Where an implausible pairing can still be built is by pinning both halves, because a value you write explicitly is never re-drawn: put a `low_end` persona next to `screen.width: 3840, screen.height: 2160` and you get exactly that, on a tier that draws a 4K screen zero times in 200 seeds.
**Rule of thumb:** pin correlated fields together, or just trust the sampler.
@@ -226,7 +226,7 @@ Pin the whole visible tuple - GPU, screen, concurrency, audio:
```python
pin = {
"gpu.vendor": "Google Inc. (Intel)",
"gpu.renderer": "ANGLE (Intel, Intel(R) Iris(R) Xe Graphics Direct3D11)",
"gpu.renderer": "ANGLE (Intel, Intel(R) HD Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)",
"gpu.class_tier": "mid_range",
"screen.width": 1920,
"screen.height": 1080,
+2 -2
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "invisible_playwright"
version = "0.16.2"
version = "0.17.0"
description = "Playwright wrapper for a patched Firefox with deterministic stealth profile."
readme = "README.md"
requires-python = ">=3.11"
@@ -69,7 +69,7 @@ dependencies = [
# metadata; nothing in src/ hardcodes a second copy (tests/test_core_pin.py
# fails if one appears). What stays invisible to install-time machinery is the
# --no-deps / lockfile residue, and _pin.py is the only layer that sees it.
"invisible_core==30.23.0",
"invisible_core==31.23.0",
# ⛔ playwright is NO LONGER a dependency: since the full fork, the Python
# client lives in src/invisible_playwright/_pw/ and the Node driver in
# src/invisible_playwright/_driver/. Reintroducing it would not visibly
+69 -22
View File
@@ -40,10 +40,12 @@ SECOND = b"""<!doctype html><html><head><title>second</title></head>
<body><div id=t>page two</div></body></html>"""
def _serve(body):
def _serve(body, asked=None):
class H(http.server.BaseHTTPRequestHandler):
def do_GET(self):
page = SECOND if self.path.startswith("/second") else body
if asked is not None:
asked.append(self.path)
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(page)))
@@ -278,25 +280,29 @@ def test_the_public_API_WAITS_for_an_element_that_arrives_late(firefox_binary):
@pytest.mark.e2e
@pytest.mark.xfail(reason="[B185] Page.goBack answers success and does nothing "
"in the shipped engine - the Node driver fails the "
"same way, so this is not the server",
strict=True)
def test_the_public_API_navigates_BACK_and_FORWARD_without_node(firefox_binary):
"""⛔ XFAIL ON AN ENGINE DEFECT, MEASURED ON BOTH ARMS.
"""⛔ EXPECTED-RED FOR THREE WEEKS, AND THE REASON GIVEN WAS WRONG.
`Page.goBack` answers `{success: true}` and then nothing happens: no
navigation event, no state change, the title stays on the page you were
already on. Measured on 2026-08-27 with `history.length == 2`, so the
history entries exist and the command simply does not act on them.
The marker here said `Page.goBack` answers `{success: true}` and then
nothing happens. The engine was never standing still: it goes back in 28
milliseconds. What was missing was a road for it to say so.
The control is what makes this an engine defect rather than a gap here: the
SAME call through the Node driver, same binary, times out with `waiting for
navigation until load`. Two different clients, one engine, one behaviour.
A `PageTarget`'s channel binds to a content actor only when that actor is
CREATED, and binding works by REPLACING that actor's `receiveMessage`. A
document restored from the back-forward cache makes an ALREADY created
actor current again, so the channel kept pointing at the newer one and
every word from the restored document was dropped - including a commit for
the very frame the client was tracking. The Node driver failed identically
because it is a client too, waiting for events that never arrived, and that
control was read as "the engine is broken" when it only said "not the
client".
`strict=True` on purpose: the day the engine is fixed this must turn RED so
somebody deletes the xfail, instead of quietly passing forever as an
expected failure that is no longer failing.
⛔ AND KEEPING THE CACHE ON IS WHY THIS EXISTED AT ALL. Upstream disables
the back-forward cache, so it never needs the bookkeeping; this fork keeps
it so that `pageshow`'s `persisted` behaves the way it does for a person,
and the other half of that decision was never written. It is now. The
`strict=True` marker that used to sit here did its job: the day the engine
was fixed it turned red and asked to be deleted.
"""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
srv = socketserver.TCPServer(("127.0.0.1", 0), _serve(PAGE))
@@ -310,12 +316,11 @@ def test_the_public_API_navigates_BACK_and_FORWARD_without_node(firefox_binary):
page.goto(url)
page.goto(url + "second")
assert page.title() == "second"
# ⛔ A SHORT TIMEOUT because this failure is EXPECTED: at the
# default 30 seconds the xfail holds a browser open for half a
# minute, and the tests running beside it start failing on load.
# That is the rule about never measuring under load, applied to the
# bench itself.
page.go_back(timeout=3000)
# A short timeout on purpose, for the opposite reason it had while
# this was expected-red: the defect made the call wait out its
# whole deadline, so a generous one would let a regression come
# back as a slow pass on a loaded machine instead of a red test.
page.go_back(timeout=5000)
assert page.title() == "seam"
page.go_forward()
assert page.title() == "second"
@@ -326,6 +331,48 @@ def test_the_public_API_navigates_BACK_and_FORWARD_without_node(firefox_binary):
srv.shutdown()
@pytest.mark.e2e
def test_going_back_RESTORES_the_document_instead_of_fetching_it_again(
firefox_binary):
"""⛔ THE TEST ABOVE PASSES BOTH WAYS, AND ONLY ONE OF THEM IS RIGHT.
`go_back()` landing on the right title proves the client learned where the
page went. It does NOT prove the page came out of the back-forward cache:
turn the cache off and the same assertion passes on a freshly fetched
document, with the stealth property this fork exists to keep - `pageshow`
reporting `persisted` the way it does for a person - quietly gone.
So this counts what the SERVER was asked for. A restore makes no request;
a reload makes a second one. The two ways of being green stop looking
alike.
"""
os.environ[factory.CHOICE_ENV] = factory.JUGGLER
asked: list = []
srv = socketserver.TCPServer(("127.0.0.1", 0), _serve(PAGE, asked))
threading.Thread(target=srv.serve_forever, daemon=True).start()
url = "http://127.0.0.1:%d/" % srv.server_address[1]
from invisible_playwright import InvisiblePlaywright
try:
with InvisiblePlaywright(seed=42, binary_path=firefox_binary,
headless=True) as browser:
page = browser.new_page()
page.goto(url)
page.goto(url + "second")
before = [p for p in asked if not p.startswith("/second")
and "favicon" not in p]
page.go_back(timeout=5000)
assert page.title() == "seam"
after = [p for p in asked if not p.startswith("/second")
and "favicon" not in p]
assert after == before, (
"going back fetched the document again (%r -> %r): it was not "
"restored from the back-forward cache, so pageshow.persisted "
"is false where a real browser reports true" % (before, after))
finally:
os.environ.pop(factory.CHOICE_ENV, None)
srv.shutdown()
@pytest.mark.e2e
def test_set_content_runs_in_the_MAIN_world_without_node(firefox_binary):
"""⛔ THE KNOWN-BAD OF `set_content`. Run from the utility world it answers
+96 -17
View File
@@ -216,27 +216,106 @@ def test_top_level_fields_are_either_pinnable_or_listed_as_deliberately_not():
# ── the page's own examples have to run ────────────────────────────────────
def test_the_pin_dicts_in_the_pages_examples_would_be_accepted():
"""The key tables and the worked examples drift apart independently: the
examples are what people copy."""
blocks = re.findall(r"```python\n(.*?)```", _doc(), re.S)
checked = 0
bad = {}
for block in blocks:
#: How many worked examples the page carried when the executing test below was
#: written. A FLOOR, not an equality: the page is meant to grow.
#:
#: It is a floor rather than `assert checked`, and that distinction is the whole
#: reason it exists. Until 2026-09-16 the extraction saw only `pin = {...}` and
#: was blind to the opening example, which passes `pin={...}` as a keyword
#: argument - and `assert checked` stayed green throughout, because the two
#: other examples kept the count off zero. A count that only has to be non-zero
#: cannot notice that it stopped seeing a third of the page.
_EXAMPLES_FLOOR = 3
def _example_pins() -> list[dict]:
"""Every `pin` dict on the page, in BOTH of the shapes the page writes.
`pin = {...}` is an `ast.Assign`. The page's opening example hands
`pin={...}` straight to the constructor, which is an `ast.keyword` and was
invisible to the first version of this extraction - so the block a reader
meets first was the one block nothing checked, and it was one of the two
that raised.
`literal_eval` rather than a walk over the key nodes, because the executing
test needs the VALUES. A pin assembled out of names or calls raises here
rather than being skipped, which is right: it is not something a reader can
copy either.
"""
pins: list[dict] = []
for block in re.findall(r"```python\n(.*?)```", _doc(), re.S):
try:
tree = ast.parse(block)
except SyntaxError: # fragments with `...` in them
continue
for node in ast.walk(tree):
if not (isinstance(node, ast.Assign) and isinstance(node.value, ast.Dict)):
if isinstance(node, ast.Assign) and isinstance(node.value, ast.Dict) \
and any(getattr(t, "id", "") == "pin" for t in node.targets):
value = node.value
elif isinstance(node, ast.keyword) and node.arg == "pin" \
and isinstance(node.value, ast.Dict):
value = node.value
else:
continue
if not any(getattr(t, "id", "") == "pin" for t in node.targets):
continue
for key_node in node.value.keys:
if not isinstance(key_node, ast.Constant) or not isinstance(key_node.value, str):
continue
checked += 1
if key_node.value not in _valid_keys():
bad[key_node.value] = "rejected by the validator"
assert checked, "no `pin = {...}` example left on the page to check"
pins.append(ast.literal_eval(value))
return pins
def _examples() -> list[dict]:
"""The page's examples, with the count asserted in ONE place.
Both tests below need the same floor, and a number written twice is a
number that drifts.
"""
pins = _example_pins()
assert len(pins) >= _EXAMPLES_FLOOR, (
f"found {len(pins)} `pin` example(s) on the page, expected at least "
f"{_EXAMPLES_FLOOR}. Either the page lost an example, or the extraction "
f"stopped matching the way they are written - and an extraction that "
f"finds nothing reads exactly like a page with nothing wrong on it")
return pins
def _label(pin: dict) -> str:
"""Enough of an example to find it on the page."""
return ", ".join(sorted(pin))[:120]
def test_the_pin_dicts_in_the_pages_examples_would_be_accepted():
"""The key tables and the worked examples drift apart independently: the
examples are what people copy.
KEYS only. Kept beside the executing test below rather than replaced by it:
it is the cheaper half, it names the offending key directly instead of
reporting whatever the validator happened to raise first, and it keeps
saying something about a key whose value is awkward to produce.
"""
bad = {}
for pin in _examples():
for key in pin:
if key not in _valid_keys():
bad[key] = "rejected by the validator"
assert not bad, f"the page's worked examples use keys the API refuses: {bad}"
def test_the_pages_examples_run_exactly_as_written():
"""The VALUES too, through the real validator. A key table cannot see one.
Measured 2026-09-16: two of the page's three examples named GPU renderer
strings that no persona in the pool presents - an RTX 4090 in the opening
block, an Iris Xe in "mimic a specific real device" - and both raised
`ValueError: pin gpu.renderer/gpu.vendor (...) names no validated GPU
persona` on the first lines a reader would copy. Every key in them was
valid, so the test above was green the whole time: the GPU refusal is on
the VALUE, which is the half nothing here was reading.
"""
raised = {}
for pin in _examples():
try:
generate_profile(seed=42, pin=pin)
except Exception as exc:
raised[_label(pin)] = f"{type(exc).__name__}: {exc}"
assert not raised, (
f"these worked examples raise when run exactly as the page writes "
f"them: {raised}. A reader copies the block, gets a traceback, and has "
f"no way to know that it is the page that is wrong")
+291
View File
@@ -0,0 +1,291 @@
"""E2E: the patched Firefox AUTHENTICATES to an HTTP proxy and goes out through it.
**What went wrong (issue #206).** With an authenticated HTTP proxy the browser
started without an error and the page came out of the HOST address, while the
same credentials over `socks5` worked. The cause is in the engine, not here:
Gecko carries username and password on `nsIProxyInfo` for SOCKS only, so
supplying them for `http` made the construction throw inside the channel
filter, the filter never answered, and necko carried on with no proxy at all.
A direct connection, and nothing said so.
**Why no gate here could have seen it.** Measured on this tree before the file
was written: the two HTTP arms of `test_proxy_reaches_the_browser.py`
(`test_what_the_page_receives_came_through_the_proxy` and
`test_a_context_proxy_is_the_road_that_context_goes_out_on`) launch with no
credentials at all; the only authenticated end-to-end arm is SOCKS5, in
`test_proxy_socks_auth_e2e.py`; and the single test that puts `http` and
credentials together,
`test_credentials_and_bypass_travel_in_the_shape_the_engine_wants`, asserts on
a Python dict and never opens a browser. So the product had never once been
driven out through an authenticated HTTP proxy under test, and the one
combination that was broken is the one nothing exercised.
**The assertion is positive and double, on purpose.** "The proxy received
something" would have been GREEN on the leak: a browser that connects directly
leaves no trace on the proxy, so an empty recorder and a healthy proxy are the
same observation, and the negative form cannot tell them apart. What is
asserted instead is that this proxy ROUTED the page's own request, and that the
bytes the page displays are bytes only this proxy instance could have produced
- the target host is reserved by RFC 2606 and resolves nowhere, and the body
carries this proxy's own listening port.
Hermetic, like the SOCKS file beside it: a local HTTP proxy that refuses with
407 until it is shown the right `Proxy-Authorization`. No network, no external
site, nobody's real credentials.
"""
from __future__ import annotations
import base64
import socket
import threading
import pytest
_USER = "ferd_http_user"
_PASS = "ferd_http_pw_42"
#: Reserved by RFC 2606 to resolve nowhere, so a 200 for it can only have come
#: from the proxy. The same device as the neighbouring file, and the reason
#: both of them are written in the positive form.
_ONLY_VIA_PROXY = "only-via-proxy.invalid"
_MARKER = "ANSWER-FROM-THE-AUTHENTICATED-PROXY"
def _decode_basic(header: str) -> tuple[str, str]:
"""`Basic <base64>` back into the pair it carries.
Anything that is not a decodable Basic credential is returned as a pair
that cannot match the expected one, so a malformed header is recorded
rather than swallowed: the test's failure message is the only place the
reader learns what the browser actually offered.
"""
scheme, _, blob = header.partition(" ")
if scheme.lower() != "basic":
return (header, "")
try:
decoded = base64.b64decode(blob).decode("utf-8", "replace")
except Exception:
return (header, "")
user, _, password = decoded.partition(":")
return (user, password)
class _AuthenticatingProxy:
"""An HTTP proxy that answers 407 until it is shown the right credentials.
It records the two things a direct connection cannot produce: the
credentials it was given, and the request lines it routed AFTER accepting
them. It answers each request itself instead of forwarding it - what is in
question is whether the browser talks to it at all, and for a host that
exists in no DNS this object is the only possible source of a 200.
"""
def __init__(self) -> None:
self.credentials: list[tuple[str, str]] = []
self.routed: list[str] = []
self.refused: list[str] = []
self._expected = "Basic " + base64.b64encode(
("%s:%s" % (_USER, _PASS)).encode()).decode()
self._sock = socket.socket()
self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Port 0, read back off the listening socket: run_e2e.py runs four
# workers at once, and a port chosen in advance is one that two workers
# can be handed in the same moment.
self._sock.bind(("127.0.0.1", 0))
self.port = self._sock.getsockname()[1]
self._sock.listen(32)
threading.Thread(target=self._serve, daemon=True).start()
@property
def url(self) -> str:
return "http://127.0.0.1:%d" % self.port
@property
def body(self) -> str:
"""What only THIS proxy instance can put on a page.
The port is in it deliberately. A bare marker would also be served by a
second copy of this fixture running in a parallel worker, and the point
of the assertion is the road the page took, not the string.
"""
return "%s:%d" % (_MARKER, self.port)
def _serve(self) -> None:
while True:
try:
conn, _ = self._sock.accept()
except OSError:
return
threading.Thread(target=self._answer, args=(conn,),
daemon=True).start()
def _answer(self, conn: socket.socket) -> None:
try:
conn.settimeout(10)
data = b""
while b"\r\n\r\n" not in data:
chunk = conn.recv(65536)
if not chunk:
return
data += chunk
lines = data.split(b"\r\n\r\n", 1)[0].decode("latin-1").split("\r\n")
request_line = lines[0]
offered = None
for line in lines[1:]:
name, _, value = line.partition(":")
if name.strip().lower() == "proxy-authorization":
offered = value.strip()
if offered is not None:
self.credentials.append(_decode_basic(offered))
if offered != self._expected:
self.refused.append(request_line)
self._send(conn, "407 Proxy Authentication Required",
"proxy authentication required",
challenge='Basic realm="invisible-playwright"')
return
self.routed.append(request_line)
self._send(conn, "200 OK", self.body)
except Exception:
pass
finally:
try:
conn.close()
except Exception:
pass
@staticmethod
def _send(conn: socket.socket, status: str, text: str,
challenge: str | None = None) -> None:
body = text.encode()
head = "HTTP/1.1 %s\r\nContent-Type: text/plain\r\n" % status
if challenge is not None:
head += "Proxy-Authenticate: %s\r\n" % challenge
head += "Content-Length: %d\r\nConnection: close\r\n\r\n" % len(body)
conn.sendall(head.encode() + body)
def close(self) -> None:
try:
self._sock.close()
except Exception:
pass
@pytest.fixture
def authenticating_proxy():
proxy = _AuthenticatingProxy()
try:
yield proxy
finally:
proxy.close()
@pytest.mark.e2e
def test_the_page_goes_out_through_an_authenticated_http_proxy(
firefox_binary, authenticating_proxy):
"""The gate issue #206 needed and this repository did not have.
The navigation error is caught rather than left to propagate, and that is
not leniency - it is the whole diagnosis. Both known-bad engines fail
INSIDE `goto`, so an uncaught error puts a bare Gecko code in the report
and none of the assertions below ever print. The two codes mean opposite
things and the message names them: NS_ERROR_UNKNOWN_HOST is the browser
resolving the name itself, i.e. no proxy at all, which is issue #206;
NS_ERROR_PROXY_CONNECTION_REFUSED is the browser reaching the proxy and
being turned away, i.e. the credentials did not arrive. Nothing is
swallowed: a caught error fails the first assertion, and `shown` stays
empty so it would fail the second one too.
"""
from invisible_playwright import InvisiblePlaywright
navigation_error = None
shown = ""
with InvisiblePlaywright(seed=42, binary_path=firefox_binary,
humanize=False, timezone="UTC",
proxy={"server": authenticating_proxy.url,
"username": _USER,
"password": _PASS}) as browser:
page = browser.new_page()
try:
page.goto("http://%s/" % _ONLY_VIA_PROXY,
wait_until="domcontentloaded", timeout=30_000)
shown = page.locator("body").inner_text()
except Exception as exc: # noqa: BLE001 - re-raised below
navigation_error = exc
assert navigation_error is None, (
"the navigation never completed through the authenticated proxy: %s. "
"NS_ERROR_UNKNOWN_HOST means the browser resolved the name itself and "
"went out with no proxy at all, which is issue #206; "
"NS_ERROR_PROXY_CONNECTION_REFUSED means it reached the proxy and was "
"refused, i.e. the credentials never arrived. The proxy refused %r and "
"was offered the credentials %r"
% (navigation_error, authenticating_proxy.refused[:5],
authenticating_proxy.credentials[:5]))
assert authenticating_proxy.body in shown, (
"the page did not receive the authenticated proxy's own body. It read "
"%r, and only this proxy can serve %r for a host that resolves "
"nowhere. Credentials the proxy was offered: %r"
% (shown[:200], authenticating_proxy.body,
authenticating_proxy.credentials[:5]))
assert any(_ONLY_VIA_PROXY in line for line in authenticating_proxy.routed), (
"the proxy never routed the navigation after authenticating it. "
"Routed: %r, refused with 407: %r"
% (authenticating_proxy.routed[:5], authenticating_proxy.refused[:5]))
assert (_USER, _PASS) in authenticating_proxy.credentials, (
"the browser never offered the configured proxy credentials; the proxy "
"saw: %r" % (authenticating_proxy.credentials[:5],))
@pytest.mark.e2e
def test_a_context_proxy_with_credentials_is_the_road_that_context_goes_out_on(
authenticating_proxy, firefox_binary):
"""The same question one level down, because the report measured both.
Issue #206 listed the launch proxy and the context proxy as two separate
arms and both leaked, which is what you would expect from a cause that
lives under both: the channel filter is one, and neither road writes any
network.proxy preference.
The fix is one function too, so this arm cannot fail while the one above
passes for a reason inside the engine. It can fail for a reason inside the
WIRING: `Browser.setBrowserProxy` and `Browser.setContextProxy` are two
commands, two handlers and two stores, and the eager refusal that stops an
inexpressible proxy from becoming a silent direct connection is installed
at two call sites. One of them could be removed on its own, and then a
context would go out in the clear while every launch stayed proxied - the
exact shape of the original bug, on the road nothing was watching.
Same assertions as above and for the same reason: what the PAGE read, not
what the proxy logged. A browser that ignores the proxy leaves no trace on
it, so a count of zero reads as "not yet" rather than as a leak.
"""
from invisible_playwright import InvisiblePlaywright
navigation_error = None
shown = ""
with InvisiblePlaywright(seed=42, binary_path=firefox_binary,
humanize=False, timezone="UTC") as browser:
context = browser.new_context(proxy={"server": authenticating_proxy.url,
"username": _USER,
"password": _PASS})
page = context.new_page()
try:
page.goto("http://%s/" % _ONLY_VIA_PROXY,
wait_until="domcontentloaded", timeout=30_000)
shown = page.locator("body").inner_text()
except Exception as exc: # noqa: BLE001 - re-raised below
navigation_error = exc
assert navigation_error is None, (
"the context never navigated through its own authenticated proxy: %s. "
"The browser was launched with NO proxy, so going out in the clear here "
"is the context proxy being dropped rather than a launch-level "
"problem. Routed: %r, refused with 407: %r"
% (navigation_error, authenticating_proxy.routed[:5],
authenticating_proxy.refused[:5]))
assert authenticating_proxy.body in shown, (
"the page did not receive the proxy's own body, so the context did not "
"go out through it. It read %r" % (shown[:200],))
assert (_USER, _PASS) in authenticating_proxy.credentials, (
"the context never offered its proxy credentials; the proxy saw: %r"
% (authenticating_proxy.credentials[:5],))