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
|
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause
"""Security regression tests for DNS-pinned network connections."""
import socket
from unittest.mock import Mock
import httpcore
import httpx
import pytest
from webmentions_ssg.public_transport import (
DeadlineStream,
NetworkDeadline,
PublicHTTPTransport,
PublicNetworkBackend,
)
from webmentions_ssg.url_security import UnsafeAddressError
@pytest.mark.parametrize("host", ["127.0.0.1", "169.254.169.254", "::1"])
def test_backend_rejects_private_ip_without_socket(
monkeypatch: pytest.MonkeyPatch, host: str
) -> None:
create_socket = Mock(side_effect=AssertionError("must not open socket"))
monkeypatch.setattr(socket, "socket", create_socket)
with pytest.raises(UnsafeAddressError):
PublicNetworkBackend(NetworkDeadline(5)).connect_tcp(host, 80)
create_socket.assert_not_called()
def test_rebinding_cannot_change_socket_peer(monkeypatch: pytest.MonkeyPatch) -> None:
"""The address is resolved exactly once and the socket sees only that IP."""
dns = Mock(return_value=("93.184.216.34",))
monkeypatch.setattr("webmentions_ssg.public_transport.public_addresses", dns)
socket_instance = Mock()
create_socket = Mock(return_value=socket_instance)
monkeypatch.setattr(socket, "socket", create_socket)
monkeypatch.setattr(
socket, "getaddrinfo", Mock(side_effect=AssertionError("second resolution"))
)
stream = PublicNetworkBackend(NetworkDeadline(5)).connect_tcp(
"rebinding.example", 443, timeout=2.0
)
assert isinstance(stream, DeadlineStream)
assert stream.get_extra_info("socket") is socket_instance
dns.assert_called_once()
assert dns.call_args.args == ("rebinding.example",)
assert 0 < dns.call_args.kwargs["lifetime"] <= 2.0
socket_instance.connect.assert_called_once_with(("93.184.216.34", 443))
create_socket.assert_called_once_with(socket.AF_INET, socket.SOCK_STREAM)
class FakeStream(httpcore.NetworkStream):
"""In-memory TCP/TLS stream so HTTP framing and SNI can be tested."""
def __init__(self, response: bytes) -> None:
self.response = response
self.writes = bytearray()
self.sni: str | None = None
def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
part, self.response = self.response[:max_bytes], self.response[max_bytes:]
return part
def write(self, buffer: bytes, timeout: float | None = None) -> None:
self.writes.extend(buffer)
def start_tls(
self, ssl_context, server_hostname: str | None = None, timeout: float | None = None
) -> httpcore.NetworkStream:
self.sni = server_hostname
return self
def get_extra_info(self, info: str):
return None
def close(self) -> None:
pass
@pytest.mark.parametrize("scheme", ["http", "https"])
def test_transport_keeps_original_http_host_and_tls_sni(
monkeypatch: pytest.MonkeyPatch, scheme: str
) -> None:
stream = FakeStream(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK")
backend = Mock(return_value=stream)
monkeypatch.setattr(PublicNetworkBackend, "connect_tcp", backend)
with httpx.Client(transport=PublicHTTPTransport(5.0), trust_env=False) as client:
response = client.get(f"{scheme}://source.example/path")
assert response.status_code == 200
assert response.text == "OK"
assert b"Host: source.example\r\n" in stream.writes
assert b"GET /path HTTP/1.1\r\n" in stream.writes
assert stream.sni == ("source.example" if scheme == "https" else None)
backend.assert_called_once()
assert backend.call_args.kwargs["host"] == "source.example"
assert backend.call_args.kwargs["port"] == (443 if scheme == "https" else 80)
def test_deadline_clips_each_read_and_stops_trickle(
monkeypatch: pytest.MonkeyPatch,
) -> None:
clock = [100.0]
monkeypatch.setattr("webmentions_ssg.public_transport.time.monotonic", lambda: clock[0])
fake_stream = Mock()
fake_stream.read.return_value = b"x"
stream = DeadlineStream(fake_stream, NetworkDeadline(5.0))
clock[0] = 103.0
assert stream.read(1, timeout=5.0) == b"x"
assert fake_stream.read.call_args.kwargs["timeout"] == pytest.approx(2.0)
clock[0] = 105.1
with pytest.raises(httpcore.ReadTimeout, match="Overall HTTP request deadline"):
stream.read(1, timeout=5.0)
assert fake_stream.read.call_count == 1
def test_redirects_go_through_same_destination_guard(
monkeypatch: pytest.MonkeyPatch,
) -> None:
redirect = FakeStream(
b"HTTP/1.1 302 Found\r\nLocation: http://internal.example/\r\n"
b"Content-Length: 0\r\n\r\n"
)
checked_hosts: list[str] = []
def connect(
self: PublicNetworkBackend, host: str, port: int, **kwargs: object
) -> httpcore.NetworkStream:
checked_hosts.append(host)
if host == "internal.example":
raise UnsafeAddressError("Non-public network address")
return redirect
monkeypatch.setattr(PublicNetworkBackend, "connect_tcp", connect)
with (
httpx.Client(transport=PublicHTTPTransport(5.0), follow_redirects=True) as client,
pytest.raises(UnsafeAddressError, match="Non-public"),
):
client.get("http://source.example/post")
assert checked_hosts == ["source.example", "internal.example"]
|