Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER — Universal Web Intelligence Engine7# File : tests/unit/core/test_http_engine.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"""HttpEngine against real local servers: the fixture site and tiny ad-hoc aiohttp applications.4243No database. Loopback is reachable only through `NetGuard(test_allow=...)` with the exact ports44of the servers started here; every other private destination stays blocked, which is what the45SSRF tests rely on.46"""47import shutil48import socket49import ssl50import subprocess51import sys52import tracemalloc53from pathlib import Path5455import pytest56from aiohttp import web5758from spider.config import Settings59from spider.contracts import ERROR_CLASSES60from spider.engine.http import HttpEngine, decode_body, parse_retry_after, sniff_mime61from spider.netguard import NetGuard6263sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "fixtures" / "site"))64SETTINGS = Settings(env="test")656667@pytest.fixture68async def site():69 from server import start_fixture70 fx = await start_fixture()71 try:72 yield fx73 finally:74 await fx.close()757677@pytest.fixture78async def engine(site):79 eng = HttpEngine(NetGuard(test_allow=frozenset({("127.0.0.1", site.port)})), SETTINGS)80 try:81 yield eng82 finally:83 await eng.close()848586class Mini:87 """A tiny server with programmable routes and a hit counter."""8889 def __init__(self):90 self.hits: list[tuple[str, dict]] = []91 self.routes: dict[str, tuple[int, dict, bytes]] = {}92 self.port = 093 self.runner = None9495 def route(self, path, status=200, body=b"<html><body><p>ok</p></body></html>", **headers):96 self.routes[path] = (status, {"Content-Type": "text/html; charset=utf-8"} | headers, body)9798 async def _handle(self, request: web.Request) -> web.Response:99 self.hits.append((request.path, dict(request.headers)))100 status, headers, body = self.routes.get(request.path, (404, {"Content-Type": "text/plain"}, b"nope"))101 return web.Response(status=status, headers=headers, body=body)102103 def count(self, path):104 return sum(1 for p, _ in self.hits if p == path)105106 async def start(self, ssl_context=None):107 app = web.Application()108 app.router.add_route("*", "/{tail:.*}", self._handle)109 self.runner = web.AppRunner(app)110 await self.runner.setup()111 s = web.TCPSite(self.runner, "127.0.0.1", 0, ssl_context=ssl_context)112 await s.start()113 self.port = self.runner.addresses[0][1]114 self.base = f"{'https' if ssl_context else 'http'}://127.0.0.1:{self.port}"115 return self116117 def engine(self) -> HttpEngine:118 return HttpEngine(NetGuard(test_allow=frozenset({("127.0.0.1", self.port)})), SETTINGS)119120121@pytest.fixture122async def mini():123 m = await Mini().start()124 try:125 yield m126 finally:127 await m.runner.cleanup()128129130@pytest.fixture131def connects(monkeypatch):132 """Every TCP connect() issued by this process during the test (asyncio goes through socket.connect)."""133 seen = []134 real = socket.socket.connect135136 def spy(self, address):137 seen.append(address)138 return real(self, address)139 monkeypatch.setattr(socket.socket, "connect", spy)140 return seen141142143# --------------------------------------------------------------------------- bounded bodies144async def test_oversized_body_is_cut_at_the_cap(site, engine, tmp_path):145 tracemalloc.start()146 try:147 fr = await engine.fetch(site.url("/err/big"), out_dir=tmp_path, max_bytes=2_000_000) # 50 MiB served148 _, peak = tracemalloc.get_traced_memory()149 finally:150 tracemalloc.stop()151 assert not fr.ok and fr.error_class == "too_large" and "2000000" in fr.error_detail152 assert fr.body_path is None and fr.size == 0 and list(tmp_path.iterdir()) == []153 assert peak < 12_000_000, f"peak allocation {peak} bytes: the body was not streamed with a cap"154 assert ERROR_CLASSES["too_large"] is False # never retried155156157async def test_gzip_bomb_is_stopped_on_decompressed_size(site, engine, tmp_path):158 tracemalloc.start()159 try:160 fr = await engine.fetch(site.url("/err/gzip-bomb"), out_dir=tmp_path, max_bytes=3_000_000) # 100 MiB inflated161 _, peak = tracemalloc.get_traced_memory()162 finally:163 tracemalloc.stop()164 assert not fr.ok and fr.error_class == "too_large", (fr.error_class, fr.error_detail)165 assert fr.body_path is None and list(tmp_path.iterdir()) == []166 assert peak < 20_000_000, f"peak allocation {peak} bytes while inflating"167168169async def test_body_under_the_cap_is_stored_and_hashed(site, engine, tmp_path):170 import hashlib171 fr = await engine.fetch(site.url("/err/big?mb=1"), out_dir=tmp_path, max_bytes=2_000_000)172 assert fr.ok and fr.size == 1 << 20173 assert hashlib.sha256(Path(fr.body_path).read_bytes()).hexdigest() == fr.sha256174175176# --------------------------------------------------------------------------- hostile content177async def test_bad_encoding_is_decoded_with_correct_accents(site, engine, tmp_path):178 fr = await engine.fetch(site.url("/err/bad-encoding"), out_dir=tmp_path)179 assert fr.ok and fr.charset == "utf-8" # the declaration lies: the bytes are Latin-1180 text, used = decode_body(Path(fr.body_path).read_bytes(), fr.charset)181 assert "Événement à Québec : température élevée, fenêtre fermée." in text182 assert used != "utf-8" and "�" not in text183184185@pytest.mark.parametrize("raw,declared,expect_text,expect_cs", [186 ("été à Québec".encode(), "utf-8", "été à Québec", "utf-8"),187 ("été à Québec".encode("latin-1"), "utf-8", "été à Québec", "cp1252"),188 ("été à Québec".encode("latin-1"), "", "été à Québec", "cp1252"),189 ('<meta charset="iso-8859-1">été'.encode("latin-1"), "", '<meta charset="iso-8859-1">été', "iso-8859-1"),190 ("l’aube — « oui »".encode("cp1252"), "windows-1252", "l’aube — « oui »", "windows-1252"),191 ("été".encode(), "no-such-charset", "été", "utf-8"),192 (b"\xff\xfe\x00 binary \x81", "utf-8", None, "cp1252"),193 (b"", "", "", "utf-8"),194])195def test_decode_body_table(raw, declared, expect_text, expect_cs):196 text, cs = decode_body(raw, declared)197 assert cs == expect_cs198 if expect_text is not None:199 assert text == expect_text200201202async def test_wrong_mime_is_sniffed_as_html(site, engine, tmp_path):203 fr = await engine.fetch(site.url("/err/wrong-mime"), out_dir=tmp_path)204 assert fr.ok and fr.headers["content-type"].startswith("image/png") and fr.mime == "text/html"205206207async def test_pdf_is_sniffed_from_magic_bytes(site, engine, tmp_path):208 fr = await engine.fetch(site.url("/docs/report.pdf"), out_dir=tmp_path)209 assert fr.ok and fr.mime == "application/pdf" and Path(fr.body_path).read_bytes().startswith(b"%PDF-")210211212@pytest.mark.parametrize("body,declared,expected", [213 (b"%PDF-1.7\n...", "text/html", "application/pdf"),214 (b"\x89PNG\r\n\x1a\n....", "text/html", "image/png"),215 (b"<!DOCTYPE html><html>", "image/png", "text/html"),216 (b" \n<html lang=fr>", "application/octet-stream", "text/html"),217 (b"RIFF\x00\x00\x00\x00WEBPVP8 ", "", "image/webp"),218 (b"RIFF\x00\x00\x00\x00WAVEfmt ", "audio/wav", "audio/wav"),219 (b'<?xml version="1.0"?><urlset>', "text/plain", "application/xml"),220 (b'{"a": 1}', "application/json", "application/json"),221 (b'{"a": 1}', "text/plain", "text/plain"),222 (b"\x00\x01\x02", "", "application/octet-stream"),223])224def test_sniff_mime_table(body, declared, expected):225 assert sniff_mime(body, declared) == expected226227228async def test_truncated_body_is_handled_and_flagged(site, engine, tmp_path):229 fr = await engine.fetch(site.url("/err/truncated"), out_dir=tmp_path)230 assert fr.error_class in (None, "invalid_content")231 if fr.ok: # what arrived is kept, and the truncation is said232 assert 0 < fr.size < 4096 and fr.error_detail.startswith("truncated payload")233 assert Path(fr.body_path).stat().st_size == fr.size234235236# --------------------------------------------------------------------------- redirects237async def test_redirect_chain_is_followed_with_each_hop_recorded(site, engine, tmp_path):238 fr = await engine.fetch(site.url("/r/1"), out_dir=tmp_path)239 assert fr.ok and fr.final_url == site.url("/landing") and fr.url == site.url("/r/1")240 assert [(r["from"], r["to"], r["status"]) for r in fr.redirects] == [241 (site.url("/r/1"), site.url("/r/2"), 301), (site.url("/r/2"), site.url("/r/3"), 302),242 (site.url("/r/3"), site.url("/landing"), 307)]243 assert [q.path for q in site.state.requests if q.path != "/robots.txt"] == ["/r/1", "/r/2", "/r/3", "/landing"]244245246async def test_redirect_loop_is_detected(site, engine, tmp_path):247 fr = await engine.fetch(site.url("/loop/a"), out_dir=tmp_path)248 assert not fr.ok and fr.error_class == "redirect_loop"249 assert site.state.hits("/loop/a") + site.state.hits("/loop/b") <= 3250 assert ERROR_CLASSES["redirect_loop"] is False251252253@pytest.mark.parametrize("path,target", [("/r/internal", ("127.0.0.2", 9)), ("/r/metadata", ("169.254.169.254", 80))])254async def test_redirect_to_private_address_is_ssrf_with_no_connection(site, engine, tmp_path, connects, path, target):255 fr = await engine.fetch(site.url(path), out_dir=tmp_path)256 assert not fr.ok and fr.error_class == "ssrf", (fr.error_class, fr.error_detail)257 assert fr.redirects and fr.redirects[0]["to"].startswith(f"http://{target[0]}")258 assert connects, "the spy saw no connection at all"259 assert {a[:2] for a in connects} == {("127.0.0.1", site.port)}, connects260 assert engine.guard.blocked_log and ERROR_CLASSES["ssrf"] is False261262263async def test_redirect_to_an_unlisted_loopback_listener_never_connects(mini, tmp_path):264 victim = socket.socket()265 victim.bind(("127.0.0.1", 0))266 victim.listen(5)267 victim.setblocking(False)268 vport = victim.getsockname()[1]269 mini.route("/robots.txt", 404)270 mini.route("/go", 302, b"", Location=f"http://127.0.0.1:{vport}/admin")271 mini.route("/file", 302, b"", Location="file:///etc/passwd")272 mini.route("/creds", 302, b"", Location=f"http://user:pw@127.0.0.1:{mini.port}/ok")273 eng = mini.engine()274 try:275 fr = await eng.fetch(mini.base + "/go", out_dir=tmp_path)276 assert fr.error_class == "ssrf"277 with pytest.raises(BlockingIOError):278 victim.accept()279 assert (await eng.fetch(mini.base + "/file", out_dir=tmp_path)).error_class == "ssrf"280 assert (await eng.fetch(mini.base + "/creds", out_dir=tmp_path)).error_class == "ssrf"281 assert (await eng.fetch(f"http://127.0.0.1:{vport}/direct", out_dir=tmp_path)).error_class == "ssrf"282 with pytest.raises(BlockingIOError):283 victim.accept()284 finally:285 await eng.close()286 victim.close()287288289async def test_redirect_out_of_scope_is_a_policy_refusal(site, engine, tmp_path, connects):290 fr = await engine.fetch(site.url("/r/external"), out_dir=tmp_path, in_scope=lambda u: u.startswith(site.base_url))291 assert not fr.ok and fr.error_class == "policy" and "external.invalid" in fr.error_detail292 assert {a[:2] for a in connects} == {("127.0.0.1", site.port)}293 assert ERROR_CLASSES["policy"] is False294295296# --------------------------------------------------------------------------- errors and timeouts297async def test_slow_response_times_out(site, engine, tmp_path):298 import time299 t0 = time.monotonic()300 fr = await engine.fetch(site.url("/err/slow?ms=5000"), out_dir=tmp_path, total_timeout=1.0)301 assert not fr.ok and fr.error_class == "timeout"302 assert time.monotonic() - t0 < 4.5 # well before the 5 s the server would take303 assert ERROR_CLASSES["timeout"] is True304305306@pytest.mark.parametrize("path,cls,status,retryable", [307 ("/err/404", "http_404", 404, False), ("/err/410", "http_404", 410, False),308 ("/err/403", "access_denied", 403, False), ("/err/500", "http_5xx", 500, True),309 ("/err/429", "http_429", 429, True),310])311async def test_http_errors_are_classified(site, engine, tmp_path, path, cls, status, retryable):312 fr = await engine.fetch(site.url(path), out_dir=tmp_path)313 assert (fr.ok, fr.error_class, fr.status) == (False, cls, status)314 assert ERROR_CLASSES[cls] is retryable315 if status == 429:316 assert fr.retry_after_s == 1.0317 assert site.state.hits(path) == 1 # the engine itself never retries318319320def test_parse_retry_after():321 assert parse_retry_after("7") == 7.0 and parse_retry_after(None) is None and parse_retry_after("soon") is None322 assert parse_retry_after("999999") == 3600.0 and parse_retry_after("-5") == 0.0323 assert parse_retry_after("Wed, 21 Oct 2015 07:28:00 GMT") == 0.0 # a date in the past324325326@pytest.mark.parametrize("path,kw,header,value", [327 ("/cond/etag", {"etag": '"fixture-etag-v1"'}, "If-None-Match", '"fixture-etag-v1"'),328 ("/cond/lastmod", {"last_modified": "Wed, 02 Dec 2026 12:00:00 GMT"}, "If-Modified-Since",329 "Wed, 02 Dec 2026 12:00:00 GMT"),330])331async def test_conditional_request_yields_not_modified(site, engine, tmp_path, path, kw, header, value):332 first = await engine.fetch(site.url(path), out_dir=tmp_path)333 assert first.ok and not first.not_modified and (first.etag or first.last_modified) == value334 fr = await engine.fetch(site.url(path), out_dir=tmp_path, **kw)335 assert fr.ok and fr.not_modified and fr.status == 304 and fr.body_path is None336 reqs = [q for q in site.state.requests if q.path == path]337 assert header not in reqs[0].headers and reqs[1].headers[header] == value338339340# --------------------------------------------------------------------------- robots341async def test_robots_disallowed_url_is_never_requested(site, engine, tmp_path):342 for p in ("/private/secret", "/no-spider/page", "/__fixture/requests"):343 fr = await engine.fetch(site.url(p), out_dir=tmp_path)344 assert not fr.ok and fr.error_class == "robots", p345 assert site.state.hits(p) == 0346 assert ERROR_CLASSES["robots"] is False347348349@pytest.mark.parametrize("status", [500, 503, 429])350async def test_unreachable_robots_means_host_disallowed(mini, tmp_path, status):351 mini.route("/robots.txt", status, b"oops")352 mini.route("/page")353 eng = mini.engine()354 try:355 for _ in range(3):356 fr = await eng.fetch(mini.base + "/page", out_dir=tmp_path)357 assert not fr.ok and fr.error_class == "robots" and f"http_{status}" in fr.error_detail358 assert mini.count("/page") == 0, "a page was fetched although robots.txt could not be read"359 assert mini.count("/robots.txt") == 1360 rb = await eng.robots_for(mini.base + "/page")361 assert rb.disallow_all362 finally:363 await eng.close()364365366async def test_robots_connection_refused_means_host_disallowed(tmp_path):367 s = socket.socket()368 s.bind(("127.0.0.1", 0))369 port = s.getsockname()[1]370 s.close() # nothing listens there any more371 eng = HttpEngine(NetGuard(test_allow=frozenset({("127.0.0.1", port)})), SETTINGS)372 try:373 fr = await eng.fetch(f"http://127.0.0.1:{port}/page", out_dir=tmp_path)374 assert not fr.ok and fr.error_class == "robots" and "unreachable" in fr.error_detail375 finally:376 await eng.close()377378379async def test_absent_robots_allows_and_is_fetched_once_per_host(mini, tmp_path):380 import asyncio381 mini.route("/robots.txt", 404)382 for i in range(6):383 mini.route(f"/p{i}")384 eng = mini.engine()385 try:386 res = await asyncio.gather(*(eng.fetch(f"{mini.base}/p{i}", out_dir=tmp_path / str(i)) for i in range(6)))387 assert all(r.ok for r in res)388 assert mini.count("/robots.txt") == 1, "robots.txt fetched per URL instead of once per host"389 uas = {h.get("User-Agent", "") for _, h in mini.hits}390 assert len(uas) == 1 and next(iter(uas)).startswith("SpiderBot/") and "+https://" in next(iter(uas))391 finally:392 await eng.close()393394395async def test_crawl_delay_and_redirect_into_disallowed_path(mini, tmp_path):396 mini.route("/robots.txt", 200, b"User-agent: *\nCrawl-delay: 1\n\nUser-agent: SpiderBot\nCrawl-delay: 7\n"397 b"Disallow: /private/\n", **{"Content-Type": "text/plain"})398 mini.route("/go", 302, b"", Location="/private/x")399 mini.route("/private/x")400 eng = mini.engine()401 try:402 rb = await eng.robots_for(mini.base + "/anything")403 assert rb.crawl_delay("SpiderBot") == 7.0 and rb.crawl_delay("OtherBot") == 1.0404 fr = await eng.fetch(mini.base + "/go", out_dir=tmp_path)405 assert fr.error_class == "robots" and mini.count("/private/x") == 0 # each hop is checked406 finally:407 await eng.close()408409410# --------------------------------------------------------------------------- TLS411@pytest.fixture412def self_signed(tmp_path):413 if not shutil.which("openssl"):414 pytest.skip("openssl is not installed: cannot generate a self-signed certificate")415 key, crt = tmp_path / "key.pem", tmp_path / "crt.pem"416 r = subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", str(key), "-out", str(crt),417 "-days", "1", "-subj", "/CN=127.0.0.1", "-addext", "subjectAltName=IP:127.0.0.1"],418 capture_output=True, timeout=60, check=False)419 if r.returncode != 0:420 pytest.skip(f"openssl could not generate a certificate: {r.stderr.decode()[:200]}")421 ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)422 ctx.load_cert_chain(str(crt), str(key))423 return ctx424425426async def test_self_signed_certificate_is_a_tls_error_and_never_ignored(self_signed, tmp_path):427 m = Mini()428 m.route("/robots.txt", 404)429 m.route("/secret", body=b"<html><body>behind an untrusted certificate</body></html>")430 await m.start(ssl_context=self_signed)431 eng = m.engine()432 try:433 fr = await eng.fetch(m.base + "/secret", out_dir=tmp_path / "a")434 assert not fr.ok and fr.error_class == "tls", (fr.error_class, fr.error_detail)435 direct = await eng.fetch(m.base + "/secret", out_dir=tmp_path / "b", check_robots=False)436 assert not direct.ok and direct.error_class == "tls", (direct.error_class, direct.error_detail)437 assert m.hits == [], "a request went through although the certificate is not trusted"438 assert fr.body_path is None and ERROR_CLASSES["tls"] is False439 finally:440 await eng.close()441 await m.runner.cleanup()442