An open source, non-profit web search engine
Let the remote index client say what it is and where it points
Daoud Clarke63cd5a624609
diff --git a/mwmbl/crawl.py b/mwmbl/crawl.pyindex a65691a..82a1421 100644--- a/mwmbl/crawl.py+++ b/mwmbl/crawl.py@@ -36,6 +36,7 @@ from mwmbl.crawler.env_vars import (CRAWLER_WORKERS,MWMBL_API_KEY,MWMBL_CONTACT_INFO,+ MWMBL_REMOTE_SERVER,SUBMIT_MODE_DRY_RUN,SUBMIT_MODE_OFF,)@@ -49,7 +50,10 @@ from mwmbl.tinysearchengine.rank import score_resultfrom mwmbl.tokenizer import tokenizeBATCH_QUEUE_KEY = "batch-queue"-REMOTE_SERVER = "https://api.mwmbl.org"+# Reads (RemoteIndex) and writes (results, curated domains) have to agree about which+# deployment they are talking to, or pointing a crawler at beta would send it there for half+# its traffic and to production for the other half.+REMOTE_SERVER = MWMBL_REMOTE_SERVER_curated_domains_cache: set[str] = set()_curated_domains_fetched_at: float = 0.0diff --git a/mwmbl/crawler/env_vars.py b/mwmbl/crawler/env_vars.pyindex a73548f..a806729 100644--- a/mwmbl/crawler/env_vars.py+++ b/mwmbl/crawler/env_vars.py@@ -42,3 +42,9 @@ SUBMIT_MODES = {SUBMIT_MODE_INDEX, SUBMIT_MODE_DRY_RUN, SUBMIT_MODE_OFF}CRAWL_SUBMIT_MODE = os.environ.get("CRAWL_SUBMIT_MODE", SUBMIT_MODE_INDEX)if CRAWL_SUBMIT_MODE not in SUBMIT_MODES:raise ValueError(f"CRAWL_SUBMIT_MODE must be one of {sorted(SUBMIT_MODES)}, got {CRAWL_SUBMIT_MODE!r}")++# Where the crawler reads the main index from and submits its results to. Hardcoded to+# production until now, in two places, which is also what every rankeval script gets when it+# constructs RemoteIndex() with no argument - so an evaluation sweep aimed itself at+# api.mwmbl.org by default. Beta exists precisely so that it does not have to.+MWMBL_REMOTE_SERVER = os.environ.get("MWMBL_REMOTE_SERVER", "https://api.mwmbl.org")diff --git a/mwmbl/rankeval/evaluation/remote_index.py b/mwmbl/rankeval/evaluation/remote_index.pyindex 7aa05ed..626eee6 100644--- a/mwmbl/rankeval/evaluation/remote_index.py+++ b/mwmbl/rankeval/evaluation/remote_index.py@@ -7,14 +7,25 @@ from logging import getLoggerimport requests+from mwmbl.crawler.env_vars import MWMBL_REMOTE_SERVERfrom mwmbl.tinysearchengine.indexer import Documentfrom mwmbl.utils import request_cachelogger = getLogger(__name__)+# This client names itself, for the same reason the crawler names itself when it fetches+# somebody else's site: whoever reads the logs should be able to tell what a request is and+# who to talk to about it. Without a User-Agent these arrive as python-requests/x.y.z, which+# is indistinguishable from any other script - and since crawl.run_indexing calls this once+# per term on every indexing pass, that is a large and permanently anonymous share of+# api.mwmbl.org's traffic. Version it separately from CRAWLER_VERSION: importing that would+# pull justext and the SSRF guard into every rankeval script for the sake of a string.+REMOTE_INDEX_VERSION = "0.1.0"+USER_AGENT = f"mwmbl-remote-index/{REMOTE_INDEX_VERSION} (+https://github.com/mwmbl/mwmbl)"+class RemoteIndex:- def __init__(self, remote_server: str = "https://api.mwmbl.org"):+ def __init__(self, remote_server: str = MWMBL_REMOTE_SERVER):self.remote_server = remote_serverself.url = f"{remote_server}/api/v1/search/raw?s="@@ -22,6 +33,7 @@ class RemoteIndex:url = self.url + queryresponse = Nonewith request_cache() as session:+ session.headers["User-Agent"] = USER_AGENTfor i in range(3):try:response = session.get(url, timeout=15, force_refresh=refresh)diff --git a/test/test_remote_index.py b/test/test_remote_index.pynew file mode 100644index 0000000..c5155b3--- /dev/null+++ b/test/test_remote_index.py@@ -0,0 +1,62 @@+"""The client the crawler's index sync and every rankeval script use to read the main index.++Two things are pinned here, both of which were true of api.mwmbl.org's traffic before they+were fixed. It sends a User-Agent that names it, so that its share of the API's traffic is+attributable rather than arriving as an anonymous python-requests. And the server it talks+to comes from the environment, so that an evaluation sweep is not aimed at production by+the mere fact of calling RemoteIndex() with no argument.+"""++import importlib+from unittest.mock import MagicMock, patch++from mwmbl.rankeval.evaluation.remote_index import USER_AGENT, RemoteIndex+++def _session_returning(payload):+ """A request_cache() stand-in: a context manager yielding a session that returns payload."""+ session = MagicMock()+ session.headers = {}+ session.get.return_value = MagicMock(json=MagicMock(return_value=payload))+ cache = MagicMock()+ cache.__enter__ = MagicMock(return_value=session)+ cache.__exit__ = MagicMock(return_value=False)+ return cache, session+++def test_retrieve_identifies_itself():+ cache, session = _session_returning({"results": []})+ with patch("mwmbl.rankeval.evaluation.remote_index.request_cache", return_value=cache):+ RemoteIndex().retrieve("python tutorial")++ assert session.headers["User-Agent"] == USER_AGENT+++def test_user_agent_names_the_project_and_a_way_to_find_it():+ assert USER_AGENT.startswith("mwmbl-remote-index/")+ assert "github.com/mwmbl/mwmbl" in USER_AGENT+++def test_retrieve_reads_the_raw_endpoint_on_the_configured_server():+ cache, session = _session_returning({"results": []})+ with patch("mwmbl.rankeval.evaluation.remote_index.request_cache", return_value=cache):+ RemoteIndex("https://beta.mwmbl.org").retrieve("cat")++ url = session.get.call_args[0][0]+ assert url == "https://beta.mwmbl.org/api/v1/search/raw?s=cat"+++def test_default_server_comes_from_the_environment():+ with patch.dict("os.environ", {"MWMBL_REMOTE_SERVER": "https://beta.mwmbl.org"}):+ env_vars = importlib.reload(importlib.import_module("mwmbl.crawler.env_vars"))+ assert env_vars.MWMBL_REMOTE_SERVER == "https://beta.mwmbl.org"++ # Restore the module for anything importing it later in the session.+ importlib.reload(importlib.import_module("mwmbl.crawler.env_vars"))+++def test_default_server_is_production_when_unset():+ import mwmbl.crawler.env_vars as env_vars++ assert env_vars.MWMBL_REMOTE_SERVER == "https://api.mwmbl.org"+ assert RemoteIndex().remote_server == "https://api.mwmbl.org"