An open source, non-profit web search engine
Fix Super Search review issues + harden crawler against SSRF
Daoud Clarkee6c9321efa91
diff --git a/mwmbl/crawler/retrieve.py b/mwmbl/crawler/retrieve.pyindex 42095e8..b7975b8 100644--- a/mwmbl/crawler/retrieve.py+++ b/mwmbl/crawler/retrieve.py@@ -12,17 +12,21 @@ from requests import ReadTimeoutfrom urllib3.exceptions import NewConnectionError, MaxRetryErrorfrom mwmbl.crawler.env_vars import MWMBL_CONTACT_INFO+from mwmbl.crawler.ssrf import UnsafeURLError, validate_urlfrom mwmbl.justext.core import html_to_domfrom mwmbl.justext.paragraph import Paragraph-ALLOWED_EXCEPTIONS = (ValueError, ConnectionError, ReadTimeout, TimeoutError,+# UnsafeURLError subclasses ValueError, so it is already covered here, but list+# it explicitly for clarity: an SSRF-blocked URL is skipped like any other bad URL.+ALLOWED_EXCEPTIONS = (ValueError, UnsafeURLError, ConnectionError, ReadTimeout, TimeoutError,OSError, NewConnectionError, MaxRetryError, SSLCertVerificationError)POST_BATCH_URL = '/api/v1/crawler/batches/'POST_NEW_BATCH_URL = '/api/v1/crawler/batches/new'TIMEOUT_SECONDS = 3+MAX_REDIRECTS = 5MAX_FETCH_SIZE = 1024*1024MAX_URL_LENGTH = 150BAD_URL_REGEX = re.compile(r'\/\/localhost\b|\.jpg$|\.png$|\.js$|\.gz$|\.zip$|\.pdf$|\.bz2$|\.ipynb$|\.py$')@@ -44,27 +48,41 @@ def fetch(url):"""Fetch with a maximum timeout and maximum fetch size to avoid big pages bringing us down.+ Redirects are followed manually so each hop can be re-validated against the+ SSRF guard: a public URL must not be able to 3xx us into an internal address.+https://stackoverflow.com/a/22347526"""- r = requests.get(url, stream=True, timeout=TIMEOUT_SECONDS, headers={"User-Agent": USER_AGENT})+ headers = {"User-Agent": USER_AGENT}+ for _ in range(MAX_REDIRECTS + 1):+ validate_url(url)+ r = requests.get(url, stream=True, timeout=TIMEOUT_SECONDS,+ headers=headers, allow_redirects=False)- size = 0- start = time.time()+ if r.is_redirect and r.next is not None:+ r.close()+ url = urljoin(url, r.headers.get("Location", ""))+ continue- content = b""- for chunk in r.iter_content(1024):- if time.time() - start > TIMEOUT_SECONDS:- raise ValueError('Timeout reached')+ size = 0+ start = time.time()- content += chunk+ content = b""+ for chunk in r.iter_content(1024):+ if time.time() - start > TIMEOUT_SECONDS:+ raise ValueError('Timeout reached')- size += len(chunk)- if size > MAX_FETCH_SIZE:- logger.debug(f"Maximum size reached for URL {url}")- break+ content += chunk++ size += len(chunk)+ if size > MAX_FETCH_SIZE:+ logger.debug(f"Maximum size reached for URL {url}")+ break++ return r.status_code, content- return r.status_code, content+ raise ValueError(f"Too many redirects for URL {url}")def robots_allowed(url):diff --git a/mwmbl/crawler/ssrf.py b/mwmbl/crawler/ssrf.pynew file mode 100644index 0000000..c418d71--- /dev/null+++ b/mwmbl/crawler/ssrf.py@@ -0,0 +1,89 @@+"""SSRF (server-side request forgery) protection for outbound URL fetches.++Any code that fetches a URL whose host is influenced by external data (crawled+pages, search-result links, user submissions) should validate it here first.+We resolve the host to its IP address(es) and refuse to fetch anything that+points at a private, loopback, link-local, reserved or otherwise internal+address — most importantly the cloud metadata endpoint (169.254.169.254).++This does not pin the connection to the resolved IP, so a small DNS-rebinding+(time-of-check/time-of-use) window remains; closing that would require custom+transport adapters and is left as a future hardening step. Callers that follow+HTTP redirects must re-validate each hop, since a public URL can 3xx to an+internal one.+"""+import ipaddress+import socket+from urllib.parse import urlparse++ALLOWED_SCHEMES = frozenset({"http", "https"})+++class UnsafeURLError(ValueError):+ """Raised when a URL resolves to an address we refuse to fetch."""+++def _ip_is_safe(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:+ """Return True only for ordinary, routable public addresses."""+ # Unwrap IPv4-mapped IPv6 (e.g. ::ffff:127.0.0.1) so the v4 checks apply.+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:+ ip = ip.ipv4_mapped+ return not (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_reserved+ or ip.is_multicast+ or ip.is_unspecified+ )+++def is_safe_host(host: str) -> bool:+ """Return True if every address ``host`` resolves to is a public address.++ ``host`` may be an IP literal or a hostname. Hostnames are resolved with+ ``getaddrinfo``; resolution failure is treated as unsafe.+ """+ if not host:+ return False++ # IP literal? Check it directly without a DNS lookup.+ try:+ return _ip_is_safe(ipaddress.ip_address(host))+ except ValueError:+ pass++ try:+ infos = socket.getaddrinfo(host, None)+ except socket.gaierror:+ return False++ addresses = {info[4][0] for info in infos}+ if not addresses:+ return False+ for addr in addresses:+ try:+ ip = ipaddress.ip_address(addr)+ except ValueError:+ return False+ if not _ip_is_safe(ip):+ return False+ return True+++def validate_url(url: str) -> None:+ """Raise :class:`UnsafeURLError` if ``url`` is not safe to fetch."""+ try:+ parsed = urlparse(url)+ except ValueError as e:+ raise UnsafeURLError(f"Could not parse URL: {url}") from e++ if parsed.scheme.lower() not in ALLOWED_SCHEMES:+ raise UnsafeURLError(f"Refusing to fetch non-http(s) URL: {url}")++ host = parsed.hostname+ if not host:+ raise UnsafeURLError(f"URL has no host: {url}")++ if not is_safe_host(host):+ raise UnsafeURLError(f"Refusing to fetch internal/private address: {url}")diff --git a/mwmbl/quota.py b/mwmbl/quota.pyindex 04799e2..a5fe140 100644--- a/mwmbl/quota.py+++ b/mwmbl/quota.py@@ -91,6 +91,20 @@ def increment_monthly_super_search(user_id: int) -> int:return cache.incr(key)+def decrement_monthly_super_search(user_id: int) -> None:+ """Refund one super-search increment (e.g. when the request is rejected over-limit).++ Never drops below 0. No-op if the counter is missing.+ """+ key = _super_search_monthly_key(user_id)+ try:+ if cache.get(key, default=0) > 0:+ cache.decr(key)+ except ValueError:+ # decr() raises if the key vanished between the get and the decr; ignore.+ pass++# ---------------------------------------------------------------------------# Key scanning (used by background jobs only — requires django-redis)# ---------------------------------------------------------------------------diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.pyindex 88775ee..10d3d45 100644--- a/mwmbl/settings_common.py+++ b/mwmbl/settings_common.py@@ -285,3 +285,4 @@ SUPER_SEARCH_MAX_CONCURRENT_PER_HOST = 4SUPER_SEARCH_MAX_LINKS_PER_PAGE = 3SUPER_SEARCH_RESULTS_PER_SOURCE = 10SUPER_SEARCH_FINAL_RESULTS_LIMIT = 100+SUPER_SEARCH_CRAWL_WORKERS = 8 # threads in the dedicated crawl pooldiff --git a/mwmbl/tinysearchengine/super_search.py b/mwmbl/tinysearchengine/super_search.pyindex a373c89..af08fdb 100644--- a/mwmbl/tinysearchengine/super_search.py+++ b/mwmbl/tinysearchengine/super_search.py@@ -14,6 +14,7 @@ See plan: /api/v2/super-search/import asyncioimport copyimport heapq+from concurrent.futures import ThreadPoolExecutorimport jsonimport loggingimport re@@ -33,7 +34,7 @@ from mwmbl.crawler.retrieve import crawl_urlfrom mwmbl.models import MwmblUserfrom mwmbl.quota import (check_rate_limit,- get_monthly_super_search_count,+ decrement_monthly_super_search,increment_monthly_super_search,)from mwmbl.search_auth import SearchApiKeyAuth@@ -54,6 +55,21 @@ _SENTINEL: object = object()_URL_EXT_RE = re.compile(r"\.\w{1,5}$")_URL_TOKEN_RE = re.compile(r"[-_+]+")+# Dedicated, bounded pool for the (synchronous, self-timeout-bounded) crawl_url+# calls. Keeping crawls off the default executor stops a burst of page fetches+# from starving the threads used by score_documents / the ORM, and caps how many+# crawl threads can keep running after the pipeline deadline fires.+_CRAWL_EXECUTOR = ThreadPoolExecutor(+ max_workers=getattr(settings, "SUPER_SEARCH_CRAWL_WORKERS", 8),+ thread_name_prefix="ss-crawl",+)+++async def _crawl(url: str):+ """Run the synchronous crawl_url on the dedicated crawl executor."""+ loop = asyncio.get_running_loop()+ return await loop.run_in_executor(_CRAWL_EXECUTOR, crawl_url, url)+# ---------------------------------------------------------------------------# Event payload schemas@@ -340,14 +356,14 @@ async def _call_source(name: str, fn, client: httpx.AsyncClient, query: str, limasync def _follow_links(- parent: Document, parent_source: str, query: str, emit, all_docs: list[Document],- last_results_key: list,+ parent: Document, query: str, emit, all_docs: list[Document],+ last_results_key: list, lock: asyncio.Lock,) -> None:"""Crawl the parent URL, score its outbound links, and collect the best for final ranking."""max_links = settings.SUPER_SEARCH_MAX_LINKS_PER_PAGEtry:- result = await asyncio.to_thread(crawl_url, parent.url)+ result = await _crawl(parent.url)except Exception as e: # noqa: BLE001logger.info("crawl_url failed for %s: %s", parent.url, e)return@@ -366,7 +382,7 @@ async def _follow_links(all_docs.append(Document(title=parent_title, url=parent.url, extract=parent_extract))if not raw_links:- await _emit_final_results(query, all_docs, emit, last_results_key)+ await _emit_final_results(query, all_docs, emit, last_results_key, lock)returnterms = tokenize(query)@@ -378,7 +394,7 @@ async def _follow_links(returnfetches = await asyncio.gather(- *[asyncio.to_thread(crawl_url, d.url) for d, _ in ranked],+ *[_crawl(d.url) for d, _ in ranked],return_exceptions=True,)@@ -397,26 +413,33 @@ async def _follow_links(if doc.url and doc.title and doc.extract:all_docs.append(doc)- await _emit_final_results(query, all_docs, emit, last_results_key)+ await _emit_final_results(query, all_docs, emit, last_results_key, lock)async def _emit_final_results(- query: str, all_docs: list[Document], emit, last_results_key: list+ query: str, all_docs: list[Document], emit, last_results_key: list, lock: asyncio.Lock) -> None:terms = tokenize(query)final_limit = getattr(settings, "SUPER_SEARCH_FINAL_RESULTS_LIMIT", 100)- seen: set[str] = set()- unique: list[Document] = []- for doc in all_docs:- if doc.url and doc.title and doc.extract and doc.url not in seen:- seen.add(doc.url)- unique.append(doc)-- if terms:- unique = [doc for doc in unique if _doc_passes_term_filter(doc, terms)]+ # Serialize the score → dedup-check → emit sequence: concurrent secondary+ # tasks would otherwise both pass the dedup check before either updates the+ # key, emitting duplicate identical `results` frames and re-scoring the same+ # set in parallel.+ async with lock:+ seen: set[str] = set()+ unique: list[Document] = []+ for doc in all_docs:+ if doc.url and doc.title and doc.extract and doc.url not in seen:+ seen.add(doc.url)+ unique.append(doc)++ if terms:+ unique = [doc for doc in unique if _doc_passes_term_filter(doc, terms)]++ if not unique:+ return- if unique:final_scores = await asyncio.to_thread(score_documents, ltr_model, query, unique)ranked = sorted(zip(unique, final_scores), key=lambda x: -x[1])[:final_limit]key = tuple(doc.url for doc, _ in ranked)@@ -429,7 +452,9 @@ async def _emit_final_results())-async def _run_pipeline(query: str, emit, all_docs: list[Document], last_results_key: list) -> None:+async def _run_pipeline(+ query: str, emit, all_docs: list[Document], last_results_key: list, lock: asyncio.Lock+) -> None:per_source_limit = settings.SUPER_SEARCH_RESULTS_PER_SOURCEtop_k = getattr(settings, "SUPER_SEARCH_TOP_K", 10)limits = httpx.Limits(max_connections=20, max_keepalive_connections=10)@@ -487,10 +512,10 @@ async def _run_pipeline(query: str, emit, all_docs: list[Document], last_resultsif _maybe_promote(doc, score):await emit("result_promoted", _result_payload(doc, score, name, "direct"))secondary.append(- asyncio.create_task(_follow_links(doc, name, query, emit, all_docs, last_results_key))+ asyncio.create_task(_follow_links(doc, query, emit, all_docs, last_results_key, lock)))if all_docs:- await _emit_final_results(query, all_docs, emit, last_results_key)+ await _emit_final_results(query, all_docs, emit, last_results_key, lock)if secondary:results = await asyncio.gather(*secondary, return_exceptions=True)@@ -509,6 +534,7 @@ async def _sse_stream(query: str, monthly_usage: int, monthly_limit: int):reason = "complete"all_docs: list[Document] = []last_results_key: list = [None]+ results_lock = asyncio.Lock()async def emit(event_type: str, data: Any) -> None:await queue.put((event_type, data))@@ -517,7 +543,7 @@ async def _sse_stream(query: str, monthly_usage: int, monthly_limit: int):nonlocal reasontry:await asyncio.wait_for(- _run_pipeline(query, emit, all_docs, last_results_key),+ _run_pipeline(query, emit, all_docs, last_results_key, results_lock),timeout=settings.SUPER_SEARCH_DEADLINE_SECONDS,)except asyncio.TimeoutError:@@ -532,7 +558,7 @@ async def _sse_stream(query: str, monthly_usage: int, monthly_limit: int):finally:if reason in ("complete", "timed_out"):try:- await _emit_final_results(query, all_docs, emit, last_results_key)+ await _emit_final_results(query, all_docs, emit, last_results_key, results_lock)except Exception:logger.exception("super-search failed to emit final results")await queue.put(_SENTINEL)@@ -633,14 +659,17 @@ def init_router() -> None:raise HttpError(429, "Rate limit exceeded: maximum 5 requests per second.")monthly_limit = settings.SUPER_SEARCH_MONTHLY_LIMIT- current = await sync_to_async(get_monthly_super_search_count)(user.id)- if current >= monthly_limit:+ # Increment first, then check: this makes the quota check atomic under+ # concurrent requests (a check-then-increment would let racing requests+ # both pass). Refund the increment if the caller is over the limit.+ monthly_usage = await sync_to_async(increment_monthly_super_search)(user.id)+ if monthly_usage > monthly_limit:+ await sync_to_async(decrement_monthly_super_search)(user.id)raise HttpError(429,f"Super Search monthly quota exceeded: {monthly_limit} requests per month "- f"and you have used {current}.",+ f"and you have used {monthly_limit}.",)- monthly_usage = await sync_to_async(increment_monthly_super_search)(user.id)return StreamingHttpResponse(_sse_stream(q, monthly_usage, monthly_limit),diff --git a/mwmbl/tinysearchengine/super_search_sources/arxiv.py b/mwmbl/tinysearchengine/super_search_sources/arxiv.pyindex 7fb64cd..5410a7f 100644--- a/mwmbl/tinysearchengine/super_search_sources/arxiv.py+++ b/mwmbl/tinysearchengine/super_search_sources/arxiv.py@@ -1,8 +1,10 @@"""ArXiv search via the public Atom API."""import logging-from xml.etree import ElementTree as ET+from xml.etree.ElementTree import ParseErrorimport httpx+from defusedxml.common import DefusedXmlException+from defusedxml.ElementTree import fromstringfrom mwmbl.tinysearchengine.indexer import Document@@ -25,8 +27,8 @@ async def search(client: httpx.AsyncClient, query: str, limit: int) -> list[Docu},)response.raise_for_status()- root = ET.fromstring(response.text)- except (httpx.HTTPError, ET.ParseError) as e:+ root = fromstring(response.text)+ except (httpx.HTTPError, ParseError, DefusedXmlException) as e:logger.info("ArXiv source failed: %s", e)return []diff --git a/mwmbl/views.py b/mwmbl/views.pyindex 530bbdd..eb66caa 100644--- a/mwmbl/views.py+++ b/mwmbl/views.py@@ -23,6 +23,7 @@ from mwmbl.justext.core import html_to_dom, ParagraphMaker, classify_paragraphs,from requests.exceptions import RequestExceptionfrom mwmbl.crawler.app import stats_manager+from mwmbl.crawler.ssrf import UnsafeURLError, validate_urlfrom mwmbl.justext.utils import get_stoplistfrom mwmbl.models import Curation, FlagCuration, DomainSubmissionfrom mwmbl.search_setup import ranker, index_path@@ -138,7 +139,12 @@ def add_url(request):query = request.POST["query"]try:- response = requests.get(new_url, timeout=5)+ validate_url(new_url)+ except UnsafeURLError:+ return HttpResponseBadRequest("Refusing to fetch that URL.")++ try:+ response = requests.get(new_url, timeout=5, allow_redirects=False)except RequestException as e:return HttpResponseBadRequest(f"Could not fetch URL: {str(e)}")diff --git a/pyproject.toml b/pyproject.tomlindex f759e4b..3ccf455 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -47,6 +47,7 @@ dependencies = ["django-redis>=5.4.0","polar-sdk>=0.10.0","httpx>=0.27.0",+ "defusedxml>=0.7.0",][project.optional-dependencies]diff --git a/test/test_ssrf.py b/test/test_ssrf.pynew file mode 100644index 0000000..d353db0--- /dev/null+++ b/test/test_ssrf.py@@ -0,0 +1,149 @@+"""Tests for the SSRF guard and its wiring into fetch() and add_url()."""+import socket++import pytest+from allauth.account.models import EmailAddress+from django.contrib.auth import get_user_model+from django.test import Client+from django.urls import reverse++from mwmbl.crawler import retrieve+from mwmbl.crawler.ssrf import UnsafeURLError, is_safe_host, validate_url++User = get_user_model()+++# ---------------------------------------------------------------------------+# Unit: is_safe_host / validate_url+# ---------------------------------------------------------------------------+[email protected]("host", [+ "127.0.0.1",+ "127.0.0.2",+ "0.0.0.0",+ "10.0.0.1",+ "192.168.1.1",+ "172.16.0.1",+ "169.254.169.254", # cloud metadata endpoint+ "::1",+ "::ffff:127.0.0.1", # IPv4-mapped loopback+])+def test_internal_ip_literals_are_unsafe(host):+ assert is_safe_host(host) is False+++def test_public_ip_literal_is_safe():+ assert is_safe_host("93.184.216.34") is True+++def test_localhost_resolving_to_loopback_is_unsafe(monkeypatch):+ monkeypatch.setattr(+ socket, "getaddrinfo",+ lambda *a, **k: [(socket.AF_INET, None, None, "", ("127.0.0.1", 0))],+ )+ assert is_safe_host("localhost") is False+++def test_hostname_resolving_to_private_ip_is_unsafe(monkeypatch):+ monkeypatch.setattr(+ socket, "getaddrinfo",+ lambda *a, **k: [(socket.AF_INET, None, None, "", ("10.1.2.3", 0))],+ )+ assert is_safe_host("internal.corp") is False+++def test_hostname_resolving_to_public_ip_is_safe(monkeypatch):+ monkeypatch.setattr(+ socket, "getaddrinfo",+ lambda *a, **k: [(socket.AF_INET, None, None, "", ("93.184.216.34", 0))],+ )+ assert is_safe_host("example.com") is True+++def test_resolution_failure_is_unsafe(monkeypatch):+ def boom(*a, **k):+ raise socket.gaierror("nope")+ monkeypatch.setattr(socket, "getaddrinfo", boom)+ assert is_safe_host("does-not-resolve.invalid") is False+++def test_validate_url_rejects_non_http_scheme():+ with pytest.raises(UnsafeURLError):+ validate_url("file:///etc/passwd")+ with pytest.raises(UnsafeURLError):+ validate_url("ftp://example.com/x")+++def test_validate_url_rejects_internal():+ with pytest.raises(UnsafeURLError):+ validate_url("http://127.0.0.1/admin")+++# ---------------------------------------------------------------------------+# fetch() integration+# ---------------------------------------------------------------------------++class _FakeResponse:+ def __init__(self, status_code, headers=None, is_redirect=False, body=b"hello"):+ self.status_code = status_code+ self.headers = headers or {}+ self.is_redirect = is_redirect+ self.next = object() if is_redirect else None+ self._body = body++ def iter_content(self, n):+ yield self._body++ def close(self):+ pass+++def test_fetch_blocks_internal_url_without_request(monkeypatch):+ calls = []+ monkeypatch.setattr(retrieve.requests, "get",+ lambda *a, **k: calls.append(a) or _FakeResponse(200))+ with pytest.raises(UnsafeURLError):+ retrieve.fetch("http://127.0.0.1/secret")+ assert calls == [], "requests.get must not be called for an internal URL"+++def test_fetch_blocks_redirect_to_internal(monkeypatch):+ calls = []++ def fake_get(url, **kwargs):+ calls.append(url)+ # First (public) hop redirects to an internal address.+ return _FakeResponse(301, headers={"Location": "http://127.0.0.1/"}, is_redirect=True)++ monkeypatch.setattr(retrieve.requests, "get", fake_get)+ with pytest.raises(UnsafeURLError):+ retrieve.fetch("http://93.184.216.34/start")+ assert len(calls) == 1, "must stop after the first hop, before fetching the internal redirect target"+++def test_fetch_returns_content_for_public_url(monkeypatch):+ monkeypatch.setattr(retrieve.requests, "get",+ lambda *a, **k: _FakeResponse(200, body=b"page body"))+ status, content = retrieve.fetch("http://93.184.216.34/page")+ assert status == 200+ assert content == b"page body"+++# ---------------------------------------------------------------------------+# add_url view+# ---------------------------------------------------------------------------++def test_add_url_rejects_internal_url(monkeypatch):+ user = User.objects.create_user(username="ssrfuser", email="[email protected]", password="x")+ EmailAddress.objects.create(user=user, email="[email protected]", verified=True, primary=True)++ # Fail loudly if the view ever reaches the network for an internal URL.+ def boom(*a, **k):+ raise AssertionError("requests.get must not be called for an internal URL")+ monkeypatch.setattr("mwmbl.views.requests.get", boom)++ client = Client()+ client.force_login(user)+ response = client.post(reverse("add_url"), {"new_url": "http://169.254.169.254/", "query": "x"})+ assert response.status_code == 400diff --git a/test/test_super_search.py b/test/test_super_search.pyindex 918f704..db825f4 100644--- a/test/test_super_search.py+++ b/test/test_super_search.py@@ -6,6 +6,7 @@ These tests:- Verify quota, auth, event ordering, and forbidden-symbol presence inthe orchestrator (architecture guard)."""+import asyncioimport jsonfrom pathlib import Pathfrom unittest.mock import patch@@ -323,6 +324,118 @@ def test_source_failure_emits_source_failed(client, api_key, monkeypatch):assert types[-1] == "done"+@override_settings(SUPER_SEARCH_MONTHLY_LIMIT=2)+def test_quota_increment_refunded_when_over_limit(client, api_key, monkeypatch):+ """An over-limit request is rejected and the increment is refunded, so the+ stored counter is not left permanently inflated (increment-first + refund)."""+ key = _super_search_monthly_key(api_key.user.id)+ cache.set(key, 2, timeout=3600) # already at the limit+ _stub_sources(monkeypatch, {"hn": []})++ response = client.get(+ "/api/v2/super-search/?q=python",+ HTTP_X_API_KEY=api_key.raw_key,+ )+ assert response.status_code == 429+ assert cache.get(key) == 2, "the rejected request must not leave the counter incremented"+ cache.delete(key)+++@override_settings(SUPER_SEARCH_DEADLINE_SECONDS=0.05, SUPER_SEARCH_PER_SOURCE_TIMEOUT=2.0)+def test_pipeline_deadline_times_out(client, api_key, monkeypatch):+ """When the pipeline overruns the deadline, the stream still terminates with+ a `done` event whose reason is `timed_out`."""+ cache.delete(_super_search_monthly_key(api_key.user.id))++ import mwmbl.tinysearchengine.super_search as ss++ async def slow_source(client, query, limit):+ await asyncio.sleep(0.5)+ return []++ monkeypatch.setattr(ss, "SOURCES", {"hn": slow_source})++ response = client.get(+ "/api/v2/super-search/?q=python",+ HTTP_X_API_KEY=api_key.raw_key,+ )+ events = _parse_sse(_read_stream(response))+ assert events[-1][0] == "done"+ assert events[-1][1]["reason"] == "timed_out"+++@override_settings(SUPER_SEARCH_TOP_K=2)+def test_link_following_adds_followed_docs(client, api_key, monkeypatch):+ """A promoted page is crawled, its outbound links followed, and the followed+ docs appear in the final ranking — exercises page_fetched / link_followed."""+ cache.delete(_super_search_monthly_key(api_key.user.id))+ _stub_sources(monkeypatch, {+ "hn": [Document(title="Python parent", url="https://parent.example/",+ extract="python parent text")],+ })+ _stub_scoring(monkeypatch, [0.9] + [0.0] * 20)++ def fake_crawl(url):+ if url == "https://parent.example/":+ return {"url": url, "status": 200, "content": {+ "title": "Python parent", "extract": "python parent text",+ "links": ["https://child.example/python-guide"], "extra_links": [],+ }}+ return {"url": url, "status": 200, "content": {+ "title": "Python child", "extract": "about python", "links": [], "extra_links": [],+ }}++ monkeypatch.setattr("mwmbl.tinysearchengine.super_search.crawl_url", fake_crawl)++ response = client.get(+ "/api/v2/super-search/?q=python",+ HTTP_X_API_KEY=api_key.raw_key,+ )+ assert response.status_code == 200+ events = _parse_sse(_read_stream(response))+ types = [t for t, _ in events]++ assert "page_fetched" in types+ followed = [d for t, d in events if t == "link_followed"]+ assert any(d["url"] == "https://child.example/python-guide" and d["from"] == "https://parent.example/"+ for d in followed)++ final = [d for t, d in events if t == "results"][-1]["results"]+ final_urls = {r["url"] for r in final}+ assert "https://child.example/python-guide" in final_urls+++@override_settings(SUPER_SEARCH_TOP_K=3)+def test_no_duplicate_consecutive_results_frames(client, api_key, monkeypatch):+ """The dedup guard must never emit two consecutive identical `results` frames."""+ cache.delete(_super_search_monthly_key(api_key.user.id))+ _stub_sources(monkeypatch, {+ "hn": [+ Document(title="Python one", url="https://one.example/", extract="python one"),+ Document(title="Python two", url="https://two.example/", extract="python two"),+ ],+ })+ _stub_scoring(monkeypatch, [0.9, 0.8] + [0.0] * 40)++ def fake_crawl(url):+ return {"url": url, "status": 200, "content": None}++ monkeypatch.setattr("mwmbl.tinysearchengine.super_search.crawl_url", fake_crawl)++ response = client.get(+ "/api/v2/super-search/?q=python",+ HTTP_X_API_KEY=api_key.raw_key,+ )+ events = _parse_sse(_read_stream(response))+ results_keys = [tuple(r["url"] for r in d["results"]) for t, d in events if t == "results"]+ for prev, nxt in zip(results_keys, results_keys[1:]):+ assert prev != nxt, "consecutive identical results frames must be deduplicated"++# ---------------------------------------------------------------------------# Architecture guard: no forbidden sync symbols in the orchestrator# ---------------------------------------------------------------------------diff --git a/uv.lock b/uv.lockindex 421f19e..5fd5809 100644--- a/uv.lock+++ b/uv.lock@@ -709,6 +709,7 @@ version = "0.1.0"source = { editable = "." }dependencies = [{ name = "boto3" },+ { name = "defusedxml" },{ name = "dj-database-url" },{ name = "django" },{ name = "django-allauth" },@@ -777,6 +778,7 @@ dev = [requires-dist = [{ name = "beautifulsoup4", marker = "extra == 'indexer'", specifier = "==4.10.0" },{ name = "boto3", specifier = "==1.35.99" },+ { name = "defusedxml", specifier = ">=0.7.0" },{ name = "dj-database-url", specifier = ">=2.1.0" },{ name = "django", specifier = ">=4.2.4" },{ name = "django-allauth", specifier = "==0.57.2" },