Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER — Universal Web Intelligence Engine7# File : tests/unit/browser/test_browser_states.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"""Interactive state exploration on real browsers, and the proof that nothing unsafe is ever activated."""42from __future__ import annotations4344import hashlib45from pathlib import Path4647import pytest48import pytest_asyncio49from browser_testlib import UA_SUFFIX5051from spider.contracts import CaptureOptions, RenderRequest5253pytestmark = [pytest.mark.browser, pytest.mark.asyncio(loop_scope="session")]545556@pytest_asyncio.fixture(scope="module", loop_scope="session")57async def explored(pool, server, tmp_path_factory):58 server.clear()59 req = RenderRequest(url=server.url("/p/states.html"), out_dir=str(tmp_path_factory.mktemp("states")),60 capture=CaptureOptions(interactive_states=True, full_page=False, webp_derivatives=True),61 user_agent_suffix=UA_SUFFIX, timeout_s=90,62 ssrf_allow=[f"127.0.0.1:{server.port}"])63 return await pool.render(req)646566def state_by_text(result, text):67 return next(s for s in result.states if text in s.new_text)686970async def test_states_are_discovered(explored):71 assert explored.ok and explored.budgets_hit == []72 root = explored.states[0]73 assert root.state_id == "s0" and root.depth == 0 and root.actions == [] and root.parent_state_id is None74 expected = {"TAB-TWO-TEXT": ("tab", "#t2"), "TAB-THREE-TEXT": ("tab", "#t3"),75 "ACCORDION-TEXT": ("accordion", "#acc"), "DETAILS-TEXT": ("details", "#det > summary"),76 "SLIDE-2": ("carousel", "#next"), "SLIDE-3": ("carousel", "#prev"),77 "SHARED-PANEL-TEXT": ("menu", "#pop-a"), "ROW-2-LOADED": ("load_more", "#more")}78 for text, (control, selector) in expected.items():79 s = state_by_text(explored, text)80 assert s.depth == 1 and s.parent_state_id == "s0", text81 (action,) = s.actions82 assert (action.type, action.control, action.selector) == ("click", control, selector)83 assert action.name and action.role in ("tab", "button")84 assert state_by_text(explored, "TAB-TWO-TEXT").actions[0].name == "Specifications"85 assert len({s.state_id for s in explored.states}) == len(explored.states)868788async def test_state_fingerprints_captures_and_new_text(explored, server):89 for s in explored.states[1:]:90 assert len(s.dom_hash_before) == 32 and len(s.visual_hash_before) == 6491 assert s.dom_hash_before != s.dom_hash_after, s.state_id92 assert s.new_text.strip()93 view, changed = s.captures[0], s.captures[1]94 assert view.kind == changed.kind == "state" and view.state_id == changed.state_id == s.state_id95 assert (view.width, view.height) == (1280, 800)96 assert 0 < changed.width <= 1280 and 0 < changed.height < 80097 assert changed.css.w == changed.width and changed.css.h == changed.height # dpr 198 assert 0 <= changed.css.x and changed.css.x + changed.css.w <= 128099 for c in s.captures:100 assert c.sha256 == hashlib.sha256(Path(c.path).read_bytes()).hexdigest()101 assert [c.kind for c in s.captures[2:]] == ["derivative", "derivative"]102 assert {c.derived_from for c in s.captures[2:]} == {view.sha256, changed.sha256}103 html = Path(s.html_path).read_text()104 assert s.new_text.splitlines()[0].split()[0] in html105 tab2 = state_by_text(explored, "TAB-TWO-TEXT")106 assert tab2.visual_hash_before != tab2.visual_hash_after107 slide = state_by_text(explored, "SLIDE-2")108 assert slide.visual_hash_before != slide.visual_hash_after109 # the changed region of the carousel is the slide: 400 × 80 px110 assert (slide.captures[1].width, slide.captures[1].height) == (400, 80)111 assert server.non_get() == []112113114async def test_deduplication_noop_and_depth(explored):115 m = explored.metrics["states"]116 shared = state_by_text(explored, "SHARED-PANEL-TEXT")117 dup = [d for d in m["duplicates"] if d["selector"] == "#pop-b"]118 assert dup and dup[0]["to"] == shared.state_id # two controls, one state: recorded once119 assert [n["selector"] for n in m["noops"] if n["from"] == "s0"] == ["#noop"]120 assert not any("Inert" in (a.name or "") for s in explored.states for a in s.actions)121 nested = state_by_text(explored, "NESTED-DETAILS-TEXT") # revealed by the second tab: depth 2122 assert nested.depth == 2 and [a.selector for a in nested.actions] == ["#t2", "#nested > summary"]123 assert nested.parent_state_id == state_by_text(explored, "TAB-TWO-TEXT").state_id124 again = state_by_text(explored, "ROW-3-LOADED") # "show more" pressed again from its own state125 assert [a.selector for a in again.actions] == ["#more", "#more"]126 assert max(s.depth for s in explored.states) == 2127 # the carousel wraps around: next from "previous" lands on a known state, not a new one128 assert any(d["control"] == "carousel" for d in m["duplicates"])129 assert m["states"] == len(explored.states) - 1 and m["actions"] == m["activated"]130 assert m["already_active"] >= 1 # the selected tab is not clicked131132133async def test_return_to_reference_is_verified(explored):134 r = explored.metrics["states"]["returns"]135 assert r["unverified"] == 0 and explored.metrics["states"]["reference_drift"] == 0136 assert r["reverse"] >= 7 # toggles reversed and checked by fingerprint137 assert r["reload"] >= 1 # "show more" cannot be reversed: reload + replay138 assert r["verified"] >= r["reverse"] + 1139 # every state shares the reference as "before" unless it was reached from another state140 root = explored.states[0]141 for s in explored.states[1:]:142 if s.depth == 1:143 assert s.dom_hash_before == root.dom_hash_after, s.state_id144145146async def test_state_budgets(pool, make_request):147 res = await pool.render(make_request("/p/states.html", interactive_states=True, max_states=2))148 assert "max_states" in res.budgets_hit and len(res.states) - 1 == 2149 res = await pool.render(make_request("/p/states.html", interactive_states=True, max_actions=3))150 assert "max_actions" in res.budgets_hit and res.metrics["states"]["actions"] == 3151 res = await pool.render(make_request("/p/states.html", interactive_states=True, max_states=0))152 assert res.ok and res.states == []153154155async def test_tab_state_on_webkit(pool, make_request):156 res = await pool.render(make_request("/p/states.html", engine="webkit", interactive_states=True, max_actions=3))157 assert res.ok and res.engine == "webkit"158 tab = state_by_text(res, "TAB-TWO-TEXT")159 assert tab.actions[0].selector == "#t2" and tab.dom_hash_before != tab.dom_hash_after160 assert tab.visual_hash_before != tab.visual_hash_after and len(tab.captures) == 2161 assert res.metrics["states"]["returns"]["unverified"] == 0162163164UNSAFE = {165 "#form-submit": "unsafe: inside_form", "#form-plain": "unsafe: inside_form",166 "#buy": "unsafe: inline_handler_side_effect", "#cart": "unsafe: label_denied",167 "#delete": "unsafe: label_denied", "#supprimer": "unsafe: label_denied", "#abonner": "unsafe: label_denied",168 "#envoyer": "unsafe: label_denied", "#reserver": "unsafe: label_denied", "#login": "unsafe: label_denied",169 "#dl": "unsafe: link_to_document", "#plain-link": "unsafe: link_to_document",170 "#nav": "unsafe: inline_handler_side_effect", "#hidden-fetch": "unsafe: inline_handler_side_effect",171 "#in-ancestor": "unsafe: inline_handler_side_effect", "#formaction": "unsafe: has_formaction",172 "#submit-outside": "unsafe: type_submit", "#accept": "unsafe: label_denied", "#refuse": "unsafe: label_denied",173 "#ok": "ambiguous: generic_label", "#continue": "ambiguous: generic_label",174 "#suivant": "ambiguous: generic_label", "#mystery": "ambiguous: no_disclosure_signal",175}176177178@pytest.mark.parametrize("engine", ["chromium", "webkit"])179async def test_danger_page_nothing_unsafe_is_activated(pool, make_request, server, engine):180 server.clear()181 res = await pool.render(make_request("/p/danger.html", engine=engine, interactive_states=True))182 assert res.ok183 skipped = {s.selector: s for s in res.skipped_actions}184 for selector, reason in UNSAFE.items():185 assert selector in skipped, selector186 assert skipped[selector].reason.startswith(reason), (selector, skipped[selector].reason)187 assert skipped[selector].name188 # the only control activated is the harmless <details>189 assert [a.selector for s in res.states for a in s.actions] == ["#safe > summary"]190 assert "SAFE-DETAILS-TEXT" in res.states[1].new_text191 assert res.metrics["states"]["actions"] == 1 and res.metrics["states"]["skipped"] == len(res.skipped_actions)192 # the server proves it: no request other than GET, no hit on any side-effect endpoint193 assert server.non_get() == []194 assert server.hits("/api/side-effect") == []195 assert {h["path"] for h in server.log} <= {"/p/danger.html", "/favicon.ico"}196 # what the page itself fired on load was stopped at the network layer and recorded197 blocked = [e for e in res.network_errors if e["reason"] == "blocked_non_get"]198 assert {e["method"] for e in blocked} >= {"POST", "DELETE", "PUT"} and len(blocked) >= 3199 assert res.metrics["network"]["blocked"]["blocked_non_get"] == len(blocked)200 assert res.metrics["network"]["dialogs"] == [{"type": "alert", "message": "hello dialog", "action": "dismissed"}]201 assert res.signals["dialogs"] == 1202 assert server.url("/api/side-effect/popup") in res.observed_routes # popup blocked, URL kept as a route203 assert res.metrics["network"]["blocked"].get("popup_blocked", 0) >= 1204205206async def test_refusal_stops_everything(pool, make_request, server):207 server.clear()208 res = await pool.render(make_request("/p/captcha.html", interactive_states=True, tiles=True, sections=True,209 full_page=True, elements=["h1"]))210 assert res.ok is False and res.refusal == "captcha" and res.error_class == "captcha"211 assert "hcaptcha" in res.error_detail212 assert res.states == [] and res.skipped_actions == [] and "states" not in res.metrics213 assert [c.kind for c in res.captures] == ["viewport"] # the evidence, nothing more214 assert Path(res.captures[0].path).is_file() and "scroll" not in res.metrics215 assert {h["path"] for h in server.log} <= {"/p/captcha.html", "/fake/hcaptcha.com/challenge.html", "/favicon.ico"}216217218async def test_click_time_recheck_refuses_an_element_that_is_not_safe(open_page, server, tmp_path):219 """A selector is re-classified when it is about to be clicked: the DOM may have changed since discovery."""220 from spider.browser.capture import CaptureSession221 from spider.browser.netguard import NetworkGuard222 from spider.browser.states import StateExplorer, UnsafeControlError223224 page = await open_page("/p/danger.html")225 server.clear()226 session = CaptureSession(page, tmp_path, CaptureOptions(), profile="desktop", engine="chromium",227 engine_version="test", nominal_dpr=1)228 explorer = StateExplorer(page, session, NetworkGuard(), url=page.url, max_states=5, max_actions=5)229 for selector, kind in (("#buy", "accordion"), ("#cart", "tab"), ("#ok", ""), ("#form-plain", "accordion")):230 with pytest.raises(UnsafeControlError):231 await explorer._click(selector, kind)232 assert {s.selector for s in explorer.skipped} == {"#buy", "#cart", "#ok", "#form-plain"}233 assert all("at click time" in s.reason for s in explorer.skipped)234 await explorer._click("#safe > summary", "details")235 assert await page.evaluate("document.querySelector('#safe').open") is True236 assert server.log == []237