httpx-secure 1.3.0__tar.gz → 2.0.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.
@@ -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,205 @@
1
+ Metadata-Version: 2.5
2
+ Name: httpx-secure
3
+ Version: 2.0.0
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 HTTPX
40
+ `AsyncClient`. Add your own destination rules without changing HTTPX's request
41
+ API. Python 3.11+, with asyncio or Trio.
42
+
43
+ ## Installation
44
+
45
+ ```sh
46
+ pip install httpx-secure
47
+ ```
48
+
49
+ HTTP/2 remains optional: install `httpx[http2]` when configuring an HTTP/2 client.
50
+
51
+ ## Quick Start
52
+
53
+ Configure a direct client before making requests:
54
+
55
+ ```python
56
+ import asyncio
57
+ import httpx
58
+ from httpx_secure import SSRFProtectionError, httpx_ssrf_protection
59
+
60
+ async def main():
61
+ async with httpx.AsyncClient(trust_env=False) as client:
62
+ httpx_ssrf_protection(client)
63
+ try:
64
+ await client.get("http://127.0.0.1/private")
65
+ except SSRFProtectionError as error:
66
+ print(f"Blocked: {error.hostname}")
67
+
68
+ asyncio.run(main()) # Blocked: 127.0.0.1
69
+ ```
70
+
71
+ The returned object is the same client. Keep using its ordinary `get`, `post`,
72
+ `send`, `stream` and async context-manager interfaces. HTTPX continues to own
73
+ timeouts, authentication, TLS configuration and response streaming.
74
+ See [connection authorization](#connection-authorization) for the policy boundary.
75
+
76
+ ## Custom Validation
77
+
78
+ A validator receives the logical hostname, selected `IPv4Address` or
79
+ `IPv6Address`, and effective destination port. It may return a bool directly or
80
+ asynchronously. The global-address check runs first and cannot be overridden by
81
+ an accepting custom validator.
82
+
83
+ For example, restrict connections to port 443:
84
+
85
+ ```python
86
+ import asyncio
87
+ import httpx
88
+ from httpx_secure import httpx_ssrf_protection
89
+
90
+ def https_port_only(hostname, address, port):
91
+ return port == 443
92
+
93
+ async def main():
94
+ async with httpx.AsyncClient(trust_env=False) as client:
95
+ httpx_ssrf_protection(client, custom_validator=https_port_only)
96
+ # Make requests with client here.
97
+
98
+ asyncio.run(main())
99
+ ```
100
+
101
+ Set `check_globally_reachable=False` only when your custom validator owns the
102
+ entire destination policy, such as explicitly permitting a particular internal
103
+ service. A custom validator is required in that configuration.
104
+
105
+ ## Supported Clients
106
+
107
+ Call the helper while exclusively configuring the client on its owning async
108
+ runtime. A newly created client or a client inside its context manager is
109
+ supported. Already-used clients are supported when every response has finished
110
+ or been closed and no requests remain active or queued.
111
+
112
+ The helper retains the existing client, standard `AsyncHTTPTransport` instances,
113
+ connection pools, SSL contexts, HTTP-version settings, limits and direct mounts.
114
+ Existing idle HTTP/1.1 and HTTP/2 connections expire before reuse. Their pools close
115
+ them on the next request or during client closure.
116
+
117
+ Setup fails before changing any route when the client has:
118
+
119
+ - HTTP, HTTPS or SOCKS proxy routes, including environment-created proxy mounts;
120
+ - Unix-domain sockets, custom transports or custom network backends;
121
+ - custom client routing instead of HTTPX's normal transport selection;
122
+ - active requests, pending requests or open streamed responses; or
123
+ - unsupported transport/connection state.
124
+
125
+ For an intended direct client, `trust_env=False` avoids environment-created proxy
126
+ routes. `trust_env=True` is supported when no proxy route is actually configured;
127
+ existing environment-derived SSL trust is retained. The helper does not remove
128
+ proxies or silently fall back to weaker protection for unsupported routes.
129
+
130
+ Sharing a transport between clients also shares its connector policy. Configure
131
+ such transports exclusively; do not mutate routing or replace transports after
132
+ installation. Async task sharing after setup follows HTTPX's normal client
133
+ lifecycle. Cross-thread or cross-event-loop configuration is not supported.
134
+
135
+ <a id="how-it-works"></a>
136
+
137
+ ## Connection Authorization
138
+
139
+ For a new connection, the connector selects an IP, applies the global-address and
140
+ 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
142
+ verification/SNI, redirects, cookies and Host authority. Absolute redirects that
143
+ need another connection receive that destination's policy check.
144
+
145
+ **Hostname selection can open and close plain TCP probes, including to a denied
146
+ address. Probes send no HTTP or application data.** This package does not promise
147
+ zero TCP contact with denied addresses. Literal IPs do not need a selection probe.
148
+ A failed validated-IP connection does not fall back to an unvalidated hostname.
149
+
150
+ Authorization lasts for the established connection's lifetime. The bounded
151
+ address-selection cache stores approved selections and denials; expiry affects
152
+ new connections, not requests on an established socket. To apply a changed custom
153
+ policy immediately, close the client and create/configure another client.
154
+
155
+ The default check uses Python's `ipaddress.is_global` classification and also
156
+ blocks non-global IPv4 addresses embedded in the well-known NAT64 prefix. It is
157
+ an endpoint-IP policy, not a network firewall or a policy for what an authorized
158
+ remote application may do. Caller-supplied Host/SNI overrides and the client's
159
+ trusted routing configuration remain the caller's responsibility.
160
+
161
+ ## API Reference
162
+
163
+ ### httpx_ssrf_protection
164
+
165
+ Accepts an existing `httpx.AsyncClient` and returns that **same instance**.
166
+ See [the function reference](https://github.com/Zaczero/pkgs/blob/main/httpx-secure/httpx_secure/__init__.py)
167
+ or `help(httpx_ssrf_protection)` for its signature and defaults.
168
+
169
+ | Parameter | Meaning |
170
+ | --- | --- |
171
+ | `client` | Quiescent existing client with supported direct routes. |
172
+ | `check_globally_reachable` | Apply the global-IP and NAT64 checks. |
173
+ | `custom_validator` | Optional sync/async `(hostname, address, port) -> bool` policy; required when the global check is disabled. |
174
+ | `dns_cache_size` | Maximum cached selections/denials; zero disables retention. Keys distinguish hostname, port and local bind address. |
175
+ | `dns_cache_ttl` | Cache lifetime in seconds, applied to new connections. |
176
+ | `happy_eyeballs_delay` | Seconds between hostname-selection probe attempts. |
177
+
178
+ The current request's connect timeout bounds cache-lock waiting, probe,
179
+ asynchronous validation and final TCP connection together. TLS, pool, read and
180
+ write timeouts retain HTTPX/HTTPcore's separate phase semantics. Custom-validator
181
+ exceptions propagate; temporary connection failures and cancellation are not
182
+ cached as denials.
183
+
184
+ `TypeError` reports a non-`AsyncClient` or non-callable validator. `ValueError`
185
+ reports unsupported routing/configuration or a completely disabled policy.
186
+ `RuntimeError` reports a closed/already-protected client or setup attempted during
187
+ active use. Finish or close outstanding responses before retrying setup.
188
+
189
+ ### SSRFProtectionError
190
+
191
+ An HTTPX `RequestError` raised when the selected destination is denied. Each
192
+ failure is a fresh exception with the current `request`, logical `hostname`,
193
+ selected `ip_addr` (`IPv4Address`, `IPv6Address`, or None for an invalid address)
194
+ and effective `port`.
195
+
196
+ Its `invalid_ip`, `non_global` and `custom_validation_failed` classmethods construct
197
+ the corresponding unbound errors; requests through HTTPX bind them to the current
198
+ request. DNS/connection failures use HTTPX `ConnectError`, and connect deadlines
199
+ use `ConnectTimeout`. Catch those separately when deciding whether to retry.
200
+
201
+ ## Support
202
+
203
+ [Issues and questions](https://github.com/Zaczero/pkgs/issues) ·
204
+ [Private security reports](https://github.com/Zaczero/pkgs/security/advisories/new) ·
205
+ [Premium support](https://monicz.dev/#get-in-touch)
@@ -0,0 +1,171 @@
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 HTTPX
6
+ `AsyncClient`. Add your own destination rules without changing HTTPX's request
7
+ API. Python 3.11+, with asyncio or Trio.
8
+
9
+ ## Installation
10
+
11
+ ```sh
12
+ pip install httpx-secure
13
+ ```
14
+
15
+ HTTP/2 remains optional: install `httpx[http2]` when configuring an HTTP/2 client.
16
+
17
+ ## Quick Start
18
+
19
+ Configure a direct client before making requests:
20
+
21
+ ```python
22
+ import asyncio
23
+ import httpx
24
+ from httpx_secure import SSRFProtectionError, httpx_ssrf_protection
25
+
26
+ async def main():
27
+ async with httpx.AsyncClient(trust_env=False) as client:
28
+ httpx_ssrf_protection(client)
29
+ try:
30
+ await client.get("http://127.0.0.1/private")
31
+ except SSRFProtectionError as error:
32
+ print(f"Blocked: {error.hostname}")
33
+
34
+ asyncio.run(main()) # Blocked: 127.0.0.1
35
+ ```
36
+
37
+ The returned object is the same client. Keep using its ordinary `get`, `post`,
38
+ `send`, `stream` and async context-manager interfaces. HTTPX continues to own
39
+ timeouts, authentication, TLS configuration and response streaming.
40
+ See [connection authorization](#connection-authorization) for the policy boundary.
41
+
42
+ ## Custom Validation
43
+
44
+ A validator receives the logical hostname, selected `IPv4Address` or
45
+ `IPv6Address`, and effective destination port. It may return a bool directly or
46
+ asynchronously. The global-address check runs first and cannot be overridden by
47
+ an accepting custom validator.
48
+
49
+ For example, restrict connections to port 443:
50
+
51
+ ```python
52
+ import asyncio
53
+ import httpx
54
+ from httpx_secure import httpx_ssrf_protection
55
+
56
+ def https_port_only(hostname, address, port):
57
+ return port == 443
58
+
59
+ async def main():
60
+ async with httpx.AsyncClient(trust_env=False) as client:
61
+ httpx_ssrf_protection(client, custom_validator=https_port_only)
62
+ # Make requests with client here.
63
+
64
+ asyncio.run(main())
65
+ ```
66
+
67
+ Set `check_globally_reachable=False` only when your custom validator owns the
68
+ entire destination policy, such as explicitly permitting a particular internal
69
+ service. A custom validator is required in that configuration.
70
+
71
+ ## Supported Clients
72
+
73
+ Call the helper while exclusively configuring the client on its owning async
74
+ runtime. A newly created client or a client inside its context manager is
75
+ supported. Already-used clients are supported when every response has finished
76
+ or been closed and no requests remain active or queued.
77
+
78
+ The helper retains the existing client, standard `AsyncHTTPTransport` instances,
79
+ connection pools, SSL contexts, HTTP-version settings, limits and direct mounts.
80
+ Existing idle HTTP/1.1 and HTTP/2 connections expire before reuse. Their pools close
81
+ them on the next request or during client closure.
82
+
83
+ Setup fails before changing any route when the client has:
84
+
85
+ - HTTP, HTTPS or SOCKS proxy routes, including environment-created proxy mounts;
86
+ - Unix-domain sockets, custom transports or custom network backends;
87
+ - custom client routing instead of HTTPX's normal transport selection;
88
+ - active requests, pending requests or open streamed responses; or
89
+ - unsupported transport/connection state.
90
+
91
+ For an intended direct client, `trust_env=False` avoids environment-created proxy
92
+ routes. `trust_env=True` is supported when no proxy route is actually configured;
93
+ existing environment-derived SSL trust is retained. The helper does not remove
94
+ proxies or silently fall back to weaker protection for unsupported routes.
95
+
96
+ Sharing a transport between clients also shares its connector policy. Configure
97
+ such transports exclusively; do not mutate routing or replace transports after
98
+ installation. Async task sharing after setup follows HTTPX's normal client
99
+ lifecycle. Cross-thread or cross-event-loop configuration is not supported.
100
+
101
+ <a id="how-it-works"></a>
102
+
103
+ ## Connection Authorization
104
+
105
+ For a new connection, the connector selects an IP, applies the global-address and
106
+ 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
108
+ verification/SNI, redirects, cookies and Host authority. Absolute redirects that
109
+ need another connection receive that destination's policy check.
110
+
111
+ **Hostname selection can open and close plain TCP probes, including to a denied
112
+ address. Probes send no HTTP or application data.** This package does not promise
113
+ zero TCP contact with denied addresses. Literal IPs do not need a selection probe.
114
+ A failed validated-IP connection does not fall back to an unvalidated hostname.
115
+
116
+ Authorization lasts for the established connection's lifetime. The bounded
117
+ address-selection cache stores approved selections and denials; expiry affects
118
+ new connections, not requests on an established socket. To apply a changed custom
119
+ policy immediately, close the client and create/configure another client.
120
+
121
+ The default check uses Python's `ipaddress.is_global` classification and also
122
+ blocks non-global IPv4 addresses embedded in the well-known NAT64 prefix. It is
123
+ an endpoint-IP policy, not a network firewall or a policy for what an authorized
124
+ remote application may do. Caller-supplied Host/SNI overrides and the client's
125
+ trusted routing configuration remain the caller's responsibility.
126
+
127
+ ## API Reference
128
+
129
+ ### httpx_ssrf_protection
130
+
131
+ Accepts an existing `httpx.AsyncClient` and returns that **same instance**.
132
+ See [the function reference](https://github.com/Zaczero/pkgs/blob/main/httpx-secure/httpx_secure/__init__.py)
133
+ or `help(httpx_ssrf_protection)` for its signature and defaults.
134
+
135
+ | Parameter | Meaning |
136
+ | --- | --- |
137
+ | `client` | Quiescent existing client with supported direct routes. |
138
+ | `check_globally_reachable` | Apply the global-IP and NAT64 checks. |
139
+ | `custom_validator` | Optional sync/async `(hostname, address, port) -> bool` policy; required when the global check is disabled. |
140
+ | `dns_cache_size` | Maximum cached selections/denials; zero disables retention. Keys distinguish hostname, port and local bind address. |
141
+ | `dns_cache_ttl` | Cache lifetime in seconds, applied to new connections. |
142
+ | `happy_eyeballs_delay` | Seconds between hostname-selection probe attempts. |
143
+
144
+ The current request's connect timeout bounds cache-lock waiting, probe,
145
+ asynchronous validation and final TCP connection together. TLS, pool, read and
146
+ write timeouts retain HTTPX/HTTPcore's separate phase semantics. Custom-validator
147
+ exceptions propagate; temporary connection failures and cancellation are not
148
+ cached as denials.
149
+
150
+ `TypeError` reports a non-`AsyncClient` or non-callable validator. `ValueError`
151
+ reports unsupported routing/configuration or a completely disabled policy.
152
+ `RuntimeError` reports a closed/already-protected client or setup attempted during
153
+ active use. Finish or close outstanding responses before retrying setup.
154
+
155
+ ### SSRFProtectionError
156
+
157
+ An HTTPX `RequestError` raised when the selected destination is denied. Each
158
+ failure is a fresh exception with the current `request`, logical `hostname`,
159
+ selected `ip_addr` (`IPv4Address`, `IPv6Address`, or None for an invalid address)
160
+ and effective `port`.
161
+
162
+ Its `invalid_ip`, `non_global` and `custom_validation_failed` classmethods construct
163
+ the corresponding unbound errors; requests through HTTPX bind them to the current
164
+ request. DNS/connection failures use HTTPX `ConnectError`, and connect deadlines
165
+ use `ConnectTimeout`. Catch those separately when deciding whether to retry.
166
+
167
+ ## Support
168
+
169
+ [Issues and questions](https://github.com/Zaczero/pkgs/issues) ·
170
+ [Private security reports](https://github.com/Zaczero/pkgs/security/advisories/new) ·
171
+ [Premium support](https://monicz.dev/#get-in-touch)