aboutsummaryrefslogtreecommitdiff
path: root/tests/test_url_security.py
blob: fba6d7d64e8b36f34fe4d850e69bb886dcb43f7c (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
import pytest

from webmentions_ssg.url_security import (
    NonPublicAddressError,
    ensure_public_url,
)


class FakeAnswers:
    def __init__(self, *addresses: str):
        self._addresses = addresses

    def addresses(self):
        return iter(self._addresses)


@pytest.mark.parametrize(
    ("url", "resolved_addresses"),
    [
        ("http://127.0.0.1/", ["127.0.0.1"]),
        ("http://127.0.0.1:8080/test", ["127.0.0.1"]),
        ("http://[::1]/", ["::1"]),
        ("http://10.0.0.1/", ["10.0.0.1"]),
        ("http://172.16.0.1/", ["172.16.0.1"]),
        ("http://192.168.1.1/", ["192.168.1.1"]),
        ("http://169.254.169.254/", ["169.254.169.254"]),
        ("http://localhost/", ["127.0.0.1", "::1"]),
        ("http://internal.example/", ["192.168.1.10"]),
    ],
)
def test_ensure_public_url_rejects_non_public_addresses(
    monkeypatch: pytest.MonkeyPatch,
    url: str,
    resolved_addresses: list[str],
) -> None:
    monkeypatch.setattr(
        "webmentions_ssg.url_security.dns.resolver.resolve_name",
        lambda hostname: FakeAnswers(*resolved_addresses),
    )

    with pytest.raises(NonPublicAddressError):
        ensure_public_url(url)