SPB Git

Repository Public

test_browser_replay.py 11.5 KB 228 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_replay.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"""Replay sanitiser: the replay document must be inert and must never contact the origin."""42from __future__ import annotations4344import re4546import pytest4748from spider.browser.replay import BLANK_IMAGE, CSP, build_replay, sanitise_css4950BASE = "https://origin.example/dir/page.html"51RES = {"https://origin.example/a.css": "res/a.css", "https://origin.example/img/a.png": "res/a.png",52       "https://origin.example/bg.png": "res/bg.png"}535455def replay(html: str, **kw) -> str:56    return build_replay(html, BASE, RES, **kw)575859def body_of(out: str) -> str:60    """Output without the fixed preamble (comment, CSP meta, banner)."""61    out = out.split("-->", 1)[1]62    out = re.sub(r"<meta http-equiv=\"Content-Security-Policy\"[^>]*>", "", out)63    return re.sub(r"<div data-spider-replay-banner.*?</div>", "", out, flags=re.DOTALL)646566XSS = [67    "<script>alert(1)</script>",68    "<SCRIPT SRC=https://evil.example/x.js></SCRIPT>",69    "<svg onload=alert(1)>",70    "<svg><script>alert(1)</script></svg>",71    "<svg><script href='https://evil.example/x.js'/></svg>",72    "<svg><a xlink:href='javascript:alert(1)'><text>x</text></a></svg>",73    "<svg><animate attributeName=href values='javascript:alert(1)' /><a id=x><text>t</text></a></svg>",74    "<svg><use href='https://evil.example/sprite.svg#x'/></svg>",75    "<img src=x onerror=alert(1)>",76    "<img src='javascript:alert(1)'>",77    "<body onload=alert(1)>",78    "<iframe srcdoc='<script>alert(1)</script>'></iframe>",79    "<iframe src='javascript:alert(1)'></iframe>",80    "<iframe src='data:text/html,<script>alert(1)</script>'></iframe>",81    "<object data='https://evil.example/o.swf'></object>",82    "<object data='javascript:alert(1)'><p>fallback</p></object>",83    "<embed src='https://evil.example/e.swf'>",84    "<link rel=import href='https://evil.example/i.html'>",85    "<link rel=stylesheet href='https://evil.example/x.css'>",86    "<link rel=preload as=script href='https://evil.example/x.js'>",87    "<base href='https://evil.example/'><img src='p.png'>",88    "<meta http-equiv=refresh content='0;url=https://evil.example/'>",89    "<meta http-equiv='Set-Cookie' content='a=b'>",90    "<a href='javascript:alert(1)'>x</a>",91    "<a href=' jAvA\tsCrIpT:alert(1)'>x</a>",92    "<a href='java&#10;script:alert(1)'>x</a>",93    "<a href='vbscript:msgbox(1)'>x</a>",94    "<a href='data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg=='>x</a>",95    "<form action='https://origin.example/submit' method=post><button formaction='https://evil.example/'>go</button></form>",96    "<input type=image src='https://evil.example/i.png' formaction='https://evil.example/'>",97    "<div style='background:url(javascript:alert(1))'>x</div>",98    "<div style='background:url(https://tracker.example/p.gif)'>x</div>",99    "<div style='width:expression(alert(1))'>x</div>",100    "<div style='behavior:url(x.htc)'>x</div>",101    "<style>@import url('https://evil.example/x.css');</style>",102    "<style>@import 'https://evil.example/x.css';</style>",103    "<style>body{background:url(javascript:alert(1))}</style>",104    "<style>a{background:\\75 rl(https://evil.example/esc.png)}</style>",105    "<style></style><script>alert(1)</script>",106    "<style>x{}</style ><img src=x onerror=alert(1)>",107    "<noscript><img src='https://tracker.example/ns.gif'></noscript>",108    "<noscript><p title='</noscript><img src=x onerror=alert(1)>'></noscript>",109    "<textarea></textarea><script>alert(1)</script>",110    "<title></title><script>alert(1)</script>",111    "<math><mi xlink:href='javascript:alert(1)'>x</mi></math>",112    "<video src='https://evil.example/v.mp4' poster='https://evil.example/p.png' onloadstart=alert(1)></video>",113    "<audio src='https://evil.example/a.mp3' autoplay></audio>",114    "<img srcset='https://evil.example/a.png 1x, https://evil.example/b.png 2x'>",115    "<picture><source srcset='https://evil.example/a.webp'><img src='https://evil.example/a.png'></picture>",116    "<a href='https://origin.example/x' ping='https://evil.example/ping' target=_blank>x</a>",117    "<div><template shadowrootmode=open><script>alert(1)</script><p onclick=alert(1)>s</p></template></div>",118    "<!--><script>alert(1)</script>-->",119    "<![CDATA[<script>alert(1)</script>]]>",120    "<p>ok</p><plaintext><script>alert(1)</script>",121    "<frameset><frame src='https://evil.example/'></frameset>",122    "<button onclick=\"fetch('/x',{method:'POST'})\" formaction=/x>b</button>",123    "<isindex action='javascript:alert(1)' type=image>",124    "<img src='data:image/svg+xml,<svg onload=alert(1)>'>",125    "<table background='https://evil.example/bg.png'><tr><td>x</td></tr></table>",126    "<svg><image href='https://evil.example/i.png'/><foreignObject><iframe src='https://evil.example/'></iframe></foreignObject></svg>",127]128129130@pytest.mark.parametrize("payload", XSS)131def test_xss_inputs_are_neutralised(payload):132    out = replay(f"<!doctype html><html><head><title>t</title></head><body>{payload}<p>END</p></body></html>")133    body = body_of(out)134    low = body.lower()135    assert "<script" not in low136    assert not re.search(r"<[^>]+\son[a-z]+\s*=", low), body137    assert "javascript:" not in re.sub(r"&[a-z#0-9]+;", "", low) or "value=" in low138    assert "evil.example" not in low, body139    assert "tracker.example" not in low, body140    assert "srcdoc" not in low and "<object" not in low and "<embed" not in low and "<base" not in low141    assert "http-equiv" not in low142    assert "formaction" not in low and " action=" not in low and "ping=" not in low143    assert "@import" not in low and "expression(" not in low and "behavior" not in low144    # no URL that would load from the network without a click145    for m in re.finditer(r"""(?:src|srcset|poster|data|background)\s*=\s*"([^"]*)\"""", body):146        assert not re.match(r"\s*(https?:)?//", m.group(1)), m.group(0)147    for m in re.finditer(r"url\(([^)]*)\)", body):148        assert "http" not in m.group(1).lower()149150151def test_csp_banner_and_structure():152    out = replay("<!doctype html><html><head><title>T</title></head><body><p>Hello</p></body></html>")153    assert out.startswith("<!DOCTYPE html>\n<!-- SPIDER static replay")154    assert f'<meta http-equiv="Content-Security-Policy" content="{CSP}">' in out155    assert CSP.startswith("default-src 'none'; img-src data: blob: 'self'; style-src 'unsafe-inline' 'self'; "156                          "font-src 'self' data:")157    assert out.index("Content-Security-Policy") < out.index("<title>")158    assert "data-spider-replay-banner" in out and "<p>Hello</p>" in out159    assert out.count("<head>") == 1160161162def test_csp_present_without_head_or_body():163    out = replay("just text <b onclick=x()>bold</b>")164    assert "Content-Security-Policy" in out and "<b>bold</b>" in out and "onclick" not in out165    assert build_replay("", BASE).count("Content-Security-Policy") == 1166167168def test_resources_are_rewritten_to_local_artifacts():169    out = replay('<html><head><link rel="stylesheet" href="/a.css"><link rel="stylesheet" href="/missing.css">'170                 '<style>.a{background:url("/bg.png")} .b{background:url(/nope.png)}</style></head>'171                 '<body><img src="/img/a.png" srcset="/img/a.png 1x, /img/zzz.png 2x"><img src="/img/zzz.png">'172                 '<img src="data:image/png;base64,AAAA"></body></html>')173    assert '<link rel="stylesheet" href="res/a.css">' in out and "missing.css" not in out174    assert 'url("res/bg.png")' in out and "nope.png" not in out175    assert '<img src="res/a.png" srcset="res/a.png 1x">' in out176    assert f'<img src="{BLANK_IMAGE}">' in out177    assert '<img src="data:image/png;base64,AAAA">' in out178179180def test_base_is_removed_but_honoured_for_resolution():181    out = build_replay('<html><head><base href="https://origin.example/sub/"></head><body><img src="../img/a.png">'182                       '<a href="next">n</a></body></html>', BASE, RES)183    assert "<base" not in out and 'src="res/a.png"' in out184    assert 'href="https://origin.example/sub/next"' in out185186187def test_links_are_absolute_and_inert_until_clicked():188    out = replay('<a href="/next?a=1" target="_blank">n</a><a href="#top">t</a><a href="mailto:a@b.c">m</a>')189    assert '<a href="https://origin.example/next?a=1" rel="noopener noreferrer nofollow">n</a>' in out190    assert 'href="#top"' in out and 'href="mailto:a@b.c"' in out and "target=" not in out191    assert "href=" not in body_of(replay('<a href="/next">n</a>', keep_links=False))192193194def test_forms_are_disabled():195    out = replay('<form action="/s" method="post"><input name="q" value="v"><select><option>a</option></select>'196                 '<textarea>t</textarea><button>go</button></form>')197    assert "action=" not in out and "inert" in out198    assert out.count(' disabled=""') == 4199    assert 'value="v"' in out and "<textarea" in out200201202def test_text_is_escaped_not_reinterpreted():203    out = replay("<p>&lt;script&gt;alert(1)&lt;/script&gt; &amp; 5 &lt; 6</p>")204    assert "<p>&lt;script&gt;alert(1)&lt;/script&gt; &amp; 5 &lt; 6</p>" in out205206207def test_frames_point_to_local_snapshots_or_blank():208    out = build_replay('<iframe src="/frame.html" data-spider-frame="0">inner</iframe><iframe src="https://x.example/"></iframe>',209                       BASE, {"https://origin.example/frame.html": "frames/frame-0.html"})210    assert 'src="frames/frame-0.html"' in out and 'src="about:blank"' in out and out.count('sandbox=""') == 2211    assert "inner" not in body_of(out)212213214def test_declarative_shadow_dom_is_kept_and_cleaned():215    out = replay('<div><template shadowrootmode="open"><p onclick="x()">shadow text</p><script>1</script></template></div>')216    assert '<template shadowrootmode="open"><p>shadow text</p></template>' in out217218219def test_sanitise_css_direct():220    css = sanitise_css("a{background:url( 'https://origin.example/bg.png' )} b{background:url(//evil.example/x)}"221                       "/* c */ @import url(x.css); </style><script>", BASE, RES)222    assert 'url("res/bg.png")' in css and "evil" not in css and "@import" not in css and "</" not in css223224225def test_is_pure_and_deterministic():226    html = "<html><body><p>x</p><img src='/img/a.png'></body></html>"227    assert replay(html) == replay(html)228
Files main
Menu

Theme