aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDennis Fink2026-11-19 21:18:37 +0100
committerDennis Fink2026-11-19 21:18:37 +0100
commiteb11fb64e9cad6fbda2065362189653416d98577 (patch)
tree0bc5737b1c273ea6f04adc015154565c385dc719
parent88f54d9a7699944b7d56f978e724b1c0b54dde98 (diff)
downloadwebmentions-ssg-eb11fb64e9cad6fbda2065362189653416d98577.tar.gz
webmentions-ssg-eb11fb64e9cad6fbda2065362189653416d98577.zip
test: expand failure and migration coverage
Add regression coverage for malformed input, lost task claims, moderation races, network failures, serializer validation, and production configuration guards. Exercise migration downgrade, backfill, and autogeneration paths plus additional receiver and sender edge cases.
-rw-r--r--tests/forms/test_validators.py24
-rw-r--r--tests/tasks/test_json_serializer.py27
-rw-r--r--tests/tasks/test_sender.py12
-rw-r--r--tests/tasks/test_source_parser.py41
-rw-r--r--tests/tasks/test_verification.py40
-rw-r--r--tests/test_auth.py10
-rw-r--r--tests/test_cli.py92
-rw-r--r--tests/test_config.py24
-rw-r--r--tests/test_init.py58
-rw-r--r--tests/test_migration_env.py57
-rw-r--r--tests/test_moderation_policy.py5
-rw-r--r--tests/test_net.py74
-rw-r--r--tests/views/test_endpoint.py16
-rw-r--r--tests/views/test_moderation.py76
-rw-r--r--tests/views/test_received.py46
15 files changed, 601 insertions, 1 deletions
diff --git a/tests/forms/test_validators.py b/tests/forms/test_validators.py
index 2c427d3..1f73e6f 100644
--- a/tests/forms/test_validators.py
+++ b/tests/forms/test_validators.py
@@ -91,3 +91,27 @@ def test_url_max_bytes_rejects_malformed_unicode(app: Flask) -> None:
form = URLForm(MultiDict({"url": "\ud800"}))
with app.app_context(), pytest.raises(ValidationError, match="valid UTF-8"):
MaxURLBytes()(form, form.url)
+
+
+def test_max_url_bytes_skips_empty_field_data(app: Flask) -> None:
+ form = URLForm()
+ form.url.data = None
+ with app.app_context():
+ MaxURLBytes()(form, form.url)
+
+
+def test_strict_http_url_rejects_non_string_field_data() -> None:
+ from wtforms.validators import StopValidation
+
+ from webmentions_ssg.forms.validators import StrictHTTPURL
+
+ form = URLForm()
+ form.url.data = None
+ with pytest.raises(StopValidation, match="Invalid URL"):
+ StrictHTTPURL()(form, form.url)
+
+
+def test_nonpublic_ip_validator_reports_malformed_host() -> None:
+ form = URLForm(MultiDict({"url": "http://[invalid"}))
+ with pytest.raises(ValidationError, match="Invalid input"):
+ RejectNonPublicIPLiteral()(form, form.url)
diff --git a/tests/tasks/test_json_serializer.py b/tests/tasks/test_json_serializer.py
index 6077ebd..32a862a 100644
--- a/tests/tasks/test_json_serializer.py
+++ b/tests/tasks/test_json_serializer.py
@@ -98,3 +98,30 @@ def test_compression_with_json(app: Flask) -> None:
raw = huey.huey.serializer.serialize(payload)
assert raw.startswith(b"\x1f\x8b")
assert huey.huey.serializer.deserialize(raw) == payload
+
+
+@pytest.mark.parametrize(
+ ("encoded", "expected_error", "message"),
+ [
+ (
+ b'{"type":"error","value":"not metadata"}',
+ TypeError,
+ "Invalid Huey JSON error metadata",
+ ),
+ (
+ b'{"type":"dict","value":[["key",1],["key",2]]}',
+ ValueError,
+ "Duplicate Huey JSON dictionary key",
+ ),
+ (
+ b'{"type":"dict","value":[["key",1],[42,2]]}',
+ ValueError,
+ "Invalid Huey JSON dictionary entry",
+ ),
+ ],
+)
+def test_rejects_invalid_huey_json_structure(
+ encoded: bytes, expected_error: type[Exception], message: str
+) -> None:
+ with pytest.raises(expected_error, match=message):
+ TaggedJSONSerializer().deserialize(encoded)
diff --git a/tests/tasks/test_sender.py b/tests/tasks/test_sender.py
index 5be2177..4954d04 100644
--- a/tests/tasks/test_sender.py
+++ b/tests/tasks/test_sender.py
@@ -739,3 +739,15 @@ def test_send_does_not_persist_unsafe_status_url(
assert mention.status == SentWebmentionStatus.SENT
assert mention.endpoint_response_status == HTTPStatus.CREATED
assert mention.status_url == expected
+
+
+def test_reserve_send_attempt_rejects_lost_claim(
+ app: Flask, sender_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ identifier = create_sent_webmention(app)
+ monkeypatch.setattr(sender_module, "rows_affected", lambda result: 0)
+
+ with app.app_context():
+ webmention = db.session.get(SentWebmention, identifier)
+ assert webmention is not None
+ assert sender_module.reserve_send_attempt(webmention, datetime.now(UTC)) is None
diff --git a/tests/tasks/test_source_parser.py b/tests/tasks/test_source_parser.py
index 38752b0..38a5dc1 100644
--- a/tests/tasks/test_source_parser.py
+++ b/tests/tasks/test_source_parser.py
@@ -1014,3 +1014,44 @@ def test_normalize_target_url_ignores_url_rejected_by_validator(
)
is None
)
+
+
+def test_outgoing_targets_skip_urls_with_unparseable_hostname(
+ source_parser_module: ModuleType, monkeypatch: MonkeyPatch
+) -> None:
+ document = parse_html(
+ '<div><a href="https://bad.example/post">bad</a>'
+ '<a href="https://good.example/post">good</a></div>'
+ )
+ content = document.find("div")
+ assert content is not None
+ original = source_parser_module.normalize_hostname
+
+ def invalid_hostname(url: str, *, from_url: bool = False) -> str:
+ if "bad.example" in url:
+ raise ValueError("Malformed URL hostname")
+ return original(url, from_url=from_url)
+
+ monkeypatch.setattr(source_parser_module, "normalize_hostname", invalid_hostname)
+ assert list(
+ source_parser_module.iter_outgoing_targets(
+ content,
+ {},
+ base_url=SOURCE_URL,
+ source_url=SOURCE_URL,
+ )
+ ) == ["https://good.example/post"]
+
+
+def test_stable_content_text_excludes_hidden_markup(
+ source_parser_module: ModuleType,
+) -> None:
+ document = parse_html(
+ "<div>Hello<script>secret-script</script>"
+ "<style>secret-style</style><template>secret-template</template>world</div>"
+ )
+ content = document.find("div")
+ assert content is not None
+ normalized = source_parser_module.stable_content_text(content)
+ assert "Hello" in normalized and "world" in normalized
+ assert "secret-" not in normalized
diff --git a/tests/tasks/test_verification.py b/tests/tasks/test_verification.py
index f36da44..d9c2f77 100644
--- a/tests/tasks/test_verification.py
+++ b/tests/tasks/test_verification.py
@@ -834,3 +834,43 @@ def test_stale_recovery_records_history_and_attempt_count(
assert events[0].status == "received"
assert events[0].recovery_attempts == 2
enqueue.assert_called_once_with(identifier)
+
+
+def test_verification_claim_race_rolls_back_without_status_event(
+ app: Flask, verification: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from webmentions_ssg.models.received import ReceivedWebmentionStatusEvent
+
+ identifier = create_webmention(app)
+ monkeypatch.setattr(verification, "rows_affected", lambda changed: 0)
+
+ with app.app_context():
+ assert verification.claim_for_verification(identifier) is None
+ row = db.session.get(ReceivedWebmention, identifier)
+ assert row is not None
+ assert row.status == "received"
+ assert db.session.scalar(
+ sa.select(sa.func.count(ReceivedWebmentionStatusEvent.id))
+ ) == 0
+
+
+def test_stale_verification_claim_race_does_not_enqueue(
+ app: Flask, verification: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from webmentions_ssg.models.received import ReceivedWebmentionStatusEvent
+
+ identifier = create_webmention(app, status="verifying")
+ set_webmention_updated_at(app, identifier, datetime.now(UTC) - timedelta(hours=1))
+ enqueue = Mock()
+ monkeypatch.setattr(verification, "verify_webmention", enqueue)
+ monkeypatch.setattr(verification, "rows_affected", lambda changed: 0)
+
+ with app.app_context():
+ assert verification.recover_stale_verifications() == 0
+ row = db.session.get(ReceivedWebmention, identifier)
+ assert row is not None
+ assert row.status == "verifying"
+ assert db.session.scalar(
+ sa.select(sa.func.count(ReceivedWebmentionStatusEvent.id))
+ ) == 0
+ enqueue.assert_not_called()
diff --git a/tests/test_auth.py b/tests/test_auth.py
index 27e8fb0..2a3d517 100644
--- a/tests/test_auth.py
+++ b/tests/test_auth.py
@@ -161,3 +161,13 @@ def test_password_change_invalidates_existing_session(app: Flask) -> None:
)
def test_is_safe_next_url(next_url: str, expected: bool) -> None:
assert is_safe_next_url(next_url) is expected
+
+
+def test_safe_next_url_fails_closed_when_url_parser_rejects_path(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def invalid_url(_: str) -> object:
+ raise ValueError("Malformed URL")
+
+ monkeypatch.setattr(auth, "urlsplit", invalid_url)
+ assert is_safe_next_url("/local/path") is False
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 5699bb3..1507544 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -900,3 +900,95 @@ def test_users_cli_accepts_minimum_whitespace_and_unbounded_passwords(
assert result.exit_code == 0, result.output
user = _get_user(app, "alice")
assert user is not None and user.check_password(passphrase)
+
+
+def test_all_migrations_can_downgrade_to_empty_schema(database_app: Flask) -> None:
+ """Exercise every downgrade, including the two merged migration branches."""
+ with database_app.app_context():
+ migrate_upgrade()
+ assert _database_revision(database_app) == _head_revision(database_app)
+ assert "received_webmentions" in inspect(db.engine).get_table_names()
+
+ migrate_downgrade(revision="base")
+ with db.engine.connect() as connection:
+ tables = set(inspect(connection).get_table_names())
+ # Alembic may keep its empty version table after downgrading to base.
+ assert tables <= {"alembic_version"}
+ if "alembic_version" in tables:
+ assert (
+ connection.execute(sa.text("SELECT count(*) FROM alembic_version"))
+ .scalar_one()
+ == 0
+ )
+
+
+def test_fingerprint_migration_backfills_existing_sent_target(
+ database_app: Flask,
+) -> None:
+ from webmentions_ssg.models.utils import target_digest
+
+ source_uuid = "0" * 31 + "1"
+ sent_uuid = "0" * 31 + "2"
+ target = "https://target.example/legacy"
+ with database_app.app_context():
+ migrate_upgrade(revision="c0272f25ce17")
+ with db.engine.begin() as connection:
+ connection.execute(
+ sa.text(
+ "INSERT INTO sources (uuid, path, url, content_hash, revision, "
+ "last_seen_at, revised_at) VALUES (:uuid, 'post/index.html', "
+ "'https://source.example/post', :hash, 1, "
+ "CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
+ ),
+ {"uuid": source_uuid, "hash": "0" * 32},
+ )
+ connection.execute(
+ sa.text(
+ "INSERT INTO sent_webmentions "
+ "(uuid, source_id, target, active, desired_revision, attempt_count) "
+ "VALUES (:uuid, :source_id, :target, 1, 1, 0)"
+ ),
+ {"uuid": sent_uuid, "source_id": source_uuid, "target": target},
+ )
+
+ migrate_upgrade(revision="d845aa7fbc19")
+ with db.engine.connect() as connection:
+ row = connection.execute(
+ sa.text("SELECT target, target_digest FROM sent_webmentions")
+ ).one()
+ assert row.target == target
+ assert row.target_digest == target_digest(target)
+ assert any(
+ constraint["column_names"] == ["source_id", "target_digest"]
+ for constraint in inspect(connection).get_unique_constraints(
+ "sent_webmentions"
+ )
+ )
+
+
+def test_autogenerate_skips_empty_migration_revisions(
+ database_app: Flask, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from types import SimpleNamespace
+ from unittest.mock import Mock
+
+ with database_app.app_context():
+ migrate_upgrade(revision="f63641044cc1")
+ callback = database_app.extensions["migrate"].configure_args[
+ "process_revision_directives"
+ ]
+ config = callback.__globals__["config"]
+ monkeypatch.setattr(
+ config, "cmd_opts", SimpleNamespace(autogenerate=True), raising=False
+ )
+ empty = Mock()
+ empty.upgrade_ops.is_empty.return_value = True
+ directives = [empty]
+ callback(None, None, directives)
+ assert directives == []
+
+ nonempty = Mock()
+ nonempty.upgrade_ops.is_empty.return_value = False
+ directives = [nonempty]
+ callback(None, None, directives)
+ assert directives == [nonempty]
diff --git a/tests/test_config.py b/tests/test_config.py
index 75b8a4a..43c29ab 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -7,7 +7,7 @@
from pathlib import Path
import pytest
-from flask import request
+from flask import Flask, request
from flask_limiter.util import get_remote_address
from wtforms import Field, ValidationError
from wtforms.form import BaseForm
@@ -560,3 +560,25 @@ def test_uppercase_sqlite_pragma_keys_support_environment_convention(
app = create_app(EnvStyleSQLiteConfig)
assert app.config["SQLITE_PRAGMAS"]["cache_size"] == -8192
assert app.config["SQLITE_PRAGMAS"]["synchronous"] == "NORMAL"
+
+
+def test_production_rejects_in_memory_rate_limiter(app: Flask) -> None:
+ from webmentions_ssg.config import validated_config_overrides
+
+ config = dict(app.config)
+ config.update(
+ TESTING=False,
+ DEBUG=False,
+ SECRET_KEY="a-long-unique-production-secret-for-tests",
+ ALLOWED_TARGET_HOSTNAMES=["example.org"],
+ RATELIMIT_STORAGE_URI="memory://",
+ )
+ with pytest.raises(RuntimeError, match="RATELIMIT_STORAGE_URI"):
+ validated_config_overrides(config, config_class=TestingConfig)
+
+
+def test_sqlite_pragmas_reject_non_string_names() -> None:
+ from webmentions_ssg.config import validate_sqlite_pragmas
+
+ with pytest.raises(ValueError, match="unsupported PRAGMA 42"):
+ validate_sqlite_pragmas({42: True})
diff --git a/tests/test_init.py b/tests/test_init.py
index 0966b19..373af01 100644
--- a/tests/test_init.py
+++ b/tests/test_init.py
@@ -8,6 +8,7 @@ import subprocess
import sys
from pathlib import Path
+import pytest
from flask import Flask
from sqlalchemy import create_engine
@@ -207,3 +208,60 @@ def test_sqlite_connect_listener_does_not_touch_other_dbapis() -> None:
# Non-SQLite DB-API connections bypass the listener completely.
set_sqlite_pragmas(object(), object())
+
+
+@pytest.mark.parametrize("development", [False, True])
+def test_create_app_selects_default_configuration_from_environment(
+ monkeypatch: pytest.MonkeyPatch, development: bool
+) -> None:
+ import webmentions_ssg as package
+
+ class DefaultTestConfig(TestingConfig):
+ LOG_FILE = str(Path.cwd() / "testing" / "default-config-test.log")
+
+ class DevelopmentTestConfig(DefaultTestConfig):
+ CONFIG_SELECTION = "development"
+
+ class ProductionTestConfig(DefaultTestConfig):
+ CONFIG_SELECTION = "production"
+
+ monkeypatch.setattr(package, "DevelopmentConfig", DevelopmentTestConfig)
+ monkeypatch.setattr(package, "ProductionConfig", ProductionTestConfig)
+ if development:
+ monkeypatch.setenv("WEBMENTIONS_SSG_DEV", "true")
+ else:
+ monkeypatch.delenv("WEBMENTIONS_SSG_DEV", raising=False)
+
+ application = create_app()
+ assert application.config["CONFIG_SELECTION"] == (
+ "development" if development else "production"
+ )
+
+
+def test_sqlite_connect_rejects_journal_mode_that_cannot_be_applied(
+ app: Flask, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from unittest.mock import Mock
+
+ from webmentions_ssg import extensions
+
+ cursor = Mock()
+ cursor.fetchall.return_value = [(0, "main", "/tmp/test-file.sqlite")]
+ cursor.fetchone.side_effect = [("DELETE",), ("DELETE",)]
+
+ class FakeConnection:
+ def __init__(self) -> None:
+ self.autocommit = False
+
+ def cursor(self) -> Mock:
+ return cursor
+
+ connection = FakeConnection()
+ with app.app_context(), monkeypatch.context() as patcher:
+ patcher.setattr(extensions.sqlite3, "Connection", FakeConnection)
+ with pytest.raises(RuntimeError, match="journal_mode WAL was not applied"):
+ extensions.set_sqlite_pragmas(connection, None)
+
+ assert connection.autocommit is False
+ cursor.close.assert_called_once_with()
+ cursor.execute.assert_any_call("PRAGMA journal_mode = WAL")
diff --git a/tests/test_migration_env.py b/tests/test_migration_env.py
new file mode 100644
index 0000000..07462dc
--- /dev/null
+++ b/tests/test_migration_env.py
@@ -0,0 +1,57 @@
+# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Test Alembic's offline configuration and legacy Flask-SQLAlchemy fallback."""
+
+import runpy
+from contextlib import nullcontext
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+from alembic import context
+from flask import Flask
+
+
+def test_offline_migration_uses_legacy_engine_url_and_metadata(
+ app: Flask, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ class LegacyURL:
+ def __str__(self) -> str:
+ return "sqlite:///legacy%20database.sqlite"
+
+ metadata = object()
+ legacy_db = SimpleNamespace(
+ engine=SimpleNamespace(url=LegacyURL()), metadata=metadata
+ )
+ config = Mock()
+ config.get_main_option.return_value = "sqlite:///offline.sqlite"
+ configure = Mock()
+ run_migrations = Mock()
+
+ with app.app_context(), monkeypatch.context() as patcher:
+ patcher.setattr(app.extensions["migrate"], "db", legacy_db)
+ patcher.setattr(context, "config", config, raising=False)
+ patcher.setattr(context, "is_offline_mode", Mock(return_value=True))
+ patcher.setattr(context, "configure", configure, raising=False)
+ patcher.setattr(context, "begin_transaction", lambda: nullcontext())
+ patcher.setattr(context, "run_migrations", run_migrations, raising=False)
+
+ runpy.run_path(
+ str(
+ Path(__file__).parents[1]
+ / "webmentions_ssg"
+ / "migrations"
+ / "env.py"
+ )
+ )
+
+ config.set_main_option.assert_called_once_with(
+ "sqlalchemy.url", "sqlite:///legacy%%20database.sqlite"
+ )
+ configure.assert_called_once_with(
+ url="sqlite:///offline.sqlite", target_metadata=metadata, literal_binds=True
+ )
+ run_migrations.assert_called_once_with()
diff --git a/tests/test_moderation_policy.py b/tests/test_moderation_policy.py
index 48a34ac..3421ba5 100644
--- a/tests/test_moderation_policy.py
+++ b/tests/test_moderation_policy.py
@@ -60,3 +60,8 @@ def test_allowlist_is_fail_closed_and_blocklist_takes_precedence(app: Flask) ->
== "Source domain is blocked"
)
assert rejection_reason("https://example.org/post") is None
+
+
+def test_rejection_reason_reports_invalid_source_hostname(app: Flask) -> None:
+ with app.app_context():
+ assert rejection_reason("http://[not-an-ip") == "Invalid source hostname"
diff --git a/tests/test_net.py b/tests/test_net.py
index 6ff267d..ec62472 100644
--- a/tests/test_net.py
+++ b/tests/test_net.py
@@ -6,6 +6,8 @@
import ipaddress
import socket
+
+import dns.exception
from http import HTTPStatus
from unittest.mock import Mock, PropertyMock, patch
@@ -358,3 +360,75 @@ def test_is_retryable_status(app: Flask, status: int, expected: bool) -> None:
)
def test_media_type_of(headers: dict[str, str], expected: str) -> None:
assert media_type_of(httpx.Headers(headers)) == expected
+
+
+@pytest.mark.parametrize("seconds", [0, -0.1])
+def test_request_deadline_requires_positive_timeout(seconds: float) -> None:
+ with pytest.raises(ValueError, match="REQUEST_TOTAL_TIMEOUT_SECONDS"):
+ RequestDeadline(seconds)
+
+
+def test_deadline_stream_bounds_write_and_tls_timeouts() -> None:
+ stream = Mock(spec=httpcore.NetworkStream)
+ stream.start_tls.return_value = Mock(spec=httpcore.NetworkStream)
+ deadline = RequestDeadline(30)
+ wrapper = DeadlineStream(stream, deadline)
+
+ wrapper.write(b"payload", timeout=120)
+ written_timeout = stream.write.call_args.kwargs["timeout"]
+ assert 0 < written_timeout <= 30
+
+ secure = wrapper.start_tls(Mock(), server_hostname="example.org", timeout=120)
+ assert isinstance(secure, DeadlineStream)
+ assert secure._deadline is deadline
+ assert stream.start_tls.call_args.kwargs["server_hostname"] == "example.org"
+ tls_timeout = stream.start_tls.call_args.kwargs["timeout"]
+ assert 0 < tls_timeout <= 30
+
+
+def test_network_backend_applies_local_bind_and_socket_options(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ sock = Mock()
+ monkeypatch.setattr(socket, "socket", Mock(return_value=sock))
+ options = [(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)]
+
+ stream = PublicNetworkBackend(RequestDeadline(5)).connect_tcp(
+ "8.8.8.8", 443, local_address="0.0.0.0", socket_options=options
+ )
+
+ sock.bind.assert_called_once_with(("0.0.0.0", 0))
+ sock.setsockopt.assert_any_call(*options[0])
+ sock.connect.assert_called_once_with(("8.8.8.8", 443))
+ stream.close()
+ sock.close.assert_called_once()
+
+
+def test_network_backend_rejects_empty_public_address_list(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ "webmentions_ssg.net.resolve_public_addresses", lambda *args, **kwargs: ()
+ )
+ create_socket = Mock(side_effect=AssertionError("must not open socket"))
+ monkeypatch.setattr(socket, "socket", create_socket)
+
+ with pytest.raises(httpcore.ConnectError, match="No public addresses available"):
+ PublicNetworkBackend(RequestDeadline(5)).connect_tcp("example.org", 443)
+ create_socket.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "failure", [ValueError("invalid"), dns.exception.DNSException("lookup failed")]
+)
+def test_dns_resolution_errors_are_wrapped(
+ monkeypatch: pytest.MonkeyPatch, failure: Exception
+) -> None:
+ from webmentions_ssg.net import resolve_hostname
+
+ resolver = Mock(side_effect=failure)
+ monkeypatch.setattr("webmentions_ssg.net.dns.resolver.resolve_name", resolver)
+
+ with pytest.raises(AddressResolutionError, match="Could not resolve hostname"):
+ resolve_hostname("missing.example", lifetime=1.5)
+ resolver.assert_called_once_with("missing.example", lifetime=1.5)
diff --git a/tests/views/test_endpoint.py b/tests/views/test_endpoint.py
index bf99ed4..63c17c6 100644
--- a/tests/views/test_endpoint.py
+++ b/tests/views/test_endpoint.py
@@ -529,3 +529,19 @@ def test_endpoint_records_initial_and_resubmission_events(
"Received submission",
"Resubmitted after cooldown",
]
+
+
+def test_submission_returns_none_when_competing_insert_cannot_be_found(
+ app: Flask, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from webmentions_ssg.views import endpoint
+
+ find = Mock(return_value=None)
+ insert = Mock(return_value=None)
+ monkeypatch.setattr(endpoint, "find_received_webmention", find)
+ monkeypatch.setattr(endpoint, "try_insert_received_webmention", insert)
+
+ with app.app_context():
+ assert endpoint.record_submission(SOURCE_URL, TARGET_URL) is None
+ assert find.call_count == 2
+ insert.assert_called_once_with(SOURCE_URL, TARGET_URL)
diff --git a/tests/views/test_moderation.py b/tests/views/test_moderation.py
index 78ff661..92446c4 100644
--- a/tests/views/test_moderation.py
+++ b/tests/views/test_moderation.py
@@ -276,3 +276,79 @@ def test_admin_actions_enforce_csrf(app: Flask, client: FlaskClient) -> None:
).status_code
== HTTPStatus.BAD_REQUEST
)
+
+
+def test_block_domains_survives_unique_constraint_race(
+ app: Flask, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from sqlalchemy.exc import IntegrityError
+
+ from webmentions_ssg.views.moderation import block_domains
+
+ with app.app_context():
+ session = db.session()
+ real_flush = session.flush
+
+ def simulated_concurrent_insert(*args: object, **kwargs: object) -> None:
+ if any(
+ isinstance(obj, BlockedDomain) and obj.domain == "a-loser.example"
+ for obj in session.new
+ ):
+ raise IntegrityError("duplicate", {}, Exception("concurrent insert"))
+ real_flush(*args, **kwargs)
+
+ with monkeypatch.context() as patcher:
+ patcher.setattr(session, "flush", simulated_concurrent_insert)
+ assert block_domains({"a-loser.example", "b-winner.example"}) == 1
+
+ assert set(db.session.scalars(sa.select(BlockedDomain.domain))) == {
+ "b-winner.example"
+ }
+
+
+def test_moderation_add_recovers_from_duplicate_insert_race(
+ app: Flask, client: FlaskClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from sqlalchemy.exc import IntegrityError
+
+ log_in(app, client)
+ commit = Mock(side_effect=IntegrityError("duplicate", {}, Exception("race")))
+ rollback = Mock(wraps=db.session.rollback)
+ with monkeypatch.context() as patcher:
+ patcher.setattr(db.session, "commit", commit)
+ patcher.setattr(db.session, "rollback", rollback)
+ response = client.post(
+ "/moderation/blocked/add", data={"domain": "racing.example"}
+ )
+
+ assert response.status_code == HTTPStatus.FOUND
+ assert response.headers["Location"].endswith("/moderation")
+ commit.assert_called_once()
+ rollback.assert_called_once()
+
+
+@pytest.mark.parametrize("kind", ["invalid", "blocked"])
+def test_moderation_delete_rejects_bad_kind_or_invalid_form(
+ app: Flask,
+ client: FlaskClient,
+ monkeypatch: pytest.MonkeyPatch,
+ kind: str,
+) -> None:
+ from webmentions_ssg.views import moderation
+
+ log_in(app, client)
+ form = Mock()
+ form.validate_on_submit.return_value = False
+ monkeypatch.setattr(moderation, "ConfirmActionForm", Mock(return_value=form))
+ with app.app_context():
+ entry = BlockedDomain(domain="example.test")
+ db.session.add(entry)
+ db.session.commit()
+ entry_id = entry.id
+
+ response = client.post(f"/moderation/{kind}/{entry_id}/delete")
+ assert response.status_code == (
+ HTTPStatus.NOT_FOUND if kind == "invalid" else HTTPStatus.BAD_REQUEST
+ )
+ with app.app_context():
+ assert db.session.get(BlockedDomain, entry_id) is not None
diff --git a/tests/views/test_received.py b/tests/views/test_received.py
index ed31dc5..baea6c7 100644
--- a/tests/views/test_received.py
+++ b/tests/views/test_received.py
@@ -1394,3 +1394,49 @@ def test_received_bulk_delete_preserves_only_remaining_history(
history = db.session.scalars(sa.select(ReceivedWebmentionStatusEvent)).all()
assert len(history) == 1
assert history[0].webmention_uuid == second
+
+
+@pytest.mark.parametrize("failure", ["csrf", "invalid-source"])
+def test_single_received_block_source_rejects_invalid_request(
+ app: Flask,
+ client: FlaskClient,
+ views_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+ failure: str,
+) -> None:
+ log_in(app, client)
+ identifier = create_received_webmention(
+ app,
+ source="not-a-url" if failure == "invalid-source" else SOURCE_URL,
+ )
+ mock_admin_action_form(views_module, monkeypatch, valid=failure != "csrf")
+
+ response = client.post(f"/received/{identifier}/block-source")
+ assert response.status_code == HTTPStatus.BAD_REQUEST
+ with app.app_context():
+ from webmentions_ssg.models.moderation import BlockedDomain
+
+ assert db.session.scalar(sa.select(sa.func.count(BlockedDomain.id))) == 0
+
+
+def test_single_received_block_source_redirects_with_filters(
+ app: Flask, client: FlaskClient
+) -> None:
+ from webmentions_ssg.models.moderation import BlockedDomain
+
+ log_in(app, client)
+ identifier = create_received_webmention(app, source="https://spammer.example/post")
+ response = client.post(
+ f"/received/{identifier}/block-source",
+ query_string={"status": "verified", "page": 3},
+ )
+ assert response.status_code == HTTPStatus.FOUND
+ assert parse_qs(urlsplit(response.headers["Location"]).query) == {
+ "status": ["verified"],
+ "page": ["3"],
+ }
+ with app.app_context():
+ assert set(db.session.scalars(sa.select(BlockedDomain.domain))) == {
+ "spammer.example"
+ }
+ assert db.session.get(ReceivedWebmention, identifier) is not None