Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER — Universal Web Intelligence Engine7# File : tests/integration/test_politeness_denials.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"""Access denials are never worked around: the URL is blocked, the host may be suspended for everyone.4243The walls are simulations served by the fixture site; its request log proves what was (not) requested.44Each test starts from an empty database, so no suspension leaks from one test to the next.45"""46import asyncio4748import pytest4950pytestmark = pytest.mark.pg51HOST = "127.0.0.1"525354async def db(stack, sql, *args):55 async with stack.orch.pool.acquire() as c:56 return await c.fetch(sql, *args)575859async def submit_ordered(stack, paths: list[str]) -> str:60 """One job fetching `paths` (depth 0) in exactly this order: created_at decides between equal tasks."""61 r = await stack.client.post("/v1/crawl", json={"urls": [stack.url(p) for p in paths], "render": "http",62 "use_sitemaps": False, "budgets": {"max_depth": 0, "max_pages": 20}})63 assert r.status_code == 202, r.text64 job_id = r.json()["job_id"]65 for i, p in enumerate(paths):66 await db(stack, "update tasks set created_at = now() - make_interval(secs => $3) where job_id=$1 and "67 "payload->>'url'=$2", job_id, stack.url(p), float(100 - i))68 return job_id697071async def urls_of(stack, job_id) -> dict:72 rows = await db(stack, "select url, status, reason, http_status from urls where job_id=$1", job_id)73 return {r["url"][len(stack.site.base_url):]: dict(r) for r in rows}747576def pages(stack) -> list[str]:77 return [q.path for q in stack.site.state.requests if q.path != "/robots.txt"]787980async def host_state(stack) -> dict:81 return dict((await db(stack, "select *, extract(epoch from suspended_until - now()) as left_s from host_state "82 "where host=$1", HOST))[0])838485async def test_captcha_blocks_url_suspends_host_and_stops_every_request(stack):86 job_id = await submit_ordered(stack, ["/wall/captcha", "/about", "/legal", "/contact"])87 await stack.start_worker(concurrency=4)88 job = await stack.wait(job_id, timeout=30)89 assert job["status"] == "blocked", job90 u = await urls_of(stack, job_id)91 assert u["/wall/captcha"]["status"] == "blocked" and u["/wall/captcha"]["reason"].startswith("captcha"), u92 for p in ("/about", "/legal", "/contact"):93 assert u[p]["status"] == "blocked" and u[p]["reason"] == "host_suspended:captcha", u[p]94 await asyncio.sleep(1.0)95 assert pages(stack) == ["/wall/captcha"], "requests were sent to the host after the CAPTCHA was detected"96 assert stack.site.state.side_effects == []97 # visible to operators, with the reason98 pol = (await stack.client.get("/v1/policies")).json()99 (s,) = pol["suspended_hosts"]100 assert s["host"] == HOST and s["suspended_reason"].startswith("captcha") and s["suspension_count"] == 1101 hs = await host_state(stack)102 assert 3500 < hs["left_s"] <= 3600 and hs["in_flight"] == 0103 # never bypassed: no new job, no new monitor for that host, for anyone104 r = await stack.client.post("/v1/scrape", json={"url": stack.url("/about"), "render": "http"})105 assert r.status_code == 403 and r.json()["error"]["code"] == "source_blocked", r.text106 r = await stack.client.post("/v1/monitor", json={"name": "m", "request": {"url": stack.url("/about")}})107 assert r.status_code == 403 and r.json()["error"]["code"] == "source_blocked", r.text108 assert pages(stack) == ["/wall/captcha"]109 # the refusal page itself is kept as evidence110 (snap,) = await stack.results(job_id)111 assert snap["meta"]["refusal"] == "captcha" and {a["kind"] for a in snap["artifacts"]} == {"html"}112 ev = [e["type"] for e in await db(stack, "select type from job_events where job_id=$1 order by id", job_id)]113 assert "host.suspended" in ev and "url.blocked" in ev114115116async def test_work_queued_by_another_job_is_blocked_when_the_host_gets_suspended(stack):117 first = await submit_ordered(stack, ["/wall/captcha"])118 other = await submit_ordered(stack, ["/about", "/legal"])119 await db(stack, "update tasks set priority = 9 where job_id=$1", first)120 await stack.start_worker(concurrency=4)121 assert (await stack.wait(first, timeout=30))["status"] == "blocked"122 job = await stack.wait(other, timeout=30)123 assert job["status"] == "blocked" and job["progress"]["urls"] == {"blocked": 2}, job124 assert {u["reason"] for u in (await urls_of(stack, other)).values()} == {"host_suspended:captcha"}125 assert pages(stack) == ["/wall/captcha"]126127128async def test_suspension_duration_doubles_on_recurrence(stack):129 await stack.start_worker(concurrency=2)130 left = []131 for n in (1, 2, 3):132 job_id = await submit_ordered(stack, ["/wall/captcha"])133 assert (await stack.wait(job_id, timeout=30))["status"] == "blocked"134 hs = await host_state(stack)135 assert hs["suspension_count"] == n136 left.append(hs["left_s"])137 # the operator lifts the suspension (the counter is kept): the next offence costs twice as much138 await db(stack, "update host_state set suspended_until = null where host=$1", HOST)139 assert 3500 < left[0] <= 3600 and 7100 < left[1] <= 7200 and 14300 < left[2] <= 14400, left140 assert stack.site.state.hits("/wall/captcha") == 3141142143async def test_login_wall_is_blocked_and_the_form_is_never_submitted(stack):144 await stack.start_worker(concurrency=2)145 job_id = await submit_ordered(stack, ["/wall/login"])146 job = await stack.wait(job_id, timeout=30)147 assert job["status"] == "blocked", job148 u = (await urls_of(stack, job_id))["/wall/login"]149 assert u["status"] == "blocked" and u["reason"].startswith("login_wall"), u150 assert pages(stack) == ["/wall/login", "/login"]151 assert all(q.method == "GET" for q in stack.site.state.requests)152 assert stack.site.state.side_effects == [], "a credential form was submitted"153 hs = await host_state(stack)154 assert hs["suspended_until"] is None and hs["consecutive_denied"] == 1 # one wall is not yet a suspension155156157async def test_paywall_is_blocked_and_not_worked_around(stack):158 await stack.start_worker(concurrency=2)159 job_id = await submit_ordered(stack, ["/wall/paywall"])160 job = await stack.wait(job_id, timeout=30)161 assert job["status"] == "blocked", job162 u = (await urls_of(stack, job_id))["/wall/paywall"]163 assert u["status"] == "blocked" and u["reason"].startswith("paywall"), u164 assert pages(stack) == ["/wall/paywall"] and stack.site.state.side_effects == []165 # the teaser is evidence of the refusal, not indexed content166 async with stack.orch.pool.acquire() as c:167 assert await c.fetchval("select count(*) from search_documents") == 0168169170async def test_http_403_is_blocked_and_fetched_once(stack):171 await stack.start_worker(concurrency=2)172 job_id = await submit_ordered(stack, ["/err/403"])173 job = await stack.wait(job_id, timeout=30)174 assert job["status"] == "blocked", job175 u = (await urls_of(stack, job_id))["/err/403"]176 assert u["status"] == "blocked" and u["http_status"] == 403 and u["reason"].startswith("access_denied"), u177 await asyncio.sleep(0.5)178 assert stack.site.state.hits("/err/403") == 1179 r = await stack.client.post(f"/v1/jobs/{job_id}/retry")180 assert r.status_code == 409 and r.json()["error"]["code"] == "nothing_to_retry" # blocked is never retried181182183async def test_three_consecutive_denials_suspend_the_host(stack):184 job_id = await submit_ordered(stack, ["/wall/login", "/wall/paywall", "/err/403", "/about", "/legal"])185 await stack.start_worker(concurrency=4)186 job = await stack.wait(job_id, timeout=30)187 assert job["status"] == "blocked", job188 u = await urls_of(stack, job_id)189 assert [u[p]["reason"].split(":")[0] for p in ("/wall/login", "/wall/paywall", "/err/403")] == \190 ["login_wall", "paywall", "access_denied"]191 assert u["/about"]["reason"] == u["/legal"]["reason"] == "host_suspended:access_denied"192 assert pages(stack) == ["/wall/login", "/login", "/wall/paywall", "/err/403"]193 hs = await host_state(stack)194 assert hs["suspension_count"] == 1 and 3500 < hs["left_s"] <= 3600195196197async def test_a_success_between_denials_resets_the_counter(stack):198 job_id = await submit_ordered(stack, ["/wall/login", "/wall/paywall", "/about", "/err/403", "/legal"])199 await stack.start_worker(concurrency=4)200 job = await stack.wait(job_id, timeout=30)201 assert job["status"] == "partial" and job["progress"]["urls"] == {"blocked": 3, "fetched": 2}, job202 hs = await host_state(stack)203 assert hs["suspended_until"] is None and hs["suspension_count"] == 0 and hs["consecutive_denied"] == 0204