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 @@ -20,6 +20,20 @@ with ProoflineClient(os.environ["PROOFLINE_TOKEN"]) as client:

When no token is passed, the clients read `PROOFLINE_TOKEN` from the environment, keep the token in memory, and redact it from diagnostic output. `AsyncProoflineClient` exposes the same methods as coroutines that you call with `await`. The [SDK guide](https://proofline.sh/docs/sdks/) and [API reference](https://proofline.sh/docs/api/) cover every operation.

## Custom CA certificates

Both clients use the operating system root store and ignore ambient `SSL_CERT_FILE` and `SSL_CERT_DIR` overrides (`trust_env=False`). Behind a TLS-inspecting proxy, pass `ca_cert` or set `PROOFLINE_CA_CERT` to a PEM certificate bundle. Extra roots are merged beside the system roots; certificate and hostname verification stay enabled.

```python
from pathlib import Path
from proofline import ProoflineClient

with ProoflineClient(ca_cert=Path("/etc/ssl/certs/corp-proxy-ca.pem")) as client:
...
```

An explicit `ca_cert` takes precedence over `PROOFLINE_CA_CERT`, and an empty `PROOFLINE_CA_CERT` counts as unset. Unreadable files raise `OSError`, and empty, malformed, oversized, or non-PEM bundles raise `ValueError` at client construction before any request is sent.

## Errors and refusals

A refused request raises `ProoflineError` with the server problem's `status`, `type`, `title` and `detail`. When a review request creates nothing, the error also carries `refusal`, whose `reason` names the setting to change, such as `NO_LINKED_ENVIRONMENT` or `ENVIRONMENT_NOT_READY`, and `repository_name`. `RunNowRefusal` names the type of `refusal`. A refusal that does not match the public contract keeps its status, `title` and `detail` with the type `urn:proofline:sdk:invalid-response` and no `refusal`. Any other status, such as the 402 a review request answers when credits cannot pay, is a plain problem with no `refusal`. The token is redacted from every text field, and `repr` and `str` show only the status.
Expand Down
8 changes: 6 additions & 2 deletions proofline/_sync_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,13 @@ def close(self) -> None:


class Transport(httpx2.BaseTransport):
def __init__(self) -> None:
def __init__(self, *, ssl_context: ssl.SSLContext | None = None) -> None:
self._pool = httpcore2.ConnectionPool(
ssl_context=httpcore2.default_ssl_context(),
ssl_context=(
ssl_context
if ssl_context is not None
else httpcore2.default_ssl_context(_trust_env=False)
),
network_backend=NetworkBackend(),
max_connections=100,
max_keepalive_connections=20,
Expand Down
130 changes: 130 additions & 0 deletions proofline/_tls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
"""TLS trust-store isolation and additive custom CA root loading.

By default, both sync and async clients trust only the operating system's
root store and ignore ambient ``SSL_CERT_FILE`` / ``SSL_CERT_DIR`` overrides.
Passing ``ca_cert`` or setting ``PROOFLINE_CA_CERT`` merges additional PEM root
certificates beside the system roots without weakening certificate or hostname
verification.
"""

from __future__ import annotations

import base64
import binascii
import errno
import os
import ssl
import stat
from pathlib import Path

import httpcore2

CA_CERT_ENV = "PROOFLINE_CA_CERT"
MAX_CA_CERT_BYTES = 4 * 1024 * 1024
_PEM_BEGIN = "-----BEGIN CERTIFICATE-----"
_PEM_END = "-----END CERTIFICATE-----"


def _resolve_path(ca_cert: str | os.PathLike[str] | None) -> Path | None:
if ca_cert is not None:
raw_path = os.fspath(ca_cert)
if not isinstance(raw_path, str):
raise TypeError("ca_cert must be a str or os.PathLike[str].")
if not raw_path or not raw_path.strip():
raise ValueError("The CA certificate path must not be empty.")
return Path(raw_path)
env_value = os.environ.get(CA_CERT_ENV)
if env_value is None or env_value == "":
return None
if not env_value.strip():
raise ValueError(f"{CA_CERT_ENV} must not be whitespace-only.")
return Path(env_value)


def _read_bounded(path: Path) -> bytes:
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NONBLOCK", 0)
fd = os.open(path, flags)
owned = True
try:
metadata = os.fstat(fd)
if stat.S_ISDIR(metadata.st_mode):
raise IsADirectoryError(errno.EISDIR, os.strerror(errno.EISDIR), str(path))
if not stat.S_ISREG(metadata.st_mode):
raise ValueError(f"The CA certificate path {path} must be a regular file.")
owned = False
handle = os.fdopen(fd, "rb")
except BaseException:
if owned:
os.close(fd)
raise
with handle:
data = handle.read(MAX_CA_CERT_BYTES + 1)
if len(data) > MAX_CA_CERT_BYTES:
raise ValueError(
f"The CA certificate file {path} exceeds the {MAX_CA_CERT_BYTES}-byte limit."
)
return data


def _parse_pem_certificates(raw: bytes, path: Path) -> list[str]:
try:
text = raw.decode("utf-8-sig")
except UnicodeDecodeError:
raise ValueError(f"The CA certificate file {path} is not valid UTF-8 PEM.") from None

certificates: list[str] = []
seen: set[bytes] = set()
in_block = False
body_lines: list[str] = []

for line in text.splitlines():
stripped = line.strip()
if stripped == _PEM_BEGIN:
if in_block:
raise ValueError(f"The CA certificate file {path} has malformed PEM framing.")
in_block = True
body_lines = []
elif stripped == _PEM_END:
if not in_block:
raise ValueError(f"The CA certificate file {path} has malformed PEM framing.")
body = "".join(body_lines)
if not body:
raise ValueError(
f"The CA certificate file {path} contains an empty PEM certificate."
)
try:
der = base64.b64decode(body.encode("ascii"), validate=True)
except (UnicodeEncodeError, binascii.Error, ValueError):
raise ValueError(
f"The CA certificate file {path} contains an invalid PEM certificate."
) from None
if der not in seen:
seen.add(der)
certificates.append(ssl.DER_cert_to_PEM_cert(der))
in_block = False
body_lines = []
elif in_block:
body_lines.append(stripped)

if in_block:
raise ValueError(f"The CA certificate file {path} has an unterminated PEM certificate.")
if not certificates:
raise ValueError(f"The CA certificate file {path} contains no PEM certificate.")
return certificates


def build_ssl_context(ca_cert: str | os.PathLike[str] | None = None) -> ssl.SSLContext:
"""Build an SSLContext using OS roots (ignoring SSL_CERT_*) plus optional PEM roots."""
path = _resolve_path(ca_cert)
context = httpcore2.default_ssl_context(_trust_env=False)
if path is None:
return context
raw = _read_bounded(path)
for certificate in _parse_pem_certificates(raw, path):
try:
context.load_verify_locations(cadata=certificate)
except (ssl.SSLError, ValueError):
raise ValueError(
f"The CA certificate file {path} contains an invalid X.509 certificate."
) from None
return context
29 changes: 25 additions & 4 deletions proofline/_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import math
import os
import re
import ssl
from asyncio import sleep as async_sleep
from collections.abc import AsyncIterator, Callable, Generator, Iterator
from contextlib import contextmanager
Expand All @@ -17,6 +18,7 @@
from urllib.parse import urlsplit

import anyio
import httpcore2
import httpx2
from pydantic import SecretStr

Expand Down Expand Up @@ -433,10 +435,16 @@ async def aclose(self) -> None:


class RetryTransport(httpx2.BaseTransport):
def __init__(self, token: SecretStr, timeout: float) -> None:
def __init__(
self,
token: SecretStr,
timeout: float,
*,
ssl_context: ssl.SSLContext | None = None,
) -> None:
self._token = token
self._timeout = timeout
self._inner = SyncHTTPTransport()
self._inner = SyncHTTPTransport(ssl_context=ssl_context)

def handle_request(self, request: httpx2.Request) -> httpx2.Response:
for attempt in range(4):
Expand Down Expand Up @@ -484,10 +492,23 @@ def close(self) -> None:


class AsyncRetryTransport(httpx2.AsyncBaseTransport):
def __init__(self, token: SecretStr, timeout: float) -> None:
def __init__(
self,
token: SecretStr,
timeout: float,
*,
ssl_context: ssl.SSLContext | None = None,
) -> None:
self._token = token
self._timeout = timeout
self._inner = httpx2.AsyncHTTPTransport()
self._inner = httpx2.AsyncHTTPTransport(
verify=(
ssl_context
if ssl_context is not None
else httpcore2.default_ssl_context(_trust_env=False)
),
trust_env=False,
)

async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response:
for attempt in range(4):
Expand Down
13 changes: 10 additions & 3 deletions proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import math
import os
from asyncio import sleep as async_sleep
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
from string import hexdigits
Expand All @@ -15,7 +16,7 @@
import httpx2
from pydantic import SecretStr

from . import _transport
from . import _tls, _transport
from ._generated.api.default import (
get_agent_session,
get_agent_session_prompt,
Expand Down Expand Up @@ -220,9 +221,11 @@ def __init__(
*,
base_url: str = "https://proofline.sh",
timeout: float = 30,
ca_cert: str | os.PathLike[str] | None = None,
) -> None:
self._api = _configuration(token, base_url, timeout)
self._base_url = _transport.base_url(base_url)
ssl_context = _tls.build_ssl_context(ca_cert)
self._http = httpx2.Client(
base_url=self._base_url,
auth=_transport.BearerAuth(self._api.token),
Expand All @@ -233,7 +236,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, ssl_context=ssl_context),
)
self._api.set_httpx_client(self._http)
self.mcp = McpClient(self._http)
Expand Down Expand Up @@ -590,9 +593,11 @@ def __init__(
*,
base_url: str = "https://proofline.sh",
timeout: float = 30,
ca_cert: str | os.PathLike[str] | None = None,
) -> None:
self._api = _configuration(token, base_url, timeout)
self._base_url = _transport.base_url(base_url)
ssl_context = _tls.build_ssl_context(ca_cert)
self._http = httpx2.AsyncClient(
base_url=self._base_url,
auth=_transport.BearerAuth(self._api.token),
Expand All @@ -603,7 +608,9 @@ 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, ssl_context=ssl_context
),
)
self._api.set_async_httpx_client(self._http)
self.mcp = AsyncMcpClient(self._http)
Expand Down
Loading