aboutsummaryrefslogtreecommitdiff
path: root/tests/test_forms.py
blob: 7f09da6cbe9a14053bec9905445b7cff76b5c98d (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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

import pytest
from flask import Flask
from werkzeug.datastructures import MultiDict
from wtforms import Form, StringField, ValidationError

from webmentions_ssg.forms import (
    AllowedTargetHostname,
    ConfirmActionForm,
    LoginForm,
    MaxURLBytes,
    RejectNonPublicIPLiteral,
    ReceivedWebmentionFilterForm,
    WebmentionSubmissionForm,
)

VALID_SOURCE = "https://source.example/post"
VALID_TARGET = "https://dennisfink.me/blog/example/"


class URLForm(Form):
    url = StringField("URL")


@pytest.mark.parametrize(
    ("form_data", "invalid_field", "expected_error"),
    [
        pytest.param(
            {"target": VALID_TARGET},
            "source",
            "This field is required.",
            id="source-required",
        ),
        pytest.param(
            {"source": "not a URL", "target": VALID_TARGET},
            "source",
            "Invalid URL.",
            id="source-url",
        ),
        pytest.param(
            {"source": "ftp://source.example/post", "target": VALID_TARGET},
            "source",
            "source must begin with http or https",
            id="source-scheme",
        ),
        pytest.param(
            {"source": VALID_SOURCE},
            "target",
            "This field is required.",
            id="target-required",
        ),
        pytest.param(
            {"source": VALID_SOURCE, "target": "not a URL"},
            "target",
            "Invalid URL.",
            id="target-url",
        ),
        pytest.param(
            {"source": VALID_SOURCE, "target": "ftp://dennisfink.me/blog/example/"},
            "target",
            "target must begin with http or https",
            id="target-scheme",
        ),
        pytest.param(
            {"source": "http:///source.example/post", "target": VALID_TARGET},
            "source",
            "Invalid URL.",
            id="source-missing-host",
        ),
        pytest.param(
            {"source": VALID_SOURCE, "target": "https://dennisfink.me:invalid/"},
            "target",
            "Invalid URL.",
            id="target-invalid-port",
        ),
    ],
)
def test_endpoint_form_rejects_invalid_field_syntax(
    app: Flask, form_data: dict[str, str], invalid_field: str, expected_error: str
) -> None:
    with app.test_request_context("/endpoint", method="POST"):
        form = WebmentionSubmissionForm(
            formdata=MultiDict(form_data), meta={"csrf": False}
        )

        assert not form.validate()
        assert expected_error in form.errors[invalid_field]


@pytest.mark.parametrize("scheme", ["http", "https", "HTTP", "HTTPS"])
def test_endpoint_form_accepts_http_schemes_case_insensitively(
    app: Flask, scheme: str
) -> None:
    with app.test_request_context("/endpoint", method="POST"):
        form = WebmentionSubmissionForm(
            formdata=MultiDict(
                {
                    "source": f"{scheme}://source.example/post",
                    "target": f"{scheme}://dennisfink.me/blog/example/",
                }
            ),
            meta={"csrf": False},
        )
        assert form.validate()


def test_endpoint_form_accepts_valid_data(app: Flask) -> None:
    with app.test_request_context("/endpoint", method="POST"):
        form = WebmentionSubmissionForm(
            formdata=MultiDict({"source": VALID_SOURCE, "target": VALID_TARGET}),
            meta={"csrf": False},
        )

        assert form.validate()
        assert form.errors == {}


@pytest.mark.parametrize(
    ("form_data", "invalid_field"),
    [
        pytest.param({"password": "secret"}, "username", id="username-required"),
        pytest.param({"username": "admin"}, "password", id="password-required"),
    ],
)
def test_login_form_requires_credentials(
    app: Flask, form_data: dict[str, str], invalid_field: str
) -> None:
    with app.test_request_context("/login", method="POST"):
        form = LoginForm(formdata=MultiDict(form_data), meta={"csrf": False})

        assert not form.validate()
        assert "This field is required." in form.errors[invalid_field]


def test_login_form_accepts_credentials(app: Flask) -> None:
    with app.test_request_context("/login", method="POST"):
        form = LoginForm(
            formdata=MultiDict({"username": "admin", "password": "secret"}),
            meta={"csrf": False},
        )
        assert form.validate()


def test_received_filter_form_accepts_valid_get_params(app: Flask) -> None:
    with app.test_request_context("/received", method="GET"):
        form = ReceivedWebmentionFilterForm(
            formdata=MultiDict(
                {
                    "status": "declined",
                    "q": "example.org",
                    "date_from": "2026-11-08",
                    "date_to": "2026-11-14",
                }
            ),
            meta={"csrf": False},
        )
        assert form.validate()
        assert form.status.data == "declined"
        assert form.q.data == "example.org"
        assert form.date_from.data.isoformat() == "2026-11-08"
        assert form.date_to.data.isoformat() == "2026-11-14"
        assert "csrf_token" not in form._fields


@pytest.mark.parametrize(
    "data",
    [
        {"status": "unknown"},
        {"date_from": "not-a-date"},
        {"date_from": "2026-11-8"},
        {"date_to": "2026-02-30"},
        {"date_from": "2026-11-15", "date_to": "2026-11-08"},
    ],
)
def test_received_filter_form_rejects_invalid_get_params(
    app: Flask, data: dict[str, str]
) -> None:
    with app.test_request_context("/received", method="GET"):
        form = ReceivedWebmentionFilterForm(
            formdata=MultiDict(data), meta={"csrf": False}
        )
        assert not form.validate()
        assert form.errors


def test_admin_action_form_accepts_submission(app: Flask) -> None:
    with app.test_request_context(method="POST"):
        form = ConfirmActionForm(meta={"csrf": False})
        assert form.validate()


def test_endpoint_does_not_do_dns_in_web_request(
    app: Flask, monkeypatch: pytest.MonkeyPatch
) -> None:
    def unexpected_dns_lookup(*args: object, **kwargs: object) -> None:
        raise AssertionError("No DNS lookup belongs in form validation")

    monkeypatch.setattr(
        "webmentions_ssg.net.dns.resolver.resolve_name", unexpected_dns_lookup
    )
    with app.test_request_context("/endpoint", method="POST"):
        for source in (VALID_SOURCE, "ftp://source.example/post", "not a URL"):
            form = WebmentionSubmissionForm(
                formdata=MultiDict({"source": source, "target": VALID_TARGET}),
                meta={"csrf": False},
            )
            assert form.validate() is (source == VALID_SOURCE)


@pytest.mark.parametrize(
    "source", ["http://127.0.0.1/", "http://[::1]/", "http://169.254.169.254/"]
)
def test_endpoint_rejects_private_ip_literals(app: Flask, source: str) -> None:
    with app.test_request_context("/endpoint", method="POST"):
        form = WebmentionSubmissionForm(
            formdata=MultiDict({"source": source, "target": VALID_TARGET}),
            meta={"csrf": False},
        )
        assert not form.validate()
        assert "URL must use a public address." in form.errors["source"]


def test_endpoint_rejects_private_ip_literal_with_trailing_dot(app: Flask) -> None:
    with app.test_request_context("/endpoint", method="POST"):
        form = WebmentionSubmissionForm(
            formdata=MultiDict(
                {"source": "http://127.0.0.1./", "target": VALID_TARGET}
            ),
            meta={"csrf": False},
        )
        assert not form.validate()
        assert "URL must use a public address." in form.errors["source"]


def test_endpoint_handles_malformed_ipv6_without_crashing(app: Flask) -> None:
    with app.test_request_context("/endpoint", method="POST"):
        form = WebmentionSubmissionForm(
            formdata=MultiDict({"source": VALID_SOURCE, "target": "http://[::1"}),
            meta={"csrf": False},
        )
        assert not form.validate()
        assert "Invalid URL." in form.errors["target"]


def test_endpoint_form_applies_configurable_url_byte_limit_to_both_fields(
    app: Flask,
) -> None:
    with app.test_request_context("/endpoint", method="POST"):
        app.config["MAX_WEBMENTION_URL_BYTES"] = len(VALID_SOURCE.encode("utf-8"))
        form = WebmentionSubmissionForm(
            formdata=MultiDict({"source": VALID_SOURCE + "x", "target": VALID_TARGET}),
            meta={"csrf": False},
        )
        assert not form.validate()
        assert "source" in form.errors
        assert any("bytes" in message for message in form.errors["source"])

        app.config["MAX_WEBMENTION_URL_BYTES"] = len(VALID_TARGET.encode("utf-8"))
        form = WebmentionSubmissionForm(
            formdata=MultiDict({"source": VALID_SOURCE, "target": VALID_TARGET + "x"}),
            meta={"csrf": False},
        )
        assert not form.validate()
        assert "target" in form.errors
        assert any("bytes" in message for message in form.errors["target"])


@pytest.mark.parametrize("field_name", ["source", "target"])
@pytest.mark.parametrize(
    "invalid_url",
    [
        pytest.param("http://ex☃mple.test/", id="invalid-idn"),
        pytest.param("https://example.com/a\nb", id="newline"),
        pytest.param("https://example.com/a\rb", id="carriage-return"),
        pytest.param("https://example.com/\x00b", id="nul"),
        pytest.param("https://example.com/a b", id="ascii-space"),
        pytest.param("https://example.com/a\u00a0b", id="unicode-whitespace"),
        pytest.param("https://example.com/\x7fb", id="del"),
        pytest.param("https://example.com/a\x80b", id="c1-control"),
    ],
)
def test_endpoint_rejects_invalid_httpx_urls_and_whitespace(
    app: Flask, field_name: str, invalid_url: str
) -> None:
    data = {"source": VALID_SOURCE, "target": VALID_TARGET}
    data[field_name] = invalid_url
    with app.test_request_context("/endpoint", method="POST"):
        form = WebmentionSubmissionForm(formdata=MultiDict(data), meta={"csrf": False})
        assert not form.validate()
        assert "Invalid URL." in form.errors[field_name]


def test_endpoint_accepts_encoded_path_space(app: Flask) -> None:
    with app.test_request_context("/endpoint", method="POST"):
        form = WebmentionSubmissionForm(
            formdata=MultiDict(
                {"source": "https://source.example/a%20b", "target": VALID_TARGET}
            ),
            meta={"csrf": False},
        )
        assert form.validate()


def test_endpoint_form_rejects_matching_source_and_target(app: Flask) -> None:
    with app.test_request_context("/endpoint", method="POST"):
        form = WebmentionSubmissionForm(
            formdata=MultiDict({"source": VALID_TARGET, "target": VALID_TARGET}),
            meta={"csrf": False},
        )

        assert not form.validate()
        assert "Field must not be equal to target." in form.errors["source"]


def test_allowed_hostname_accepts_configured_hostname(app: Flask) -> None:
    app.config["ALLOWED_TARGET_HOSTNAMES"] = ["dennisfink.me"]
    form = URLForm(MultiDict({"url": "https://dennisfink.me/blog/example/"}))
    with app.app_context():
        AllowedTargetHostname()(form, form.url)


def test_allowed_hostname_rejects_unconfigured_hostname(app: Flask) -> None:
    app.config["ALLOWED_TARGET_HOSTNAMES"] = ["dennisfink.me"]
    form = URLForm(MultiDict({"url": "https://example.com/post"}))
    with app.app_context(), pytest.raises(ValidationError, match="Invalid input"):
        AllowedTargetHostname()(form, form.url)


def test_allowed_hostname_uses_custom_message(app: Flask) -> None:
    app.config["ALLOWED_TARGET_HOSTNAMES"] = ["dennisfink.me"]
    form = URLForm(MultiDict({"url": "https://example.com/post"}))
    with (
        app.app_context(),
        pytest.raises(ValidationError, match="Hostname is not allowed"),
    ):
        AllowedTargetHostname("Hostname is not allowed")(form, form.url)


@pytest.mark.parametrize(
    "address",
    ["64:ff9b::a9fe:a9fe", "::10.0.0.1", "2002:a9fe:a9fe::1", "::ffff:169.254.169.254"],
)
def test_public_ip_literal_rejects_ipv6_transition_addresses(address: str) -> None:
    form = URLForm(MultiDict({"url": f"https://[{address}]/"}))
    with pytest.raises(ValidationError, match="URL must use a public address"):
        RejectNonPublicIPLiteral()(form, form.url)


def test_public_ip_literal_accepts_public_ipv6_address() -> None:
    form = URLForm(MultiDict({"url": "https://[2606:2800:220:1:248:1893:25c8:1946]/"}))
    RejectNonPublicIPLiteral()(form, form.url)


def test_allowed_hostname_handles_invalid_ipv6(app: Flask) -> None:
    form = URLForm(MultiDict({"url": "http://[::1"}))
    with app.app_context(), pytest.raises(ValidationError, match="Invalid input"):
        AllowedTargetHostname()(form, form.url)


def test_url_max_bytes_respects_utf8_byte_length_and_current_config(app: Flask) -> None:
    validator = MaxURLBytes()
    form = URLForm(MultiDict({"url": "é" * 3}))
    with app.app_context():
        app.config["MAX_WEBMENTION_URL_BYTES"] = 6
        validator(form, form.url)
        app.config["MAX_WEBMENTION_URL_BYTES"] = 5
        with pytest.raises(ValidationError, match="5 bytes"):
            validator(form, form.url)


def test_url_max_bytes_custom_message(app: Flask) -> None:
    form = URLForm(MultiDict({"url": "too-long"}))
    with app.app_context():
        app.config["MAX_WEBMENTION_URL_BYTES"] = 2
        with pytest.raises(ValidationError, match="URL too long"):
            MaxURLBytes(message="URL too long")(form, form.url)


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)