httpx-secure 1.0.0__tar.gz → 1.2.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.2.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
@@ -29,8 +29,8 @@ Classifier: Topic :: Software Development :: Libraries :: Python Modules
29
29
  Classifier: Topic :: System :: Networking
30
30
  Classifier: Typing :: Typed
31
31
  Requires-Python: >=3.9
32
- Requires-Dist: anyio
33
- Requires-Dist: httpx
32
+ Requires-Dist: anyio>=3.0.0
33
+ Requires-Dist: httpx>=0.20.0
34
34
  Description-Content-Type: text/markdown
35
35
 
36
36
  # httpx-secure
@@ -65,7 +65,7 @@ from httpx_secure import httpx_ssrf_protection
65
65
  client = httpx_ssrf_protection(
66
66
  httpx.AsyncClient(),
67
67
  dns_cache_size=1000, # Cache up to 1000 DNS resolutions
68
- dns_cache_ttl=300, # Cache for 5 minutes
68
+ dns_cache_ttl=600, # Cache for 10 minutes
69
69
  )
70
70
 
71
71
  await client.get("https://public.domain") # Allowed
@@ -30,7 +30,7 @@ from httpx_secure import httpx_ssrf_protection
30
30
  client = httpx_ssrf_protection(
31
31
  httpx.AsyncClient(),
32
32
  dns_cache_size=1000, # Cache up to 1000 DNS resolutions
33
- dns_cache_ttl=300, # Cache for 5 minutes
33
+ dns_cache_ttl=600, # Cache for 10 minutes
34
34
  )
35
35
 
36
36
  await client.get("https://public.domain") # Allowed
@@ -3,12 +3,11 @@ 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
11
- from httpx import RequestError
9
+ from anyio import Lock, connect_tcp, fail_after
10
+ from httpx import ConnectError, ConnectTimeout, RequestError
12
11
 
13
12
  TYPE_CHECKING = False
14
13
  if TYPE_CHECKING:
@@ -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.2.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()
@@ -96,7 +95,9 @@ class _SSRFProtectionHook:
96
95
  "_cache",
97
96
  "_locks",
98
97
  "check_globally_reachable",
98
+ "connect_timeout",
99
99
  "custom_validator",
100
+ "happy_eyeballs_delay",
100
101
  )
101
102
 
102
103
  def __init__(
@@ -104,6 +105,7 @@ class _SSRFProtectionHook:
104
105
  *,
105
106
  cache: _DNSCache,
106
107
  check_globally_reachable: bool,
108
+ connect_timeout: float | None,
107
109
  custom_validator: (
108
110
  Callable[
109
111
  [str, _IPAddress, int],
@@ -111,39 +113,28 @@ class _SSRFProtectionHook:
111
113
  ]
112
114
  | None
113
115
  ),
116
+ happy_eyeballs_delay: float,
114
117
  ):
115
118
  self._cache = cache
116
119
  self._locks: WeakValueDictionary[_CacheKey, Lock] = WeakValueDictionary()
117
120
  self.check_globally_reachable = check_globally_reachable
121
+ self.connect_timeout = connect_timeout
118
122
  self.custom_validator = custom_validator
123
+ self.happy_eyeballs_delay = happy_eyeballs_delay
119
124
 
120
- async def _resolve(self, hostname: str, port: int) -> str:
125
+ async def _resolve(self, request: Request, hostname: str, port: int) -> str:
121
126
  try:
122
- addr_info = await to_thread.run_sync(
123
- getaddrinfo,
124
- hostname,
125
- port,
126
- 0,
127
- SOCK_STREAM,
128
- IPPROTO_TCP,
129
- )
130
- except gaierror as e:
131
- raise SSRFProtectionError(
132
- f"Failed to resolve hostname {hostname!r}: {e}",
133
- hostname=hostname,
134
- ip_addr=None,
135
- port=port,
136
- ) from e
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])
127
+ with fail_after(self.connect_timeout):
128
+ async with await connect_tcp(
129
+ hostname,
130
+ port,
131
+ happy_eyeballs_delay=self.happy_eyeballs_delay,
132
+ ) as stream:
133
+ return stream._raw_socket.getpeername()[0]
134
+ except TimeoutError as e:
135
+ raise ConnectTimeout(str(e), request=request) from e
136
+ except OSError as e:
137
+ raise ConnectError(str(e), request=request) from e
147
138
 
148
139
  async def _validate(
149
140
  self,
@@ -183,12 +174,15 @@ class _SSRFProtectionHook:
183
174
 
184
175
  async def _process(
185
176
  self,
177
+ request: Request,
186
178
  hostname: str,
187
179
  port: int,
188
180
  ) -> str:
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
- ip_str = await self._resolve(hostname, port)
204
- await self._validate(ip_str, port, hostname)
199
+ ip_str = await self._resolve(request, hostname, port)
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
 
@@ -210,7 +212,7 @@ class _SSRFProtectionHook:
210
212
  hostname = url.host
211
213
  port = url.port or (443 if url.scheme in {"https", "wss"} else 80)
212
214
 
213
- ip_str = await self._process(hostname, port)
215
+ ip_str = await self._process(request, hostname, port)
214
216
 
215
217
  request.url = url.copy_with(host=ip_str)
216
218
  request.headers["Host"] = hostname
@@ -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
  """
@@ -254,7 +257,9 @@ def httpx_ssrf_protection(
254
257
  _SSRFProtectionHook(
255
258
  cache=_DNSCache(dns_cache_size, dns_cache_ttl),
256
259
  check_globally_reachable=check_globally_reachable,
260
+ connect_timeout=client.timeout.connect,
257
261
  custom_validator=custom_validator,
262
+ happy_eyeballs_delay=happy_eyeballs_delay,
258
263
  ),
259
264
  )
260
265
  return client
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "httpx-secure"
3
3
  requires-python = ">=3.9"
4
- dependencies = ["httpx", "anyio"]
4
+ dependencies = ["httpx>=0.20.0", "anyio>=3.0.0"]
5
5
  description = "Drop-in SSRF protection for httpx"
6
6
  readme = "README.md"
7
7
  license = "0BSD"
@@ -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 httpx import AsyncClient, Request
7
+ from anyio import getaddrinfo
8
+ from httpx import AsyncClient, ConnectError, 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 = OSError("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(ConnectError, match="Name or service not known"):
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():
@@ -109,8 +109,8 @@ dev = [
109
109
 
110
110
  [package.metadata]
111
111
  requires-dist = [
112
- { name = "anyio" },
113
- { name = "httpx" },
112
+ { name = "anyio", specifier = ">=3.0.0" },
113
+ { name = "httpx", specifier = ">=0.20.0" },
114
114
  ]
115
115
 
116
116
  [package.metadata.requires-dev]
File without changes
File without changes
File without changes
File without changes
File without changes