aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--tests/test_status_url_security.py150
-rw-r--r--webmentions_ssg/__init__.py3
-rw-r--r--webmentions_ssg/tasks/sender.py13
-rw-r--r--webmentions_ssg/templates/sent_source.html6
4 files changed, 169 insertions, 3 deletions
diff --git a/tests/test_status_url_security.py b/tests/test_status_url_security.py
new file mode 100644
index 0000000..8a9c4f2
--- /dev/null
+++ b/tests/test_status_url_security.py
@@ -0,0 +1,150 @@
+# 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/webmentions_ssg/__init__.py b/webmentions_ssg/__init__.py
index 04746d6..61add02 100644
--- a/webmentions_ssg/__init__.py
+++ b/webmentions_ssg/__init__.py
@@ -21,6 +21,7 @@ from sqlalchemy.orm import DeclarativeBase
from webmentions_ssg.config import DefaultConfig, DevelopmentConfig, ProductionConfig
from .tasks import Huey
+from .url_security import is_http_url
APP_NAME = "webmentions-ssg"
VERSION = "0.0.2"
@@ -126,6 +127,8 @@ def create_app(config_class: type[DefaultConfig] | None = None) -> Flask:
"""
return {"VERSION": VERSION}
+ app.add_template_filter(is_http_url)
+
from .views import root_page
app.register_blueprint(root_page)
diff --git a/webmentions_ssg/tasks/sender.py b/webmentions_ssg/tasks/sender.py
index cceefcd..8834934 100644
--- a/webmentions_ssg/tasks/sender.py
+++ b/webmentions_ssg/tasks/sender.py
@@ -257,7 +257,14 @@ def post_webmention(
if response.status_code == 201 and (
location := response.headers.get("Location")
):
- status_url = urljoin(str(response.url), location)
+ try:
+ candidate = urljoin(str(response.url), location)
+ except ValueError:
+ # A malformed Location must not fail an otherwise successful send.
+ pass
+ else:
+ if is_http_url(candidate):
+ status_url = candidate
return (response.status_code, status_url)
@@ -399,7 +406,9 @@ def send_webmention(webmention_uuid: uuid.UUID) -> None:
webmention.endpoint = endpoint
webmention.response_status = response_status
- webmention.status_url = status_url
+ webmention.status_url = (
+ status_url if status_url is not None and is_http_url(status_url) else None
+ )
webmention.last_sent_at = datetime.now(UTC)
diff --git a/webmentions_ssg/templates/sent_source.html b/webmentions_ssg/templates/sent_source.html
index e840f8f..8d22068 100644
--- a/webmentions_ssg/templates/sent_source.html
+++ b/webmentions_ssg/templates/sent_source.html
@@ -154,7 +154,11 @@ SPDX-License-Identifier: BSD-3-Clause
{% if webmention.status_url is not none %}
<div>
<strong>Status:</strong>
- <a href="{{ webmention.status_url }}" class="text-break">{{ webmention.status_url }}</a>
+ {% if webmention.status_url | is_http_url %}
+ <a href="{{ webmention.status_url }}" class="text-break">{{ webmention.status_url }}</a>
+ {% else %}
+ <span class="text-break">{{ webmention.status_url }}</span>
+ {% endif %}
</div>
{% endif %}
</td>