diff --git a/README.md b/README.md index 250fb32e..4d4674cf 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,20 @@ asyncio.run(main()) The [SDK guide](https://proofline.sh/docs/sdks/) and [API reference](https://proofline.sh/docs/api/) cover every operation. +## Proxies + +On a network where only a forward proxy reaches the internet, such as many self-hosted CI runners, pass the proxy to either client. The clients never read `HTTPS_PROXY`, `NO_PROXY` or other environment variables, so name the proxy explicitly: + +```python +import os +from proofline import ProoflineClient + +with ProoflineClient(proxy=os.environ["HTTPS_PROXY"]) as client: + ... +``` + +The value is an `http://` or `https://` URL with a host, an optional port and optional `user:password` credentials, which are sent to the proxy as Basic `Proxy-Authorization`. Every request goes through a CONNECT tunnel to the HTTPS origin: the proxy sees the origin's host and port, the origin's name is resolved by the proxy, and the token stays inside the TLS session with Proofline. A proxy is refused for a plain HTTP `base_url`, because the proxy would read the forwarded request. The HTTP timeout and a wait's deadline also bound the connection to the proxy and the tunnel request. A proxy that refuses the tunnel raises `ProoflineError` with type `urn:proofline:sdk:transport-unavailable`, and its `detail` names only the proxy's status, such as 407 when the proxy needs credentials. Neither the proxy URL nor its credentials appear in errors. + ## Resolve a repository Use the registered host and full repository path, including any subgroups. The token needs `reviews:read` and access to the repository. diff --git a/proofline/_sync_http.py b/proofline/_sync_http.py index 0ef0b5b0..f597acb9 100644 --- a/proofline/_sync_http.py +++ b/proofline/_sync_http.py @@ -128,6 +128,9 @@ def mapped_errors() -> Iterator[None]: yield except httpcore2.TimeoutException: raise httpx2.ReadTimeout("The request deadline expired.") from None + except httpcore2.ProxyError as error: + # The proxy answered CONNECT with a non-2xx status; the message names it. + raise httpx2.ProxyError(str(error)) from None except (httpcore2.NetworkError, httpcore2.ProtocolError): raise httpx2.TransportError("The HTTP transport failed.") from None @@ -146,8 +149,28 @@ def close(self) -> None: class Transport(httpx2.BaseTransport): - def __init__(self) -> None: - self._pool = httpcore2.ConnectionPool( + def __init__(self, proxy: httpx2.Proxy | None = None) -> None: + self._pool: httpcore2.ConnectionPool + if proxy is None: + self._pool = httpcore2.ConnectionPool( + ssl_context=httpcore2.default_ssl_context(), + network_backend=NetworkBackend(), + max_connections=100, + max_keepalive_connections=20, + keepalive_expiry=5, + ) + return + # The same bounded backend connects to the proxy, and the CONNECT exchange + # and the TLS handshake inside the tunnel read through the bounded stream. + # The origin's host name is resolved by the proxy, never on this host. + self._pool = httpcore2.HTTPProxy( + proxy_url=httpcore2.URL( + scheme=proxy.url.raw_scheme, + host=proxy.url.raw_host, + port=proxy.url.port, + target=proxy.url.raw_path, + ), + proxy_auth=proxy.raw_auth, ssl_context=httpcore2.default_ssl_context(), network_backend=NetworkBackend(), max_connections=100, diff --git a/proofline/_transport.py b/proofline/_transport.py index d3e99302..76f63a47 100644 --- a/proofline/_transport.py +++ b/proofline/_transport.py @@ -148,6 +148,41 @@ def base_url(value: str) -> str: return value.rstrip("/") +def proxy(value: str | None, origin: str) -> httpx2.Proxy | None: + """Accept one explicit HTTP(S) forward proxy for an HTTPS origin. + + The clients never read proxy environment variables. Through the proxy each + request travels in a CONNECT tunnel, so the token stays inside the TLS + session with the origin and the proxy sees only the origin's host and port. + """ + if value is None: + return None + try: + if not isinstance(value, str): + raise ValueError + parts = urlsplit(value) + if ( + parts.scheme not in ("http", "https") + or not parts.hostname + or parts.path not in ("", "/") + or parts.query + or parts.fragment + or any(ord(character) <= 32 for character in value) + ): + raise ValueError + parts.port + configured = httpx2.Proxy(value) + except (ValueError, httpx2.InvalidURL): + # The value can carry proxy credentials, so the message never repeats it. + raise ValueError( + "Use an http:// or https:// proxy URL with a host, an optional port and no path." + ) from None + if urlsplit(origin).scheme != "https": + # A plain HTTP request would be forwarded with its token readable by the proxy. + raise ValueError("A proxy is used only with an HTTPS base URL.") + return configured + + def invalid_response() -> ProoflineError: return ProoflineError( 0, "urn:proofline:sdk:invalid-response", "Proofline returned an invalid API response." @@ -157,6 +192,15 @@ def invalid_response() -> ProoflineError: def network_error(error: httpx2.HTTPError) -> ProoflineError: if isinstance(error, httpx2.TimeoutException): return timeout_error() + if isinstance(error, httpx2.ProxyError): + # Only the proxy's status is kept: 407 asks for credentials, 403 is its policy. + status = re.match(r"\d{3}(?= |$)", str(error)) + answer = f" with HTTP {status[0]}" if status else "" + return ProoflineError( + 0, + "urn:proofline:sdk:transport-unavailable", + f"The proxy refused the tunnel to the Proofline API{answer}.", + ) return ProoflineError( 0, "urn:proofline:sdk:transport-unavailable", "Could not reach the Proofline API." ) @@ -454,10 +498,10 @@ async def aclose(self) -> None: class RetryTransport(httpx2.BaseTransport): - def __init__(self, token: SecretStr, timeout: float) -> None: + def __init__(self, token: SecretStr, timeout: float, proxy: httpx2.Proxy | None = None) -> None: self._token = token self._timeout = timeout - self._inner = SyncHTTPTransport() + self._inner = SyncHTTPTransport(proxy) def handle_request(self, request: httpx2.Request) -> httpx2.Response: for attempt in range(4): @@ -507,10 +551,10 @@ def close(self) -> None: class AsyncRetryTransport(httpx2.AsyncBaseTransport): - def __init__(self, token: SecretStr, timeout: float) -> None: + def __init__(self, token: SecretStr, timeout: float, proxy: httpx2.Proxy | None = None) -> None: self._token = token self._timeout = timeout - self._inner = httpx2.AsyncHTTPTransport() + self._inner = httpx2.AsyncHTTPTransport(proxy=proxy) async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response: for attempt in range(4): diff --git a/proofline/client.py b/proofline/client.py index 49e1a9e1..891bf75a 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -213,6 +213,11 @@ class ProoflineClient(Operations): Name resolution, connection, TLS and socket operations stop at the configured HTTP timeout and at a wait deadline. + + proxy names an HTTP or HTTPS forward proxy, such as + "http://user:password@proxy.internal:3128". Requests reach the HTTPS origin + through a CONNECT tunnel, under the same timeouts. Proxy environment + variables are never read. """ def __init__( @@ -221,9 +226,11 @@ def __init__( *, base_url: str = "https://proofline.sh", timeout: float = 30, + proxy: str | None = None, ) -> None: self._api = _configuration(token, base_url, timeout) self._base_url = _transport.base_url(base_url) + tunnel = _transport.proxy(proxy, self._base_url) self._http = httpx2.Client( base_url=self._base_url, auth=_transport.BearerAuth(self._api.token), @@ -234,7 +241,7 @@ def __init__( timeout=httpx2.Timeout(timeout), follow_redirects=False, trust_env=False, - transport=_transport.RetryTransport(self._api.token, timeout), + transport=_transport.RetryTransport(self._api.token, timeout, tunnel), ) self._api.set_httpx_client(self._http) self.mcp = McpClient(self._http) @@ -587,15 +594,22 @@ def wait_for_review( class AsyncProoflineClient(AsyncOperations): + """Asynchronous typed HTTP operations for asyncio and Trio. + + proxy names an HTTP or HTTPS forward proxy, as for ProoflineClient. + """ + def __init__( self, token: str | SecretStr | None = None, *, base_url: str = "https://proofline.sh", timeout: float = 30, + proxy: str | None = None, ) -> None: self._api = _configuration(token, base_url, timeout) self._base_url = _transport.base_url(base_url) + tunnel = _transport.proxy(proxy, self._base_url) self._http = httpx2.AsyncClient( base_url=self._base_url, auth=_transport.BearerAuth(self._api.token), @@ -606,7 +620,7 @@ def __init__( timeout=httpx2.Timeout(timeout), follow_redirects=False, trust_env=False, - transport=_transport.AsyncRetryTransport(self._api.token, timeout), + transport=_transport.AsyncRetryTransport(self._api.token, timeout, tunnel), ) self._api.set_async_httpx_client(self._http) self.mcp = AsyncMcpClient(self._http) diff --git a/tests/http_server.py b/tests/http_server.py index 455674f7..760c8373 100644 --- a/tests/http_server.py +++ b/tests/http_server.py @@ -3,12 +3,15 @@ from __future__ import annotations import json +import socket +import ssl import threading import time from collections.abc import Callable from contextlib import AbstractContextManager from dataclasses import dataclass, field from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from socketserver import BaseRequestHandler, ThreadingTCPServer from typing import Any, Self @@ -34,7 +37,9 @@ class Reply: class Server(AbstractContextManager["Server"]): - def __init__(self, respond: Callable[[Request, int], Reply]) -> None: + def __init__( + self, respond: Callable[[Request, int], Reply], tls: ssl.SSLContext | None = None + ) -> None: self.requests: list[Request] = [] self._lock = threading.Lock() owner = self @@ -93,10 +98,13 @@ def dispatch(self) -> None: self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) self._server.daemon_threads = True + if tls is not None: + self._server.socket = tls.wrap_socket(self._server.socket, server_side=True) self._thread = threading.Thread( target=self._server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True ) - self.url = f"http://127.0.0.1:{self._server.server_port}" + scheme = "http" if tls is None else "https" + self.url = f"{scheme}://127.0.0.1:{self._server.server_port}" def __enter__(self) -> Self: self._thread.start() @@ -106,3 +114,73 @@ def __exit__(self, *args: object) -> None: self._server.shutdown() self._server.server_close() self._thread.join(timeout=2) + + +class TunnelProxy(AbstractContextManager["TunnelProxy"]): + """A loopback CONNECT proxy that tunnels every target to one local port. + + It records each CONNECT head it reads. A status other than 200 refuses the + tunnel, and status None reads the head and never answers. + """ + + def __init__(self, target_port: int, status: int | None = 200) -> None: + self.heads: list[bytes] = [] + owner = self + + class Handler(BaseRequestHandler): + def handle(self) -> None: + client: socket.socket = self.request + head = b"" + while b"\r\n\r\n" not in head: + chunk = client.recv(4096) + if not chunk: + return + head += chunk + owner.heads.append(head) + if status is None: + owner._stop.wait(5) + return + if status != 200: + client.sendall( + f"HTTP/1.1 {status} Refused\r\nContent-Length: 0\r\n\r\n".encode() + ) + return + upstream = socket.create_connection(("127.0.0.1", target_port)) + client.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n") + + def pipe(source: socket.socket, sink: socket.socket) -> None: + try: + while data := source.recv(65536): + sink.sendall(data) + except OSError: + pass + finally: + for side in (source, sink): + try: + side.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + back = threading.Thread(target=pipe, args=(upstream, client), daemon=True) + back.start() + pipe(client, upstream) + back.join(timeout=5) + upstream.close() + + self._stop = threading.Event() + self._server = ThreadingTCPServer(("127.0.0.1", 0), Handler) + self._server.daemon_threads = True + self._thread = threading.Thread( + target=self._server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True + ) + self.port = self._server.server_address[1] + + def __enter__(self) -> Self: + self._thread.start() + return self + + def __exit__(self, *args: object) -> None: + self._stop.set() + self._server.shutdown() + self._server.server_close() + self._thread.join(timeout=2) diff --git a/tests/test_proxy.py b/tests/test_proxy.py new file mode 100644 index 00000000..6c0538bd --- /dev/null +++ b/tests/test_proxy.py @@ -0,0 +1,195 @@ +from __future__ import annotations + +import base64 +import inspect +import shutil +import socket +import ssl +import subprocess +import time +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Any + +import httpcore2 +import pytest +from pydantic import SecretStr + +from proofline import AsyncProoflineClient, ProoflineClient, ProoflineError + +from .fixtures import FINDING, ORG, REVIEW, TOKEN, finding +from .http_server import Reply, Server, TunnelProxy + +Client = ProoflineClient | AsyncProoflineClient +MODES = pytest.mark.parametrize("mode", ["sync", "async"]) +# The origin's name is resolvable only by the proxy, as on a network whose only +# route out is the proxy. +ORIGIN = "api.proofline.invalid" +PROXY_PASSWORD = "proxy-p@ss" + + +@asynccontextmanager +async def session(mode: str, **kwargs: Any) -> AsyncIterator[Client]: + if mode == "sync": + with ProoflineClient(SecretStr(TOKEN), **kwargs) as client: + yield client + else: + async with AsyncProoflineClient(SecretStr(TOKEN), **kwargs) as async_client: + yield async_client + + +async def call(client: Client, name: str, *args: Any, **kwargs: Any) -> Any: + result = getattr(client, name)(*args, **kwargs) + return await result if inspect.isawaitable(result) else result + + +def proxy_url(port: int) -> str: + return f"http://ci-runner:{PROXY_PASSWORD.replace('@', '%40')}@127.0.0.1:{port}" + + +@pytest.fixture +def origin_tls(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> ssl.SSLContext: + """Serve TLS for ORIGIN and make both clients trust only its certificate.""" + openssl = shutil.which("openssl") + if openssl is None: + pytest.skip("openssl is required to issue the loopback certificate") + certificate, key = tmp_path / "origin.pem", tmp_path / "origin.key" + subprocess.run( + [ + openssl, + "req", + "-x509", + "-newkey", + "ec", + "-pkeyopt", + "ec_paramgen_curve:prime256v1", + "-nodes", + "-days", + "1", + "-subj", + f"/CN={ORIGIN}", + "-addext", + f"subjectAltName=DNS:{ORIGIN}", + "-keyout", + str(key), + "-out", + str(certificate), + ], + check=True, + capture_output=True, + ) + monkeypatch.setattr( + httpcore2, + "default_ssl_context", + lambda **_: ssl.create_default_context(cafile=str(certificate)), + ) + server = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + server.load_cert_chain(certificate, key) + return server + + +@MODES +async def test_requests_tunnel_through_the_proxy_with_the_token_inside_tls( + mode: str, origin_tls: ssl.SSLContext, monkeypatch: pytest.MonkeyPatch +) -> None: + lookups: list[str] = [] + original = socket.getaddrinfo + + def resolve(host: Any, *args: Any, **kwargs: Any) -> Any: + lookups.append(str(host)) + return original(host, *args, **kwargs) + + monkeypatch.setattr(socket, "getaddrinfo", resolve) + with Server(lambda request, index: Reply(body=finding()), tls=origin_tls) as server: + target = int(server.url.rsplit(":", 1)[1]) + with TunnelProxy(target) as proxy: + async with session( + mode, base_url=f"https://{ORIGIN}", proxy=proxy_url(proxy.port) + ) as client: + first = await call(client, "get_finding", ORG, FINDING) + second = await call(client, "get_finding", ORG, FINDING) + assert first.id == second.id == FINDING + # One tunnel carries both requests; the proxy sees the host and its credentials. + assert len(proxy.heads) == 1 + head = proxy.heads[0].decode() + assert head.startswith(f"CONNECT {ORIGIN}:443 HTTP/1.1\r\n") + credentials = base64.b64encode(f"ci-runner:{PROXY_PASSWORD}".encode()).decode() + assert f"Proxy-Authorization: Basic {credentials}\r\n" in head + assert TOKEN not in head + assert "authorization: bearer" not in head.lower() + # The origin gets the token and its own host name through the TLS session. + assert [request.headers["Authorization"] for request in server.requests] == [ + f"Bearer {TOKEN}" + ] * 2 + assert server.requests[0].headers["Host"] == ORIGIN + assert server.requests[0].path == f"/api/v1/organizations/{ORG}/findings/{FINDING}" + assert ORIGIN not in lookups + + +@MODES +@pytest.mark.parametrize("status", [407, 403]) +async def test_a_refused_tunnel_is_a_transport_problem_that_names_only_the_status( + mode: str, status: int +) -> None: + with TunnelProxy(target_port=9, status=status) as proxy: + async with session( + mode, base_url=f"https://{ORIGIN}", proxy=proxy_url(proxy.port) + ) as client: + with pytest.raises(ProoflineError) as raised: + await call(client, "get_finding", ORG, FINDING) + error = raised.value + assert (error.status, error.type) == (0, "urn:proofline:sdk:transport-unavailable") + assert error.detail == f"The proxy refused the tunnel to the Proofline API with HTTP {status}." + shown = f"{error.detail} {error} {error!r}" + assert TOKEN not in shown and PROXY_PASSWORD not in shown and "ci-runner" not in shown + # A refused tunnel is not a retryable API answer. + assert len(proxy.heads) == 1 + + +@MODES +async def test_a_silent_proxy_keeps_the_wait_deadline(mode: str) -> None: + with TunnelProxy(target_port=9, status=None) as proxy: + async with session( + mode, base_url=f"https://{ORIGIN}", proxy=proxy_url(proxy.port) + ) as client: + started = time.monotonic() + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=0.3) + elapsed = time.monotonic() - started + assert result.status == "TIMED_OUT" + assert result.review is None + assert elapsed < 2 + assert len(proxy.heads) == 1 + + +@pytest.mark.parametrize("client_type", [ProoflineClient, AsyncProoflineClient]) +@pytest.mark.parametrize( + "value", + [ + "socks5://user:secret@127.0.0.1:1080", + "proxy.internal:3128", + "http://", + "http://user:secret@proxy.internal:3128/path", + "http://user:secret@proxy.internal:3128?mode=1", + "http://user:secret@proxy.internal:3128#part", + "http://user:secret@proxy.internal:99999", + " http://user:secret@proxy.internal:3128", + "http://user:secret@proxy.internal:3128\n", + 3128, + ], +) +def test_proxy_urls_are_checked_without_repeating_them( + client_type: type[Client], value: Any +) -> None: + with pytest.raises(ValueError) as raised: + client_type(TOKEN, proxy=value) + assert "secret" not in str(raised.value) + + +@pytest.mark.parametrize("client_type", [ProoflineClient, AsyncProoflineClient]) +def test_a_proxy_never_carries_a_plain_http_origin(client_type: type[Client]) -> None: + # The proxy would read a forwarded plain HTTP request, token included. + with pytest.raises(ValueError, match="HTTPS base URL"): + client_type(TOKEN, base_url="http://127.0.0.1:8080", proxy="http://127.0.0.1:3128") + client_type(TOKEN, base_url="http://127.0.0.1:8080") + client_type(TOKEN, proxy="https://proxy.internal")