aboutsummaryrefslogtreecommitdiff
path: root/tests/test_public_transport.py
diff options
context:
space:
mode:
authorDennis Fink2026-11-12 19:57:08 +0100
committerDennis Fink2026-11-12 19:57:08 +0100
commit4bd1d9e348918b2e55db47a1ac3489d035cf55e2 (patch)
treef7ed41a374a8a4136792039a262dc62aa8cf8c59 /tests/test_public_transport.py
parent7035e9f9467684cccae2b7ff3faaa62e6a9f91aa (diff)
downloadwebmentions-ssg-4bd1d9e348918b2e55db47a1ac3489d035cf55e2.tar.gz
webmentions-ssg-4bd1d9e348918b2e55db47a1ac3489d035cf55e2.zip
refactor(core): split modules by responsibility
Break up monolithic views, task helpers, networking, CLI, and application extension setup so each module owns a focused concern. Reorganize the test suite around the new boundaries while preserving existing Webmention behavior and coverage.
Diffstat (limited to 'tests/test_public_transport.py')
-rw-r--r--tests/test_public_transport.py156
1 files changed, 0 insertions, 156 deletions
diff --git a/tests/test_public_transport.py b/tests/test_public_transport.py
deleted file mode 100644
index df7a1c3..0000000
--- a/tests/test_public_transport.py
+++ /dev/null
@@ -1,156 +0,0 @@
-# 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"]