diff options
| author | Dennis Fink | 2026-11-17 14:44:00 +0100 |
|---|---|---|
| committer | Dennis Fink | 2026-11-17 14:44:00 +0100 |
| commit | 227092b57acc886469e16bcc4c0d3256e86d3d1e (patch) | |
| tree | c1de8d5f8f3a37562e482f84e8017213c08a05d6 /tests | |
| parent | f98b0e446b41325c494bd97900b7bbf730a7d67e (diff) | |
| download | webmentions-ssg-227092b57acc886469e16bcc4c0d3256e86d3d1e.tar.gz webmentions-ssg-227092b57acc886469e16bcc4c0d3256e86d3d1e.zip | |
feat(receiver): add source domain access rules
Add persistent source block and allow lists with authenticated
management, single-row and bulk blocking actions, and optional
fail-closed allowlist mode.
Reject disallowed sources before enqueueing and recheck policy in
verification workers, while sharing canonical hostname normalization
across receiver, sender, and configuration paths.
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/tasks/test_verification.py | 29 | ||||
| -rw-r--r-- | tests/test_cli.py | 14 | ||||
| -rw-r--r-- | tests/test_config.py | 27 | ||||
| -rw-r--r-- | tests/test_hostname.py | 72 | ||||
| -rw-r--r-- | tests/test_net.py | 14 | ||||
| -rw-r--r-- | tests/test_source_policy.py | 67 | ||||
| -rw-r--r-- | tests/views/test_admin.py | 40 | ||||
| -rw-r--r-- | tests/views/test_source_domains.py | 297 |
8 files changed, 530 insertions, 30 deletions
diff --git a/tests/tasks/test_verification.py b/tests/tasks/test_verification.py index c336b19..c5550c8 100644 --- a/tests/tasks/test_verification.py +++ b/tests/tasks/test_verification.py @@ -15,7 +15,7 @@ import sqlalchemy as sa from flask import Flask from webmentions_ssg import db -from webmentions_ssg.models import ReceivedWebmention +from webmentions_ssg.models import BlockedSource, ReceivedWebmention from webmentions_ssg.net import AddressResolutionError SOURCE_URL = "https://source.example/article" @@ -337,6 +337,7 @@ def test_source_mentions_target_rejects_unsupported_media_type( ], ) def test_determine_verification_outcome_returns_outcome( + app: Flask, verification: ModuleType, monkeypatch: pytest.MonkeyPatch, mentions: bool, @@ -350,10 +351,30 @@ def test_determine_verification_outcome_returns_outcome( uuid.uuid7(), SOURCE_URL, TARGET_URL, datetime.now(UTC) ) - assert verification.determine_verification_outcome(claim) == ( - expected_status, - expected_reason, + with app.app_context(): + assert verification.determine_verification_outcome(claim) == ( + expected_status, + expected_reason, + ) + + +def test_verify_webmention_refuses_domain_blocked_after_enqueue( + app: Flask, verification: ModuleType, monkeypatch: pytest.MonkeyPatch +) -> None: + identifier = create_webmention(app) + with app.app_context(): + db.session.add(BlockedSource(domain="source.example")) + db.session.commit() + + fetch = Mock(return_value=True) + monkeypatch.setattr(verification, "source_mentions_target", fetch) + verification.verify_webmention.call_local(identifier) + + assert get_webmention_state(app, identifier) == ( + "failed", + "Source domain is blocked", ) + fetch.assert_not_called() @patch("webmentions_ssg.tasks.verification.source_mentions_target") diff --git a/tests/test_cli.py b/tests/test_cli.py index c98b2fc..f5535d2 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -243,6 +243,20 @@ def test_upgrade_applies_pending_migrations_and_preserves_data( assert "sent_webmentions" in inspect(connection).get_table_names() +@pytest.mark.parametrize("existing_head", ("3e8c87a96b2d", "9a4e0c8211d6")) +def test_upgrade_merges_existing_migration_branches( + database_app: Flask, existing_head: str +) -> None: + """Existing installations on either branch can upgrade to a single head.""" + with database_app.app_context(): + migrate_upgrade(revision=existing_head) + migrate_upgrade() + + assert _database_revision(database_app) == _head_revision(database_app) + tables = set(inspect(db.engine).get_table_names()) + assert {"blocked_sources", "allowed_sources", "source_documents"} <= tables + + def test_upgrade_is_safe_to_run_when_already_current(database_app: Flask) -> None: runner = database_app.test_cli_runner() assert runner.invoke(args=["db", "create-db"]).exit_code == 0 diff --git a/tests/test_config.py b/tests/test_config.py index d075e7d..4a5f4cb 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -39,6 +39,15 @@ def test_session_cookie_defaults( assert config_class.SESSION_COOKIE_SAMESITE == "Lax" +def test_source_allowlist_mode_requires_boolean_configuration(tmp_path: Path) -> None: + class BadSourceModeConfig(TestingConfig): + LOG_FILE = str(tmp_path / "mode-test.log") + SOURCE_ALLOWLIST_ENABLED = "yes" + + with pytest.raises(ValueError, match="SOURCE_ALLOWLIST_ENABLED"): + create_app(BadSourceModeConfig) + + def test_explicit_config_overrides_session_cookie_defaults() -> None: class CookieOverrideConfig(TestingConfig): SESSION_COOKIE_SECURE = True @@ -141,6 +150,7 @@ def test_allowed_hostnames_are_normalized_at_startup(tmp_path: Path) -> None: (["example.com", None], ValueError), (["example.com", ""], ValueError), (["example.com", " "], ValueError), + (["*.example.com"], ValueError), ], ) def test_invalid_allowed_hostnames_fail_at_startup( @@ -154,6 +164,23 @@ def test_invalid_allowed_hostnames_fail_at_startup( create_app(InvalidHostnameConfig) +def test_hostname_config_shares_admin_canonicalization(tmp_path: Path) -> None: + class InternationalizedHosts(TestingConfig): + LOG_FILE = str(tmp_path / "idn.log") + ALLOWED_TARGET_HOSTNAMES = {"BÜCHER.example.", "EXAMPLE.COM"} + IGNORED_TARGET_HOSTNAMES = {"*.BÜCHER.example.", "EXAMPLE.COM."} + + app = create_app(InternationalizedHosts) + assert app.config["ALLOWED_TARGET_HOSTNAMES"] == { + "xn--bcher-kva.example", + "example.com", + } + assert app.config["IGNORED_TARGET_HOSTNAMES"] == { + "*.xn--bcher-kva.example", + "example.com", + } + + def test_ignored_hostnames_are_normalized_at_startup(tmp_path: Path) -> None: class MixedCaseConfig(TestingConfig): LOG_FILE = str(tmp_path / "test.log") diff --git a/tests/test_hostname.py b/tests/test_hostname.py new file mode 100644 index 0000000..0faaacd --- /dev/null +++ b/tests/test_hostname.py @@ -0,0 +1,72 @@ +# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me> +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Regression tests for the one shared hostname normalizer.""" + +import pytest + +from webmentions_ssg.hostname import normalize_hostname + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Example.COM.", "example.com"), + ("blog.Example.COM", "blog.example.com"), + ("bücher.example", "xn--bcher-kva.example"), + ("198.51.100.10", "198.51.100.10"), + ("2001:db8::1", "2001:db8::1"), + ], +) +def test_normalize_bare_hostname(value: str, expected: str) -> None: + assert normalize_hostname(value) == expected + + +@pytest.mark.parametrize( + "value", + [ + "", + " example.com", + "https://example.com", + "example.com/path", + "*.example.com", + "-bad.example", + "bad-.example", + "example..com", + "example.com:8080", + "hello_foo.example", + "a" * 64 + ".example", + ], +) +def test_reject_invalid_bare_hostname(value: str) -> None: + with pytest.raises(ValueError): + normalize_hostname(value) + + +@pytest.mark.parametrize( + ("url", "expected"), + [ + ("https://EXAMPLE.com./path", "example.com"), + ("http://[2001:db8::1]/", "2001:db8::1"), + ("https://BÜCHER.example.:8443/post", "xn--bcher-kva.example"), + ], +) +def test_normalize_url_hostname(url: str, expected: str) -> None: + assert normalize_hostname(url, from_url=True) == expected + + +@pytest.mark.parametrize("url", ["https:///path", "http://[::1", "invalid"]) +def test_reject_url_without_valid_hostname(url: str) -> None: + with pytest.raises(ValueError): + normalize_hostname(url, from_url=True) + + +def test_wildcard_mode_is_explicit() -> None: + assert normalize_hostname("*.EXAMPLE.com.", allow_patterns=True) == "*.example.com" + assert ( + normalize_hostname("blog?.example.com", allow_patterns=True) + == "blog?.example.com" + ) + with pytest.raises(ValueError): + normalize_hostname("*.example.com") diff --git a/tests/test_net.py b/tests/test_net.py index 472ae91..6ff267d 100644 --- a/tests/test_net.py +++ b/tests/test_net.py @@ -25,7 +25,6 @@ from webmentions_ssg.net import ( is_http_url, is_public_address, media_type_of, - normalized_hostname, read_limited_body, resolve_public_addresses, ) @@ -344,19 +343,6 @@ def test_is_retryable_status(app: Flask, status: int, expected: bool) -> None: @pytest.mark.parametrize( - ("url", "expected"), - [ - pytest.param("https://EXAMPLE.com./path", "example.com", id="trailing-dot"), - pytest.param("http://[2001:db8::1]/", "2001:db8::1", id="ipv6"), - pytest.param("https:///path", None, id="missing-host"), - pytest.param("http://[::1", None, id="malformed-ipv6"), - ], -) -def test_normalized_hostname(url: str, expected: str | None) -> None: - assert normalized_hostname(url) == expected - - -@pytest.mark.parametrize( ("headers", "expected"), [ pytest.param({}, "", id="missing"), diff --git a/tests/test_source_policy.py b/tests/test_source_policy.py new file mode 100644 index 0000000..cddfa3a --- /dev/null +++ b/tests/test_source_policy.py @@ -0,0 +1,67 @@ +# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me> +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Domain normalization and receiver admission policy.""" + +import pytest +from flask import Flask + +from webmentions_ssg import db +from webmentions_ssg.models import AllowedSource, BlockedSource +from webmentions_ssg.source_policy import ( + source_domain_from_url, + source_rejection_reason, +) + + +def test_source_domain_from_url() -> None: + assert ( + source_domain_from_url("https://BÜCHER.example.:8443/post") + == "xn--bcher-kva.example" + ) + assert source_domain_from_url("https://[2001:db8::1]/post") == "2001:db8::1" + assert source_domain_from_url("invalid") is None + + +def test_blocked_domain_matches_itself_and_subdomains_but_not_suffixes( + app: Flask, +) -> None: + with app.app_context(): + db.session.add(BlockedSource(domain="example.org")) + db.session.commit() + for source in ( + "https://example.org/post", + "https://blog.example.org/post", + "https://A.blog.Example.ORG./post", + ): + assert source_rejection_reason(source) == "Source domain is blocked" + for source in ( + "https://notexample.org/post", + "https://example.org.evil/post", + "https://other.net/post", + ): + assert source_rejection_reason(source) is None + + +def test_allowlist_is_fail_closed_and_blocklist_takes_precedence(app: Flask) -> None: + app.config["SOURCE_ALLOWLIST_ENABLED"] = True + with app.app_context(): + assert ( + source_rejection_reason("https://example.org/post") + == "Source domain is not allowlisted" + ) + db.session.add(AllowedSource(domain="example.org")) + db.session.commit() + assert source_rejection_reason("https://blog.example.org/post") is None + assert ( + source_rejection_reason("https://notexample.org/post") + == "Source domain is not allowlisted" + ) + db.session.add(BlockedSource(domain="blog.example.org")) + db.session.commit() + assert ( + source_rejection_reason("https://blog.example.org/post") + == "Source domain is blocked" + ) + assert source_rejection_reason("https://example.org/post") is None diff --git a/tests/views/test_admin.py b/tests/views/test_admin.py index a475ad5..175bcfd 100644 --- a/tests/views/test_admin.py +++ b/tests/views/test_admin.py @@ -795,11 +795,12 @@ def test_received_bulk_toolbar_and_shared_confirmation_modal( assert 'id="received-select-all"' in html assert 'id="received-selected-count"' in html assert 'data-received-bulk-action="reverify"' in html + assert 'data-received-bulk-action="block-sources"' in html assert 'data-received-bulk-action="delete"' in html assert 'data-title="Delete all declined webmentions?"' in html assert html.count('id="confirmation-modal"') == 1 assert 'id="confirmation-modal-form"' in html - assert 'received-bulk-actions.js' in html + assert "received-bulk-actions.js" in html def test_received_delete_all_declined_available_without_matching_rows( @@ -815,12 +816,18 @@ def test_received_delete_all_declined_available_without_matching_rows( assert 'data-title="Delete all declined webmentions?"' in html assert 'id="confirmation-modal-form"' in html assert 'data-received-bulk-action="delete"' not in html + assert 'data-received-bulk-action="block-sources"' not in html assert 'id="received-select-all"' not in html @pytest.mark.parametrize( "path", - ["/received/bulk/reverify", "/received/bulk/delete", "/received/declined/delete"], + [ + "/received/bulk/reverify", + "/received/bulk/block-sources", + "/received/bulk/delete", + "/received/declined/delete", + ], ) def test_received_bulk_actions_require_login(client: FlaskClient, path: str) -> None: response = client.post(path) @@ -831,7 +838,12 @@ def test_received_bulk_actions_require_login(client: FlaskClient, path: str) -> @pytest.mark.parametrize( "path", - ["/received/bulk/reverify", "/received/bulk/delete", "/received/declined/delete"], + [ + "/received/bulk/reverify", + "/received/bulk/block-sources", + "/received/bulk/delete", + "/received/declined/delete", + ], ) def test_received_bulk_actions_reject_invalid_form( app: Flask, @@ -854,7 +866,12 @@ def test_received_bulk_actions_reject_invalid_form( @pytest.mark.parametrize( "path", - ["/received/bulk/reverify", "/received/bulk/delete", "/received/declined/delete"], + [ + "/received/bulk/reverify", + "/received/bulk/block-sources", + "/received/bulk/delete", + "/received/declined/delete", + ], ) def test_received_bulk_actions_reject_invalid_filters_before_mutating( app: Flask, @@ -881,7 +898,7 @@ def test_received_bulk_actions_reject_invalid_filters_before_mutating( verify.assert_not_called() -@pytest.mark.parametrize("action", ["reverify", "delete"]) +@pytest.mark.parametrize("action", ["reverify", "block-sources", "delete"]) @pytest.mark.parametrize("selection", [[], ["bad-uuid"]]) def test_received_bulk_actions_reject_empty_or_malformed_selection( app: Flask, @@ -907,7 +924,7 @@ def test_received_bulk_actions_reject_empty_or_malformed_selection( verify.assert_not_called() -@pytest.mark.parametrize("action", ["reverify", "delete"]) +@pytest.mark.parametrize("action", ["reverify", "block-sources", "delete"]) def test_received_bulk_actions_reject_duplicate_oversized_or_stale_selection( app: Flask, client: FlaskClient, @@ -932,9 +949,7 @@ def test_received_bulk_actions_reject_duplicate_oversized_or_stale_selection( assert stale.status_code == HTTPStatus.NOT_FOUND app.config["RECEIVED_MAX_PAGE_SIZE"] = 1 - oversized = client.post( - path, data={"webmention_uuids": [str(first), str(second)]} - ) + oversized = client.post(path, data={"webmention_uuids": [str(first), str(second)]}) assert oversized.status_code == HTTPStatus.BAD_REQUEST with app.app_context(): @@ -1022,7 +1037,9 @@ def test_delete_all_declined_received_webmentions_ignores_age_and_filters( monkeypatch: pytest.MonkeyPatch, ) -> None: log_in(app, client) - failed = create_received_webmention(app, status="failed", updated_at=datetime.now(UTC)) + failed = create_received_webmention( + app, status="failed", updated_at=datetime.now(UTC) + ) removed = create_received_webmention( app, source="https://other.example/post", @@ -1086,8 +1103,7 @@ def test_received_bulk_delete_requires_real_csrf_token( html = client.get("/received").get_data(as_text=True) match = re.search( - r'<input\b(?=[^>]*name="csrf_token")(?=[^>]*value="([^"]+)")[^>]*>', - html, + r'<input\b(?=[^>]*name="csrf_token")(?=[^>]*value="([^"]+)")[^>]*>', html ) assert match is not None valid = client.post( diff --git a/tests/views/test_source_domains.py b/tests/views/test_source_domains.py new file mode 100644 index 0000000..c9e72b2 --- /dev/null +++ b/tests/views/test_source_domains.py @@ -0,0 +1,297 @@ +# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me> +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Authenticated source-domain management and early endpoint rejection.""" + +import uuid +from datetime import UTC, datetime +from http import HTTPStatus +from unittest.mock import Mock + +import pytest +import sqlalchemy as sa +from flask import Flask +from flask.testing import FlaskClient + +from webmentions_ssg import db +from webmentions_ssg.models import ( + AllowedSource, + BlockedSource, + ReceivedWebmention, + ReceivedWebmentionStatus, +) +from webmentions_ssg.tasks.verification import VerificationClaim + +from .helpers import SOURCE_URL, TARGET_URL, create_received_webmention, log_in + + +def test_source_rules_require_login(client: FlaskClient) -> None: + for method, path, data in ( + ("get", "/source-domains", None), + ("post", "/source-domains/blocked/add", {"domain": "bad.example"}), + ("post", "/source-domains/blocked/1/delete", None), + ): + response = client.open(path, method=method.upper(), data=data) + assert response.status_code == HTTPStatus.FOUND + assert "/login" in response.headers["Location"] + + +def test_add_and_unblock_source_domain(app: Flask, client: FlaskClient) -> None: + log_in(app, client) + response = client.post( + "/source-domains/blocked/add", data={"domain": "SPAM.Example."} + ) + assert response.status_code == HTTPStatus.FOUND + response = client.post( + "/source-domains/blocked/add", data={"domain": "spam.example"} + ) + assert response.status_code == HTTPStatus.FOUND + + with app.app_context(): + rows = db.session.scalars(sa.select(BlockedSource)).all() + assert len(rows) == 1 + assert rows[0].domain == "spam.example" + entry_id = rows[0].id + + response = client.get("/source-domains") + assert response.status_code == HTTPStatus.OK + assert b"spam.example" in response.data + assert b"Unblock" in response.data + assert b"Source rules" in response.data + + response = client.post(f"/source-domains/blocked/{entry_id}/delete") + assert response.status_code == HTTPStatus.FOUND + with app.app_context(): + assert db.session.scalar(sa.select(sa.func.count(BlockedSource.id))) == 0 + + +def test_allowlist_can_be_managed_while_mode_is_off( + app: Flask, client: FlaskClient +) -> None: + log_in(app, client) + response = client.post( + "/source-domains/allowed/add", data={"domain": "friends.example"} + ) + assert response.status_code == HTTPStatus.FOUND + with app.app_context(): + row = db.session.scalar(sa.select(AllowedSource)) + assert row is not None + assert row.domain == "friends.example" + assert b"disabled" in client.get("/source-domains").data + + +@pytest.mark.parametrize( + "domain", ["https://spam.example", "*.example.com", "example.com/path", "bad host"] +) +def test_invalid_domains_are_rejected( + client: FlaskClient, app: Flask, domain: str +) -> None: + log_in(app, client) + response = client.post("/source-domains/blocked/add", data={"domain": domain}) + assert response.status_code == HTTPStatus.BAD_REQUEST + + +def test_invalid_list_kind_and_missing_entry(app: Flask, client: FlaskClient) -> None: + log_in(app, client) + assert ( + client.post("/source-domains/nope/add", data={"domain": "test.org"}).status_code + == 404 + ) + assert client.post("/source-domains/blocked/123/delete").status_code == 404 + + +def test_received_row_can_block_domain(app: Flask, client: FlaskClient) -> None: + log_in(app, client) + mention_id = create_received_webmention(app, source="https://spam.example/article") + response = client.get("/received") + assert b"Block this domain" in response.data + response = client.post(f"/received/{mention_id}/block-source") + assert response.status_code == HTTPStatus.FOUND + with app.app_context(): + rule = db.session.scalar(sa.select(BlockedSource)) + assert rule is not None and rule.domain == "spam.example" + + +def test_block_selected_source_domains_deduplicates_and_preserves_mentions( + app: Flask, client: FlaskClient +) -> None: + from urllib.parse import parse_qs, urlsplit + + log_in(app, client) + first = create_received_webmention(app, source="https://SPAM.Example./article") + same_domain = create_received_webmention( + app, source="https://spam.example/another-article" + ) + second = create_received_webmention(app, source="https://second.example/article") + unselected = create_received_webmention(app, source="https://other.example/article") + with app.app_context(): + db.session.add(BlockedSource(domain="second.example")) + db.session.commit() + + response = client.post( + "/received/bulk/block-sources", + query_string={"page": 3, "status": "verified", "sort": "source"}, + data={"webmention_uuids": [str(first), str(same_domain), str(second)]}, + ) + + assert response.status_code == HTTPStatus.FOUND + assert parse_qs(urlsplit(response.headers["Location"]).query) == { + "page": ["3"], + "status": ["verified"], + "sort": ["source"], + } + with app.app_context(): + assert set(db.session.scalars(sa.select(BlockedSource.domain))) == { + "spam.example", + "second.example", + } + for identifier in (first, same_domain, second, unselected): + assert db.session.get(ReceivedWebmention, identifier) is not None + from webmentions_ssg.source_policy import source_rejection_reason + + assert ( + source_rejection_reason("https://child.spam.example/post") + == "Source domain is blocked" + ) + assert source_rejection_reason("https://other.example/post") is None + + # Repeating the action is idempotent. + response = client.post( + "/received/bulk/block-sources", + data={"webmention_uuids": [str(first), str(same_domain)]}, + ) + assert response.status_code == HTTPStatus.FOUND + with app.app_context(): + assert db.session.scalar(sa.select(sa.func.count(BlockedSource.id))) == 2 + + +def test_bulk_block_rejects_invalid_source_without_partial_changes( + app: Flask, client: FlaskClient +) -> None: + log_in(app, client) + valid = create_received_webmention(app, source="https://valid.example/post") + invalid = create_received_webmention(app, source="not-a-url") + + response = client.post( + "/received/bulk/block-sources", + data={"webmention_uuids": [str(valid), str(invalid)]}, + ) + assert response.status_code == HTTPStatus.BAD_REQUEST + with app.app_context(): + assert db.session.scalar(sa.select(sa.func.count(BlockedSource.id))) == 0 + + +def test_bulk_block_action_enforces_csrf(app: Flask, client: FlaskClient) -> None: + log_in(app, client) + identifier = create_received_webmention(app) + app.config["WTF_CSRF_ENABLED"] = True + + response = client.post( + "/received/bulk/block-sources", data={"webmention_uuids": str(identifier)} + ) + assert response.status_code == HTTPStatus.BAD_REQUEST + with app.app_context(): + assert db.session.scalar(sa.select(sa.func.count(BlockedSource.id))) == 0 + + +def test_endpoint_rejects_blocked_without_queue_or_insert( + app: Flask, client: FlaskClient, monkeypatch: pytest.MonkeyPatch +) -> None: + from webmentions_ssg.views import endpoint + + enqueue = Mock() + monkeypatch.setattr(endpoint, "verify_webmention", enqueue) + with app.app_context(): + db.session.add(BlockedSource(domain="source.example")) + db.session.commit() + + response = client.post( + "/endpoint", data={"source": SOURCE_URL, "target": TARGET_URL} + ) + assert response.status_code == HTTPStatus.FORBIDDEN + assert response.json == {"error": "Source domain is blocked"} + enqueue.assert_not_called() + with app.app_context(): + assert db.session.scalar(sa.select(sa.func.count(ReceivedWebmention.uuid))) == 0 + + +def test_allowlist_mode_rejects_unlisted_and_allows_listed( + app: Flask, client: FlaskClient, monkeypatch: pytest.MonkeyPatch +) -> None: + from webmentions_ssg.views import endpoint + + app.config["SOURCE_ALLOWLIST_ENABLED"] = True + enqueue = Mock() + monkeypatch.setattr(endpoint, "verify_webmention", enqueue) + data = {"source": SOURCE_URL, "target": TARGET_URL} + assert client.post("/endpoint", data=data).status_code == HTTPStatus.FORBIDDEN + + with app.app_context(): + db.session.add(AllowedSource(domain="source.example")) + db.session.commit() + + assert client.post("/endpoint", data=data).status_code == HTTPStatus.CREATED + enqueue.assert_called_once() + + +def test_worker_checks_rules_before_fetch( + app: Flask, monkeypatch: pytest.MonkeyPatch +) -> None: + from webmentions_ssg.tasks import verification + + claim = VerificationClaim( + webmention_uuid=uuid.uuid7(), + source=SOURCE_URL, + target=TARGET_URL, + lease_started_at=datetime.now(UTC), + ) + fetch = Mock() + monkeypatch.setattr(verification, "source_mentions_target", fetch) + with app.app_context(): + db.session.add(BlockedSource(domain="source.example")) + db.session.commit() + assert verification.determine_verification_outcome(claim) == ( + ReceivedWebmentionStatus.FAILED, + "Source domain is blocked", + ) + fetch.assert_not_called() + + +def test_queued_worker_skips_fetch_after_source_is_blocked( + app: Flask, monkeypatch: pytest.MonkeyPatch +) -> None: + from webmentions_ssg.tasks import verification + + with app.app_context(): + mention = ReceivedWebmention( + uuid=uuid.uuid7(), source=SOURCE_URL, target=TARGET_URL + ) + db.session.add(mention) + db.session.commit() + identifier = mention.uuid + + # A user blocks the domain after the submission has already been queued. + db.session.add(BlockedSource(domain="source.example")) + db.session.commit() + + fetch = Mock() + monkeypatch.setattr(verification, "source_mentions_target", fetch) + verification.verify_webmention.call_local(identifier) + fetch.assert_not_called() + with app.app_context(): + mention = db.session.get(ReceivedWebmention, identifier) + assert mention is not None + assert mention.status == ReceivedWebmentionStatus.FAILED + assert mention.failure_reason == "Source domain is blocked" + + +def test_admin_actions_enforce_csrf(app: Flask, client: FlaskClient) -> None: + log_in(app, client) + app.config["WTF_CSRF_ENABLED"] = True + assert ( + client.post( + "/source-domains/blocked/add", data={"domain": "spam.example"} + ).status_code + == HTTPStatus.BAD_REQUEST + ) |
