Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Refuse cookies on crawler sessions and fix allowlist seeding

Daoud Clarke21f8482e0b68
diff --git a/mwmbl/crawler/retrieve.py b/mwmbl/crawler/retrieve.py
index a86f623..bb00fa2 100644
--- a/mwmbl/crawler/retrieve.py
+++ b/mwmbl/crawler/retrieve.py
@@ -4,6 +4,7 @@ import re
import ssl
import threading
import time
+from http.cookiejar import DefaultCookiePolicy
from logging import getLogger
from multiprocessing.pool import ThreadPool
from ssl import SSLCertVerificationError
@@ -105,6 +106,10 @@ def get_session() -> requests.Session:
session = requests.Session()
# Otherwise every request scans os.environ for proxy and CA bundle settings.
session.trust_env = False
+ # The session outlives the fetch - for ever, on Super Search's long-lived executor - so
+ # a stored cookie would grow without bound and be sent on other users' fetches. An
+ # empty allowlist refuses every cookie, as a fresh requests.get per fetch did.
+ session.cookies.set_policy(DefaultCookiePolicy(allowed_domains=[]))
session.mount("https://", SharedContextAdapter())
_thread_local.session = session
return _thread_local.session
diff --git a/mwmbl/redis_url_queue.py b/mwmbl/redis_url_queue.py
index 8392c82..2acf07d 100644
--- a/mwmbl/redis_url_queue.py
+++ b/mwmbl/redis_url_queue.py
@@ -4,6 +4,7 @@ import random
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from logging import getLogger
+from random import Random
from typing import Callable
from redis import Redis
@@ -36,6 +37,10 @@ MAX_OTHER_DOMAINS = 10000
NUM_TOP_DOMAIN_URLS_TO_INCLUDE = 50
NUM_OTHER_URLS_TO_INCLUDE = 100
+# Seeded so that two CI runs with the same allowlist start from the same place. Only the
+# allowlist path uses it: forked crawl workers each get a copy, so they would seed in lockstep.
+ALLOWLIST_RANDOM = Random(1)
+
# Discount URLs crawled recently - this is the scale - currently 10 months
SCORE_TIME_CONSTANT = 60 * 60 * 24 * 30 * 10
@@ -114,6 +119,7 @@ class RedisURLQueue:
# PYTHONHASHSEED the crawler image sets.
domains = sorted(CRAWL_ALLOWED_DOMAINS)
seed_domains = sorted(CRAWL_ALLOWED_DOMAINS)
+ seed_random = ALLOWLIST_RANDOM
else:
top_scoring_domains = set(self.redis.zrange(DOMAIN_SCORE_KEY, 0, 2000, desc=True))
top_other_domains = top_scoring_domains - DOMAINS.keys()
@@ -134,20 +140,23 @@ class RedisURLQueue:
domains += list(top_other_domains)
seed_domains = list(DOMAINS.keys() | curated_domains)
+ seed_random = random
# Add a random url as the root domain of one of DOMAINS. The seed needs the same
# blacklist filter as the rest: it is a URL we are about to fetch.
seed_domains = [domain for domain in seed_domains if not self.blacklist_provider.is_domain_blacklisted(domain)]
- random_domain = random.choice(seed_domains)
+ random_domain = seed_random.choice(seed_domains)
urls = [f"https://{random_domain}/"]
# At most one URL per domain, since the batch is crawled concurrently: the samples
- # above can pick a core domain again, and the seed can repeat any of them.
+ # above can pick a core domain again, and the seed can repeat any of them. Unless the
+ # seed's domain is the only one, as with a single-domain allowlist: dropping it then
+ # would leave that domain's queued URLs never popped.
domains = [
- domain
- for domain in dict.fromkeys(domains)
- if domain != random_domain and not self.blacklist_provider.is_domain_blacklisted(domain)
+ domain for domain in dict.fromkeys(domains) if not self.blacklist_provider.is_domain_blacklisted(domain)
]
+ if domains != [random_domain]:
+ domains = [domain for domain in domains if domain != random_domain]
logger.info(f"Getting batch from domains {domains}")
# Pop the highest scoring URL from each domain
diff --git a/test/test_crawler_ci_options.py b/test/test_crawler_ci_options.py
index ba26823..0996f4b 100644
--- a/test/test_crawler_ci_options.py
+++ b/test/test_crawler_ci_options.py
@@ -107,13 +107,25 @@ def test_allowed_domains_pick_the_seed_deterministically(url_queue):
with (
patch("mwmbl.redis_url_queue.CRAWL_ALLOWED_DOMAINS", allowed),
- patch("mwmbl.redis_url_queue.random", Random(1)),
+ patch("mwmbl.redis_url_queue.ALLOWLIST_RANDOM", Random(1)),
+ # The shared generator is reseeded per forked worker, so it must not be the one used.
+ patch("mwmbl.redis_url_queue.random", Random(2)),
):
batch = url_queue.get_batch("test_user")
assert batch[0] == f"https://{expected_domain}/"
+def test_single_allowed_domain_still_pops_its_queued_urls(url_queue):
+ """The seed is the only domain, so leaving it out of the batch would strand its queue."""
+ url_queue.queue_urls([found_url("https://mwmbl.org/page")])
+
+ with patch("mwmbl.redis_url_queue.CRAWL_ALLOWED_DOMAINS", frozenset({"mwmbl.org"})):
+ batch = url_queue.get_batch("test_user")
+
+ assert batch == ["https://mwmbl.org/", "https://mwmbl.org/page"]
+
+
def test_no_allowlist_leaves_domain_selection_alone(url_queue):
"""The default path must keep sampling the live queue as before."""
url_queue.queue_urls([found_url(f"https://example{i}.com/page") for i in range(20)])
diff --git a/test/test_retrieve_concurrency.py b/test/test_retrieve_concurrency.py
index b9923c7..841cbba 100644
--- a/test/test_retrieve_concurrency.py
+++ b/test/test_retrieve_concurrency.py
@@ -5,9 +5,11 @@ concurrently with a per-thread delay.
import ssl
import threading
+from http.client import HTTPMessage
import fakeredis
import requests
+from requests.cookies import MockRequest, MockResponse
from urllib3 import HTTPSConnectionPool
from mwmbl.crawler import retrieve
@@ -110,3 +112,15 @@ def test_crawl_batch_counts_fetches_overlapping_on_a_domain(monkeypatch):
totals = redis.hgetall(retrieve.DOMAIN_OVERLAP_KEY)
assert totals == {b"fetches": b"3", b"overlapped": b"1", b"duplicate_domains": b"1"}
assert int(redis.get(retrieve.DOMAIN_IN_FLIGHT_KEY.format(domain="a.test"))) == 0
+
+
+def test_session_keeps_no_cookies():
+ """Sessions live as long as their thread, so a stored cookie would leak into later fetches."""
+ headers = HTTPMessage()
+ headers["Set-Cookie"] = "tracker=1; Path=/"
+ request = requests.Request("GET", "https://example.com/").prepare()
+ session = get_session()
+
+ session.cookies.extract_cookies(MockResponse(headers), MockRequest(request))
+
+ assert len(session.cookies) == 0