An open source, non-profit web search engine
Merge main into claude/remote-index-identify
Claude5d9bf838d8b7
diff --cc mwmbl/crawl.pyindex 512704c,37e640a..df63118--- a/mwmbl/crawl.py+++ b/mwmbl/crawl.py@@@ -42,33 -52,17 +55,33 @@@ from mwmbl.crawler.env_vars importSUBMIT_MODE_DRY_RUN,SUBMIT_MODE_OFF,)- from mwmbl.crawler.retrieve import CRAWLER_VERSION, crawl_url-from mwmbl.crawler.retrieve import CRAWLER_VERSION, USER_AGENT, crawl_batch++from mwmbl.crawler.retrieve import CRAWLER_VERSION, crawl_batchfrom mwmbl.indexer.index_batches import index_batches, index_pagesfrom mwmbl.indexer.update_urls import record_urls_in_databasefrom mwmbl.rankeval.evaluation.remote_index import RemoteIndexfrom mwmbl.redis_url_queue import RedisURLQueuefrom mwmbl.tinysearchengine.indexer import Document, TinyIndexfrom mwmbl.tinysearchengine.rank import score_result- from mwmbl.tokenizer import tokenize+ from mwmbl.utils import prune_request_cacheBATCH_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++# How the crawler names itself to our own API, most of which is the index sync: one raw search+# per term, for the top hundred terms of every indexing pass. The version is there so that+# crawlers running old code can be told apart and asked to upgrade; the username is the+# account's public name, looked up from the API key, so that a crawler causing trouble can be+# traced to an account without its operator's email address ending up in the API's logs and+# user agent counters. The contact address stays in USER_AGENT, which goes only to the+# third-party sites being crawled.+API_PRODUCT = f"mwmbl-crawler/{CRAWLER_VERSION}"+PROJECT_URL = "https://github.com/mwmbl/mwmbl"+USER_URL = f"{REMOTE_SERVER}/api/v1/platform/user"++_username: Optional[str] = None_curated_domains_cache: set[str] = set()_curated_domains_fetched_at: float = 0.0@@@ -100,36 -105,79 +124,109 @@@ def _fetch_curated_domains() -> set[strreturn _curated_domains_cache+def _fetch_username() -> Optional[str]:+ """The public username MWMBL_API_KEY belongs to, or None if it cannot be found out.++ Remembered once found, per process. Not remembered when it fails, so a crawler that started+ while the API was unreachable, or before the API accepted keys here, names itself on a+ later pass - that is one request per indexing pass beside the hundred it already makes.+ """+ global _username+ if _username is not None or not MWMBL_API_KEY:+ return _username+ try:+ response = requests.get(+ USER_URL,+ timeout=10,+ headers={"User-Agent": api_user_agent(None), "X-API-Key": MWMBL_API_KEY},+ )+ response.raise_for_status()+ _username = response.json()["username"]+ logger.info(f"Identifying to the index as user {_username}")+ except requests.RequestException:+ logger.warning("Could not look up the username for MWMBL_API_KEY; requests to the API will not include it")+ return _username+++def api_user_agent(username: Optional[str]) -> str:+ # Django allows non-ASCII letters in a username, and a header value has to be latin-1.+ identity = f"+{PROJECT_URL}; user {quote(username, safe='@.+-_')}" if username else f"+{PROJECT_URL}"+ return f"{API_PRODUCT} ({identity})"+++ # How long to wait before reporting the same error from the same process again. The loops+ # retry every ten seconds, so a persistent failure would otherwise send a report each time.+ ERROR_REPORT_INTERVAL_SECONDS = 3600.0+ _error_last_reported_at: dict[tuple[ErrorContext, str, str, int | None], float] = {}+++ # The server accepts at most this many frames. A traceback deeper than that is almost always+ # recursion, where the innermost frames are the ones that say what went wrong.+ MAX_ERROR_FRAMES = 200+++ def _module_path(filename: str) -> str:+ """+ The path of a source file relative to the Python path entry it was imported from.++ An absolute path names the volunteer's home directory, which often carries their name -+ the reason the crawler identifies itself by a generated device name, not its hostname.+ """+ containing_entries = [entry for entry in sys.path if entry and filename.startswith(entry.rstrip("/") + "/")]+ if not containing_entries:+ return os.path.basename(filename)+ longest_entry = max(containing_entries, key=len)+ return os.path.relpath(filename, longest_entry)+++ def report_error(context: ErrorContext, error: Exception):+ """+ Send an error the crawl loops caught to the Mwmbl server, which passes it on to Sentry.++ The loops catch everything and retry, which keeps a volunteer's crawler running but means+ a crawler failing on every pass looks, from our side, exactly like one that has stopped.+ Reporting goes through our own endpoint rather than straight to Sentry so that volunteers'+ machines only ever talk to Mwmbl, and so each report arrives tied to an API key.+ """+ if not CRAWL_REPORT_ERRORS or CRAWL_SUBMIT_MODE == SUBMIT_MODE_OFF:+ return++ frames = traceback.extract_tb(error.__traceback__)+ exception_type = f"{type(error).__module__}.{type(error).__qualname__}"+ innermost = frames[-1]+ error_key = (context, exception_type, innermost.filename, innermost.lineno)+ now = time.monotonic()+ last_reported_at = _error_last_reported_at.get(error_key)+ if last_reported_at is not None and now - last_reported_at < ERROR_REPORT_INTERVAL_SECONDS:+ return+ _error_last_reported_at[error_key] = now++ # Messages can name local files too - "No such file or directory: '/home/...'".+ message = str(error).replace(str(Path.home()), "~")[:MAX_ERROR_MESSAGE_LENGTH]+ report = CrawlerErrorReport(+ context=context,+ exception_type=exception_type,+ message=message,+ frames=[+ ErrorFrame(filename=_module_path(frame.filename), lineno=frame.lineno, function=frame.name, line=frame.line)+ for frame in frames[-MAX_ERROR_FRAMES:]+ ],+ crawler_version=CRAWLER_VERSION,+ device_name=get_device_name(data_path),+ )+ # Failing to report must not become a second error in the loop that caught the first.+ try:+ response = requests.post(+ f"{REMOTE_SERVER}/api/v1/crawler/errors",+ json=report.dict(),- headers={"X-API-Key": MWMBL_API_KEY, "User-Agent": USER_AGENT},++ headers={"X-API-Key": MWMBL_API_KEY, "User-Agent": api_user_agent(_username)},+ timeout=10,+ )+ response.raise_for_status()+ except requests.RequestException:+ logger.exception("Failed to report error to the Mwmbl server")++def count_new_index_entries(term: str, new_items: list[Document], remote_items: list[Document]) -> int:"""Estimate how many of our new local items the main index will actually keep for a term.@@@ -306,7 -356,10 +405,10 @@@ class Crawlerterm_new_doc_count = index_batches(batches, index_path)logger.info(f"Indexed, top terms to sync: {term_new_doc_count.most_common(10)}")- remote_index = RemoteIndex(user_agent=api_user_agent(_fetch_username()))+ # Once a round is often enough to keep the cache at roughly an hour's worth of terms,+ # and the rounds are minutes apart, so the sweep costs nothing worth measuring.+ prune_request_cache()- remote_index = RemoteIndex(expire_after=REMOTE_INDEX_CACHE_EXPIRY)++ remote_index = RemoteIndex(user_agent=api_user_agent(_fetch_username()), expire_after=REMOTE_INDEX_CACHE_EXPIRY)with TinyIndex(Document, index_path, "w") as local_index:for term, count in term_new_doc_count.most_common(100):logger.info(f"Syncing term {term} with {count} new local items")diff --cc mwmbl/platform/api.pyindex 76fd6c8,bee6d45..2f46035--- a/mwmbl/platform/api.py+++ b/mwmbl/platform/api.py@@@ -75,7 -92,9 +92,9 @@@ from mwmbl.platform.schemas importVoteStats,VoteStatsRequest,)+ from mwmbl.polar_webhooks import validate_event+ from mwmbl.quota import get_monthly_combined_search_api_count, get_monthly_combined_search_count-from mwmbl.search_auth import invalidate_api_key_cache, invalidate_user_api_key_cache+from mwmbl.search_auth import AccountApiKeyAuth, invalidate_api_key_cache, invalidate_user_api_key_cachefrom mwmbl.signals import schedule_blacklist_rebuildfrom mwmbl.usernames import generate_usernamefrom mwmbl.utils import normalize_domain, validate_domain@@@ -1112,14 -1189,10 +1189,14 @@@ def update_device(request, device_id: i@router.get("/user",- auth=JWTAuth(),+ auth=[JWTAuth(), AccountApiKeyAuth()],response=UserProfileResponse,summary="Get current user profile",- description="Returns the authenticated user's username, email, plan, email confirmation status, and join date.",+ description=(- "Returns the authenticated user's username, email, plan, and email confirmation status. "++ "Returns the authenticated user's username, email, plan, email confirmation status, and join date. "+ "Accepts a Bearer token or an API key of any scope in the `X-API-Key` header, so a "+ "crawler can look up the username its key belongs to."+ ),tags=["Users"],)def get_current_user(request):diff --cc mwmbl/rankeval/evaluation/remote_index.pyindex 8fad349,89f4d76..fd88b73--- a/mwmbl/rankeval/evaluation/remote_index.py+++ b/mwmbl/rankeval/evaluation/remote_index.py@@@ -13,30 -14,24 +15,43 @@@ from mwmbl.utils import request_cachlogger = 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 = MWMBL_REMOTE_SERVER, user_agent: str = USER_AGENT):- def __init__(self, remote_server: str = "https://api.mwmbl.org", expire_after: Optional[timedelta] = None):++ def __init__(++ self,++ remote_server: str = MWMBL_REMOTE_SERVER,++ user_agent: str = USER_AGENT,++ expire_after: Optional[timedelta] = None,++ ):+ """expire_after is how long a cached copy of the index's results may be reused.++ None never expires it, which is what the evaluation scripts want: they replay one+ set of queries over and over against an index that moves slowly enough not to+ matter. A caller that runs for weeks against a moving index wants a real expiry -+ see REMOTE_INDEX_CACHE_EXPIRY in crawl.py.+ """self.remote_server = remote_server+ # A caller that knows more about itself than this module does - the crawler, with its+ # version and its user's name - says so here rather than being lumped in with scripts.+ self.user_agent = user_agent+ self.expire_after = expire_afterself.url = f"{remote_server}/api/v1/search/raw?s="def retrieve(self, query: str, refresh: bool = False):url = self.url + queryresponse = None- with request_cache() as session:+ with request_cache(self.expire_after) as session:+ session.headers["User-Agent"] = self.user_agentfor i in range(3):try:response = session.get(url, timeout=15, force_refresh=refresh)diff --cc mwmbl/search_auth.pyindex 5fb9101,060873c..ba22bb7--- a/mwmbl/search_auth.py+++ b/mwmbl/search_auth.py@@@ -55,28 -62,21 +62,43 @@@ class SearchApiKeyAuth(APIKeyHeader)return api_key+ class CrawlApiKeyAuth(APIKeyHeader):+ """A crawl-scoped key in X-API-Key, for endpoints only trusted crawlers may use."""++ param_name = "X-API-Key"++ def authenticate(self, request, key: str | None):+ if not key:+ return None+ key_hash = hashlib.sha256(key.encode()).hexdigest()+ api_key = ApiKey.objects.filter(key=key_hash, scopes__contains=[ApiKey.Scope.CRAWL]).first()+ if api_key is not None:+ ApiKey.objects.filter(pk=api_key.pk).update(last_used=datetime.now(timezone.utc))+ return api_key+++class AccountApiKeyAuth(APIKeyHeader):+ """Identify the account an API key belongs to, whatever the key's scopes.++ Scopes gate what a key may do, and saying whose key it is is not one of those things: a+ crawler holds a crawl-scoped key and still needs to know its own username. Not cached,+ unlike SearchApiKeyAuth, because nothing calls this per search. Sets request.user so that+ a view written for JWTAuth works unchanged under either.+ """++ param_name = "X-API-Key"++ def authenticate(self, request, key: str | None):+ if not key:+ return None+ key_hash = hashlib.sha256(key.encode()).hexdigest()+ api_key = ApiKey.objects.select_related("user").filter(key=key_hash).first()+ if api_key is None:+ return None+ request.user = api_key.user+ return api_key.user++async def authenticate_user(request) -> MwmblUser:"""Resolve the requesting user from either an X-API-Key header or a JWT.diff --cc test/test_crawl_functional.pyindex 84de41d,87390c4..04acdde--- a/test/test_crawl_functional.py+++ b/test/test_crawl_functional.py@@@ -214,6 -215,10 +215,11 @@@ class TestCrawlFunctionalremaining_batches = fake_redis.llen("batch-queue")assert remaining_batches == 0+ # A never-expiring cache of the index's answers fills the disk:+ # see test_request_cache.py- mock_remote_index.assert_called_once_with(expire_after=REMOTE_INDEX_CACHE_EXPIRY)++ mock_remote_index.assert_called_once()++ assert mock_remote_index.call_args.kwargs["expire_after"] == REMOTE_INDEX_CACHE_EXPIRY+def test_crawl_url_functionality(self, mock_environment):"""Test individual URL crawling functionality"""mock_html_content = b"""<!DOCTYPE html>