Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Lowercase domain names and clean up unnormalizable submissions

Daoud Clarkeaa1d0797e791
diff --git a/mwmbl/migrations/0032_normalize_domain_submission_names.py b/mwmbl/migrations/0032_normalize_domain_submission_names.py
index c5b1ef5..bb0a404 100644
--- a/mwmbl/migrations/0032_normalize_domain_submission_names.py
+++ b/mwmbl/migrations/0032_normalize_domain_submission_names.py
@@ -1,17 +1,31 @@
+import re
+
from django.db import migrations
-from mwmbl.utils import normalize_domain
+# Frozen copies of mwmbl.utils.parse_url/normalize_domain: a migration has to keep producing the
+# same data forever, so it must not depend on application code that is free to change.
+URL_REGEX = re.compile("^(([^:/?#]+):)?(//([^/?#]*)|///)?([^?#]*)(\\?[^#]*)?(#.*)?")
+DOMAIN_END_REGEX = re.compile(r"[/?#]")
+
+BATCH_SIZE = 1000
+
+
+def normalize_domain(domain_or_url: str) -> str:
+ netloc = URL_REGEX.match(domain_or_url).group(4)
+ if not netloc:
+ netloc = DOMAIN_END_REGEX.split(domain_or_url, maxsplit=1)[0]
+ return netloc.lower()
def normalize_names(apps, schema_editor):
DomainSubmission = apps.get_model("mwmbl", "DomainSubmission")
submissions_to_update = []
- for submission in DomainSubmission.objects.all():
+ for submission in DomainSubmission.objects.all().iterator(chunk_size=BATCH_SIZE):
normalized_name = normalize_domain(submission.name)
- if normalized_name != submission.name and normalized_name != "":
+ if normalized_name != submission.name:
submission.name = normalized_name
submissions_to_update.append(submission)
- DomainSubmission.objects.bulk_update(submissions_to_update, ["name"])
+ DomainSubmission.objects.bulk_update(submissions_to_update, ["name"], batch_size=BATCH_SIZE)
class Migration(migrations.Migration):
diff --git a/mwmbl/migrations/0033_fix_domain_submission_names.py b/mwmbl/migrations/0033_fix_domain_submission_names.py
new file mode 100644
index 0000000..445a826
--- /dev/null
+++ b/mwmbl/migrations/0033_fix_domain_submission_names.py
@@ -0,0 +1,53 @@
+import re
+
+from django.db import migrations
+
+# Frozen copies of mwmbl.utils.parse_url/normalize_domain: a migration has to keep producing the
+# same data forever, so it must not depend on application code that is free to change.
+URL_REGEX = re.compile("^(([^:/?#]+):)?(//([^/?#]*)|///)?([^?#]*)(\\?[^#]*)?(#.*)?")
+DOMAIN_END_REGEX = re.compile(r"[/?#]")
+VALID_DOMAIN_REGEX = re.compile(r"^[\w-]{1,63}(\.[\w-]{1,63})+$")
+
+BATCH_SIZE = 1000
+
+
+def normalize_domain(domain_or_url: str) -> str:
+ netloc = URL_REGEX.match(domain_or_url).group(4)
+ if not netloc:
+ netloc = DOMAIN_END_REGEX.split(domain_or_url, maxsplit=1)[0]
+ return netloc.lower()
+
+
+def fix_names(apps, schema_editor):
+ """
+ Re-run the normalisation from migration 0032, which has already been applied in production with
+ a version that neither lowercased names nor dealt with names that cannot be reduced to a domain
+ at all (e.g. "http://"). Submissions still holding such a name are deleted: there is no domain
+ to recover from them, and the submission list reverses the domain URL for every submission, so
+ a single one of them makes the whole page fail.
+ """
+ DomainSubmission = apps.get_model("mwmbl", "DomainSubmission")
+ submissions_to_update = []
+ ids_to_delete = []
+ for submission in DomainSubmission.objects.all().iterator(chunk_size=BATCH_SIZE):
+ normalized_name = normalize_domain(submission.name)
+ if VALID_DOMAIN_REGEX.fullmatch(normalized_name) is None:
+ ids_to_delete.append(submission.id)
+ elif normalized_name != submission.name:
+ submission.name = normalized_name
+ submissions_to_update.append(submission)
+
+ DomainSubmission.objects.bulk_update(submissions_to_update, ["name"], batch_size=BATCH_SIZE)
+ for start in range(0, len(ids_to_delete), BATCH_SIZE):
+ DomainSubmission.objects.filter(id__in=ids_to_delete[start:start + BATCH_SIZE]).delete()
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("mwmbl", "0032_normalize_domain_submission_names"),
+ ]
+
+ operations = [
+ migrations.RunPython(fix_names, migrations.RunPython.noop),
+ ]
diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.py
index 8d52270..b4901a1 100644
--- a/mwmbl/platform/api.py
+++ b/mwmbl/platform/api.py
@@ -156,7 +156,9 @@ def delete_user(request, username: str):
)
@paginate
def get_domain_submissions_for_domain(request, domain: str) -> list[DomainSubmissionSchema]:
- return DomainSubmission.objects.filter(name=domain).all()
+ # Submissions are stored under the normalized domain, so look them up the same way, otherwise a
+ # client cannot find back a submission it made using the URL it submitted.
+ return DomainSubmission.objects.filter(name=normalize_domain(domain)).all()
@router.get(
diff --git a/mwmbl/settings_test.py b/mwmbl/settings_test.py
index f23178b..6d17034 100644
--- a/mwmbl/settings_test.py
+++ b/mwmbl/settings_test.py
@@ -28,3 +28,8 @@ DOMAIN_LINKS_BLOOM_FILTER_PATH = "/tmp/test_links_{domain_group}.bloom"
NUM_DOMAINS_IN_BLOOM_FILTER = 1000
REQUEST_CACHE_PATH = "/tmp/test_request_cache"
+
+# The front end is not built when running the tests, so there is no Vite manifest to resolve assets
+# against. In dev mode django-vite points at the dev server instead of reading the manifest, which
+# lets views that render the base template be tested.
+DJANGO_VITE_DEV_MODE = True
diff --git a/mwmbl/utils.py b/mwmbl/utils.py
index f2e4c03..3c5645b 100644
--- a/mwmbl/utils.py
+++ b/mwmbl/utils.py
@@ -76,15 +76,21 @@ def parse_url(url: str) -> ParsedUrl:
VALID_DOMAIN_REGEX = re.compile(r"^[\w-]{1,63}(\.[\w-]{1,63})+$")
+# Everything from the first of these characters onwards is a path, query string or fragment.
+DOMAIN_END_REGEX = re.compile(r"[/?#]")
+
def normalize_domain(domain_or_url: str) -> str:
"""
- Extract the domain from a URL. A bare domain is returned unchanged, and any path is stripped.
+ Extract the domain from a URL. A bare domain is returned unchanged, and any path, query string
+ or fragment is stripped. The domain is lowercased so that a domain has a single representation
+ however it was typed: domains are compared as strings elsewhere, e.g. against the curated
+ domains when deciding how many URLs to queue for a domain.
"""
netloc = parse_url(domain_or_url).netloc
- if netloc is not None:
- return netloc
- return domain_or_url.split("/")[0]
+ if not netloc:
+ netloc = DOMAIN_END_REGEX.split(domain_or_url, maxsplit=1)[0]
+ return netloc.lower()
def validate_domain(domain_or_url: str):
diff --git a/test/test_domain_submissions.py b/test/test_domain_submissions.py
index 6a2cb8c..7125bd8 100644
--- a/test/test_domain_submissions.py
+++ b/test/test_domain_submissions.py
@@ -13,8 +13,9 @@ from ninja_jwt.tokens import RefreshToken
from mwmbl.models import DomainSubmission, MwmblUser
-migration_module = importlib.import_module("mwmbl.migrations.0032_normalize_domain_submission_names")
-normalize_names = migration_module.normalize_names
+normalize_names = importlib.import_module(
+ "mwmbl.migrations.0032_normalize_domain_submission_names").normalize_names
+fix_names = importlib.import_module("mwmbl.migrations.0033_fix_domain_submission_names").fix_names
@pytest.fixture
@@ -77,6 +78,50 @@ def test_api_stores_bare_domain(client, access_token):
assert DomainSubmission.objects.get().name == "www.idolbronze.com"
+def test_fix_migration_lowercases_names(user):
+ submission = DomainSubmission.objects.create(name="WWW.IdolBronze.com", submitted_by=user)
+
+ fix_names(django_apps, None)
+
+ submission.refresh_from_db()
+ assert submission.name == "www.idolbronze.com"
+
+
+def test_fix_migration_deletes_names_that_are_not_domains(user):
+ DomainSubmission.objects.create(name="http://", submitted_by=user)
+ DomainSubmission.objects.create(name="https:///some/path", submitted_by=user)
+ kept = DomainSubmission.objects.create(name="example.com", submitted_by=user)
+
+ fix_names(django_apps, None)
+
+ assert list(DomainSubmission.objects.all()) == [kept]
+
+
+def test_submission_list_renders_after_fix_migration(client, user):
+ DomainSubmission.objects.create(name="http://", submitted_by=user)
+
+ fix_names(django_apps, None)
+
+ response = client.get(reverse("domain_submissions"))
+ assert response.status_code == 200
+
+
+def test_api_finds_submission_whatever_the_case(client, access_token):
+ client.post(
+ "/api/v1/platform/domain-submissions/?domain=https://WWW.IdolBronze.com/",
+ HTTP_AUTHORIZATION=f"Bearer {access_token}",
+ )
+
+ response = client.get("/api/v1/platform/domain-submissions/domains/WWW.IdolBronze.com")
+
+ assert response.status_code == 200
+ assert [item["name"] for item in response.json()["items"]] == ["www.idolbronze.com"]
+
+
@pytest.mark.django_db
def test_api_rejects_invalid_domain(client, access_token):
response = client.post(
diff --git a/test/test_utils.py b/test/test_utils.py
index 218033e..f9b5208 100644
--- a/test/test_utils.py
+++ b/test/test_utils.py
@@ -45,3 +45,20 @@ def test_normalize_domain_leaves_bare_domain_alone():
def test_normalize_domain_strips_path_without_scheme():
assert normalize_domain("www.example.com/some/path") == "www.example.com"
+
+
+def test_normalize_domain_strips_query_and_fragment_without_scheme():
+ assert normalize_domain("www.example.com?q=1") == "www.example.com"
+ assert normalize_domain("www.example.com#fragment") == "www.example.com"
+
+
+def test_normalize_domain_lowercases():
+ assert normalize_domain("https://WWW.Example.COM/") == "www.example.com"
+ assert normalize_domain("Example.COM") == "example.com"
+
+
+def test_validate_domain_rejects_url_without_a_domain():
+ with pytest.raises(ValidationError):
+ validate_domain("http://")
+ with pytest.raises(ValidationError):
+ validate_domain("https:///some/path")