aboutsummaryrefslogtreecommitdiff
path: root/tests/test_status_url_security.py
blob: 8a9c4f28ed596df9eb9aeedca1f27593b90b1c31 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
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