SPB Git

Repository Public

test_browser_guard.py 20.2 KB 418 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : SPIDER — Universal Web Intelligence Engine7# File             : tests/unit/browser/test_browser_guard.py8# Module           : Tests9# Repository       : https://git.spboucher.ai/spider10# Project Website  : Not specified11# Created          : 2026-12-0412# Last Modified    : 2026-12-0413#14# Author           : Simon-Pierre Boucher15# Position         : Professor of Finance16# Institution      : Université du Québec en Outaouais (UQO)17# Organization     : SP Boucher18# Website          : https://spboucher.ai19# Git              : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development      : dev@spboucher.ai23# Support          : support@spboucher.ai24# Security/Admin   : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License          : ISC33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Hard rules on real browsers: network guard, access refusals, navigation allowlist, proxy, watchdog, pool."""42from __future__ import annotations4344import asyncio45import os46import shutil47import socket48import ssl49import time50from pathlib import Path5152import pytest53import pytest_asyncio54from aiohttp import web5556from spider.browser import BrowserPool57from spider.browser import pool as pool_mod5859pytestmark = [pytest.mark.browser, pytest.mark.asyncio(loop_scope="session")]606162# ------------------------------------------------------------------------------------ network layer63@pytest.mark.parametrize("engine", ["chromium", "webkit"])64async def test_non_get_is_blocked_at_the_network_layer(pool, make_request, server, engine):65    server.clear()66    res = await pool.render(make_request("/p/post-on-load.html", engine=engine))67    assert res.ok and "POST-ON-LOAD-PAGE" in res.text68    assert "POST-BLOCKED" in res.text and "POST-SENT" not in res.text69    assert server.non_get() == [] and server.hits("/api/side-effect") == []70    (blocked,) = [e for e in res.network_errors if e["reason"] == "blocked_non_get"]71    assert blocked["method"] == "POST" and blocked["url"].endswith("/api/side-effect/tracking")727374@pytest.mark.parametrize("engine", ["chromium", "webkit"])75async def test_permission_prompts_are_denied(pool, make_request, engine):76    res = await pool.render(make_request("/p/perm.html", engine=engine))77    assert res.ok78    assert "GEO-REFUSED-1" in res.text and "NOTIF-denied" in res.text79    assert "GRANTED" not in res.text and "NOTIF-granted" not in res.text808182async def test_websockets_are_allowed_but_recorded(pool, make_request, server):83    res = await pool.render(make_request("/p/ws.html"))84    assert res.ok and "WS-HELLO" in res.text and res.signals["websockets"] == 185    (url,) = res.metrics["network"]["websockets"]86    assert url.startswith("ws://127.0.0.1") and "token=REDACTED" in url and "WSSECRET" not in url878889async def test_download_is_not_saved(pool, make_request, server):90    req = make_request("/download")91    res = await pool.render(req)92    assert res.ok is False and res.error_class == "invalid_content"93    assert not [p for p in Path(req.out_dir).rglob("*") if p.suffix == ".zip"]949596async def test_only_http_and_https_are_rendered(pool, make_request, server):97    for url in ("file:///etc/hosts", "data:text/html,<p>x</p>", "javascript:alert(1)", "ftp://127.0.0.1/x"):98        req = make_request("/p/basic.html")99        req.url = url100        res = await pool.render(req)101        assert res.ok is False and res.error_class == "policy" and res.captures == [], url102103104# ------------------------------------------------------------------------------------ access refusal105@pytest.mark.parametrize(("path", "refusal", "error_class", "status"), [106    ("/p/captcha.html", "captcha", "captcha", 200),107    ("/p/members.html", "login_wall", "login_wall", 200),108    ("/private/account", "login_wall", "login_wall", 200),109    ("/p/paywall.html", "paywall", "paywall", 200),110    ("/status/403", "access_denied", "http_403", 403),111    ("/status/401", "access_denied", "access_denied", 401),112    ("/status/451", "access_denied", "access_denied", 451),113])114async def test_access_refusals_are_detected_and_stop_the_render(pool, make_request, server, path, refusal,115                                                                error_class, status):116    server.clear()117    res = await pool.render(make_request(path, interactive_states=True, tiles=True))118    assert res.ok is False and res.refusal == refusal and res.error_class == error_class and res.status == status119    assert res.error_detail120    assert [c.kind for c in res.captures] == ["viewport"] and Path(res.captures[0].path).stat().st_size > 0121    assert res.states == [] and res.skipped_actions == [] and "scroll" not in res.metrics122    assert server.non_get() == [] and server.hits("/api/side-effect") == []123    if path == "/private/account":124        assert res.final_url.endswith("/login?next=/private/account") and "login URL" in res.error_detail125126127async def test_recaptcha_on_a_contact_form_is_not_a_refusal(pool, make_request, server):128    res = await pool.render(make_request("/p/contact.html", interactive_states=True))129    assert res.ok and res.refusal is None and res.error_class is None130    assert "Contact us" in res.text and len(server.hits("/fake/www.google.com/recaptcha/api.js")) >= 1131    assert any(s.reason.startswith("unsafe: inside_form") for s in res.skipped_actions)132    assert server.hits("/api/side-effect") == []133134135@pytest.mark.parametrize(("path", "error_class", "status"), [("/status/404", "http_404", 404),136                                                             ("/status/429", "http_429", 429),137                                                             ("/status/500", "http_5xx", 500),138                                                             ("/status/410", "http_4xx", 410)])139async def test_http_errors_are_classified(pool, make_request, path, error_class, status):140    res = await pool.render(make_request(path, interactive_states=True))141    assert res.ok is False and res.error_class == error_class and res.status == status and res.refusal is None142    assert [c.kind for c in res.captures] == ["viewport"] and res.states == []143144145@pytest.mark.parametrize("allowed", [None, ["nonexistent-host.invalid"]])146async def test_dns_and_connection_errors(pool, make_request, allowed):147    req = make_request("/p/basic.html", allowed_hosts=allowed, timeout_s=30)148    req.url = "http://nonexistent-host.invalid/"149    res = await pool.render(req)150    assert res.ok is False and res.error_class == "dns", res.error_detail151    with socket.socket() as sock:                       # a port nobody listens on152        sock.bind(("127.0.0.1", 0))153        closed_port = sock.getsockname()[1]154    req = make_request("/p/basic.html", allowed_hosts=["127.0.0.1"] if allowed else None)155    req.url = f"http://127.0.0.1:{closed_port}/"156    res = await pool.render(req)157    assert res.ok is False and res.error_class == "connect", res.error_detail158159160@pytest_asyncio.fixture(loop_scope="session")161async def tls_server(tmp_path):162    openssl = shutil.which("openssl")163    if not openssl:164        pytest.skip("openssl not available to make a self-signed certificate")165    key, cert = tmp_path / "k.pem", tmp_path / "c.pem"166    proc = await asyncio.create_subprocess_exec(167        openssl, "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", str(key), "-out", str(cert),168        "-days", "1", "-subj", "/CN=127.0.0.1", stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL)169    assert await proc.wait() == 0170    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)171    ctx.load_cert_chain(cert, key)172    hits = []173174    async def handler(request):175        hits.append(request.path)176        return web.Response(text="<p>SECRET-OVER-BAD-TLS</p>", content_type="text/html")177178    app = web.Application()179    app.router.add_get("/{tail:.*}", handler)180    runner = web.AppRunner(app, access_log=None)181    await runner.setup()182    site = web.TCPSite(runner, "127.0.0.1", 0, ssl_context=ctx)183    await site.start()184    port = site._server.sockets[0].getsockname()[1]185    yield f"https://127.0.0.1:{port}/", hits186    await runner.cleanup()187188189@pytest.mark.parametrize(("engine", "allowed"), [("chromium", None), ("webkit", None), ("chromium", ["127.0.0.1"])])190async def test_tls_errors_are_never_ignored(pool, make_request, tls_server, engine, allowed):191    url, hits = tls_server192    req = make_request("/p/basic.html", engine=engine, allowed_hosts=allowed)193    req.url = url194    res = await pool.render(req)195    assert res.ok is False and res.error_class == "tls", (res.error_class, res.error_detail)196    assert "SECRET-OVER-BAD-TLS" not in res.text and hits == []197198199# ------------------------------------------------------------------------------ navigation allowlist200async def test_main_frame_navigation_outside_allowed_hosts_is_blocked(pool, make_request, server):201    server.clear()202    res = await pool.render(make_request("/p/offhost.html", allowed_hosts=["127.0.0.1"]))203    target = server.url("/p/basic.html?from=offhost", host="localhost")204    assert res.ok and "OFFHOST-PAGE" in res.text and res.final_url == server.url("/p/offhost.html")205    assert [h for h in server.log if h["host"].startswith("localhost")] == []     # never requested206    assert target in res.observed_routes                                           # reported, not followed207    (blocked,) = [e for e in res.network_errors if e["reason"] == "navigation_not_allowed"]208    assert blocked["url"] == target and res.metrics["network"]["blocked"]["navigation_not_allowed"] == 1209210211@pytest.mark.parametrize("engine", ["chromium", "webkit"])212async def test_redirect_outside_allowed_hosts_is_blocked(pool, make_request, server, engine):213    server.clear()214    target = server.url("/p/basic.html", host="localhost")215    res = await pool.render(make_request(f"/redirect?to={target}", engine=engine, allowed_hosts=["127.0.0.1"]))216    assert res.ok is False and res.error_class == "policy" and "allowed_hosts" in res.error_detail217    assert [h for h in server.log if h["host"].startswith("localhost")] == []218    assert target in res.observed_routes and ("redirect", target) in {(link.kind, link.url) for link in res.links}219    assert any(e["reason"] == "navigation_not_allowed" for e in res.network_errors)220    assert res.captures == []221222223@pytest.mark.parametrize("engine", ["chromium", "webkit"])224async def test_allowed_redirects_are_followed_hop_by_hop(pool, make_request, server, engine):225    server.clear()226    res = await pool.render(make_request("/redirect?to=/redirect%3Fto%3D/p/basic.html", engine=engine,227                                         allowed_hosts=["127.0.0.1"]))228    assert res.ok and res.status == 200 and res.final_url == server.url("/p/basic.html")229    assert [r["status"] for r in res.metrics["network"]["redirects"]] == [302, 302]230    assert "Basic page heading" in res.text and len(server.hits("/p/basic.html")) == 1231    # and with a host allowlist that includes the second name, the cross-host redirect is followed232    target = server.url("/p/basic.html", host="localhost")233    res = await pool.render(make_request(f"/redirect?to={target}", engine=engine,234                                         allowed_hosts=["127.0.0.1", "localhost"]))235    assert res.ok and res.final_url == target236237238async def test_initial_url_outside_allowed_hosts_is_refused_without_a_request(pool, make_request, server):239    server.clear()240    res = await pool.render(make_request("/p/basic.html", allowed_hosts=["example.org"]))241    assert res.ok is False and res.error_class == "policy" and server.log == []242    assert res.network_errors[0]["reason"] == "navigation_not_allowed"243244245async def test_without_allowlist_redirects_are_native(pool, make_request, server):246    target = server.url("/p/basic.html", host="localhost")247    res = await pool.render(make_request(f"/redirect?to={target}"))248    assert res.ok and res.final_url == target and res.metrics["network"]["redirects"] == []249250251# --------------------------------------------------------------------------------------------- proxy252class RecordingProxy:253    """Minimal HTTP forward proxy (absolute-form GET only) that records what goes through it."""254255    def __init__(self) -> None:256        self.urls: list[str] = []257        self.port = 0258        self._server: asyncio.AbstractServer | None = None259260    async def start(self) -> RecordingProxy:261        self._server = await asyncio.start_server(self._handle, "127.0.0.1", 0)262        self.port = self._server.sockets[0].getsockname()[1]263        return self264265    async def stop(self) -> None:266        if self._server is not None:267            self._server.close()268269    async def _handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:270        try:271            head = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), 10)272            lines = head.decode("latin-1").split("\r\n")273            method, target, _version = lines[0].split(" ", 2)274            self.urls.append(f"{method} {target}")275            if method == "CONNECT":276                host, _, port = target.partition(":")277                up_reader, up_writer = await asyncio.open_connection(host, int(port))278                writer.write(b"HTTP/1.1 200 Connection established\r\n\r\n")279                await writer.drain()280281                async def pipe(src: asyncio.StreamReader, dst: asyncio.StreamWriter) -> None:282                    while chunk := await src.read(65536):283                        dst.write(chunk)284                        await dst.drain()285                    dst.close()286287                await asyncio.gather(pipe(reader, up_writer), pipe(up_reader, writer), return_exceptions=True)288                return289            if not target.startswith("http://"):290                writer.write(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")291                await writer.drain()292                return293            rest = target[len("http://"):]294            hostport, _, path = rest.partition("/")295            host, _, port = hostport.partition(":")296            up_reader, up_writer = await asyncio.open_connection(host, int(port or 80))297            headers = [h for h in lines[1:] if h and not h.lower().startswith(("proxy-", "connection:"))]298            up_writer.write(("\r\n".join([f"{method} /{path} HTTP/1.1", *headers, "Connection: close", "", ""])).encode("latin-1"))299            await up_writer.drain()300            while chunk := await up_reader.read(65536):301                writer.write(chunk)302                await writer.drain()303            up_writer.close()304        except Exception:  # noqa: BLE001, S110 - test helper305            pass306        finally:307            writer.close()308309310@pytest.mark.parametrize(("engine", "allowed"), [("chromium", None), ("webkit", None), ("chromium", ["127.0.0.1"])])311async def test_proxy_is_used_even_for_loopback(pool, make_request, server, engine, allowed):312    proxy = await RecordingProxy().start()313    try:314        server.clear()315        res = await pool.render(make_request("/p/basic.html", engine=engine, allowed_hosts=allowed,316                                             proxy=f"http://127.0.0.1:{proxy.port}"))317        assert res.ok, res.error_detail318        # loopback went through the proxy: plain proxying by the browser, a tunnel for the guarded fetch319        assert f"GET {server.url('/p/basic.html')}" in proxy.urls or f"CONNECT 127.0.0.1:{server.port}" in proxy.urls320        assert proxy.urls and all(str(server.port) in u for u in proxy.urls)321        assert len(server.hits("/p/basic.html")) == 1322    finally:323        await proxy.stop()324325326# ------------------------------------------------------------------------------- timeouts and the pool327async def test_page_that_never_finishes_loading_times_out(pool, make_request):328    t0 = time.monotonic()329    res = await pool.render(make_request("/hang", timeout_s=5))330    assert res.ok is False and res.error_class == "timeout"331    assert time.monotonic() - t0 < 9332    assert res.metrics["timings_ms"]["total"] < 6000333334335def alive(pid: int) -> bool:336    try:337        os.kill(pid, 0)338    except ProcessLookupError:339        return False340    except PermissionError:341        return True342    return True343344345async def test_watchdog_kills_a_render_that_hangs_and_pool_recovers(server, tmp_path, make_request):346    """A page whose script never yields blocks every evaluation: only the watchdog can end the render."""347    async with BrowserPool(close_grace_s=2) as own:348        t0 = time.monotonic()349        res = await own.render(make_request("/p/busy.html", timeout_s=3))350        elapsed = time.monotonic() - t0351        assert res.ok is False and res.error_class == "timeout" and "watchdog" in res.error_detail352        assert "render_timeout" in res.budgets_hit and own.stats["timeouts"] == 1353        assert 2.9 <= elapsed < 12, elapsed354        again = await own.render(make_request("/p/basic.html"))               # the pool is still usable355        assert again.ok and "Basic page heading" in again.text356        pids = own.tracked_pids()357        assert pids and all(alive(p) for p in pids)358    await asyncio.sleep(0.3)359    assert not any(alive(p) for p in pids)                                    # nothing left behind360361362async def test_watchdog_on_a_stuck_engine_call(server, make_request, monkeypatch):363    async def stuck(browser, req, result, info, holder=None):364        holder["context"] = await browser.new_context()365        await asyncio.sleep(3600)366367    monkeypatch.setattr(pool_mod, "render_page", stuck)368    async with BrowserPool() as own:369        t0 = time.monotonic()370        res = await own.render(make_request("/p/basic.html", timeout_s=1.5))371        assert res.error_class == "timeout" and res.metrics["watchdog"]["context_closed"] is True372        assert 1.4 <= time.monotonic() - t0 < 6373        monkeypatch.undo()374        assert (await own.render(make_request("/p/basic.html"))).ok375        assert own.stats["launches"] == 1                                     # the browser survived376377378async def test_pool_recycles_after_n_renders_and_on_memory_ceiling(server, make_request):379    async with BrowserPool(recycle_after=2) as own:380        first_pids = None381        for i in range(3):382            assert (await own.render(make_request("/p/basic.html"))).ok383            if i == 0:384                first_pids = own.tracked_pids()385        assert own.stats["launches"] == 2 and own.stats["recycled_renders"] == 1 and own.stats["renders"] == 3386        assert first_pids and set(first_pids).isdisjoint(own.tracked_pids())387        await asyncio.sleep(0.5)388        assert not any(alive(p) for p in first_pids)389        last = own.tracked_pids()390    await asyncio.sleep(0.3)391    assert not any(alive(p) for p in last)392393    async with BrowserPool(rss_ceiling_mb=1, rss_check_interval_s=0) as own:   # any browser is above 1 MB394        assert (await own.render(make_request("/p/basic.html"))).ok395        assert (await own.render(make_request("/p/basic.html"))).ok396        assert own.stats["recycled_rss"] == 1 and own.stats["launches"] == 2397398399async def test_concurrent_renders_are_isolated(pool, make_request, server):400    reqs = [make_request(p) for p in ("/p/basic.html", "/p/hydrate.html", "/p/shadow.html", "/p/spa.html")]401    results = await asyncio.gather(*(pool.render(r) for r in reqs))402    assert [r.title for r in results] == ["Basic page", "Hydration", "Shadow and frames", "SPA"]403    assert all(r.ok for r in results)404    assert len({r.metrics["manifest_path"] for r in results}) == 4405406407async def test_module_level_render_uses_a_shared_pool(make_request):408    from spider import browser409410    try:411        res = await browser.render(make_request("/p/basic.html"))412        assert res.ok and res.title == "Basic page"413        assert (await browser.render(make_request("/p/hydrate.html"))).ok414        shared = await pool_mod.shared_pool()415        assert shared.stats["launches"] == 1 and shared.stats["renders"] == 2416    finally:417        await browser.shutdown()418
Files main
Menu

Theme