httpx-secure 2.0.0__tar.gz → 2.0.1__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.5
2
2
  Name: httpx-secure
3
- Version: 2.0.0
3
+ Version: 2.0.1
4
4
  Summary: Connection-level SSRF protection for existing HTTPX async clients
5
5
  Project-URL: Issues, https://github.com/Zaczero/pkgs/issues
6
6
  Project-URL: Repository, https://github.com/Zaczero/pkgs/tree/main/httpx-secure
@@ -36,9 +36,10 @@ Description-Content-Type: text/markdown
36
36
 
37
37
  <a id="why-use-this"></a>
38
38
 
39
- Block requests to private and non-global IP addresses in an existing HTTPX
40
- `AsyncClient`. Add your own destination rules without changing HTTPX's request
41
- API. Python 3.11+, with asyncio or Trio.
39
+ Block requests to private and non-global IP addresses in an existing
40
+ [HTTPX](https://www.python-httpx.org/) `AsyncClient`. Add your own destination
41
+ rules without changing HTTPX's request API. Python 3.11+, with asyncio or
42
+ [Trio](https://trio.readthedocs.io/).
42
43
 
43
44
  ## Installation
44
45
 
@@ -127,6 +128,12 @@ routes. `trust_env=True` is supported when no proxy route is actually configured
127
128
  existing environment-derived SSL trust is retained. The helper does not remove
128
129
  proxies or silently fall back to weaker protection for unsupported routes.
129
130
 
131
+ `trust_env=False` also disables HTTPX's `SSL_CERT_FILE` and `SSL_CERT_DIR`
132
+ settings. To use system certificate stores with a direct client, pass an explicit
133
+ SSL context through `verify=`, as shown in
134
+ [HTTPX's SSL configuration guide](https://www.python-httpx.org/advanced/ssl/).
135
+ The helper preserves that context.
136
+
130
137
  Sharing a transport between clients also shares its connector policy. Configure
131
138
  such transports exclusively; do not mutate routing or replace transports after
132
139
  installation. Async task sharing after setup follows HTTPX's normal client
@@ -138,7 +145,8 @@ lifecycle. Cross-thread or cross-event-loop configuration is not supported.
138
145
 
139
146
  For a new connection, the connector selects an IP, applies the global-address and
140
147
  custom checks, and opens the data-bearing connection to that exact numeric IP
141
- and port. HTTPX and HTTPcore retain the logical origin for pooling, TLS certificate
148
+ and port. HTTPX and [HTTPcore](https://www.encode.io/httpcore/) retain the
149
+ logical origin for pooling, TLS certificate
142
150
  verification/SNI, redirects, cookies and Host authority. Absolute redirects that
143
151
  need another connection receive that destination's policy check.
144
152
 
@@ -190,7 +198,7 @@ active use. Finish or close outstanding responses before retrying setup.
190
198
 
191
199
  An HTTPX `RequestError` raised when the selected destination is denied. Each
192
200
  failure is a fresh exception with the current `request`, logical `hostname`,
193
- selected `ip_addr` (`IPv4Address`, `IPv6Address`, or None for an invalid address)
201
+ selected `ip_addr` (`IPv4Address`, `IPv6Address`, or `None` for an invalid address)
194
202
  and effective `port`.
195
203
 
196
204
  Its `invalid_ip`, `non_global` and `custom_validation_failed` classmethods construct
@@ -2,9 +2,10 @@
2
2
 
3
3
  <a id="why-use-this"></a>
4
4
 
5
- Block requests to private and non-global IP addresses in an existing HTTPX
6
- `AsyncClient`. Add your own destination rules without changing HTTPX's request
7
- API. Python 3.11+, with asyncio or Trio.
5
+ Block requests to private and non-global IP addresses in an existing
6
+ [HTTPX](https://www.python-httpx.org/) `AsyncClient`. Add your own destination
7
+ rules without changing HTTPX's request API. Python 3.11+, with asyncio or
8
+ [Trio](https://trio.readthedocs.io/).
8
9
 
9
10
  ## Installation
10
11
 
@@ -93,6 +94,12 @@ routes. `trust_env=True` is supported when no proxy route is actually configured
93
94
  existing environment-derived SSL trust is retained. The helper does not remove
94
95
  proxies or silently fall back to weaker protection for unsupported routes.
95
96
 
97
+ `trust_env=False` also disables HTTPX's `SSL_CERT_FILE` and `SSL_CERT_DIR`
98
+ settings. To use system certificate stores with a direct client, pass an explicit
99
+ SSL context through `verify=`, as shown in
100
+ [HTTPX's SSL configuration guide](https://www.python-httpx.org/advanced/ssl/).
101
+ The helper preserves that context.
102
+
96
103
  Sharing a transport between clients also shares its connector policy. Configure
97
104
  such transports exclusively; do not mutate routing or replace transports after
98
105
  installation. Async task sharing after setup follows HTTPX's normal client
@@ -104,7 +111,8 @@ lifecycle. Cross-thread or cross-event-loop configuration is not supported.
104
111
 
105
112
  For a new connection, the connector selects an IP, applies the global-address and
106
113
  custom checks, and opens the data-bearing connection to that exact numeric IP
107
- and port. HTTPX and HTTPcore retain the logical origin for pooling, TLS certificate
114
+ and port. HTTPX and [HTTPcore](https://www.encode.io/httpcore/) retain the
115
+ logical origin for pooling, TLS certificate
108
116
  verification/SNI, redirects, cookies and Host authority. Absolute redirects that
109
117
  need another connection receive that destination's policy check.
110
118
 
@@ -156,7 +164,7 @@ active use. Finish or close outstanding responses before retrying setup.
156
164
 
157
165
  An HTTPX `RequestError` raised when the selected destination is denied. Each
158
166
  failure is a fresh exception with the current `request`, logical `hostname`,
159
- selected `ip_addr` (`IPv4Address`, `IPv6Address`, or None for an invalid address)
167
+ selected `ip_addr` (`IPv4Address`, `IPv6Address`, or `None` for an invalid address)
160
168
  and effective `port`.
161
169
 
162
170
  Its `invalid_ip`, `non_global` and `custom_validation_failed` classmethods construct
@@ -17,7 +17,7 @@ from httpx_secure._network import protect_client as _protect_client
17
17
  TYPE_CHECKING = False
18
18
  if TYPE_CHECKING:
19
19
  from collections.abc import Awaitable, Callable
20
- from typing import TypeVar
20
+ from typing import Self, TypeVar
21
21
 
22
22
  from httpx import Request
23
23
 
@@ -27,7 +27,7 @@ if TYPE_CHECKING:
27
27
 
28
28
  _AsyncClientT = TypeVar('_AsyncClientT', bound=AsyncClient)
29
29
 
30
- __version__ = '2.0.0'
30
+ __version__ = '2.0.1'
31
31
 
32
32
  _NAT64_WELL_KNOWN_PREFIX = IPv6Network('64:ff9b::/96')
33
33
 
@@ -56,7 +56,7 @@ class SSRFProtectionError(RequestError):
56
56
  *,
57
57
  hostname: str,
58
58
  port: int,
59
- ) -> SSRFProtectionError:
59
+ ) -> Self:
60
60
  return cls(
61
61
  f'ip_str must be a valid IP address, got {ip_str!r}',
62
62
  hostname=hostname,
@@ -72,7 +72,7 @@ class SSRFProtectionError(RequestError):
72
72
  hostname: str,
73
73
  ip_addr: _IPAddress,
74
74
  port: int,
75
- ) -> SSRFProtectionError:
75
+ ) -> Self:
76
76
  return cls(
77
77
  f'access denied: IP address {ip_str!r} is not globally reachable',
78
78
  hostname=hostname,
@@ -88,7 +88,7 @@ class SSRFProtectionError(RequestError):
88
88
  hostname: str,
89
89
  ip_addr: _IPAddress,
90
90
  port: int,
91
- ) -> SSRFProtectionError:
91
+ ) -> Self:
92
92
  return cls(
93
93
  f'access denied: IP address {ip_str!r} failed custom validation',
94
94
  hostname=hostname,
@@ -105,7 +105,7 @@ class _DeniedAddress:
105
105
  port: int
106
106
 
107
107
  @classmethod
108
- def from_exception(cls, error: SSRFProtectionError) -> _DeniedAddress:
108
+ def from_exception(cls, error: SSRFProtectionError) -> Self:
109
109
  return cls(
110
110
  message=str(error),
111
111
  hostname=error.hostname,
@@ -122,13 +122,22 @@ class _DeniedAddress:
122
122
  )
123
123
 
124
124
 
125
+ @dataclass(frozen=True, slots=True)
126
+ class _AdmittedEndpoint:
127
+ """The validated numeric destination and the connection parameters it admits."""
128
+
129
+ address: str
130
+ port: int
131
+ local_address: str | None
132
+
133
+
125
134
  class _DNSCache:
126
135
  __slots__ = ('_cache', '_max_size', '_ttl')
127
136
 
128
137
  def __init__(self, max_size: int, ttl: float) -> None:
129
138
  self._cache: OrderedDict[
130
139
  _CacheKey,
131
- tuple[float, str | _DeniedAddress],
140
+ tuple[float, _AdmittedEndpoint | _DeniedAddress],
132
141
  ] = OrderedDict()
133
142
  self._max_size = max_size
134
143
  self._ttl = ttl
@@ -137,7 +146,7 @@ class _DNSCache:
137
146
  self,
138
147
  key: _CacheKey,
139
148
  /,
140
- ) -> str | _DeniedAddress | None:
149
+ ) -> _AdmittedEndpoint | _DeniedAddress | None:
141
150
  cached_value = self._cache.get(key)
142
151
  if cached_value is None:
143
152
  return None
@@ -155,7 +164,7 @@ class _DNSCache:
155
164
  def put(
156
165
  self,
157
166
  key: _CacheKey,
158
- value: str | _DeniedAddress,
167
+ value: _AdmittedEndpoint | _DeniedAddress,
159
168
  /,
160
169
  ) -> None:
161
170
  current_time = monotonic()
@@ -231,7 +240,8 @@ class _AddressPolicy:
231
240
  ip_str: str,
232
241
  port: int,
233
242
  hostname: str,
234
- ) -> None:
243
+ local_address: str | None,
244
+ ) -> _AdmittedEndpoint:
235
245
  try:
236
246
  ip_addr = ip_address(ip_str)
237
247
  except ValueError as e:
@@ -267,13 +277,14 @@ class _AddressPolicy:
267
277
  ip_addr=ip_addr,
268
278
  port=port,
269
279
  )
280
+ return _AdmittedEndpoint(ip_str, port, local_address)
270
281
 
271
282
  async def admit(
272
283
  self,
273
284
  hostname: str,
274
285
  port: int,
275
286
  local_address: str | None,
276
- ) -> str:
287
+ ) -> _AdmittedEndpoint:
277
288
  cache_key = (hostname, port, local_address)
278
289
  result = self._cache.get(cache_key)
279
290
  if result is not None:
@@ -295,14 +306,14 @@ class _AddressPolicy:
295
306
  ip_str = await self._resolve(hostname, port, local_address)
296
307
 
297
308
  try:
298
- await self._validate(ip_str, port, hostname)
309
+ endpoint = await self._validate(ip_str, port, hostname, local_address)
299
310
  except SSRFProtectionError as e:
300
311
  denial = _DeniedAddress.from_exception(e)
301
312
  self._cache.put(cache_key, denial)
302
313
  raise denial.exception() from None
303
314
 
304
- self._cache.put(cache_key, ip_str)
305
- return ip_str
315
+ self._cache.put(cache_key, endpoint)
316
+ return endpoint
306
317
 
307
318
 
308
319
  def httpx_ssrf_protection(
@@ -334,19 +345,24 @@ def httpx_ssrf_protection(
334
345
  for that connection's lifetime; cache expiry affects new connections only.
335
346
  Close and recreate the client to apply changed custom policy immediately.
336
347
 
348
+ Requests can raise ``SSRFProtectionError`` with the current request,
349
+ hostname, selected IP, and port. DNS/connect failures and connect deadlines
350
+ retain HTTPX's ``ConnectError``/``ConnectTimeout`` behavior. Custom-validator
351
+ exceptions propagate.
352
+
337
353
  Args:
338
- client: Existing client, with no pending requests or open response streams.
354
+ client: Existing client with no pending requests or open response streams.
339
355
  check_globally_reachable: Block non-global IPs, including non-global IPv4
340
- destinations embedded in the well-known NAT64 prefix. Defaults to True.
341
- custom_validator: Optional sync or async function(hostname, ip, port)
342
- returning bool. It runs after the global check. Required when
343
- check_globally_reachable is False.
344
- dns_cache_size: Maximum cached address selections or denials; defaults
345
- to 1000. Entries distinguish hostname, port and local bind address.
346
- dns_cache_ttl: Cache lifetime in seconds; defaults to 600. Expiry does
347
- not revoke established connections.
348
- happy_eyeballs_delay: Probe connection-attempt delay in seconds;
349
- defaults to 0.25.
356
+ destinations embedded in the well-known NAT64 prefix.
357
+ custom_validator: Optional sync or async ``(hostname, ip, port) -> bool``
358
+ hook run after the global check. Required when
359
+ ``check_globally_reachable`` is ``False``.
360
+ dns_cache_size: Maximum cached address selections or denials. Entries
361
+ distinguish hostname, port, and local bind address.
362
+ dns_cache_ttl: Cache lifetime in seconds. Expiry does not revoke
363
+ established connections.
364
+ happy_eyeballs_delay: Probe connection-attempt delay in seconds.
365
+
350
366
  Returns:
351
367
  The same client instance with SSRF protection configured.
352
368
 
@@ -357,10 +373,6 @@ def httpx_ssrf_protection(
357
373
  custom transport/backend, or unsupported transport layout is present.
358
374
  RuntimeError: The client is closed, already protected, or has active or
359
375
  pending requests. Finish or close outstanding responses before retrying.
360
-
361
- Requests can raise SSRFProtectionError with the current request, hostname,
362
- selected IP and port. DNS/connect failures and connect deadlines retain HTTPX's
363
- ConnectError/ConnectTimeout behavior. Custom-validator exceptions propagate.
364
376
  """
365
377
  if not isinstance(client, AsyncClient): # pyright: ignore[reportUnnecessaryIsInstance]
366
378
  raise TypeError(
@@ -2,13 +2,12 @@ from __future__ import annotations
2
2
 
3
3
  # This module owns the version-bounded private HTTPX/HTTPcore integration.
4
4
  # pyright: reportPrivateUsage=false
5
- from typing import TYPE_CHECKING, cast
6
-
7
5
  import httpcore
8
6
  import httpx
9
7
  from anyio import CancelScope, current_time, move_on_after
10
8
  from httpcore._backends.auto import AutoBackend
11
9
 
10
+ TYPE_CHECKING = False
12
11
  if TYPE_CHECKING:
13
12
  from collections.abc import Iterable
14
13
  from ssl import SSLContext
@@ -70,15 +69,15 @@ class _ProtectedBackend(httpcore.AsyncNetworkBackend):
70
69
  socket_options: Iterable[httpcore.SOCKET_OPTION] | None = None,
71
70
  ) -> httpcore.AsyncNetworkStream:
72
71
  with move_on_after(timeout) as scope:
73
- address = await self._policy.admit(host, port, local_address)
72
+ endpoint = await self._policy.admit(host, port, local_address)
74
73
  remaining = (
75
74
  None if timeout is None else max(0.0, scope.deadline - current_time())
76
75
  )
77
76
  stream = await self._backend.connect_tcp(
78
- address,
79
- port,
77
+ endpoint.address,
78
+ endpoint.port,
80
79
  timeout=remaining,
81
- local_address=local_address,
80
+ local_address=endpoint.local_address,
82
81
  socket_options=socket_options,
83
82
  )
84
83
  return _ProtectedStream(stream)
@@ -141,17 +140,23 @@ def protect_client(client: httpx.AsyncClient, policy: _AddressPolicy) -> None:
141
140
  if not connection.is_idle():
142
141
  raise RuntimeError('cannot protect an active connection')
143
142
  protocol = connection._connection
144
- if type(protocol) not in (
145
- httpcore.AsyncHTTP11Connection,
146
- httpcore.AsyncHTTP2Connection,
147
- ) or not hasattr(protocol, '_expire_at'):
148
- raise ValueError('unsupported HTTPcore protocol layout')
149
- expired.append(
150
- cast(
151
- 'httpcore.AsyncHTTP11Connection | httpcore.AsyncHTTP2Connection',
143
+ if (
144
+ not isinstance(
152
145
  protocol,
146
+ (
147
+ httpcore.AsyncHTTP11Connection,
148
+ httpcore.AsyncHTTP2Connection,
149
+ ),
153
150
  )
154
- )
151
+ or type(protocol)
152
+ not in (
153
+ httpcore.AsyncHTTP11Connection,
154
+ httpcore.AsyncHTTP2Connection,
155
+ )
156
+ or not hasattr(protocol, '_expire_at')
157
+ ):
158
+ raise ValueError('unsupported HTTPcore protocol layout')
159
+ expired.append(protocol)
155
160
  pools[id(pool)] = pool
156
161
  except AttributeError as error:
157
162
  raise ValueError('unsupported HTTPX/HTTPcore transport layout') from error
@@ -77,7 +77,10 @@ async def test_global_literal_policy_needs_no_resolution(address):
77
77
  custom_validator=None,
78
78
  happy_eyeballs_delay=0.25,
79
79
  )
80
- assert await policy.admit(address, 443, None) == address
80
+ endpoint = await policy.admit(address, 443, None)
81
+ assert endpoint.address == address
82
+ assert endpoint.port == 443
83
+ assert endpoint.local_address is None
81
84
 
82
85
 
83
86
  async def test_cached_denials_are_fresh_and_bound_to_current_request():
File without changes
File without changes
File without changes