An open source, non-profit web search engine
Stop publishing the crawler's hostname and API key
Daoud Clarke8cb876e7e195
diff --git a/mwmbl/crawl.py b/mwmbl/crawl.pyindex f4c9d3d..6803be1 100644--- a/mwmbl/crawl.py+++ b/mwmbl/crawl.py@@ -1,7 +1,6 @@import argparseimport loggingimport os-import platformimport randomimport timefrom datetime import datetime, timedelta, timezone@@ -31,6 +30,7 @@ print("Mwmbl crawling statistics: https://mwmbl.org/stats")django.setup()from mwmbl.crawler.batch import HashedBatch, Result, Results+from mwmbl.crawler.device import get_device_namefrom mwmbl.crawler.env_vars import (CRAWL_DELAY_SECONDS,CRAWL_SUBMIT_MODE,@@ -294,7 +294,7 @@ class Crawler:api_key=MWMBL_API_KEY,results=result_items,crawler_version=CRAWLER_VERSION,- device_name=platform.uname().node,+ device_name=get_device_name(data_path),)results_url = f"{REMOTE_SERVER}/api/v1/crawler/results"if CRAWL_SUBMIT_MODE == SUBMIT_MODE_DRY_RUN:diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.pyindex dfb107b..b9d8926 100644--- a/mwmbl/crawler/app.py+++ b/mwmbl/crawler/app.py@@ -266,7 +266,10 @@ def _register_routes(r: Router | NinjaAPI):index_path = f"{settings.DATA_PATH}/{settings.INDEX_NAME}"index_documents(documents, index_path)- filename = upload_object(results, now, api_key.user.username, "results")+ # Without api_key: the bucket is world-readable (get_batch_from_id fetches from it+ # with a plain unauthenticated GET), so uploading the object as submitted would+ # publish the plaintext key of any client still using the deprecated body field.+ filename = upload_object(results.model_copy(update={"api_key": None}), now, api_key.user.username, "results")# Update stats for the userstats_manager.record_results(results, api_key.user.username)diff --git a/mwmbl/crawler/device.py b/mwmbl/crawler/device.pynew file mode 100644index 0000000..0857bd2--- /dev/null+++ b/mwmbl/crawler/device.py@@ -0,0 +1,33 @@+"""The name a crawler reports itself as in its owner's device list."""++import secrets+from pathlib import Path++from mwmbl.crawler.env_vars import MWMBL_DEVICE_NAME++DEVICE_NAME_FILE = "device-name"+++def get_device_name(data_path: Path) -> str:+ """Return this crawler's device name, generating and storing one on first run.++ Deliberately not platform.uname().node. Every submission is uploaded to public object+ storage under a path containing the user's name, and machine hostnames routinely carry+ their owner's real name ("jane-laptop"), so reporting one publishes it.++ A random id instead: stable across restarts because it is kept in the data directory,+ and meaningless to anyone but its owner. Set MWMBL_DEVICE_NAME to choose your own -+ worth doing if you run several crawlers and want to tell them apart in the UI.+ """+ if MWMBL_DEVICE_NAME:+ return MWMBL_DEVICE_NAME++ path = data_path / DEVICE_NAME_FILE+ if path.exists():+ stored = path.read_text().strip()+ if stored:+ return stored++ name = f"crawler-{secrets.token_hex(4)}"+ path.write_text(name)+ return namediff --git a/mwmbl/crawler/env_vars.py b/mwmbl/crawler/env_vars.pyindex a73548f..f5adeda 100644--- a/mwmbl/crawler/env_vars.py+++ b/mwmbl/crawler/env_vars.py@@ -17,6 +17,11 @@ MWMBL_API_KEY = os.environ.get("MWMBL_API_KEY", "")# Contact information configuration - required for responsible crawlingMWMBL_CONTACT_INFO = os.environ.get("MWMBL_CONTACT_INFO", "[email protected]")+# Name this crawler reports itself as, so its owner can tell their crawlers apart in the+# devices list. Left unset, a random id is generated on first run and kept in the data+# directory - see mwmbl.crawler.device. The machine hostname is deliberately never used.+MWMBL_DEVICE_NAME = os.environ.get("MWMBL_DEVICE_NAME", "")+# Bounds for running the crawler somewhere that is not a volunteer's machine - CI, mainly.# The defaults are the unbounded behaviour a volunteer crawler has always had.diff --git a/test/test_batches_endpoint_removed.py b/test/test_batches_endpoint_removed.pyindex d161119..d147cee 100644--- a/test/test_batches_endpoint_removed.py+++ b/test/test_batches_endpoint_removed.py@@ -198,3 +198,23 @@ def test_devices_per_user_are_capped(crawl_user):assert Device.objects.filter(user=crawl_user).count() == MAX_DEVICES_PER_USER# The most recent survive; the least recently seen are the ones dropped.assert Device.objects.filter(user=crawl_user, hostname=f"device-{MAX_DEVICES_PER_USER + 9}").exists()+++def test_the_api_key_is_stripped_from_the_uploaded_object(api_client, crawl_api_key, crawl_user):+ """The results bucket is world-readable, so a key passed in the deprecated body field+ must not be uploaded with the rest of the submission."""+ with (+ patch("mwmbl.crawler.app.index_documents"),+ patch("mwmbl.crawler.app.upload_object", return_value="fake/path.json.gz") as upload_object,+ patch("mwmbl.crawler.app.stats_manager"),+ ):+ response = api_client.post(+ "/api/v1/crawler/results",+ content_type="application/json",+ data={"results": [], "api_key": crawl_api_key.raw_key},+ )++ assert response.status_code == 200+ uploaded = upload_object.call_args.args[0]+ assert uploaded.api_key is Nonediff --git a/test/test_crawler_device_name.py b/test/test_crawler_device_name.pynew file mode 100644index 0000000..c27487a--- /dev/null+++ b/test/test_crawler_device_name.py@@ -0,0 +1,45 @@+"""+The crawler's self-reported device name.++Submissions are uploaded to world-readable object storage, so the name must not be the+machine hostname - see mwmbl.crawler.device.+"""++from pathlib import Path+from unittest.mock import patch++from mwmbl.crawler.device import DEVICE_NAME_FILE, get_device_name+++def test_the_configured_name_wins(tmp_path: Path):+ with patch("mwmbl.crawler.device.MWMBL_DEVICE_NAME", "my-crawler"):+ assert get_device_name(tmp_path) == "my-crawler"+ assert not (tmp_path / DEVICE_NAME_FILE).exists()+++def test_a_generated_name_is_stable_across_runs(tmp_path: Path):+ with patch("mwmbl.crawler.device.MWMBL_DEVICE_NAME", ""):+ first = get_device_name(tmp_path)+ second = get_device_name(tmp_path)++ assert first == second+ assert first.startswith("crawler-")+ assert (tmp_path / DEVICE_NAME_FILE).read_text() == first+++def test_the_generated_name_does_not_leak_the_hostname(tmp_path: Path):+ import platform++ with patch("mwmbl.crawler.device.MWMBL_DEVICE_NAME", ""):+ name = get_device_name(tmp_path)++ assert platform.uname().node not in name+++def test_an_empty_stored_name_is_replaced(tmp_path: Path):+ (tmp_path / DEVICE_NAME_FILE).write_text(" \n")++ with patch("mwmbl.crawler.device.MWMBL_DEVICE_NAME", ""):+ name = get_device_name(tmp_path)++ assert name.startswith("crawler-")