Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
27 changes: 25 additions & 2 deletions proofline/_sync_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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,
Expand Down
52 changes: 48 additions & 4 deletions proofline/_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand All @@ -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."
)
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down
18 changes: 16 additions & 2 deletions proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__(
Expand All @@ -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),
Expand All @@ -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)
Expand Down Expand Up @@ -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),
Expand All @@ -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)
Expand Down
82 changes: 80 additions & 2 deletions tests/http_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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
Expand Down Expand Up @@ -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()
Expand All @@ -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)
Loading