httpx-secure 1.0.0__tar.gz → 1.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: httpx-secure
3
- Version: 1.0.0
3
+ Version: 1.1.0
4
4
  Summary: Drop-in SSRF protection for httpx
5
5
  Project-URL: Repository, https://github.com/Zaczero/httpx-secure
6
6
  Project-URL: Issues, https://github.com/Zaczero/httpx-secure/issues
@@ -3,11 +3,10 @@ from __future__ import annotations
3
3
  from collections import OrderedDict
4
4
  from inspect import isawaitable
5
5
  from ipaddress import ip_address
6
- from socket import IPPROTO_TCP, SOCK_STREAM, gaierror, getaddrinfo
7
6
  from time import monotonic
8
7
  from weakref import WeakValueDictionary
9
8
 
10
- from anyio import Lock, to_thread
9
+ from anyio import ConnectionFailed, Lock, connect_tcp
11
10
  from httpx import RequestError
12
11
 
13
12
  TYPE_CHECKING = False
@@ -24,7 +23,7 @@ if TYPE_CHECKING:
24
23
 
25
24
  _AsyncClientT = TypeVar("_AsyncClientT", bound=AsyncClient)
26
25
 
27
- __version__ = "1.0.0"
26
+ __version__ = "1.1.0"
28
27
 
29
28
 
30
29
  class SSRFProtectionError(RequestError):
@@ -51,7 +50,7 @@ class _DNSCache:
51
50
  def __init__(self, max_size: int, ttl: float) -> None:
52
51
  self._cache: OrderedDict[
53
52
  _CacheKey,
54
- tuple[float, str],
53
+ tuple[float, str | SSRFProtectionError],
55
54
  ] = OrderedDict()
56
55
  self._max_size = max_size
57
56
  self._ttl = ttl
@@ -60,7 +59,7 @@ class _DNSCache:
60
59
  self,
61
60
  key: _CacheKey,
62
61
  /,
63
- ) -> str | None:
62
+ ) -> str | SSRFProtectionError | None:
64
63
  cached_value = self._cache.get(key)
65
64
  if cached_value is None:
66
65
  return None
@@ -78,7 +77,7 @@ class _DNSCache:
78
77
  def put(
79
78
  self,
80
79
  key: _CacheKey,
81
- value: str,
80
+ value: str | SSRFProtectionError,
82
81
  /,
83
82
  ) -> None:
84
83
  current_time = monotonic()
@@ -97,6 +96,7 @@ class _SSRFProtectionHook:
97
96
  "_locks",
98
97
  "check_globally_reachable",
99
98
  "custom_validator",
99
+ "happy_eyeballs_delay",
100
100
  )
101
101
 
102
102
  def __init__(
@@ -111,23 +111,23 @@ class _SSRFProtectionHook:
111
111
  ]
112
112
  | None
113
113
  ),
114
+ happy_eyeballs_delay: float,
114
115
  ):
115
116
  self._cache = cache
116
117
  self._locks: WeakValueDictionary[_CacheKey, Lock] = WeakValueDictionary()
117
118
  self.check_globally_reachable = check_globally_reachable
118
119
  self.custom_validator = custom_validator
120
+ self.happy_eyeballs_delay = happy_eyeballs_delay
119
121
 
120
122
  async def _resolve(self, hostname: str, port: int) -> str:
121
123
  try:
122
- addr_info = await to_thread.run_sync(
123
- getaddrinfo,
124
+ async with await connect_tcp(
124
125
  hostname,
125
126
  port,
126
- 0,
127
- SOCK_STREAM,
128
- IPPROTO_TCP,
129
- )
130
- except gaierror as e:
127
+ happy_eyeballs_delay=self.happy_eyeballs_delay,
128
+ ) as stream:
129
+ addr_info = stream._raw_socket.getpeername()
130
+ except ConnectionFailed as e:
131
131
  raise SSRFProtectionError(
132
132
  f"Failed to resolve hostname {hostname!r}: {e}",
133
133
  hostname=hostname,
@@ -135,15 +135,7 @@ class _SSRFProtectionHook:
135
135
  port=port,
136
136
  ) from e
137
137
 
138
- if not addr_info:
139
- raise SSRFProtectionError(
140
- f"No IP addresses found for hostname {hostname!r}",
141
- hostname=hostname,
142
- ip_addr=None,
143
- port=port,
144
- )
145
-
146
- return str(addr_info[0][4][0])
138
+ return addr_info[0]
147
139
 
148
140
  async def _validate(
149
141
  self,
@@ -189,6 +181,8 @@ class _SSRFProtectionHook:
189
181
  cache_key = (hostname, port)
190
182
  result = self._cache.get(cache_key)
191
183
  if result is not None:
184
+ if isinstance(result, SSRFProtectionError):
185
+ raise result
192
186
  return result
193
187
 
194
188
  lock = self._locks.get(cache_key)
@@ -198,10 +192,18 @@ class _SSRFProtectionHook:
198
192
  async with lock:
199
193
  result = self._cache.get(cache_key)
200
194
  if result is not None:
195
+ if isinstance(result, SSRFProtectionError):
196
+ raise result
201
197
  return result
202
198
 
203
199
  ip_str = await self._resolve(hostname, port)
204
- await self._validate(ip_str, port, hostname)
200
+
201
+ try:
202
+ await self._validate(ip_str, port, hostname)
203
+ except SSRFProtectionError as e:
204
+ self._cache.put(cache_key, e)
205
+ raise
206
+
205
207
  self._cache.put(cache_key, ip_str)
206
208
  return ip_str
207
209
 
@@ -229,7 +231,8 @@ def httpx_ssrf_protection(
229
231
  | None
230
232
  ) = None,
231
233
  dns_cache_size: int = 1000,
232
- dns_cache_ttl: float = 300,
234
+ dns_cache_ttl: float = 600,
235
+ happy_eyeballs_delay: float = 0.25,
233
236
  ) -> _AsyncClientT:
234
237
  """
235
238
  Configure SSRF protection on an httpx AsyncClient with DNS caching.
@@ -240,7 +243,7 @@ def httpx_ssrf_protection(
240
243
  custom_validator: Additional validation function(hostname, ip, port) -> bool
241
244
  dns_cache_size: Maximum number of DNS resolutions to cache
242
245
  dns_cache_ttl: Time-to-live for cached DNS resolutions in seconds
243
-
246
+ happy_eyeballs_delay: Delay in seconds before starting the next connection attempt
244
247
  Returns:
245
248
  The same client instance with SSRF protection configured.
246
249
  """
@@ -255,6 +258,7 @@ def httpx_ssrf_protection(
255
258
  cache=_DNSCache(dns_cache_size, dns_cache_ttl),
256
259
  check_globally_reachable=check_globally_reachable,
257
260
  custom_validator=custom_validator,
261
+ happy_eyeballs_delay=happy_eyeballs_delay,
258
262
  ),
259
263
  )
260
264
  return client
@@ -74,7 +74,19 @@ line-length = 88
74
74
  target-version = "py39"
75
75
 
76
76
  [tool.ruff.lint]
77
- ignore = ["ANN", "D", "PGH", "INP", "S101", "TRY", "EM", "PLR2004", "S311"]
77
+ ignore = [
78
+ "ANN",
79
+ "D",
80
+ "E501",
81
+ "EM",
82
+ "INP",
83
+ "PGH",
84
+ "PLR",
85
+ "S101",
86
+ "S311",
87
+ "SLF001",
88
+ "TRY",
89
+ ]
78
90
  select = ["ALL"]
79
91
  fixable = ["ALL"]
80
92
  unfixable = []
@@ -1,22 +1,61 @@
1
1
  from __future__ import annotations
2
2
 
3
- from socket import gaierror
4
- from unittest.mock import patch
3
+ from ipaddress import IPv4Address, IPv6Address, ip_address
4
+ from unittest.mock import AsyncMock, Mock, patch
5
5
 
6
6
  import pytest
7
+ from anyio import ConnectionFailed, getaddrinfo
7
8
  from httpx import AsyncClient, Request
8
9
 
9
10
  from httpx_secure import SSRFProtectionError, httpx_ssrf_protection
10
11
 
12
+ TYPE_CHECKING = False
13
+ if TYPE_CHECKING:
14
+ from anyio.abc import IPAddressType
15
+
16
+ MOCK_DEFAULT_IP = "1.2.3.4"
17
+
11
18
 
12
19
  class SuccessError(BaseException):
13
20
  """Raised when SSRF validation passes successfully."""
14
21
 
15
22
 
16
- async def success_hook(_: Request):
23
+ def success_hook(_: Request):
17
24
  raise SuccessError
18
25
 
19
26
 
27
+ def mock_tcp(default_ip: str = MOCK_DEFAULT_IP):
28
+ async def connect_tcp(remote_host: IPAddressType, remote_port: int, *_, **__):
29
+ hostname = str(remote_host)
30
+ port = remote_port
31
+
32
+ if "." not in hostname:
33
+ # Resolve local hosts
34
+ addr_info = await getaddrinfo(hostname, port)
35
+ resolved_ip = addr_info[0][4][0]
36
+ else:
37
+ try:
38
+ ip_address(hostname)
39
+ resolved_ip = hostname
40
+ except ValueError:
41
+ resolved_ip = default_ip
42
+
43
+ stream = Mock()
44
+ stream._raw_socket = Mock()
45
+ stream._raw_socket.getpeername.return_value = (resolved_ip, port)
46
+ stream.__aenter__ = AsyncMock(return_value=stream)
47
+ stream.__aexit__ = AsyncMock(return_value=None)
48
+ return stream
49
+
50
+ return connect_tcp
51
+
52
+
53
+ @pytest.fixture(autouse=True)
54
+ def mock_tcp_fixture():
55
+ with patch("httpx_secure.connect_tcp", side_effect=mock_tcp()) as mock:
56
+ yield mock
57
+
58
+
20
59
  @pytest.fixture
21
60
  async def client():
22
61
  async with httpx_ssrf_protection(AsyncClient()) as client:
@@ -68,75 +107,83 @@ async def test_allows_global_addresses(client, url):
68
107
 
69
108
  async def test_dns_resolution_rewrites_host_header():
70
109
  async def success_hook(request: Request):
71
- assert request.url.host == "1.2.3.4"
110
+ assert request.url.host == MOCK_DEFAULT_IP
72
111
  assert request.headers["Host"] == "example.com"
73
112
  assert request.extensions["sni_hostname"] == "example.com"
74
113
  raise SuccessError
75
114
 
76
115
  async with httpx_ssrf_protection(AsyncClient()) as client:
77
116
  client.event_hooks["request"].append(success_hook)
117
+ with pytest.raises(SuccessError):
118
+ await client.get("https://example.com/")
78
119
 
79
- with patch("httpx_secure.getaddrinfo") as mock_getaddrinfo:
80
- mock_getaddrinfo.return_value = [
81
- (None, None, None, None, ("1.2.3.4", 443)),
82
- ]
83
- with pytest.raises(SuccessError):
84
- await client.get("https://example.com/")
85
120
 
121
+ async def test_dns_results_are_cached(mock_tcp_fixture):
122
+ call_count = 0
86
123
 
87
- async def test_dns_results_are_cached():
88
- dns_call_count = 0
124
+ async def counter(*args, **kwargs):
125
+ nonlocal call_count
126
+ call_count += 1
127
+ return await mock_tcp()(*args, **kwargs)
89
128
 
90
- def mock_getaddrinfo_counter(*_):
91
- nonlocal dns_call_count
92
- dns_call_count += 1
93
- return [(None, None, None, None, ("1.2.3.4", 443))]
129
+ mock_tcp_fixture.side_effect = counter
94
130
 
95
131
  async with httpx_ssrf_protection(AsyncClient(), dns_cache_ttl=5) as client:
96
132
  client.event_hooks["request"].append(success_hook)
97
133
 
98
- with patch("httpx_secure.getaddrinfo", side_effect=mock_getaddrinfo_counter):
99
- with pytest.raises(SuccessError):
100
- await client.get("https://example.com/")
101
- assert dns_call_count == 1
102
-
103
- with pytest.raises(SuccessError):
104
- await client.get("https://example.com/")
105
- assert dns_call_count == 1
134
+ with pytest.raises(SuccessError):
135
+ await client.get("https://example.com/")
136
+ assert call_count == 1
106
137
 
107
- with pytest.raises(SuccessError):
108
- await client.get("https://example.com/path")
109
- assert dns_call_count == 1
138
+ with pytest.raises(SuccessError):
139
+ await client.get("https://example.com/path")
140
+ assert call_count == 1
110
141
 
111
- with pytest.raises(SuccessError):
112
- await client.get("https://api.example.com/path")
113
- assert dns_call_count == 2
142
+ with pytest.raises(SuccessError):
143
+ await client.get("https://api.example.com/path")
144
+ assert call_count == 2
114
145
 
115
146
 
116
147
  async def test_custom_validator_blocks_specific_ips():
148
+ call_count = 0
149
+
150
+ def custom_validator(
151
+ _: str,
152
+ ip_addr: IPv4Address | IPv6Address,
153
+ __: int,
154
+ ) -> bool:
155
+ nonlocal call_count
156
+ call_count += 1
157
+ return str(ip_addr) not in {"8.8.8.8", "8.8.4.4"}
158
+
117
159
  async with httpx_ssrf_protection(
118
160
  AsyncClient(),
119
- custom_validator=(
120
- lambda _, ip_addr, __: str(ip_addr) not in {"8.8.8.8", "8.8.4.4"}
121
- ),
161
+ custom_validator=custom_validator,
122
162
  ) as client:
123
163
  client.event_hooks["request"].append(success_hook)
124
164
 
125
165
  with pytest.raises(SSRFProtectionError, match="failed custom validation"):
126
166
  await client.get("http://8.8.8.8/")
167
+ assert call_count == 1
127
168
 
128
169
  with pytest.raises(SuccessError):
129
170
  await client.get("http://1.1.1.1/")
171
+ assert call_count == 2
172
+
173
+ # Another request to blocked IP should still use cache
174
+ with pytest.raises(SSRFProtectionError, match="failed custom validation"):
175
+ await client.get("http://8.8.8.8/different/path")
176
+ assert call_count == 2
177
+
130
178
 
179
+ async def test_dns_resolution_failure_raises_error(mock_tcp_fixture):
180
+ mock_tcp_fixture.side_effect = ConnectionFailed(["Name or service not known"])
131
181
 
132
- async def test_dns_resolution_failure_raises_error():
133
182
  async with httpx_ssrf_protection(AsyncClient()) as client:
134
- with patch("httpx_secure.getaddrinfo") as mock_getaddrinfo:
135
- mock_getaddrinfo.side_effect = gaierror("Name or service not known")
136
- with pytest.raises(SSRFProtectionError, match="Failed to resolve hostname"):
137
- await client.get(
138
- "http://this-hostname-definitely-does-not-exist/",
139
- )
183
+ with pytest.raises(SSRFProtectionError, match="Failed to resolve hostname"):
184
+ await client.get(
185
+ "http://this-hostname-definitely-does-not-exist/",
186
+ )
140
187
 
141
188
 
142
189
  async def test_skips_global_check_when_disabled():
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes