aboutsummaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
authorDennis Fink2026-10-30 11:51:34 +0100
committerDennis Fink2026-10-30 11:51:34 +0100
commit37bc3853dded34e3d1323874927979ce510e4910 (patch)
tree7d6d2181d9bb05f4d4a8d00152c172cc92e7ab63 /tests
parent4485aeb573ceb37237ea1fbc80665ed6c4136116 (diff)
downloadwebmentions-ssg-37bc3853dded34e3d1323874927979ce510e4910.tar.gz
webmentions-ssg-37bc3853dded34e3d1323874927979ce510e4910.zip
test: align test suite with package structure
Diffstat (limited to '')
-rw-r--r--tests/__init__.py3
-rw-r--r--tests/cli/__init__.py3
-rw-r--r--tests/cli/test_init.py12
-rw-r--r--tests/forms/__init__.py3
-rw-r--r--tests/forms/test_init.py (renamed from tests/forms/test_forms.py)0
-rw-r--r--tests/tasks/__init__.py3
-rw-r--r--tests/tasks/test_consumer.py45
-rw-r--r--tests/tasks/test_init.py12
-rw-r--r--tests/tasks/test_sender.py63
-rw-r--r--tests/test_auth.py28
-rw-r--r--tests/test_config.py106
-rw-r--r--tests/test_configuration_hardening.py119
-rw-r--r--tests/test_init.py24
-rw-r--r--tests/test_status_url_security.py150
-rw-r--r--tests/test_views.py57
15 files changed, 358 insertions, 270 deletions
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..25d78d5
--- /dev/null
+++ b/tests/__init__.py
@@ -0,0 +1,3 @@
+# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
+#
+# SPDX-License-Identifier: BSD-3-Clause
diff --git a/tests/cli/__init__.py b/tests/cli/__init__.py
new file mode 100644
index 0000000..25d78d5
--- /dev/null
+++ b/tests/cli/__init__.py
@@ -0,0 +1,3 @@
+# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
+#
+# SPDX-License-Identifier: BSD-3-Clause
diff --git a/tests/cli/test_init.py b/tests/cli/test_init.py
new file mode 100644
index 0000000..cbdab8c
--- /dev/null
+++ b/tests/cli/test_init.py
@@ -0,0 +1,12 @@
+# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Test that all application CLI command groups are exposed."""
+
+from flask import Flask
+
+
+def test_cli_groups_are_registered(app: Flask) -> None:
+ commands = app.cli.commands
+ assert {"users", "mail"}.issubset(commands)
diff --git a/tests/forms/__init__.py b/tests/forms/__init__.py
new file mode 100644
index 0000000..25d78d5
--- /dev/null
+++ b/tests/forms/__init__.py
@@ -0,0 +1,3 @@
+# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
+#
+# SPDX-License-Identifier: BSD-3-Clause
diff --git a/tests/forms/test_forms.py b/tests/forms/test_init.py
index 6fe1849..6fe1849 100644
--- a/tests/forms/test_forms.py
+++ b/tests/forms/test_init.py
diff --git a/tests/tasks/__init__.py b/tests/tasks/__init__.py
new file mode 100644
index 0000000..25d78d5
--- /dev/null
+++ b/tests/tasks/__init__.py
@@ -0,0 +1,3 @@
+# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
+#
+# SPDX-License-Identifier: BSD-3-Clause
diff --git a/tests/tasks/test_consumer.py b/tests/tasks/test_consumer.py
new file mode 100644
index 0000000..6b79e37
--- /dev/null
+++ b/tests/tasks/test_consumer.py
@@ -0,0 +1,45 @@
+# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Test scheduled-task registration during consumer creation."""
+
+import importlib
+from unittest.mock import Mock
+
+import pytest
+from flask import Flask
+
+from webmentions_ssg import HUEY
+
+
+def test_consumer_registers_scanner_and_digest(
+ app: Flask, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import webmentions_ssg
+
+ app.config["SCANNER_SCHEDULE"] = "*/15 * * * *"
+ app.config["NOTIFICATION_SCHEDULE"] = "0 9 * * *"
+
+ registered_tasks: list[object] = []
+
+ def register(_schedule: object):
+ def decorator(task: object) -> object:
+ registered_tasks.append(task)
+ return task
+
+ return decorator
+
+ periodic_task = Mock(side_effect=register)
+ monkeypatch.setattr(webmentions_ssg, "create_app", Mock(return_value=app))
+ monkeypatch.setattr(HUEY, "periodic_task", periodic_task)
+
+ consumer = importlib.import_module("webmentions_ssg.tasks.consumer")
+ from webmentions_ssg.tasks import notifications, scanner
+
+ assert consumer.huey is HUEY.huey
+ assert periodic_task.call_count == 2
+ assert registered_tasks == [
+ scanner.scan_sources,
+ notifications.send_webmention_digest,
+ ]
diff --git a/tests/tasks/test_init.py b/tests/tasks/test_init.py
new file mode 100644
index 0000000..1a51fb8
--- /dev/null
+++ b/tests/tasks/test_init.py
@@ -0,0 +1,12 @@
+# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Test the public background-task package API."""
+
+from webmentions_ssg.tasks import Huey
+from webmentions_ssg.tasks.extension import Huey as ExtensionHuey
+
+
+def test_tasks_package_exports_huey_extension() -> None:
+ assert Huey is ExtensionHuey
diff --git a/tests/tasks/test_sender.py b/tests/tasks/test_sender.py
index 6a9afc1..ecfc27a 100644
--- a/tests/tasks/test_sender.py
+++ b/tests/tasks/test_sender.py
@@ -1150,3 +1150,66 @@ def test_post_webmention(
assert form["source"] == SOURCE_URL
assert form["target"] == TARGET_URL
+
+
+@pytest.mark.parametrize(
+ ("code", "location", "expected"),
+ [
+ (201, "/webmention/status/123", "https://example.com/webmention/status/123"),
+ (201, "https://status.example.org/123", "https://status.example.org/123"),
+ (201, "status/123", "https://example.com/status/123"),
+ (201, "javascript:alert(1)", None),
+ (201, "data:text/html,evil", None),
+ (201, "ftp://example.com/status", None),
+ (201, "http://[invalid", None),
+ (202, "https://example.com/status", None),
+ ],
+)
+def test_post_webmention_validates_location(
+ sender_module: ModuleType, code: int, location: str, expected: str | None
+) -> None:
+ def handler(_request: httpx.Request) -> httpx.Response:
+ return httpx.Response(code, headers={"Location": location})
+
+ with httpx.Client(transport=httpx.MockTransport(handler)) as client:
+ result = sender_module.post_webmention(
+ client, endpoint=ENDPOINT_URL, source=SOURCE_URL, target=TARGET_URL
+ )
+
+ assert result == (code, expected)
+
+
+@pytest.mark.parametrize(
+ ("status_url", "expected"),
+ [
+ ("javascript:alert(1)", None),
+ ("data:text/html,evil", None),
+ ("ftp://example.com/status", None),
+ ("https://example.com/status", "https://example.com/status"),
+ ],
+)
+def test_send_does_not_persist_unsafe_status_url(
+ app: Flask,
+ sender_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+ status_url: str,
+ expected: str | None,
+) -> None:
+ identifier = create_sent_webmention(app)
+ client_factory = MagicMock()
+ monkeypatch.setattr(sender_module.httpx, "Client", client_factory)
+ monkeypatch.setattr(
+ sender_module, "discover_webmention_endpoint", Mock(return_value=ENDPOINT_URL)
+ )
+ monkeypatch.setattr(
+ sender_module, "post_webmention", Mock(return_value=(201, status_url))
+ )
+
+ sender_module.send_webmention.call_local(identifier)
+
+ with app.app_context():
+ mention = db.session.get(SentWebmention, identifier)
+ assert mention is not None
+ assert mention.status == SentWebmentionStatus.SENT
+ assert mention.response_status == 201
+ assert mention.status_url == expected
diff --git a/tests/test_auth.py b/tests/test_auth.py
new file mode 100644
index 0000000..e0416b0
--- /dev/null
+++ b/tests/test_auth.py
@@ -0,0 +1,28 @@
+# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Test the session user loader."""
+
+from flask import Flask
+
+from webmentions_ssg import DATABASE as db
+from webmentions_ssg.auth import AUTH, load_user
+from webmentions_ssg.models import User
+
+
+def test_user_loader_is_registered(app: Flask) -> None:
+ assert AUTH._user_callback is load_user
+
+
+def test_load_user_returns_matching_user(app: Flask) -> None:
+ with app.app_context():
+ user = User(username="account", password="secret")
+ db.session.add(user)
+ db.session.commit()
+ assert load_user(user.id) is user
+
+
+def test_load_user_returns_none_for_unknown_id(app: Flask) -> None:
+ with app.app_context():
+ assert load_user(99_999) is None
diff --git a/tests/test_config.py b/tests/test_config.py
index 8d5aa5b..57ac423 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -2,9 +2,13 @@
#
# SPDX-License-Identifier: BSD-3-Clause
-"""Test built-in session cookie defaults and explicit overrides."""
+"""Test application configuration defaults, loading, and hardening."""
+
+from pathlib import Path
import pytest
+from wtforms import Field, ValidationError
+from wtforms.form import BaseForm
from webmentions_ssg import create_app
from webmentions_ssg.config import (
@@ -13,6 +17,7 @@ from webmentions_ssg.config import (
ProductionConfig,
TestingConfig,
)
+from webmentions_ssg.forms.validators import AllowedHostname
@pytest.mark.parametrize(
@@ -43,3 +48,102 @@ def test_explicit_config_overrides_session_cookie_defaults() -> None:
assert app.config["SESSION_COOKIE_SECURE"] is True
assert app.config["SESSION_COOKIE_HTTPONLY"] is False
assert app.config["SESSION_COOKIE_SAMESITE"] == "Strict"
+
+
+def test_missing_production_configuration_is_fatal(tmp_path: Path) -> None:
+ class MissingProductionConfig(ProductionConfig):
+ CONFIG_FILE = str(tmp_path / "missing.cfg")
+
+ with pytest.raises(FileNotFoundError, match="missing.cfg"):
+ create_app(MissingProductionConfig)
+
+
+def test_missing_development_configuration_is_optional(tmp_path: Path) -> None:
+ class LocalDevelopmentConfig(DevelopmentConfig):
+ CONFIG_FILE = str(tmp_path / "missing.cfg")
+ LOG_FILE = str(tmp_path / "development.log")
+
+ app = create_app(LocalDevelopmentConfig)
+ assert app.config["ALLOWED_HOSTNAMES"] == set()
+
+
+def test_endpoint_limits_are_inherited_from_defaults() -> None:
+ for config in (DefaultConfig, DevelopmentConfig, ProductionConfig, TestingConfig):
+ assert config.MAX_REDIRECTS == 20
+ assert config.MAX_SOURCE_BYTES == 1_000_000
+ assert config.REQUEST_TIMEOUT == 5.0
+
+ assert DefaultConfig.ALLOWED_HOSTNAMES == set()
+
+
+def test_allowed_hostnames_are_normalized_at_startup(tmp_path: Path) -> None:
+ class MixedCaseConfig(TestingConfig):
+ LOG_FILE = str(tmp_path / "test.log")
+ ALLOWED_HOSTNAMES = [" DennisFink.Me ", "EXAMPLE.COM", "dennisfink.me"]
+
+ app = create_app(MixedCaseConfig)
+ assert app.config["ALLOWED_HOSTNAMES"] == {"dennisfink.me", "example.com"}
+ assert isinstance(app.config["ALLOWED_HOSTNAMES"], set)
+
+ # The form validator must compare complete hostnames, never substrings.
+ target = Field()
+ validator = AllowedHostname(message="Hostname not allowed")
+ form = BaseForm({})
+ with app.app_context():
+ for url in ("https://dennisfink.me/post", "https://EXAMPLE.com/post"):
+ target.data = url
+ validator(form, target)
+
+ for url in ("https://fink/post", "https://evil-dennisfink.me/post"):
+ target.data = url
+ with pytest.raises(ValidationError, match="Hostname not allowed"):
+ validator(form, target)
+
+
+@pytest.mark.parametrize(
+ "hostnames,expected_exception",
+ [
+ ("dennisfink.me", TypeError),
+ (None, TypeError),
+ ({"dennisfink.me": True}, TypeError),
+ (123, TypeError),
+ (["example.com", None], ValueError),
+ (["example.com", ""], ValueError),
+ (["example.com", " "], ValueError),
+ ],
+)
+def test_invalid_allowed_hostnames_fail_at_startup(
+ tmp_path: Path, hostnames: object, expected_exception: type[Exception]
+) -> None:
+ class InvalidHostnameConfig(TestingConfig):
+ LOG_FILE = str(tmp_path / "test.log")
+ ALLOWED_HOSTNAMES = hostnames
+
+ with pytest.raises(expected_exception, match="ALLOWED_HOSTNAMES"):
+ create_app(InvalidHostnameConfig)
+
+
+def test_production_requires_nonempty_allowed_hostnames(tmp_path: Path) -> None:
+ config_path = tmp_path / "production.cfg"
+ config_path.write_text('RATELIMIT_STORAGE_URI = "redis://localhost:6379"\n')
+
+ class EmptyHostnamesConfig(ProductionConfig):
+ CONFIG_FILE = str(config_path)
+
+ with pytest.raises(RuntimeError, match="ALLOWED_HOSTNAMES"):
+ create_app(EmptyHostnamesConfig)
+
+
+def test_environment_allowed_hostnames_override_config_file(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ config_path = tmp_path / "development.cfg"
+ config_path.write_text('ALLOWED_HOSTNAMES = ["first.example"]\n')
+ monkeypatch.setenv("WEBMENTIONS_SSG_ALLOWED_HOSTNAMES", '["SECOND.EXAMPLE"]')
+
+ class LocalDevelopmentConfig(DevelopmentConfig):
+ CONFIG_FILE = str(config_path)
+ LOG_FILE = str(tmp_path / "development.log")
+
+ app = create_app(LocalDevelopmentConfig)
+ assert app.config["ALLOWED_HOSTNAMES"] == {"second.example"}
diff --git a/tests/test_configuration_hardening.py b/tests/test_configuration_hardening.py
deleted file mode 100644
index 753f4ca..0000000
--- a/tests/test_configuration_hardening.py
+++ /dev/null
@@ -1,119 +0,0 @@
-# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
-#
-# SPDX-License-Identifier: BSD-3-Clause
-
-"""Regression tests for configuration loading and endpoint hostname policy."""
-
-from pathlib import Path
-
-import pytest
-from wtforms import Field, ValidationError
-from wtforms.form import BaseForm
-
-from webmentions_ssg import create_app
-from webmentions_ssg.config import (
- DefaultConfig,
- DevelopmentConfig,
- ProductionConfig,
- TestingConfig,
-)
-from webmentions_ssg.forms.validators import AllowedHostname
-
-
-def test_missing_production_configuration_is_fatal(tmp_path: Path) -> None:
- class MissingProductionConfig(ProductionConfig):
- CONFIG_FILE = str(tmp_path / "missing.cfg")
-
- with pytest.raises(FileNotFoundError, match="missing.cfg"):
- create_app(MissingProductionConfig)
-
-
-def test_missing_development_configuration_is_optional(tmp_path: Path) -> None:
- class LocalDevelopmentConfig(DevelopmentConfig):
- CONFIG_FILE = str(tmp_path / "missing.cfg")
- LOG_FILE = str(tmp_path / "development.log")
-
- app = create_app(LocalDevelopmentConfig)
- assert app.config["ALLOWED_HOSTNAMES"] == set()
-
-
-def test_endpoint_limits_are_inherited_from_defaults() -> None:
- for config in (DefaultConfig, DevelopmentConfig, ProductionConfig, TestingConfig):
- assert config.MAX_REDIRECTS == 20
- assert config.MAX_SOURCE_BYTES == 1_000_000
- assert config.REQUEST_TIMEOUT == 5.0
-
- assert DefaultConfig.ALLOWED_HOSTNAMES == set()
-
-
-def test_allowed_hostnames_are_normalized_at_startup(tmp_path: Path) -> None:
- class MixedCaseConfig(TestingConfig):
- LOG_FILE = str(tmp_path / "test.log")
- ALLOWED_HOSTNAMES = [" DennisFink.Me ", "EXAMPLE.COM", "dennisfink.me"]
-
- app = create_app(MixedCaseConfig)
- assert app.config["ALLOWED_HOSTNAMES"] == {"dennisfink.me", "example.com"}
- assert isinstance(app.config["ALLOWED_HOSTNAMES"], set)
-
- # The form validator must compare complete hostnames, never substrings.
- target = Field()
- validator = AllowedHostname(message="Hostname not allowed")
- form = BaseForm({})
- with app.app_context():
- for url in ("https://dennisfink.me/post", "https://EXAMPLE.com/post"):
- target.data = url
- validator(form, target)
-
- for url in ("https://fink/post", "https://evil-dennisfink.me/post"):
- target.data = url
- with pytest.raises(ValidationError, match="Hostname not allowed"):
- validator(form, target)
-
-
-@pytest.mark.parametrize(
- "hostnames,expected_exception",
- [
- ("dennisfink.me", TypeError),
- (None, TypeError),
- ({"dennisfink.me": True}, TypeError),
- (123, TypeError),
- (["example.com", None], ValueError),
- (["example.com", ""], ValueError),
- (["example.com", " "], ValueError),
- ],
-)
-def test_invalid_allowed_hostnames_fail_at_startup(
- tmp_path: Path, hostnames: object, expected_exception: type[Exception]
-) -> None:
- class InvalidHostnameConfig(TestingConfig):
- LOG_FILE = str(tmp_path / "test.log")
- ALLOWED_HOSTNAMES = hostnames
-
- with pytest.raises(expected_exception, match="ALLOWED_HOSTNAMES"):
- create_app(InvalidHostnameConfig)
-
-
-def test_production_requires_nonempty_allowed_hostnames(tmp_path: Path) -> None:
- config_path = tmp_path / "production.cfg"
- config_path.write_text('RATELIMIT_STORAGE_URI = "redis://localhost:6379"\n')
-
- class EmptyHostnamesConfig(ProductionConfig):
- CONFIG_FILE = str(config_path)
-
- with pytest.raises(RuntimeError, match="ALLOWED_HOSTNAMES"):
- create_app(EmptyHostnamesConfig)
-
-
-def test_environment_allowed_hostnames_override_config_file(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- config_path = tmp_path / "development.cfg"
- config_path.write_text('ALLOWED_HOSTNAMES = ["first.example"]\n')
- monkeypatch.setenv("WEBMENTIONS_SSG_ALLOWED_HOSTNAMES", '["SECOND.EXAMPLE"]')
-
- class LocalDevelopmentConfig(DevelopmentConfig):
- CONFIG_FILE = str(config_path)
- LOG_FILE = str(tmp_path / "development.log")
-
- app = create_app(LocalDevelopmentConfig)
- assert app.config["ALLOWED_HOSTNAMES"] == {"second.example"}
diff --git a/tests/test_init.py b/tests/test_init.py
new file mode 100644
index 0000000..d690032
--- /dev/null
+++ b/tests/test_init.py
@@ -0,0 +1,24 @@
+# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+"""Test application initialization and its public integrations."""
+
+from flask import Flask
+
+from webmentions_ssg import VERSION, HUEY
+from webmentions_ssg.url_security import is_http_url
+
+
+def test_create_app_registers_blueprint_and_extensions(app: Flask) -> None:
+ assert "root" in app.blueprints
+ assert app.extensions["huey"] is HUEY
+ assert app.jinja_env.filters["is_http_url"] is is_http_url
+
+
+def test_create_app_exposes_version_in_templates(app: Flask) -> None:
+ with app.test_request_context():
+ context: dict[str, str] = {}
+ app.update_template_context(context)
+
+ assert context["VERSION"] == VERSION
diff --git a/tests/test_status_url_security.py b/tests/test_status_url_security.py
deleted file mode 100644
index 8a9c4f2..0000000
--- a/tests/test_status_url_security.py
+++ /dev/null
@@ -1,150 +0,0 @@
-# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
-#
-# SPDX-License-Identifier: BSD-3-Clause
-
-"""Protect outgoing Webmention status URLs from unsafe URI schemes."""
-
-import uuid
-from datetime import UTC, datetime
-from types import ModuleType
-from unittest.mock import MagicMock, Mock
-
-import httpx
-import pytest
-from flask import Flask
-from flask.testing import FlaskClient
-
-from webmentions_ssg import DATABASE as db
-from webmentions_ssg.models import SentWebmention, SentWebmentionStatus, Source, User
-
-ENDPOINT_URL = "https://example.com/webmention"
-SOURCE_URL = "https://source.example/blog/post"
-TARGET_URL = "https://example.com/article"
-
-
-@pytest.fixture
-def sender_module(app: Flask) -> ModuleType:
- _ = app
- from webmentions_ssg.tasks import sender
-
- return sender
-
-
-def create_outgoing(
- app: Flask, *, status_url: str | None = None
-) -> tuple[uuid.UUID, uuid.UUID]:
- now = datetime.now(UTC)
- with app.app_context():
- source = Source(
- path="blog/post/index.html",
- url=SOURCE_URL,
- content_hash="0" * 32,
- revision=1,
- last_seen_at=now,
- revised_at=now,
- )
- mention = SentWebmention(
- target=TARGET_URL,
- active=True,
- desired_revision=1,
- status_url=status_url,
- response_status=201 if status_url is not None else None,
- )
- source.sent_webmentions.append(mention)
- db.session.add(source)
- db.session.commit()
- return source.uuid, mention.uuid
-
-
-@pytest.mark.parametrize(
- ("code", "location", "expected"),
- [
- (201, "/webmention/status/123", "https://example.com/webmention/status/123"),
- (201, "https://status.example.org/123", "https://status.example.org/123"),
- (201, "status/123", "https://example.com/status/123"),
- (201, "javascript:alert(1)", None),
- (201, "data:text/html,evil", None),
- (201, "ftp://example.com/status", None),
- (201, "http://[invalid", None),
- (202, "https://example.com/status", None),
- ],
-)
-def test_post_webmention_validates_location(
- sender_module: ModuleType, code: int, location: str, expected: str | None
-) -> None:
- def handler(_request: httpx.Request) -> httpx.Response:
- return httpx.Response(code, headers={"Location": location})
-
- with httpx.Client(transport=httpx.MockTransport(handler)) as client:
- result = sender_module.post_webmention(
- client, endpoint=ENDPOINT_URL, source=SOURCE_URL, target=TARGET_URL
- )
-
- assert result == (code, expected)
-
-
-@pytest.mark.parametrize(
- ("status_url", "expected"),
- [
- ("javascript:alert(1)", None),
- ("data:text/html,evil", None),
- ("ftp://example.com/status", None),
- ("https://example.com/status", "https://example.com/status"),
- ],
-)
-def test_send_does_not_persist_unsafe_status_url(
- app: Flask,
- sender_module: ModuleType,
- monkeypatch: pytest.MonkeyPatch,
- status_url: str,
- expected: str | None,
-) -> None:
- _, identifier = create_outgoing(app)
- client_factory = MagicMock()
- monkeypatch.setattr(sender_module.httpx, "Client", client_factory)
- monkeypatch.setattr(
- sender_module, "discover_webmention_endpoint", Mock(return_value=ENDPOINT_URL)
- )
- monkeypatch.setattr(
- sender_module, "post_webmention", Mock(return_value=(201, status_url))
- )
-
- sender_module.send_webmention.call_local(identifier)
-
- with app.app_context():
- mention = db.session.get(SentWebmention, identifier)
- assert mention is not None
- assert mention.status == SentWebmentionStatus.SENT
- assert mention.response_status == 201
- assert mention.status_url == expected
-
-
-@pytest.mark.parametrize(
- ("status_url", "safe"),
- [
- ("https://example.com/status", True),
- ("http://example.com/status", True),
- ("javascript:alert(1)", False),
- ("data:text/html,evil", False),
- ("ftp://example.com/status", False),
- ],
-)
-def test_admin_only_links_safe_existing_status_urls(
- app: Flask, client: FlaskClient, status_url: str, safe: bool
-) -> None:
- source_identifier, _ = create_outgoing(app, status_url=status_url)
- with app.app_context():
- user = User(username="admin", password="test")
- db.session.add(user)
- db.session.commit()
- user_id = user.id
-
- with client.session_transaction() as session:
- session["_user_id"] = str(user_id)
- session["_fresh"] = True
-
- response = client.get(f"/sent/{source_identifier}")
- assert response.status_code == 200
- html = response.get_data(as_text=True)
- assert (f'href="{status_url}"' in html) is safe
- assert status_url in html
diff --git a/tests/test_views.py b/tests/test_views.py
index f8dd375..8ac57b1 100644
--- a/tests/test_views.py
+++ b/tests/test_views.py
@@ -1118,3 +1118,60 @@ def test_logout_ends_session(app: Flask, client: FlaskClient) -> None:
protected_response = client.get("/received")
assert protected_response.status_code == 302
assert "/login" in protected_response.headers["Location"]
+
+
+def create_outgoing(
+ app: Flask, *, status_url: str | None = None
+) -> tuple[uuid.UUID, uuid.UUID]:
+ now = datetime.now(UTC)
+ with app.app_context():
+ source = Source(
+ path="blog/post/index.html",
+ url="https://source.example/blog/post",
+ content_hash="0" * 32,
+ revision=1,
+ last_seen_at=now,
+ revised_at=now,
+ )
+ mention = SentWebmention(
+ target="https://example.com/article",
+ active=True,
+ desired_revision=1,
+ status_url=status_url,
+ response_status=201 if status_url is not None else None,
+ )
+ source.sent_webmentions.append(mention)
+ db.session.add(source)
+ db.session.commit()
+ return source.uuid, mention.uuid
+
+
+@pytest.mark.parametrize(
+ ("status_url", "safe"),
+ [
+ ("https://example.com/status", True),
+ ("http://example.com/status", True),
+ ("javascript:alert(1)", False),
+ ("data:text/html,evil", False),
+ ("ftp://example.com/status", False),
+ ],
+)
+def test_admin_only_links_safe_existing_status_urls(
+ app: Flask, client: FlaskClient, status_url: str, safe: bool
+) -> None:
+ source_identifier, _ = create_outgoing(app, status_url=status_url)
+ with app.app_context():
+ user = User(username="admin", password="test")
+ db.session.add(user)
+ db.session.commit()
+ user_id = user.id
+
+ with client.session_transaction() as session:
+ session["_user_id"] = str(user_id)
+ session["_fresh"] = True
+
+ response = client.get(f"/sent/{source_identifier}")
+ assert response.status_code == 200
+ html = response.get_data(as_text=True)
+ assert (f'href="{status_url}"' in html) is safe
+ assert status_url in html