cimdkit 0.1.0__tar.gz → 0.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.
- {cimdkit-0.1.0 → cimdkit-0.2.0}/CHANGELOG.md +11 -0
- {cimdkit-0.1.0 → cimdkit-0.2.0}/PKG-INFO +26 -3
- {cimdkit-0.1.0 → cimdkit-0.2.0}/README.md +25 -2
- {cimdkit-0.1.0 → cimdkit-0.2.0}/pyproject.toml +1 -1
- {cimdkit-0.1.0 → cimdkit-0.2.0}/src/cimdkit/__init__.py +5 -2
- {cimdkit-0.1.0 → cimdkit-0.2.0}/src/cimdkit/cli.py +8 -1
- {cimdkit-0.1.0 → cimdkit-0.2.0}/src/cimdkit/fetch.py +130 -13
- {cimdkit-0.1.0 → cimdkit-0.2.0}/src/cimdkit/resolver.py +5 -2
- cimdkit-0.2.0/tests/test_proxy.py +173 -0
- {cimdkit-0.1.0 → cimdkit-0.2.0}/.gitignore +0 -0
- {cimdkit-0.1.0 → cimdkit-0.2.0}/LICENSE +0 -0
- {cimdkit-0.1.0 → cimdkit-0.2.0}/src/cimdkit/__main__.py +0 -0
- {cimdkit-0.1.0 → cimdkit-0.2.0}/src/cimdkit/document.py +0 -0
- {cimdkit-0.1.0 → cimdkit-0.2.0}/src/cimdkit/errors.py +0 -0
- {cimdkit-0.1.0 → cimdkit-0.2.0}/src/cimdkit/urls.py +0 -0
- {cimdkit-0.1.0 → cimdkit-0.2.0}/tests/conftest.py +0 -0
- {cimdkit-0.1.0 → cimdkit-0.2.0}/tests/test_cli.py +0 -0
- {cimdkit-0.1.0 → cimdkit-0.2.0}/tests/test_document.py +0 -0
- {cimdkit-0.1.0 → cimdkit-0.2.0}/tests/test_fetch.py +0 -0
- {cimdkit-0.1.0 → cimdkit-0.2.0}/tests/test_resolver.py +0 -0
- {cimdkit-0.1.0 → cimdkit-0.2.0}/tests/test_tls.py +0 -0
- {cimdkit-0.1.0 → cimdkit-0.2.0}/tests/test_urls.py +0 -0
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.0 (2026-12-05)
|
|
4
|
+
|
|
5
|
+
- Fetch through an HTTP egress proxy: `proxy="http://[user:pass@]host:port"`, a `Proxy`, or
|
|
6
|
+
`"env"` for `HTTPS_PROXY`/`NO_PROXY`, on `fetch_document`, `ClientResolver` and
|
|
7
|
+
`cimdkit check --proxy`. The host is still resolved and checked locally and the proxy is
|
|
8
|
+
asked to `CONNECT` to the checked IP, so address checks and DNS-rebinding protection stay
|
|
9
|
+
on. Proxy refusals are transient errors.
|
|
10
|
+
- `proxy_dns=True` (`--proxy-dns`) lets the proxy resolve the name, for servers with no
|
|
11
|
+
public DNS or proxies that only allow `CONNECT` by host name.
|
|
12
|
+
- A bad proxy URL makes `ClientResolver(...)` fail at startup, not on the first sign-in.
|
|
13
|
+
|
|
3
14
|
## 0.1.0 (2026-11-08)
|
|
4
15
|
|
|
5
16
|
First release.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: cimdkit
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: OAuth Client ID Metadata Documents (CIMD) for authorization servers: safe fetch, spec validation, caching and redirect_uri matching for MCP clients
|
|
5
5
|
Project-URL: Homepage, https://github.com/srikrishnaL/kitforge/tree/main/packages/cimdkit
|
|
6
6
|
Project-URL: Source, https://github.com/srikrishnaL/kitforge
|
|
@@ -148,6 +148,28 @@ doc = make_document("https://app.example.com/oauth/client.json",
|
|
|
148
148
|
logo_uri="https://app.example.com/logo.png")
|
|
149
149
|
```
|
|
150
150
|
|
|
151
|
+
## Behind an egress proxy
|
|
152
|
+
|
|
153
|
+
Authorization servers in locked-down networks often reach the internet only through an HTTP
|
|
154
|
+
proxy. Pass it with `proxy=`:
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
resolver = ClientResolver(policy, proxy="http://egress.internal:3128") # or "env"
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
The host name is still resolved and checked on your server, and the proxy is asked to
|
|
161
|
+
`CONNECT` to the checked IP, so the SSRF and DNS-rebinding protections stay in place and TLS
|
|
162
|
+
still verifies the real host name. `proxy="env"` reads `HTTPS_PROXY` and `NO_PROXY`;
|
|
163
|
+
`http://user:password@host:port` sends Basic proxy credentials. If the proxy refuses or cannot
|
|
164
|
+
be reached, the error is transient, so a cached document keeps working.
|
|
165
|
+
|
|
166
|
+
If your server has no public DNS and only the proxy can resolve names, add `proxy_dns=True`:
|
|
167
|
+
the host name goes to the proxy as is. The proxy then has to refuse internal addresses itself,
|
|
168
|
+
because cimdkit can no longer see them. If your proxy only allows `CONNECT` by host name
|
|
169
|
+
(a domain allowlist), you need `proxy_dns=True` as well.
|
|
170
|
+
|
|
171
|
+
The same options work on the command line: `cimdkit check URL --proxy env [--proxy-dns]`.
|
|
172
|
+
|
|
151
173
|
## For development
|
|
152
174
|
|
|
153
175
|
`ClientResolver(allow_loopback=True)` (or `cimdkit check --allow-loopback`) lets a server on
|
|
@@ -157,8 +179,9 @@ your machine fetch documents from `127.0.0.1`/`::1`. The spec forbids this in pr
|
|
|
157
179
|
|
|
158
180
|
- It resolves and validates clients. It does not issue codes or tokens, verify
|
|
159
181
|
`private_key_jwt` assertions, or fetch `jwks_uri` and logos for you.
|
|
160
|
-
- The fetch
|
|
161
|
-
`
|
|
182
|
+
- The fetch ignores `HTTPS_PROXY` unless you pass `proxy="env"` (see above). Only plain
|
|
183
|
+
`http://` proxies with `CONNECT` are supported, not SOCKS or TLS to the proxy; pass your
|
|
184
|
+
own `transport=` for those.
|
|
162
185
|
- The cache is in memory, per process. Pass `fetch=` or wrap `resolve` to share one.
|
|
163
186
|
- It follows draft-ietf-oauth-client-id-metadata-document as of November 2026. The draft can
|
|
164
187
|
still change.
|
|
@@ -123,6 +123,28 @@ doc = make_document("https://app.example.com/oauth/client.json",
|
|
|
123
123
|
logo_uri="https://app.example.com/logo.png")
|
|
124
124
|
```
|
|
125
125
|
|
|
126
|
+
## Behind an egress proxy
|
|
127
|
+
|
|
128
|
+
Authorization servers in locked-down networks often reach the internet only through an HTTP
|
|
129
|
+
proxy. Pass it with `proxy=`:
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
resolver = ClientResolver(policy, proxy="http://egress.internal:3128") # or "env"
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
The host name is still resolved and checked on your server, and the proxy is asked to
|
|
136
|
+
`CONNECT` to the checked IP, so the SSRF and DNS-rebinding protections stay in place and TLS
|
|
137
|
+
still verifies the real host name. `proxy="env"` reads `HTTPS_PROXY` and `NO_PROXY`;
|
|
138
|
+
`http://user:password@host:port` sends Basic proxy credentials. If the proxy refuses or cannot
|
|
139
|
+
be reached, the error is transient, so a cached document keeps working.
|
|
140
|
+
|
|
141
|
+
If your server has no public DNS and only the proxy can resolve names, add `proxy_dns=True`:
|
|
142
|
+
the host name goes to the proxy as is. The proxy then has to refuse internal addresses itself,
|
|
143
|
+
because cimdkit can no longer see them. If your proxy only allows `CONNECT` by host name
|
|
144
|
+
(a domain allowlist), you need `proxy_dns=True` as well.
|
|
145
|
+
|
|
146
|
+
The same options work on the command line: `cimdkit check URL --proxy env [--proxy-dns]`.
|
|
147
|
+
|
|
126
148
|
## For development
|
|
127
149
|
|
|
128
150
|
`ClientResolver(allow_loopback=True)` (or `cimdkit check --allow-loopback`) lets a server on
|
|
@@ -132,8 +154,9 @@ your machine fetch documents from `127.0.0.1`/`::1`. The spec forbids this in pr
|
|
|
132
154
|
|
|
133
155
|
- It resolves and validates clients. It does not issue codes or tokens, verify
|
|
134
156
|
`private_key_jwt` assertions, or fetch `jwks_uri` and logos for you.
|
|
135
|
-
- The fetch
|
|
136
|
-
`
|
|
157
|
+
- The fetch ignores `HTTPS_PROXY` unless you pass `proxy="env"` (see above). Only plain
|
|
158
|
+
`http://` proxies with `CONNECT` are supported, not SOCKS or TLS to the proxy; pass your
|
|
159
|
+
own `transport=` for those.
|
|
137
160
|
- The cache is in memory, per process. Pass `fetch=` or wrap `resolve` to share one.
|
|
138
161
|
- It follows draft-ietf-oauth-client-id-metadata-document as of November 2026. The draft can
|
|
139
162
|
still change.
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "cimdkit"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.2.0"
|
|
8
8
|
description = "OAuth Client ID Metadata Documents (CIMD) for authorization servers: safe fetch, spec validation, caching and redirect_uri matching for MCP clients"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "MIT"
|
|
@@ -17,11 +17,12 @@ from .errors import (
|
|
|
17
17
|
InvalidRedirectUri,
|
|
18
18
|
TransientFetchError,
|
|
19
19
|
)
|
|
20
|
-
from .fetch import DEFAULT_MAX_BYTES, FetchResult, Response, fetch_document,
|
|
20
|
+
from .fetch import (DEFAULT_MAX_BYTES, FetchResult, Proxy, Response, fetch_document,
|
|
21
|
+
is_public_address, proxy_from_env)
|
|
21
22
|
from .resolver import ClientResolver, cache_ttl
|
|
22
23
|
from .urls import check_client_id_url, is_client_id_url, redirect_uri_matches
|
|
23
24
|
|
|
24
|
-
__version__ = "0.
|
|
25
|
+
__version__ = "0.2.0"
|
|
25
26
|
|
|
26
27
|
#: Add these to your RFC 8414 authorization server metadata.
|
|
27
28
|
SERVER_METADATA = {"client_id_metadata_document_supported": True}
|
|
@@ -45,6 +46,8 @@ __all__ = [
|
|
|
45
46
|
"cache_ttl",
|
|
46
47
|
"check_client_id_url",
|
|
47
48
|
"fetch_document",
|
|
49
|
+
"Proxy",
|
|
50
|
+
"proxy_from_env",
|
|
48
51
|
"is_client_id_url",
|
|
49
52
|
"is_public_address",
|
|
50
53
|
"make_document",
|
|
@@ -31,6 +31,12 @@ def _parser() -> argparse.ArgumentParser:
|
|
|
31
31
|
help="auth methods the server supports (default: none, private_key_jwt)")
|
|
32
32
|
c.add_argument("--allow-loopback", action="store_true",
|
|
33
33
|
help="allow fetching from 127.0.0.1 / ::1 (development only)")
|
|
34
|
+
c.add_argument("--proxy", metavar="URL",
|
|
35
|
+
help="fetch through this HTTP proxy (http://[user:pass@]host:port), "
|
|
36
|
+
"or 'env' to use HTTPS_PROXY / NO_PROXY")
|
|
37
|
+
c.add_argument("--proxy-dns", action="store_true",
|
|
38
|
+
help="let the proxy resolve the host name (no local DNS lookup or "
|
|
39
|
+
"address check)")
|
|
34
40
|
c.add_argument("--max-bytes", type=int, default=DEFAULT_MAX_BYTES)
|
|
35
41
|
c.add_argument("--timeout", type=float, default=5.0)
|
|
36
42
|
c.add_argument("--json", action="store_true", help="print the result as JSON")
|
|
@@ -47,7 +53,8 @@ def _check(args: argparse.Namespace) -> int:
|
|
|
47
53
|
else:
|
|
48
54
|
result = fetch_document(args.client_id, timeout=args.timeout,
|
|
49
55
|
max_bytes=args.max_bytes,
|
|
50
|
-
allow_loopback=args.allow_loopback
|
|
56
|
+
allow_loopback=args.allow_loopback,
|
|
57
|
+
proxy=args.proxy, proxy_dns=args.proxy_dns)
|
|
51
58
|
doc, headers = result.document, dict(result.headers)
|
|
52
59
|
meta = validate_document(doc, args.client_id, policy)
|
|
53
60
|
bad = [u for u in args.redirect_uri if meta.match_redirect_uri(u) is None]
|
|
@@ -7,6 +7,12 @@
|
|
|
7
7
|
so DNS rebinding cannot swap it afterwards;
|
|
8
8
|
* at most ``max_bytes`` (5 KB by default) are read, under one overall deadline;
|
|
9
9
|
* the body must be a JSON object with no duplicate keys.
|
|
10
|
+
|
|
11
|
+
Servers whose only way out is an HTTP egress proxy pass ``proxy=``. The host
|
|
12
|
+
is still resolved and checked locally, and the proxy is asked to CONNECT to
|
|
13
|
+
the checked address, so the guarantees above hold. ``proxy_dns=True`` instead
|
|
14
|
+
lets the proxy resolve the name (for networks with no public DNS); then the
|
|
15
|
+
proxy must be the one refusing internal addresses.
|
|
10
16
|
"""
|
|
11
17
|
|
|
12
18
|
from __future__ import annotations
|
|
@@ -16,9 +22,12 @@ import ipaddress
|
|
|
16
22
|
import json
|
|
17
23
|
import socket
|
|
18
24
|
import ssl
|
|
25
|
+
import base64
|
|
19
26
|
import time
|
|
27
|
+
import urllib.parse
|
|
28
|
+
import urllib.request
|
|
20
29
|
from dataclasses import dataclass, field
|
|
21
|
-
from typing import Callable, Dict, List, Mapping, Optional, Sequence
|
|
30
|
+
from typing import Callable, Dict, List, Mapping, Optional, Sequence, Union
|
|
22
31
|
|
|
23
32
|
from .errors import BlockedAddress, FetchError, TransientFetchError
|
|
24
33
|
from .urls import _split, _split_netloc, check_client_id_url
|
|
@@ -78,32 +87,112 @@ def _is_loopback(addr: str) -> bool:
|
|
|
78
87
|
return ip.is_loopback
|
|
79
88
|
|
|
80
89
|
|
|
90
|
+
def _is_ip(value: str) -> bool:
|
|
91
|
+
try:
|
|
92
|
+
ipaddress.ip_address(value)
|
|
93
|
+
except ValueError:
|
|
94
|
+
return False
|
|
95
|
+
return True
|
|
96
|
+
|
|
97
|
+
|
|
81
98
|
def system_resolver(host: str, port: int) -> List[str]:
|
|
82
99
|
infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
|
|
83
100
|
return list(dict.fromkeys(info[4][0] for info in infos))
|
|
84
101
|
|
|
85
102
|
|
|
103
|
+
@dataclass(frozen=True)
|
|
104
|
+
class Proxy:
|
|
105
|
+
"""An HTTP proxy that tunnels https with CONNECT."""
|
|
106
|
+
|
|
107
|
+
host: str
|
|
108
|
+
port: int
|
|
109
|
+
authorization: Optional[str] = None # "Basic ..." from user:password in the URL
|
|
110
|
+
|
|
111
|
+
@classmethod
|
|
112
|
+
def from_url(cls, url: str) -> "Proxy":
|
|
113
|
+
"""Parse ``http://[user:password@]host[:port]`` (port 80 when left out)."""
|
|
114
|
+
parts = urllib.parse.urlsplit(url if "://" in url else f"http://{url}")
|
|
115
|
+
if parts.scheme.lower() != "http":
|
|
116
|
+
raise ValueError(f"proxy must be an http:// URL, not {url!r}")
|
|
117
|
+
try:
|
|
118
|
+
port = parts.port or 80
|
|
119
|
+
except ValueError:
|
|
120
|
+
raise ValueError(f"proxy URL {url!r} has an invalid port") from None
|
|
121
|
+
if not parts.hostname:
|
|
122
|
+
raise ValueError(f"proxy URL {url!r} has no host")
|
|
123
|
+
auth = None
|
|
124
|
+
if parts.username is not None:
|
|
125
|
+
user = urllib.parse.unquote(parts.username)
|
|
126
|
+
pwd = urllib.parse.unquote(parts.password or "")
|
|
127
|
+
auth = "Basic " + base64.b64encode(f"{user}:{pwd}".encode()).decode("ascii")
|
|
128
|
+
return cls(parts.hostname, port, auth)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def proxy_from_env(host: str) -> Optional[Proxy]:
|
|
132
|
+
"""The proxy ``HTTPS_PROXY`` names for ``host``, or None (unset or in ``NO_PROXY``)."""
|
|
133
|
+
url = urllib.request.getproxies_environment().get("https")
|
|
134
|
+
if not url or urllib.request.proxy_bypass_environment(host):
|
|
135
|
+
return None
|
|
136
|
+
return Proxy.from_url(url)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _open_tunnel(proxy: Proxy, target: str, timeout: float) -> socket.socket:
|
|
140
|
+
"""Connect to the proxy and ask it to CONNECT to ``target`` (``host:port``)."""
|
|
141
|
+
sock = socket.create_connection((proxy.host, proxy.port), timeout)
|
|
142
|
+
try:
|
|
143
|
+
lines = [f"CONNECT {target} HTTP/1.1", f"Host: {target}"]
|
|
144
|
+
if proxy.authorization:
|
|
145
|
+
lines.append(f"Proxy-Authorization: {proxy.authorization}")
|
|
146
|
+
sock.sendall(("\r\n".join(lines) + "\r\n\r\n").encode("ascii"))
|
|
147
|
+
head = b""
|
|
148
|
+
while b"\r\n\r\n" not in head:
|
|
149
|
+
if len(head) > 8192:
|
|
150
|
+
raise TransientFetchError("proxy sent an oversized CONNECT reply")
|
|
151
|
+
chunk = sock.recv(1) # byte by byte: nothing past the reply may be consumed
|
|
152
|
+
if not chunk:
|
|
153
|
+
raise TransientFetchError("proxy closed the connection during CONNECT")
|
|
154
|
+
head += chunk
|
|
155
|
+
status_line = head.split(b"\r\n", 1)[0].decode("latin-1")
|
|
156
|
+
fields = status_line.split(" ", 2)
|
|
157
|
+
if len(fields) < 2 or not fields[0].startswith("HTTP/") or fields[1] != "200":
|
|
158
|
+
raise TransientFetchError(f"proxy refused CONNECT {target}: {status_line}")
|
|
159
|
+
return sock
|
|
160
|
+
except BaseException:
|
|
161
|
+
sock.close()
|
|
162
|
+
raise
|
|
163
|
+
|
|
164
|
+
|
|
86
165
|
class _PinnedHTTPSConnection(http.client.HTTPSConnection):
|
|
87
166
|
"""HTTPS to a fixed IP, with SNI and certificate checks for the real host name."""
|
|
88
167
|
|
|
89
168
|
def __init__(self, host: str, port: int, address: str, timeout: float,
|
|
90
|
-
context: ssl.SSLContext) -> None:
|
|
169
|
+
context: ssl.SSLContext, proxy: Optional[Proxy] = None) -> None:
|
|
91
170
|
super().__init__(host, port, timeout=timeout, context=context)
|
|
92
171
|
self._address = address
|
|
93
172
|
self._ctx = context
|
|
173
|
+
self._proxy = proxy
|
|
94
174
|
|
|
95
175
|
def connect(self) -> None: # pragma: no cover - exercised by the TLS test
|
|
96
|
-
|
|
176
|
+
if self._proxy is not None:
|
|
177
|
+
addr = f"[{self._address}]" if ":" in self._address else self._address
|
|
178
|
+
sock = _open_tunnel(self._proxy, f"{addr}:{self.port}", self.timeout)
|
|
179
|
+
else:
|
|
180
|
+
sock = socket.create_connection((self._address, self.port), self.timeout)
|
|
97
181
|
self.sock = self._ctx.wrap_socket(sock, server_hostname=self.host)
|
|
98
182
|
|
|
99
183
|
|
|
100
184
|
def https_transport(*, host: str, port: int, address: str, target: str,
|
|
101
185
|
headers: Mapping[str, str], timeout: float, max_bytes: int,
|
|
102
|
-
ssl_context: Optional[ssl.SSLContext] = None
|
|
103
|
-
|
|
186
|
+
ssl_context: Optional[ssl.SSLContext] = None,
|
|
187
|
+
proxy: Optional[Proxy] = None) -> Response:
|
|
188
|
+
"""Default transport: one GET over a pinned TLS connection, read with a deadline.
|
|
189
|
+
|
|
190
|
+
With ``proxy``, the connection is tunnelled through it with CONNECT to
|
|
191
|
+
``address`` (an IP, or the host name when the proxy resolves it).
|
|
192
|
+
"""
|
|
104
193
|
deadline = time.monotonic() + timeout
|
|
105
194
|
ctx = ssl_context or ssl.create_default_context()
|
|
106
|
-
conn = _PinnedHTTPSConnection(host, port, address, timeout, ctx)
|
|
195
|
+
conn = _PinnedHTTPSConnection(host, port, address, timeout, ctx, proxy)
|
|
107
196
|
try:
|
|
108
197
|
conn.request("GET", target, headers=dict(headers))
|
|
109
198
|
resp = conn.getresponse()
|
|
@@ -149,12 +238,21 @@ def fetch_document(client_id: str, *, timeout: float = DEFAULT_TIMEOUT,
|
|
|
149
238
|
resolver: Optional[Resolver] = None,
|
|
150
239
|
transport: Optional[Transport] = None,
|
|
151
240
|
ssl_context: Optional[ssl.SSLContext] = None,
|
|
152
|
-
user_agent: str = USER_AGENT
|
|
241
|
+
user_agent: str = USER_AGENT,
|
|
242
|
+
proxy: Union[str, Proxy, None] = None,
|
|
243
|
+
proxy_dns: bool = False) -> FetchResult:
|
|
153
244
|
"""Fetch and parse the document at ``client_id``. It is not validated here.
|
|
154
245
|
|
|
155
246
|
``allow_loopback`` lets a development server fetch from 127.0.0.1/::1; the
|
|
156
247
|
spec forbids that in production. ``resolver`` and ``transport`` are hooks
|
|
157
248
|
for tests and custom networking.
|
|
249
|
+
|
|
250
|
+
``proxy`` sends the fetch through an HTTP egress proxy: a URL such as
|
|
251
|
+
``"http://user:pass@egress.internal:3128"``, a :class:`Proxy`, or ``"env"``
|
|
252
|
+
for ``HTTPS_PROXY``/``NO_PROXY``. The host is still resolved and checked
|
|
253
|
+
here and the proxy is asked to CONNECT to the checked IP. Where the server
|
|
254
|
+
has no public DNS, ``proxy_dns=True`` sends the host name to the proxy
|
|
255
|
+
instead; the proxy then has to refuse private addresses itself.
|
|
158
256
|
"""
|
|
159
257
|
check_client_id_url(client_id)
|
|
160
258
|
_, netloc, rest = _split(client_id)
|
|
@@ -162,27 +260,46 @@ def fetch_document(client_id: str, *, timeout: float = DEFAULT_TIMEOUT,
|
|
|
162
260
|
port = int(port_s) if port_s else 443
|
|
163
261
|
bare = host[1:-1] if host.startswith("[") else host
|
|
164
262
|
|
|
263
|
+
via: Optional[Proxy]
|
|
264
|
+
if proxy == "env":
|
|
265
|
+
via = proxy_from_env(bare)
|
|
266
|
+
elif isinstance(proxy, str):
|
|
267
|
+
via = Proxy.from_url(proxy)
|
|
268
|
+
else:
|
|
269
|
+
via = proxy
|
|
270
|
+
if proxy_dns and proxy is None:
|
|
271
|
+
raise ValueError("proxy_dns=True needs a proxy")
|
|
272
|
+
proxy_dns = proxy_dns and via is not None # NO_PROXY hosts are fetched directly
|
|
273
|
+
|
|
274
|
+
addresses: Sequence[str]
|
|
165
275
|
try:
|
|
166
276
|
ipaddress.ip_address(bare)
|
|
167
|
-
addresses
|
|
277
|
+
addresses = [bare]
|
|
168
278
|
except ValueError:
|
|
169
|
-
|
|
170
|
-
addresses =
|
|
171
|
-
|
|
172
|
-
|
|
279
|
+
if proxy_dns:
|
|
280
|
+
addresses = [bare]
|
|
281
|
+
else:
|
|
282
|
+
try:
|
|
283
|
+
addresses = (resolver or system_resolver)(bare, port)
|
|
284
|
+
except (OSError, UnicodeError) as exc:
|
|
285
|
+
hint = "; if only your proxy can resolve it, pass proxy_dns=True" if via else ""
|
|
286
|
+
raise TransientFetchError(f"could not resolve {bare}: {exc}{hint}") from None
|
|
173
287
|
if not addresses:
|
|
174
288
|
raise TransientFetchError(f"{bare} has no addresses")
|
|
175
289
|
for addr in addresses:
|
|
290
|
+
if proxy_dns and addr == bare and not _is_ip(bare):
|
|
291
|
+
continue # a host name: the proxy resolves it and must refuse internal ones
|
|
176
292
|
if is_public_address(addr) or (allow_loopback and _is_loopback(addr)):
|
|
177
293
|
continue
|
|
178
294
|
raise BlockedAddress(
|
|
179
295
|
f"{bare} resolves to {addr}, a private or special-use address; refusing to fetch it")
|
|
180
296
|
|
|
181
297
|
headers = {"Accept": "application/json", "User-Agent": user_agent, "Host": netloc}
|
|
298
|
+
extra = {"proxy": via} if via is not None else {}
|
|
182
299
|
try:
|
|
183
300
|
resp = (transport or https_transport)(
|
|
184
301
|
host=bare, port=port, address=addresses[0], target=rest, headers=headers,
|
|
185
|
-
timeout=timeout, max_bytes=max_bytes, ssl_context=ssl_context)
|
|
302
|
+
timeout=timeout, max_bytes=max_bytes, ssl_context=ssl_context, **extra)
|
|
186
303
|
except (FetchError, TransientFetchError):
|
|
187
304
|
raise
|
|
188
305
|
except ssl.SSLCertVerificationError as exc:
|
|
@@ -10,7 +10,7 @@ from typing import Callable, Dict, Mapping, Optional
|
|
|
10
10
|
|
|
11
11
|
from .document import ClientMetadata, Policy, validate_document
|
|
12
12
|
from .errors import CIMDError, InvalidClientId, TransientFetchError
|
|
13
|
-
from .fetch import FetchResult, fetch_document
|
|
13
|
+
from .fetch import FetchResult, Proxy, fetch_document
|
|
14
14
|
from .urls import check_client_id_url, client_id_host
|
|
15
15
|
|
|
16
16
|
|
|
@@ -83,7 +83,7 @@ class ClientResolver:
|
|
|
83
83
|
Check ``error.revoke_tokens`` to see if the client's refresh tokens must go.
|
|
84
84
|
|
|
85
85
|
Extra keyword arguments go to :func:`cimdkit.fetch_document`
|
|
86
|
-
(``timeout``, ``max_bytes``, ``allow_loopback``...). Thread-safe.
|
|
86
|
+
(``timeout``, ``max_bytes``, ``allow_loopback``, ``proxy``...). Thread-safe.
|
|
87
87
|
"""
|
|
88
88
|
|
|
89
89
|
def __init__(self, policy: Optional[Policy] = None, *,
|
|
@@ -92,6 +92,9 @@ class ClientResolver:
|
|
|
92
92
|
retry_after: float = 30, clock: Callable[[], float] = time.time,
|
|
93
93
|
**fetch_options) -> None:
|
|
94
94
|
self.policy = policy or Policy()
|
|
95
|
+
proxy = fetch_options.get("proxy")
|
|
96
|
+
if isinstance(proxy, str) and proxy != "env":
|
|
97
|
+
fetch_options["proxy"] = Proxy.from_url(proxy) # bad URLs fail here, not per request
|
|
95
98
|
self._fetch = fetch or (lambda cid: fetch_document(cid, **fetch_options))
|
|
96
99
|
self.default_ttl, self.min_ttl, self.max_ttl = default_ttl, min_ttl, max_ttl
|
|
97
100
|
self.retry_after = retry_after
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""Fetching through an HTTP egress proxy (CONNECT), with the address checks intact."""
|
|
2
|
+
|
|
3
|
+
import socket
|
|
4
|
+
import threading
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
|
|
8
|
+
from cimdkit import (BlockedAddress, ClientResolver, Proxy, TransientFetchError, fetch_document,
|
|
9
|
+
proxy_from_env)
|
|
10
|
+
from cimdkit.cli import main
|
|
11
|
+
|
|
12
|
+
from conftest import CID
|
|
13
|
+
from test_tls import HOST, cert, doc_for, server # noqa: F401 (fixtures)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def test_proxy_url_parsing():
|
|
17
|
+
p = Proxy.from_url("http://bob:s%40cret@egress.internal:3128")
|
|
18
|
+
assert (p.host, p.port) == ("egress.internal", 3128)
|
|
19
|
+
assert p.authorization == "Basic Ym9iOnNAY3JldA==" # bob:s@cret
|
|
20
|
+
assert Proxy.from_url("egress.internal").port == 80
|
|
21
|
+
assert Proxy.from_url("http://egress.internal:8080").authorization is None
|
|
22
|
+
for bad in ("https://egress.internal:3128", "socks5://egress:1080", "http://:3128",
|
|
23
|
+
"http://egress:notaport"):
|
|
24
|
+
with pytest.raises(ValueError):
|
|
25
|
+
Proxy.from_url(bad)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_proxy_from_env(monkeypatch):
|
|
29
|
+
for name in ("HTTPS_PROXY", "https_proxy", "NO_PROXY", "no_proxy"):
|
|
30
|
+
monkeypatch.delenv(name, raising=False)
|
|
31
|
+
assert proxy_from_env("app.example.com") is None
|
|
32
|
+
monkeypatch.setenv("https_proxy", "http://egress.internal:3128")
|
|
33
|
+
monkeypatch.setenv("no_proxy", "intranet.example.com")
|
|
34
|
+
assert proxy_from_env("app.example.com") == Proxy("egress.internal", 3128)
|
|
35
|
+
assert proxy_from_env("intranet.example.com") is None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_proxy_gets_the_checked_address(net):
|
|
39
|
+
fetch_document(CID, proxy="http://egress.internal:3128", **net.opts())
|
|
40
|
+
req = net.requests[0]
|
|
41
|
+
assert req["proxy"] == Proxy("egress.internal", 3128)
|
|
42
|
+
assert req["address"] == "93.184.215.14" and req["host"] == "app.example.com"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_no_proxy_argument_by_default(net):
|
|
46
|
+
fetch_document(CID, **net.opts())
|
|
47
|
+
assert "proxy" not in net.requests[0] # custom transports without a proxy parameter keep working
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_private_address_still_blocked_behind_a_proxy(net):
|
|
51
|
+
net.addresses = ["10.0.0.7"]
|
|
52
|
+
with pytest.raises(BlockedAddress):
|
|
53
|
+
fetch_document(CID, proxy="http://egress.internal:3128", **net.opts())
|
|
54
|
+
assert net.requests == []
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_proxy_dns_sends_the_name(net):
|
|
58
|
+
net.addresses = OSError("no DNS here")
|
|
59
|
+
fetch_document(CID, proxy="http://egress.internal:3128", proxy_dns=True, **net.opts())
|
|
60
|
+
assert net.requests[0]["address"] == "app.example.com"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_dns_failure_behind_proxy_hints_at_proxy_dns(net):
|
|
64
|
+
net.addresses = OSError("no DNS here")
|
|
65
|
+
with pytest.raises(TransientFetchError, match="proxy_dns=True"):
|
|
66
|
+
fetch_document(CID, proxy="http://egress.internal:3128", **net.opts())
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_proxy_dns_still_checks_ip_literals(net):
|
|
70
|
+
with pytest.raises(BlockedAddress):
|
|
71
|
+
fetch_document("https://10.1.2.3/client.json", proxy="http://egress.internal:3128",
|
|
72
|
+
proxy_dns=True, **net.opts())
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_proxy_dns_needs_a_proxy(net):
|
|
76
|
+
with pytest.raises(ValueError, match="needs a proxy"):
|
|
77
|
+
fetch_document(CID, proxy_dns=True, **net.opts())
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def test_resolver_rejects_a_bad_proxy_url_up_front():
|
|
81
|
+
with pytest.raises(ValueError):
|
|
82
|
+
ClientResolver(proxy="ftp://egress.internal")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@pytest.fixture
|
|
86
|
+
def connect_proxy():
|
|
87
|
+
"""A tiny CONNECT proxy on 127.0.0.1 that records what it was asked for."""
|
|
88
|
+
seen = []
|
|
89
|
+
state = {"refuse": False}
|
|
90
|
+
lsock = socket.socket()
|
|
91
|
+
lsock.bind(("127.0.0.1", 0))
|
|
92
|
+
lsock.listen(8)
|
|
93
|
+
|
|
94
|
+
def pipe(a, b):
|
|
95
|
+
try:
|
|
96
|
+
while True:
|
|
97
|
+
data = a.recv(65536)
|
|
98
|
+
if not data:
|
|
99
|
+
break
|
|
100
|
+
b.sendall(data)
|
|
101
|
+
except OSError:
|
|
102
|
+
pass
|
|
103
|
+
finally:
|
|
104
|
+
for s in (a, b):
|
|
105
|
+
try:
|
|
106
|
+
s.shutdown(socket.SHUT_RDWR)
|
|
107
|
+
except OSError:
|
|
108
|
+
pass
|
|
109
|
+
|
|
110
|
+
def handle(conn):
|
|
111
|
+
head = b""
|
|
112
|
+
while b"\r\n\r\n" not in head:
|
|
113
|
+
chunk = conn.recv(1)
|
|
114
|
+
if not chunk:
|
|
115
|
+
conn.close()
|
|
116
|
+
return
|
|
117
|
+
head += chunk
|
|
118
|
+
lines = head.decode().split("\r\n")
|
|
119
|
+
target = lines[0].split(" ")[1]
|
|
120
|
+
auth = next((l.split(": ", 1)[1] for l in lines if l.startswith("Proxy-Authorization")),
|
|
121
|
+
None)
|
|
122
|
+
seen.append({"line": lines[0], "auth": auth})
|
|
123
|
+
if state["refuse"]:
|
|
124
|
+
conn.sendall(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n")
|
|
125
|
+
conn.close()
|
|
126
|
+
return
|
|
127
|
+
host, _, port = target.rpartition(":")
|
|
128
|
+
upstream = socket.create_connection((host.strip("[]"), int(port)))
|
|
129
|
+
conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
|
|
130
|
+
threading.Thread(target=pipe, args=(conn, upstream), daemon=True).start()
|
|
131
|
+
threading.Thread(target=pipe, args=(upstream, conn), daemon=True).start()
|
|
132
|
+
|
|
133
|
+
def serve():
|
|
134
|
+
while True:
|
|
135
|
+
try:
|
|
136
|
+
conn, _ = lsock.accept()
|
|
137
|
+
except OSError:
|
|
138
|
+
return
|
|
139
|
+
threading.Thread(target=handle, args=(conn,), daemon=True).start()
|
|
140
|
+
|
|
141
|
+
threading.Thread(target=serve, daemon=True).start()
|
|
142
|
+
yield {"url": f"http://u:p@127.0.0.1:{lsock.getsockname()[1]}", "seen": seen,
|
|
143
|
+
"state": state}
|
|
144
|
+
lsock.close()
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def test_real_fetch_through_connect_proxy(server, connect_proxy): # noqa: F811
|
|
148
|
+
server["routes"]["/oauth/client.json"] = (
|
|
149
|
+
200, {"Content-Type": "application/json"}, doc_for(server["cid"]))
|
|
150
|
+
result = fetch_document(server["cid"], proxy=connect_proxy["url"], **server["opts"])
|
|
151
|
+
assert result.document["client_name"] == "TLS test"
|
|
152
|
+
# The proxy was asked for the checked IP, TLS still verified the real host name.
|
|
153
|
+
assert connect_proxy["seen"] == [{"line": f"CONNECT 127.0.0.1:{server['port']} HTTP/1.1",
|
|
154
|
+
"auth": "Basic dTpw"}]
|
|
155
|
+
assert server["sni"] == [HOST]
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def test_proxy_refusal_is_transient(server, connect_proxy): # noqa: F811
|
|
159
|
+
connect_proxy["state"]["refuse"] = True
|
|
160
|
+
with pytest.raises(TransientFetchError, match="403"):
|
|
161
|
+
fetch_document(server["cid"], proxy=connect_proxy["url"], **server["opts"])
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def test_cli_proxy_flag_reaches_fetch(monkeypatch, capsys):
|
|
165
|
+
calls = {}
|
|
166
|
+
|
|
167
|
+
def fake_fetch(cid, **kw):
|
|
168
|
+
calls.update(kw)
|
|
169
|
+
raise TransientFetchError("stop here")
|
|
170
|
+
|
|
171
|
+
monkeypatch.setattr("cimdkit.cli.fetch_document", fake_fetch)
|
|
172
|
+
assert main(["check", CID, "--proxy", "env", "--proxy-dns"]) == 1
|
|
173
|
+
assert calls["proxy"] == "env" and calls["proxy_dns"] is True
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|