Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Repair 1,785 moderations lost to a status that was never a status

Daoud Clarkeddf26cd1407d
diff --git a/mwmbl/migrations/0037_repair_domain_submission_statuses.py b/mwmbl/migrations/0037_repair_domain_submission_statuses.py
new file mode 100644
index 0000000..0289dca
--- /dev/null
+++ b/mwmbl/migrations/0037_repair_domain_submission_statuses.py
@@ -0,0 +1,61 @@
+"""
+Repair submissions whose status is the moderator-facing *action* rather than a status, and
+constrain the column so it cannot happen again.
+
+An external moderation client posted "APPROVE"/"REJECT" - the words it shows the moderator -
+where the model's choices are "APPROVED"/"REJECTED". Django checks choices in full_clean(),
+which save() never calls, and generates no database constraint, so the words landed in the
+column verbatim. A submission holding one matches nothing: not the pending queue, not the
+approved set the curated domains (and so the blacklist override) are built from, not the
+moderation history, not the training data. The decision simply vanished. 1,785 rows across
+1,618 domains were written this way in production before this ran.
+
+The rewrite is not a guess about intent: these were decisions made by a moderator with the
+change_domain_submission_status permission, on the domain the client had just shown them.
+This applies them.
+
+Newly approved domains are subtracted from the remote blocklists when the snapshot is next
+rebuilt (BLACKLIST_SNAPSHOT_REFRESH_SECONDS, six hours), and get_curated_domains caches for
+five minutes, so both catch up on their own rather than being poked from a migration.
+"""
+from django.db import migrations, models
+
+REPAIRS = {"APPROVE": "APPROVED", "REJECT": "REJECTED"}
+
+
+def repair_statuses(apps, schema_editor):
+ DomainSubmission = apps.get_model("mwmbl", "DomainSubmission")
+ for written, intended in REPAIRS.items():
+ DomainSubmission.objects.filter(status=written).update(status=intended)
+
+
+def noop_reverse(apps, schema_editor):
+ """Irreversible on purpose: an APPROVED row repaired here is indistinguishable from one
+ that was always correct, so there is nothing to put back."""
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("mwmbl", "0036_search_result_vote_domain"),
+ ]
+
+ operations = [
+ # Before the constraints, which the rows this repairs would otherwise violate.
+ migrations.RunPython(repair_statuses, noop_reverse),
+ migrations.AddConstraint(
+ model_name="domainsubmission",
+ constraint=models.CheckConstraint(
+ condition=models.Q(status__in=["PENDING", "APPROVED", "REJECTED"]),
+ name="domain_submission_status_valid",
+ ),
+ ),
+ migrations.AddConstraint(
+ model_name="domainsubmission",
+ constraint=models.CheckConstraint(
+ condition=models.Q(
+ rejection_reason__in=["", "SPAM", "OFFENSIVE", "LANGUAGE", "OTHER"]),
+ name="domain_submission_rejection_reason_valid",
+ ),
+ ),
+ ]
diff --git a/mwmbl/models.py b/mwmbl/models.py
index 54bfe32..78e3eb6 100644
--- a/mwmbl/models.py
+++ b/mwmbl/models.py
@@ -76,6 +76,23 @@ class OldIndex(models.Model):
last_page_copied = models.IntegerField(null=True, blank=True)
+# Module level rather than class attributes because the check constraints below need them,
+# and a nested Meta cannot see names from the class body it sits in. The class attributes are
+# kept as aliases: they are what the API schemas and management commands read.
+DOMAIN_SUBMISSION_STATUS = {
+ "PENDING": "The domain submission is awaiting review",
+ "APPROVED": "The domain submission has been approved",
+ "REJECTED": "The domain submission has been rejected",
+}
+
+DOMAIN_REJECTION_REASON = {
+ "SPAM": "The domain submission was rejected because it was spam",
+ "OFFENSIVE": "The domain submission was rejected because it was offensive",
+ "LANGUAGE": "The domain is in an unsupported language",
+ "OTHER": "The domain submission was rejected for another reason",
+}
+
+
class DomainSubmission(models.Model):
class Meta:
permissions = [
@@ -89,19 +106,26 @@ class DomainSubmission(models.Model):
models.Index(fields=['name', 'status']),
models.Index(fields=['submitted_by', 'status']),
]
+ constraints = [
+ # `choices` is documentation, not enforcement: it is checked by full_clean(),
+ # which save() never calls, and it produces no database constraint at all. A
+ # moderation client that posted the action it shows the moderator - "APPROVE" for
+ # "APPROVED" - therefore wrote that straight into the column, where it matched
+ # neither the pending queue nor the approved set the curated domains are built
+ # from, and the decision disappeared. 1,785 rows were written that way before
+ # migration 0037 repaired them and added these.
+ models.CheckConstraint(
+ condition=models.Q(status__in=list(DOMAIN_SUBMISSION_STATUS)),
+ name="domain_submission_status_valid",
+ ),
+ models.CheckConstraint(
+ condition=models.Q(rejection_reason__in=[""] + list(DOMAIN_REJECTION_REASON)),
+ name="domain_submission_rejection_reason_valid",
+ ),
+ ]
- DOMAIN_SUBMISSION_STATUS = {
- "PENDING": "The domain submission is awaiting review",
- "APPROVED": "The domain submission has been approved",
- "REJECTED": "The domain submission has been rejected",
- }
-
- DOMAIN_REJECTION_REASON = {
- "SPAM": "The domain submission was rejected because it was spam",
- "OFFENSIVE": "The domain submission was rejected because it was offensive",
- "LANGUAGE": "The domain is in an unsupported language",
- "OTHER": "The domain submission was rejected for another reason",
- }
+ DOMAIN_SUBMISSION_STATUS = DOMAIN_SUBMISSION_STATUS
+ DOMAIN_REJECTION_REASON = DOMAIN_REJECTION_REASON
name = models.CharField(max_length=300)
submitted_by = models.ForeignKey(MwmblUser, on_delete=models.CASCADE, related_name="domain_submissions")
diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.py
index 293216f..e58b04d 100644
--- a/mwmbl/platform/api.py
+++ b/mwmbl/platform/api.py
@@ -261,8 +261,11 @@ def apply_decision(submission: DomainSubmission, decision, user) -> None:
of the suggestions on decisions stays measurable.
"""
submission.status = decision.status
- submission.rejection_reason = decision.rejection_reason
- submission.rejection_detail = decision.rejection_detail
+ # Both columns are NOT NULL, and ninja types a blank=True CharField as Optional, so a
+ # client that simply omits the rejection fields on an approval sends None and would
+ # otherwise get an IntegrityError back as a 500.
+ submission.rejection_reason = decision.rejection_reason or ""
+ submission.rejection_detail = decision.rejection_detail or ""
submission.status_changed_by = user
submission.status_changed_on = timezone.now()
submission.suggested_status = decision.suggested_status or ""
diff --git a/test/test_domain_submission_status_repair.py b/test/test_domain_submission_status_repair.py
new file mode 100644
index 0000000..8194bd8
--- /dev/null
+++ b/test/test_domain_submission_status_repair.py
@@ -0,0 +1,122 @@
+"""Tests for the 0037 repair of submissions holding a moderation *action* as their status.
+
+An external moderation client posted "APPROVE"/"REJECT" where the column takes
+"APPROVED"/"REJECTED", and nothing stopped it: Django checks `choices` in full_clean(),
+which save() never calls, and emits no database constraint. The decisions became invisible
+to every query that looks for a decided submission - the queue, the history, the curated
+domains, the training data. These cover both halves of the fix: the rows are repaired, and
+the column now refuses the bad value at the database, whatever writes it.
+"""
+import importlib
+
+import pytest
+from django.apps import apps as django_apps
+from django.core.cache import cache
+from django.db import IntegrityError, connection, transaction
+from django.test import override_settings
+
+from mwmbl.curated_domains import CURATED_DOMAINS_CACHE_KEY, get_curated_domains
+from mwmbl.models import DomainSubmission, MwmblUser
+
+migration_module = importlib.import_module(
+ "mwmbl.migrations.0037_repair_domain_submission_statuses")
+repair_statuses = migration_module.repair_statuses
+
+STATUS_CONSTRAINT = "domain_submission_status_valid"
+
+
+def user(db):
+ return MwmblUser.objects.create(username="moderator")
+
+
+def broken_column(db):
+ """Drop the status constraint for the duration of one test.
+
+ The rows this migration repairs are rows the database now refuses, so they cannot be
+ written any other way. Postgres DDL is transactional and pytest-django wraps each test
+ in a transaction, so the constraint comes back on rollback.
+ """
+ with connection.cursor() as cursor:
+ cursor.execute(
+ f"ALTER TABLE {DomainSubmission._meta.db_table} DROP CONSTRAINT {STATUS_CONSTRAINT}")
+ yield
+
+
[email protected](autouse=True)
+def clear_curated_cache():
+ cache.delete(CURATED_DOMAINS_CACHE_KEY)
+ yield
+ cache.delete(CURATED_DOMAINS_CACHE_KEY)
+
+
+def make_submission(user, name, status, **kwargs):
+ return DomainSubmission.objects.create(
+ name=name, submitted_by=user, status=status, **kwargs)
+
+
+def test_repair_rewrites_actions_to_statuses(user, broken_column):
+ approved = make_submission(user, "pudding.cool", "APPROVE")
+ rejected = make_submission(user, "spam.example", "REJECT", rejection_reason="SPAM")
+
+ repair_statuses(django_apps, None)
+
+ approved.refresh_from_db()
+ rejected.refresh_from_db()
+ assert approved.status == "APPROVED"
+ assert rejected.status == "REJECTED"
+ # The reason the moderator chose is untouched: only the status was ever wrong.
+ assert rejected.rejection_reason == "SPAM"
+
+
+def test_repair_leaves_correct_rows_alone(user):
+ make_submission(user, "pending.example", "PENDING")
+ make_submission(user, "good.example", "APPROVED")
+ make_submission(user, "bad.example", "REJECTED", rejection_reason="SPAM")
+
+ repair_statuses(django_apps, None)
+
+ assert DomainSubmission.objects.get(name="pending.example").status == "PENDING"
+ assert DomainSubmission.objects.get(name="good.example").status == "APPROVED"
+ assert DomainSubmission.objects.get(name="bad.example").status == "REJECTED"
+
+
+@override_settings(HAS_DATABASE=True)
+def test_repaired_approvals_reach_the_curated_domains(user, broken_column):
+ """The symptom that made this visible: an approved domain is never un-blacklisted."""
+ make_submission(user, "pudding.cool", "APPROVE")
+ assert get_curated_domains() == set()
+ cache.delete(CURATED_DOMAINS_CACHE_KEY)
+
+ repair_statuses(django_apps, None)
+
+ assert get_curated_domains() == {"pudding.cool"}
+
+
+def test_the_database_refuses_an_action_as_a_status(user):
+ with pytest.raises(IntegrityError):
+ with transaction.atomic():
+ make_submission(user, "pudding.cool", "APPROVE")
+
+
+def test_the_database_refuses_an_action_as_a_status_on_update(user):
+ """.update() bypasses save() and every validator above it, so the constraint is the only
+ thing between a bulk write and the column."""
+ make_submission(user, "pudding.cool", "PENDING")
+
+ with pytest.raises(IntegrityError):
+ with transaction.atomic():
+ DomainSubmission.objects.filter(name="pudding.cool").update(status="APPROVE")
+
+
+def test_the_database_refuses_an_unknown_rejection_reason(user):
+ with pytest.raises(IntegrityError):
+ with transaction.atomic():
+ make_submission(user, "spam.example", "REJECTED", rejection_reason="JUNK")
diff --git a/test/test_domain_submissions.py b/test/test_domain_submissions.py
index b85dda2..9823f37 100644
--- a/test/test_domain_submissions.py
+++ b/test/test_domain_submissions.py
@@ -160,3 +160,51 @@ def test_api_update_submission_status_grants_moderator_permission(client, verifi
assert response.status_code == 200
submission.refresh_from_db()
assert submission.status == "APPROVED"
+
+
+def test_api_update_status_rejects_a_moderation_action_as_a_status(client, verified_user, access_token):
+ """"APPROVE" is the word a client shows its moderator; "APPROVED" is the status.
+
+ Posting the former used to be accepted and written straight to the column - `choices` is
+ checked by full_clean(), which save() never calls - and the submission then matched
+ neither the pending queue nor the approved set, so the decision vanished. It is a 422
+ naming the field now.
+ """
+ submission = DomainSubmission.objects.create(name="example.com", submitted_by=verified_user)
+ verified_user.user_permissions.add(Permission.objects.get(
+ codename="change_domain_submission_status", content_type__app_label="mwmbl"))
+
+ response = client.post(
+ f"/api/v1/platform/domain-submissions/ids/{submission.id}",
+ data=json.dumps({"status": "APPROVE", "rejection_reason": "", "rejection_detail": ""}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {access_token}",
+ )
+
+ assert response.status_code == 422
+ assert "status must be one of" in response.content.decode()
+ submission.refresh_from_db()
+ assert submission.status == "PENDING"
+
+
+def test_api_update_status_accepts_an_approval_without_rejection_fields(client, verified_user, access_token):
+ """Both rejection columns are NOT NULL, and ninja types them Optional, so omitting them
+ on an approval sent None into the column and came back as a 500."""
+ submission = DomainSubmission.objects.create(name="example.com", submitted_by=verified_user)
+ verified_user.user_permissions.add(Permission.objects.get(
+ codename="change_domain_submission_status", content_type__app_label="mwmbl"))
+
+ response = client.post(
+ f"/api/v1/platform/domain-submissions/ids/{submission.id}",
+ data=json.dumps({"status": "APPROVED"}),
+ content_type="application/json",
+ HTTP_AUTHORIZATION=f"Bearer {access_token}",
+ )
+
+ assert response.status_code == 200
+ submission.refresh_from_db()
+ assert submission.status == "APPROVED"
+ assert submission.rejection_reason == ""
+ assert submission.rejection_detail == ""