httpx-secure 1.3.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.
@@ -49,6 +49,7 @@
49
49
 
50
50
  # Kernel Module Compile Results
51
51
  *.mod*
52
+ !h2corn/bench/grpc_client/go.mod
52
53
  *.cmd
53
54
  .tmp_versions/
54
55
  modules.order
@@ -120,7 +121,7 @@ pids
120
121
  lib-cov
121
122
 
122
123
  # Coverage directory used by tools like istanbul
123
- coverage
124
+ /coverage/
124
125
  *.lcov
125
126
 
126
127
  # nyc test coverage
@@ -370,8 +371,8 @@ venv.bak/
370
371
  # Rope project settings
371
372
  .ropeproject
372
373
 
373
- # mkdocs documentation
374
- /site
374
+ # mkdocs documentation (build output, any package)
375
+ site/
375
376
 
376
377
  # mypy
377
378
  .mypy_cache/
@@ -440,15 +441,62 @@ Cargo.lock
440
441
  # End of https://www.toptal.com/developers/gitignore/api/visualstudiocode,linux,c,cmake,direnv,dotenv,node,python,rust
441
442
 
442
443
  # Custom rules (everything added below won't be overriden by 'Generate .gitignore File' if you use 'Update' option)
444
+ #
445
+ # Commit sources and generators, not build, documentation, license, or benchmark outputs.
443
446
 
444
447
  !.envrc
448
+ !/Cargo.lock
445
449
 
446
450
  .codex
451
+ .claude/
452
+ .agents/
453
+ .codex/
454
+ **/AGENTS.md
455
+ **/CLAUDE.md
456
+ .uv-cache/
447
457
  repomix-output.xml
448
458
  uv.lock
449
- vendor/
459
+ # Free-threaded / variant venvs (uv creates .venv-t etc.; plain .venv is above)
460
+ .venv*/
461
+ **/.venv*/
462
+
463
+ # LLVM/coverage profiles (also under target/, but may land elsewhere)
464
+ .pgo/
465
+ *.profraw
466
+ *.profdata
467
+
468
+ # Per-package cargo targets (h2corn target-py314t, gometry target-local, …)
469
+ **/target-*/
450
470
 
451
471
  githead/tests/git/HEAD
452
- h2corn/bench/*.bin
453
- h2corn/bench/results/*_summary.json
454
472
  jinja2-htmlmin/tests/templates/.*
473
+
474
+ # Benchmark measurements, provenance, tables, and plots are external artifacts.
475
+ **/bench/results/
476
+ **/benches/results/
477
+ **/benchmarks/results/
478
+ **/docs/assets/benchmark-runs/
479
+ **/docs/assets/benchmark-*.svg
480
+ h2corn/bench/*.bin
481
+ h2corn/examples/grpc/gen/
482
+
483
+ # gometry: the only genuinely package-specific rules (build artifacts and
484
+ # LICENSE-*.md are already covered by the general `target/` and `**/LICENSE*.md`
485
+ # rules above). This coverage output is gometry-tool-specific:
486
+ gometry/coverage-python/
487
+ # The root Node-template `coverage` rule would otherwise hide this Rust source
488
+ # module; generated Python coverage reports remain ignored above.
489
+ !gometry/src/geometry/coverage/
490
+ !gometry/src/geometry/coverage/**
491
+
492
+ # mkdocs / properdocs build output (any package)
493
+ **/site/
494
+ test-results/
495
+
496
+ # Generated license files (any released package). Rendered at build time by
497
+ # .github/scripts/gen_licenses.py from each pyproject's SPDX expression (own
498
+ # license, one file per OR choice) and the Cargo dependency graph (rusty
499
+ # third-party bundle), then bundled into the wheel/sdist via the PEP 639
500
+ # default license-files glob. Every generated license file is LICENSE*.md;
501
+ # no license text is ever committed.
502
+ **/LICENSE*.md
@@ -0,0 +1,14 @@
1
+ # 0BSD License
2
+
3
+ Copyright (c) 2026 Kamil Monicz
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
9
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
10
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
11
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
12
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
13
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14
+ PERFORMANCE OF THIS SOFTWARE.
@@ -0,0 +1,213 @@
1
+ Metadata-Version: 2.5
2
+ Name: httpx-secure
3
+ Version: 2.0.1
4
+ Summary: Connection-level SSRF protection for existing HTTPX async clients
5
+ Project-URL: Issues, https://github.com/Zaczero/pkgs/issues
6
+ Project-URL: Repository, https://github.com/Zaczero/pkgs/tree/main/httpx-secure
7
+ Author-email: Kamil Monicz <kamil@monicz.dev>
8
+ License-Expression: 0BSD
9
+ License-File: LICENSE.md
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.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3.15
23
+ Classifier: Topic :: Internet :: WWW/HTTP
24
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
25
+ Classifier: Topic :: Security
26
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
+ Classifier: Topic :: System :: Networking
28
+ Classifier: Typing :: Typed
29
+ Requires-Python: >=3.11
30
+ Requires-Dist: anyio<5,>=4
31
+ Requires-Dist: httpcore<1.1,>=1.0.9
32
+ Requires-Dist: httpx<0.29,>=0.28.1
33
+ Description-Content-Type: text/markdown
34
+
35
+ # httpx-secure
36
+
37
+ <a id="why-use-this"></a>
38
+
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/).
43
+
44
+ ## Installation
45
+
46
+ ```sh
47
+ pip install httpx-secure
48
+ ```
49
+
50
+ HTTP/2 remains optional: install `httpx[http2]` when configuring an HTTP/2 client.
51
+
52
+ ## Quick Start
53
+
54
+ Configure a direct client before making requests:
55
+
56
+ ```python
57
+ import asyncio
58
+ import httpx
59
+ from httpx_secure import SSRFProtectionError, httpx_ssrf_protection
60
+
61
+ async def main():
62
+ async with httpx.AsyncClient(trust_env=False) as client:
63
+ httpx_ssrf_protection(client)
64
+ try:
65
+ await client.get("http://127.0.0.1/private")
66
+ except SSRFProtectionError as error:
67
+ print(f"Blocked: {error.hostname}")
68
+
69
+ asyncio.run(main()) # Blocked: 127.0.0.1
70
+ ```
71
+
72
+ The returned object is the same client. Keep using its ordinary `get`, `post`,
73
+ `send`, `stream` and async context-manager interfaces. HTTPX continues to own
74
+ timeouts, authentication, TLS configuration and response streaming.
75
+ See [connection authorization](#connection-authorization) for the policy boundary.
76
+
77
+ ## Custom Validation
78
+
79
+ A validator receives the logical hostname, selected `IPv4Address` or
80
+ `IPv6Address`, and effective destination port. It may return a bool directly or
81
+ asynchronously. The global-address check runs first and cannot be overridden by
82
+ an accepting custom validator.
83
+
84
+ For example, restrict connections to port 443:
85
+
86
+ ```python
87
+ import asyncio
88
+ import httpx
89
+ from httpx_secure import httpx_ssrf_protection
90
+
91
+ def https_port_only(hostname, address, port):
92
+ return port == 443
93
+
94
+ async def main():
95
+ async with httpx.AsyncClient(trust_env=False) as client:
96
+ httpx_ssrf_protection(client, custom_validator=https_port_only)
97
+ # Make requests with client here.
98
+
99
+ asyncio.run(main())
100
+ ```
101
+
102
+ Set `check_globally_reachable=False` only when your custom validator owns the
103
+ entire destination policy, such as explicitly permitting a particular internal
104
+ service. A custom validator is required in that configuration.
105
+
106
+ ## Supported Clients
107
+
108
+ Call the helper while exclusively configuring the client on its owning async
109
+ runtime. A newly created client or a client inside its context manager is
110
+ supported. Already-used clients are supported when every response has finished
111
+ or been closed and no requests remain active or queued.
112
+
113
+ The helper retains the existing client, standard `AsyncHTTPTransport` instances,
114
+ connection pools, SSL contexts, HTTP-version settings, limits and direct mounts.
115
+ Existing idle HTTP/1.1 and HTTP/2 connections expire before reuse. Their pools close
116
+ them on the next request or during client closure.
117
+
118
+ Setup fails before changing any route when the client has:
119
+
120
+ - HTTP, HTTPS or SOCKS proxy routes, including environment-created proxy mounts;
121
+ - Unix-domain sockets, custom transports or custom network backends;
122
+ - custom client routing instead of HTTPX's normal transport selection;
123
+ - active requests, pending requests or open streamed responses; or
124
+ - unsupported transport/connection state.
125
+
126
+ For an intended direct client, `trust_env=False` avoids environment-created proxy
127
+ routes. `trust_env=True` is supported when no proxy route is actually configured;
128
+ existing environment-derived SSL trust is retained. The helper does not remove
129
+ proxies or silently fall back to weaker protection for unsupported routes.
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
+
137
+ Sharing a transport between clients also shares its connector policy. Configure
138
+ such transports exclusively; do not mutate routing or replace transports after
139
+ installation. Async task sharing after setup follows HTTPX's normal client
140
+ lifecycle. Cross-thread or cross-event-loop configuration is not supported.
141
+
142
+ <a id="how-it-works"></a>
143
+
144
+ ## Connection Authorization
145
+
146
+ For a new connection, the connector selects an IP, applies the global-address and
147
+ custom checks, and opens the data-bearing connection to that exact numeric IP
148
+ and port. HTTPX and [HTTPcore](https://www.encode.io/httpcore/) retain the
149
+ logical origin for pooling, TLS certificate
150
+ verification/SNI, redirects, cookies and Host authority. Absolute redirects that
151
+ need another connection receive that destination's policy check.
152
+
153
+ **Hostname selection can open and close plain TCP probes, including to a denied
154
+ address. Probes send no HTTP or application data.** This package does not promise
155
+ zero TCP contact with denied addresses. Literal IPs do not need a selection probe.
156
+ A failed validated-IP connection does not fall back to an unvalidated hostname.
157
+
158
+ Authorization lasts for the established connection's lifetime. The bounded
159
+ address-selection cache stores approved selections and denials; expiry affects
160
+ new connections, not requests on an established socket. To apply a changed custom
161
+ policy immediately, close the client and create/configure another client.
162
+
163
+ The default check uses Python's `ipaddress.is_global` classification and also
164
+ blocks non-global IPv4 addresses embedded in the well-known NAT64 prefix. It is
165
+ an endpoint-IP policy, not a network firewall or a policy for what an authorized
166
+ remote application may do. Caller-supplied Host/SNI overrides and the client's
167
+ trusted routing configuration remain the caller's responsibility.
168
+
169
+ ## API Reference
170
+
171
+ ### httpx_ssrf_protection
172
+
173
+ Accepts an existing `httpx.AsyncClient` and returns that **same instance**.
174
+ See [the function reference](https://github.com/Zaczero/pkgs/blob/main/httpx-secure/httpx_secure/__init__.py)
175
+ or `help(httpx_ssrf_protection)` for its signature and defaults.
176
+
177
+ | Parameter | Meaning |
178
+ | --- | --- |
179
+ | `client` | Quiescent existing client with supported direct routes. |
180
+ | `check_globally_reachable` | Apply the global-IP and NAT64 checks. |
181
+ | `custom_validator` | Optional sync/async `(hostname, address, port) -> bool` policy; required when the global check is disabled. |
182
+ | `dns_cache_size` | Maximum cached selections/denials; zero disables retention. Keys distinguish hostname, port and local bind address. |
183
+ | `dns_cache_ttl` | Cache lifetime in seconds, applied to new connections. |
184
+ | `happy_eyeballs_delay` | Seconds between hostname-selection probe attempts. |
185
+
186
+ The current request's connect timeout bounds cache-lock waiting, probe,
187
+ asynchronous validation and final TCP connection together. TLS, pool, read and
188
+ write timeouts retain HTTPX/HTTPcore's separate phase semantics. Custom-validator
189
+ exceptions propagate; temporary connection failures and cancellation are not
190
+ cached as denials.
191
+
192
+ `TypeError` reports a non-`AsyncClient` or non-callable validator. `ValueError`
193
+ reports unsupported routing/configuration or a completely disabled policy.
194
+ `RuntimeError` reports a closed/already-protected client or setup attempted during
195
+ active use. Finish or close outstanding responses before retrying setup.
196
+
197
+ ### SSRFProtectionError
198
+
199
+ An HTTPX `RequestError` raised when the selected destination is denied. Each
200
+ failure is a fresh exception with the current `request`, logical `hostname`,
201
+ selected `ip_addr` (`IPv4Address`, `IPv6Address`, or `None` for an invalid address)
202
+ and effective `port`.
203
+
204
+ Its `invalid_ip`, `non_global` and `custom_validation_failed` classmethods construct
205
+ the corresponding unbound errors; requests through HTTPX bind them to the current
206
+ request. DNS/connection failures use HTTPX `ConnectError`, and connect deadlines
207
+ use `ConnectTimeout`. Catch those separately when deciding whether to retry.
208
+
209
+ ## Support
210
+
211
+ [Issues and questions](https://github.com/Zaczero/pkgs/issues) ·
212
+ [Private security reports](https://github.com/Zaczero/pkgs/security/advisories/new) ·
213
+ [Premium support](https://monicz.dev/#get-in-touch)
@@ -0,0 +1,179 @@
1
+ # httpx-secure
2
+
3
+ <a id="why-use-this"></a>
4
+
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/).
9
+
10
+ ## Installation
11
+
12
+ ```sh
13
+ pip install httpx-secure
14
+ ```
15
+
16
+ HTTP/2 remains optional: install `httpx[http2]` when configuring an HTTP/2 client.
17
+
18
+ ## Quick Start
19
+
20
+ Configure a direct client before making requests:
21
+
22
+ ```python
23
+ import asyncio
24
+ import httpx
25
+ from httpx_secure import SSRFProtectionError, httpx_ssrf_protection
26
+
27
+ async def main():
28
+ async with httpx.AsyncClient(trust_env=False) as client:
29
+ httpx_ssrf_protection(client)
30
+ try:
31
+ await client.get("http://127.0.0.1/private")
32
+ except SSRFProtectionError as error:
33
+ print(f"Blocked: {error.hostname}")
34
+
35
+ asyncio.run(main()) # Blocked: 127.0.0.1
36
+ ```
37
+
38
+ The returned object is the same client. Keep using its ordinary `get`, `post`,
39
+ `send`, `stream` and async context-manager interfaces. HTTPX continues to own
40
+ timeouts, authentication, TLS configuration and response streaming.
41
+ See [connection authorization](#connection-authorization) for the policy boundary.
42
+
43
+ ## Custom Validation
44
+
45
+ A validator receives the logical hostname, selected `IPv4Address` or
46
+ `IPv6Address`, and effective destination port. It may return a bool directly or
47
+ asynchronously. The global-address check runs first and cannot be overridden by
48
+ an accepting custom validator.
49
+
50
+ For example, restrict connections to port 443:
51
+
52
+ ```python
53
+ import asyncio
54
+ import httpx
55
+ from httpx_secure import httpx_ssrf_protection
56
+
57
+ def https_port_only(hostname, address, port):
58
+ return port == 443
59
+
60
+ async def main():
61
+ async with httpx.AsyncClient(trust_env=False) as client:
62
+ httpx_ssrf_protection(client, custom_validator=https_port_only)
63
+ # Make requests with client here.
64
+
65
+ asyncio.run(main())
66
+ ```
67
+
68
+ Set `check_globally_reachable=False` only when your custom validator owns the
69
+ entire destination policy, such as explicitly permitting a particular internal
70
+ service. A custom validator is required in that configuration.
71
+
72
+ ## Supported Clients
73
+
74
+ Call the helper while exclusively configuring the client on its owning async
75
+ runtime. A newly created client or a client inside its context manager is
76
+ supported. Already-used clients are supported when every response has finished
77
+ or been closed and no requests remain active or queued.
78
+
79
+ The helper retains the existing client, standard `AsyncHTTPTransport` instances,
80
+ connection pools, SSL contexts, HTTP-version settings, limits and direct mounts.
81
+ Existing idle HTTP/1.1 and HTTP/2 connections expire before reuse. Their pools close
82
+ them on the next request or during client closure.
83
+
84
+ Setup fails before changing any route when the client has:
85
+
86
+ - HTTP, HTTPS or SOCKS proxy routes, including environment-created proxy mounts;
87
+ - Unix-domain sockets, custom transports or custom network backends;
88
+ - custom client routing instead of HTTPX's normal transport selection;
89
+ - active requests, pending requests or open streamed responses; or
90
+ - unsupported transport/connection state.
91
+
92
+ For an intended direct client, `trust_env=False` avoids environment-created proxy
93
+ routes. `trust_env=True` is supported when no proxy route is actually configured;
94
+ existing environment-derived SSL trust is retained. The helper does not remove
95
+ proxies or silently fall back to weaker protection for unsupported routes.
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
+
103
+ Sharing a transport between clients also shares its connector policy. Configure
104
+ such transports exclusively; do not mutate routing or replace transports after
105
+ installation. Async task sharing after setup follows HTTPX's normal client
106
+ lifecycle. Cross-thread or cross-event-loop configuration is not supported.
107
+
108
+ <a id="how-it-works"></a>
109
+
110
+ ## Connection Authorization
111
+
112
+ For a new connection, the connector selects an IP, applies the global-address and
113
+ custom checks, and opens the data-bearing connection to that exact numeric IP
114
+ and port. HTTPX and [HTTPcore](https://www.encode.io/httpcore/) retain the
115
+ logical origin for pooling, TLS certificate
116
+ verification/SNI, redirects, cookies and Host authority. Absolute redirects that
117
+ need another connection receive that destination's policy check.
118
+
119
+ **Hostname selection can open and close plain TCP probes, including to a denied
120
+ address. Probes send no HTTP or application data.** This package does not promise
121
+ zero TCP contact with denied addresses. Literal IPs do not need a selection probe.
122
+ A failed validated-IP connection does not fall back to an unvalidated hostname.
123
+
124
+ Authorization lasts for the established connection's lifetime. The bounded
125
+ address-selection cache stores approved selections and denials; expiry affects
126
+ new connections, not requests on an established socket. To apply a changed custom
127
+ policy immediately, close the client and create/configure another client.
128
+
129
+ The default check uses Python's `ipaddress.is_global` classification and also
130
+ blocks non-global IPv4 addresses embedded in the well-known NAT64 prefix. It is
131
+ an endpoint-IP policy, not a network firewall or a policy for what an authorized
132
+ remote application may do. Caller-supplied Host/SNI overrides and the client's
133
+ trusted routing configuration remain the caller's responsibility.
134
+
135
+ ## API Reference
136
+
137
+ ### httpx_ssrf_protection
138
+
139
+ Accepts an existing `httpx.AsyncClient` and returns that **same instance**.
140
+ See [the function reference](https://github.com/Zaczero/pkgs/blob/main/httpx-secure/httpx_secure/__init__.py)
141
+ or `help(httpx_ssrf_protection)` for its signature and defaults.
142
+
143
+ | Parameter | Meaning |
144
+ | --- | --- |
145
+ | `client` | Quiescent existing client with supported direct routes. |
146
+ | `check_globally_reachable` | Apply the global-IP and NAT64 checks. |
147
+ | `custom_validator` | Optional sync/async `(hostname, address, port) -> bool` policy; required when the global check is disabled. |
148
+ | `dns_cache_size` | Maximum cached selections/denials; zero disables retention. Keys distinguish hostname, port and local bind address. |
149
+ | `dns_cache_ttl` | Cache lifetime in seconds, applied to new connections. |
150
+ | `happy_eyeballs_delay` | Seconds between hostname-selection probe attempts. |
151
+
152
+ The current request's connect timeout bounds cache-lock waiting, probe,
153
+ asynchronous validation and final TCP connection together. TLS, pool, read and
154
+ write timeouts retain HTTPX/HTTPcore's separate phase semantics. Custom-validator
155
+ exceptions propagate; temporary connection failures and cancellation are not
156
+ cached as denials.
157
+
158
+ `TypeError` reports a non-`AsyncClient` or non-callable validator. `ValueError`
159
+ reports unsupported routing/configuration or a completely disabled policy.
160
+ `RuntimeError` reports a closed/already-protected client or setup attempted during
161
+ active use. Finish or close outstanding responses before retrying setup.
162
+
163
+ ### SSRFProtectionError
164
+
165
+ An HTTPX `RequestError` raised when the selected destination is denied. Each
166
+ failure is a fresh exception with the current `request`, logical `hostname`,
167
+ selected `ip_addr` (`IPv4Address`, `IPv6Address`, or `None` for an invalid address)
168
+ and effective `port`.
169
+
170
+ Its `invalid_ip`, `non_global` and `custom_validation_failed` classmethods construct
171
+ the corresponding unbound errors; requests through HTTPX bind them to the current
172
+ request. DNS/connection failures use HTTPX `ConnectError`, and connect deadlines
173
+ use `ConnectTimeout`. Catch those separately when deciding whether to retry.
174
+
175
+ ## Support
176
+
177
+ [Issues and questions](https://github.com/Zaczero/pkgs/issues) ·
178
+ [Private security reports](https://github.com/Zaczero/pkgs/security/advisories/new) ·
179
+ [Premium support](https://monicz.dev/#get-in-touch)