httpx-secure 1.0.0__py3-none-any.whl

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.
@@ -0,0 +1,260 @@
1
+ from __future__ import annotations
2
+
3
+ from collections import OrderedDict
4
+ from inspect import isawaitable
5
+ from ipaddress import ip_address
6
+ from socket import IPPROTO_TCP, SOCK_STREAM, gaierror, getaddrinfo
7
+ from time import monotonic
8
+ from weakref import WeakValueDictionary
9
+
10
+ from anyio import Lock, to_thread
11
+ from httpx import RequestError
12
+
13
+ TYPE_CHECKING = False
14
+ if TYPE_CHECKING:
15
+ from collections.abc import Awaitable, Callable
16
+ from ipaddress import IPv4Address, IPv6Address
17
+ from typing import TypeVar, Union
18
+
19
+ from httpx import AsyncClient, Request
20
+
21
+ _IPAddress = Union[IPv4Address, IPv6Address]
22
+
23
+ _CacheKey = tuple[str, int] # (hostname, port)
24
+
25
+ _AsyncClientT = TypeVar("_AsyncClientT", bound=AsyncClient)
26
+
27
+ __version__ = "1.0.0"
28
+
29
+
30
+ class SSRFProtectionError(RequestError):
31
+ """Raised when a request would access restricted network resources."""
32
+
33
+ def __init__(
34
+ self,
35
+ message: str,
36
+ *,
37
+ request: Request | None = None,
38
+ hostname: str,
39
+ ip_addr: _IPAddress | None,
40
+ port: int,
41
+ ) -> None:
42
+ super().__init__(message, request=request)
43
+ self.hostname = hostname
44
+ self.ip_addr = ip_addr
45
+ self.port = port
46
+
47
+
48
+ class _DNSCache:
49
+ __slots__ = ("_cache", "_max_size", "_ttl")
50
+
51
+ def __init__(self, max_size: int, ttl: float) -> None:
52
+ self._cache: OrderedDict[
53
+ _CacheKey,
54
+ tuple[float, str],
55
+ ] = OrderedDict()
56
+ self._max_size = max_size
57
+ self._ttl = ttl
58
+
59
+ def get(
60
+ self,
61
+ key: _CacheKey,
62
+ /,
63
+ ) -> str | None:
64
+ cached_value = self._cache.get(key)
65
+ if cached_value is None:
66
+ return None
67
+
68
+ timestamp, value = cached_value
69
+
70
+ current_time = monotonic()
71
+ if current_time - timestamp > self._ttl:
72
+ del self._cache[key]
73
+ return None
74
+
75
+ self._cache.move_to_end(key)
76
+ return value
77
+
78
+ def put(
79
+ self,
80
+ key: _CacheKey,
81
+ value: str,
82
+ /,
83
+ ) -> None:
84
+ current_time = monotonic()
85
+ cache_hit = key in self._cache
86
+ self._cache[key] = (current_time, value)
87
+
88
+ if cache_hit:
89
+ self._cache.move_to_end(key)
90
+ elif len(self._cache) > self._max_size:
91
+ self._cache.popitem(last=False)
92
+
93
+
94
+ class _SSRFProtectionHook:
95
+ __slots__ = (
96
+ "_cache",
97
+ "_locks",
98
+ "check_globally_reachable",
99
+ "custom_validator",
100
+ )
101
+
102
+ def __init__(
103
+ self,
104
+ *,
105
+ cache: _DNSCache,
106
+ check_globally_reachable: bool,
107
+ custom_validator: (
108
+ Callable[
109
+ [str, _IPAddress, int],
110
+ bool | Awaitable[bool],
111
+ ]
112
+ | None
113
+ ),
114
+ ):
115
+ self._cache = cache
116
+ self._locks: WeakValueDictionary[_CacheKey, Lock] = WeakValueDictionary()
117
+ self.check_globally_reachable = check_globally_reachable
118
+ self.custom_validator = custom_validator
119
+
120
+ async def _resolve(self, hostname: str, port: int) -> str:
121
+ 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])
147
+
148
+ async def _validate(
149
+ self,
150
+ ip_str: str,
151
+ port: int,
152
+ hostname: str,
153
+ ) -> None:
154
+ try:
155
+ ip_addr = ip_address(ip_str)
156
+ except ValueError as e:
157
+ raise SSRFProtectionError(
158
+ f"Invalid IP address format: {ip_str!r}",
159
+ hostname=hostname,
160
+ ip_addr=None,
161
+ port=port,
162
+ ) from e
163
+
164
+ if self.check_globally_reachable and not ip_addr.is_global:
165
+ raise SSRFProtectionError(
166
+ f"Access denied: IP address {ip_str!r} is not globally reachable",
167
+ hostname=hostname,
168
+ ip_addr=ip_addr,
169
+ port=port,
170
+ )
171
+
172
+ if self.custom_validator:
173
+ result = self.custom_validator(hostname, ip_addr, port)
174
+ if isawaitable(result):
175
+ result = await result
176
+ if not result:
177
+ raise SSRFProtectionError(
178
+ f"Access denied: IP address {ip_str!r} failed custom validation",
179
+ hostname=hostname,
180
+ ip_addr=ip_addr,
181
+ port=port,
182
+ )
183
+
184
+ async def _process(
185
+ self,
186
+ hostname: str,
187
+ port: int,
188
+ ) -> str:
189
+ cache_key = (hostname, port)
190
+ result = self._cache.get(cache_key)
191
+ if result is not None:
192
+ return result
193
+
194
+ lock = self._locks.get(cache_key)
195
+ if lock is None:
196
+ lock = self._locks[cache_key] = Lock()
197
+
198
+ async with lock:
199
+ result = self._cache.get(cache_key)
200
+ if result is not None:
201
+ return result
202
+
203
+ ip_str = await self._resolve(hostname, port)
204
+ await self._validate(ip_str, port, hostname)
205
+ self._cache.put(cache_key, ip_str)
206
+ return ip_str
207
+
208
+ async def __call__(self, request: Request) -> None:
209
+ url = request.url
210
+ hostname = url.host
211
+ port = url.port or (443 if url.scheme in {"https", "wss"} else 80)
212
+
213
+ ip_str = await self._process(hostname, port)
214
+
215
+ request.url = url.copy_with(host=ip_str)
216
+ request.headers["Host"] = hostname
217
+ request.extensions["sni_hostname"] = hostname
218
+
219
+
220
+ def httpx_ssrf_protection(
221
+ client: _AsyncClientT,
222
+ *,
223
+ check_globally_reachable: bool = True,
224
+ custom_validator: (
225
+ Callable[
226
+ [str, _IPAddress, int],
227
+ bool | Awaitable[bool],
228
+ ]
229
+ | None
230
+ ) = None,
231
+ dns_cache_size: int = 1000,
232
+ dns_cache_ttl: float = 300,
233
+ ) -> _AsyncClientT:
234
+ """
235
+ Configure SSRF protection on an httpx AsyncClient with DNS caching.
236
+
237
+ Args:
238
+ client: AsyncClient to configure
239
+ check_globally_reachable: Whether to block non-global IP addresses
240
+ custom_validator: Additional validation function(hostname, ip, port) -> bool
241
+ dns_cache_size: Maximum number of DNS resolutions to cache
242
+ dns_cache_ttl: Time-to-live for cached DNS resolutions in seconds
243
+
244
+ Returns:
245
+ The same client instance with SSRF protection configured.
246
+ """
247
+ if not check_globally_reachable and custom_validator is None:
248
+ raise ValueError(
249
+ "When check_globally_reachable is False, custom_validator must be provided "
250
+ "to ensure SSRF protection is not completely disabled",
251
+ )
252
+
253
+ client.event_hooks["request"].append(
254
+ _SSRFProtectionHook(
255
+ cache=_DNSCache(dns_cache_size, dns_cache_ttl),
256
+ check_globally_reachable=check_globally_reachable,
257
+ custom_validator=custom_validator,
258
+ ),
259
+ )
260
+ return client
httpx_secure/py.typed ADDED
File without changes
@@ -0,0 +1,114 @@
1
+ Metadata-Version: 2.4
2
+ Name: httpx-secure
3
+ Version: 1.0.0
4
+ Summary: Drop-in SSRF protection for httpx
5
+ Project-URL: Repository, https://github.com/Zaczero/httpx-secure
6
+ Project-URL: Issues, https://github.com/Zaczero/httpx-secure/issues
7
+ Author-email: Kamil Monicz <kamil@monicz.dev>
8
+ License-Expression: 0BSD
9
+ License-File: LICENSE
10
+ Keywords: anyio,async,asyncio,client,dns,dns-cache,http,httpx,security,ssrf,ssrf-protection,trio,web-security
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Framework :: AnyIO
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Framework :: Trio
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: Zero-Clause BSD (0BSD)
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
25
+ Classifier: Topic :: Internet :: WWW/HTTP
26
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
27
+ Classifier: Topic :: Security
28
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
29
+ Classifier: Topic :: System :: Networking
30
+ Classifier: Typing :: Typed
31
+ Requires-Python: >=3.9
32
+ Requires-Dist: anyio
33
+ Requires-Dist: httpx
34
+ Description-Content-Type: text/markdown
35
+
36
+ # httpx-secure
37
+
38
+ [![PyPI - Python Version](https://shields.monicz.dev/pypi/pyversions/httpx-secure)](https://pypi.org/p/httpx-secure)
39
+ [![Liberapay Patrons](https://shields.monicz.dev/liberapay/patrons/Zaczero?logo=liberapay&label=Patrons)](https://liberapay.com/Zaczero/)
40
+ [![GitHub Sponsors](https://shields.monicz.dev/github/sponsors/Zaczero?logo=github&label=Sponsors&color=%23db61a2)](https://github.com/sponsors/Zaczero)
41
+
42
+ Drop-in SSRF protection for httpx.
43
+
44
+ ## Why Use This?
45
+
46
+ - **SSRF Protection**: Block requests to private/internal IP addresses
47
+ - **Custom Validation**: Extend with your own validation logic
48
+ - **Minimal Overhead**: Efficient implementation with built-in DNS caching
49
+ - **Broad Python Support**: Compatible with Python 3.9+
50
+ - [**Semantic Versioning**](https://semver.org): Predictable, reliable updates
51
+ - [**Zero-Clause BSD**](https://choosealicense.com/licenses/0bsd/): Public domain, use freely anywhere
52
+
53
+ ## Installation
54
+
55
+ ```bash
56
+ pip install httpx-secure
57
+ ```
58
+
59
+ ## Quick Start
60
+
61
+ ```python
62
+ import httpx
63
+ from httpx_secure import httpx_ssrf_protection
64
+
65
+ client = httpx_ssrf_protection(
66
+ httpx.AsyncClient(),
67
+ dns_cache_size=1000, # Cache up to 1000 DNS resolutions
68
+ dns_cache_ttl=300, # Cache for 5 minutes
69
+ )
70
+
71
+ await client.get("https://public.domain") # Allowed
72
+ await client.get("https://private.domain") # Blocked
73
+ ```
74
+
75
+ ## Custom Validation
76
+
77
+ For example, implement a simple domain whitelist to restrict requests to specific hosts:
78
+
79
+ ```python
80
+ import httpx
81
+ from httpx_secure import httpx_ssrf_protection
82
+ from ipaddress import IPv4Address, IPv6Address
83
+
84
+ def custom_validator(
85
+ hostname: str,
86
+ ip: IPv4Address | IPv6Address,
87
+ port: int
88
+ ) -> bool:
89
+ return hostname in {
90
+ "whitelisted.domain",
91
+ "webhook.partner.com",
92
+ }
93
+
94
+ client = httpx_ssrf_protection(
95
+ httpx.AsyncClient(),
96
+ custom_validator=custom_validator,
97
+ )
98
+
99
+ await client.get("https://whitelisted.domain") # Allowed
100
+ await client.get("https://unknown.domain") # Blocked
101
+ ```
102
+
103
+ ## How It Works
104
+
105
+ 1. **Cache Lookup**: First checks if the host has been recently validated and cached
106
+ 2. **DNS Resolution**: If not cached, resolves the hostname to an IP address
107
+ 3. **Validation**: Verifies the IP is globally routable, blocking private/internal addresses
108
+ 4. **Custom Validation**: If provided, your custom validator is called for additional checks
109
+ 5. **Request Modification**: Rewrites the request to use the validated IP directly
110
+
111
+ The DNS cache significantly reduces latency for repeated requests, while per-host locking ensures efficient concurrent resolution of parallel requests.
112
+
113
+ > [!TIP]
114
+ > The SSRF protection applies to all HTTP methods (GET, POST, PUT, DELETE, etc.) and automatically validates redirects to prevent SSRF attacks through redirect chains.
@@ -0,0 +1,6 @@
1
+ httpx_secure/__init__.py,sha256=Dzr6N4ARNVs7BKywMjVumGUchYLKUP7OENUyCOu0l4A,7442
2
+ httpx_secure/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ httpx_secure-1.0.0.dist-info/METADATA,sha256=AvyGhYPPSrqE_24v6mz57nw6rRx1CPSlAf56uHyiOR4,4247
4
+ httpx_secure-1.0.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
5
+ httpx_secure-1.0.0.dist-info/licenses/LICENSE,sha256=DbMza-HVDBjY0PhEqZbN3a9moBjb3uWKuUkzwcb_wuk,632
6
+ httpx_secure-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,12 @@
1
+ BSD Zero Clause License
2
+
3
+ Permission to use, copy, modify, and/or distribute this software for any
4
+ purpose with or without fee is hereby granted.
5
+
6
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
7
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
8
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
9
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
10
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
11
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
12
+ PERFORMANCE OF THIS SOFTWARE.