Skip to content
Merged
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
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ classifiers = [
"Programming Language :: Python :: 3.13",
]
dependencies = [
# The linked proxy trusts certifi's roots only, never the OS store.
"certifi>=2024.2.2",
"cryptography>=42.0.0",
"httpx>=0.24.1",
"httpx-sse>=0.4.0",
Expand All @@ -31,6 +33,7 @@ dependencies = [
"rich",
"click>=8.0",
"typer>=0.25.1,<0.30",
"websockets>=14",
]

[tool.hatch.version]
Expand Down
4 changes: 4 additions & 0 deletions src/gumloop/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from gumloop.resources import AsyncBrain
from gumloop.resources import AsyncBrowserProfiles
from gumloop.resources import AsyncChat
from gumloop.resources import AsyncCustomProxies
from gumloop.resources import AsyncDecisions
from gumloop.resources import AsyncEvaluations
from gumloop.resources import AsyncMCP
Expand All @@ -34,6 +35,7 @@
from gumloop.resources import Brain
from gumloop.resources import BrowserProfiles
from gumloop.resources import Chat
from gumloop.resources import CustomProxies
from gumloop.resources import Decisions
from gumloop.resources import Evaluations
from gumloop.resources import Models
Expand Down Expand Up @@ -120,6 +122,7 @@ def __init__(
self.artifacts = Artifacts(self._http)
self.brain = Brain(self._http)
self.browser_profiles = BrowserProfiles(self._http)
self.custom_proxies = CustomProxies(self._http)
self.oauth = OAuth(base_url=self.base_url, timeout=self.timeout)

def close(self) -> None:
Expand Down Expand Up @@ -188,6 +191,7 @@ def __init__(
self.artifacts = AsyncArtifacts(self._http)
self.brain = AsyncBrain(self._http)
self.browser_profiles = AsyncBrowserProfiles(self._http)
self.custom_proxies = AsyncCustomProxies(self._http)
self.oauth = OAuth(base_url=self.base_url, timeout=self.timeout)

async def __aenter__(self) -> AsyncGumloop:
Expand Down
4 changes: 2 additions & 2 deletions src/gumloop/cli/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def is_keyring_available() -> bool:
return not isinstance(keyring.get_keyring(), keyring.backends.fail.Keyring)


def _require_keyring() -> None:
def require_keyring() -> None:
if is_keyring_available():
return
raise GumloopError(
Expand Down Expand Up @@ -90,7 +90,7 @@ def load_credentials(profile: str = DEFAULT_PROFILE) -> Credentials:

def save_credentials(creds: Credentials, profile: str = DEFAULT_PROFILE) -> None:
"""Persist ``creds``. Fields set to ``None`` delete their keychain entry."""
_require_keyring()
require_keyring()
for field in _FIELDS:
value = getattr(creds, field)
account = _account(profile, field)
Expand Down
92 changes: 92 additions & 0 deletions src/gumloop/cli/custom_proxy_key.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
"""This machine's personal proxy on one backend: the Ed25519 key it signs in to the
linked proxy gateway with, kept in the OS keychain, and the personal proxy that key
registered as."""

from __future__ import annotations

import base64
import os
from pathlib import Path
from urllib.parse import urlsplit

import keyring
import keyring.errors
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives.serialization import Encoding
from cryptography.hazmat.primitives.serialization import NoEncryption
from cryptography.hazmat.primitives.serialization import PrivateFormat
from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import Field
from pydantic import ValidationError
from pydantic import field_validator

from gumloop import GumloopError
from gumloop.cli.credentials import KEYRING_SERVICE
from gumloop.cli.credentials import require_keyring

_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})


class CustomProxyRegistration(BaseModel):
model_config = ConfigDict(extra="forbid")

custom_proxy_id: str = Field(min_length=1)
gateway_url: str = Field(min_length=1)

@field_validator("gateway_url")
@classmethod
def _require_encrypted_gateway(cls, gateway_url: str) -> str:
"""Over plain ws:// the sign-in token and the tunnelled traffic are readable on the network."""
parts = urlsplit(gateway_url)
if parts.scheme == "wss" or (parts.scheme == "ws" and parts.hostname in _LOOPBACK_HOSTS):
return gateway_url
raise ValueError("the linked proxy gateway must use wss:// unless it runs on this computer")


def backend_host(base_url: str) -> str:
"""Each backend gets its own key and registration, so staging and production never share one."""
return urlsplit(base_url).netloc


def load_or_create_key(host: str) -> Ed25519PrivateKey:
require_keyring()
account = _key_account(host)
try:
stored = keyring.get_password(KEYRING_SERVICE, account)
if stored is None:
key = Ed25519PrivateKey.generate()
raw = key.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption())
keyring.set_password(KEYRING_SERVICE, account, base64.urlsafe_b64encode(raw).decode())
return key
except keyring.errors.KeyringError as error:
raise GumloopError(f"Could not use the personal proxy key in the OS keychain: {error}") from error
try:
return Ed25519PrivateKey.from_private_bytes(base64.urlsafe_b64decode(stored))
except ValueError as error:
raise GumloopError(f"The personal proxy key for {host} in the OS keychain is unreadable.") from error


def load_registration(host: str, home: Path | None = None) -> CustomProxyRegistration | None:
try:
return CustomProxyRegistration.model_validate_json(_registration_path(host, home).read_text(encoding="utf-8"))
except (OSError, ValidationError):
return None


def save_registration(host: str, registration: CustomProxyRegistration, home: Path | None = None) -> None:
destination = _registration_path(host, home)
destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
staging = destination.with_name(f".{destination.name}.tmp")
descriptor = os.open(staging, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(descriptor, "w", encoding="utf-8") as file:
file.write(registration.model_dump_json())
staging.replace(destination)


def _key_account(host: str) -> str:
return f"custom-proxy:{host}"


def _registration_path(host: str, home: Path | None) -> Path:
return (home or Path.home()) / ".gumloop" / "custom-proxy" / f"{host}.json"
142 changes: 142 additions & 0 deletions src/gumloop/linked_proxy/connection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
"""Keeps this machine's tunnel to the linked proxy gateway open: signs in, serves the
gateway's streams, and reconnects until the gateway refuses the sign-in or the
user signs out."""

from __future__ import annotations

import asyncio
import functools
import random
import ssl
import time
from collections.abc import Awaitable
from collections.abc import Callable
from contextlib import AbstractAsyncContextManager

import certifi
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from websockets.asyncio.client import connect as websocket_connect
from websockets.exceptions import ConnectionClosed
from websockets.exceptions import InvalidStatus
from websockets.exceptions import WebSocketException

from gumloop._http import user_agent
from gumloop.linked_proxy.destinations import Target
from gumloop.linked_proxy.frames import MAX_FRAME_LENGTH
from gumloop.linked_proxy.frames import ProtocolError
from gumloop.linked_proxy.sign_in import sign_in_token
from gumloop.linked_proxy.tunnel import Connection
from gumloop.linked_proxy.tunnel import Tunnel

# The gateway's close code and refusal header for a sign-in it won't accept.
CLOSE_SIGN_IN_REFUSED = 4001
ERROR_HEADER = "X-Gumloop-Linked-Proxy-Error"
SIGN_IN_REFUSED = "sign_in_refused"

FIRST_RETRY_SECONDS = 1.0
MAX_RETRY_SECONDS = 60.0
# A connection that stayed up this long starts the backoff over.
STABLE_SECONDS = 60.0
_OPEN_TIMEOUT_SECONDS = 10.0

Open = Callable[[str, dict[str, str]], AbstractAsyncContextManager[Connection]]


class SignInRefused(Exception):
"""The gateway won't accept this linked proxy: it was unlinked, or its owner can't use it anymore."""

def __init__(self, reason: str) -> None:
super().__init__(reason)
self.reason = reason


class SignedOut(Exception):
"""The user has no stored login for this backend."""


class GatewayTokenUnavailable(Exception):
"""Gumloop didn't hand out a gateway token this time; the connection retries."""


class GatewayConnection:
def __init__(
self,
*,
gateway_url: str,
linked_proxy_id: str,
key: Ed25519PrivateKey,
signed_in: Callable[[], bool],
gateway_token: Callable[[], str],
on_open: Callable[[Target], None] | None = None,
open_websocket: Open | None = None,
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
) -> None:
self._gateway_url = gateway_url
self._linked_proxy_id = linked_proxy_id
self._key = key
self._signed_in = signed_in
self._gateway_token = gateway_token
self._on_open = on_open
self._open = open_websocket or _open_websocket
self._sleep = sleep

async def run(self) -> None:
"""Runs until it raises ``SignInRefused`` or ``SignedOut``. Every other
failure reconnects after a random wait whose cap doubles up to ``MAX_RETRY_SECONDS``.
``gateway_token`` runs in a thread before each connect, and raises
``SignInRefused`` or ``GatewayTokenUnavailable`` when it has no token."""
retry_cap = FIRST_RETRY_SECONDS
while True:
if not self._signed_in():
raise SignedOut()
started = time.monotonic()
try:
await self._serve()
except (OSError, asyncio.TimeoutError, WebSocketException, ProtocolError, GatewayTokenUnavailable) as error:
reason = _sign_in_refusal(error)
if reason is not None:
raise SignInRefused(reason) from error
if time.monotonic() - started >= STABLE_SECONDS:
retry_cap = FIRST_RETRY_SECONDS
await self._sleep(random.uniform(FIRST_RETRY_SECONDS, retry_cap))
retry_cap = min(retry_cap * 2, MAX_RETRY_SECONDS)

async def _serve(self) -> None:
gateway_token = await asyncio.to_thread(self._gateway_token)
token = sign_in_token(
self._key,
linked_proxy_id=self._linked_proxy_id,
audience=self._gateway_url,
gateway_token=gateway_token,
)
async with self._open(self._gateway_url, {"Authorization": f"Bearer {token}"}) as websocket:
await Tunnel(websocket, on_open=self._on_open).run()


def _sign_in_refusal(error: BaseException) -> str | None:
if isinstance(error, ConnectionClosed) and error.rcvd is not None and error.rcvd.code == CLOSE_SIGN_IN_REFUSED:
return error.rcvd.reason or SIGN_IN_REFUSED
if (
isinstance(error, InvalidStatus)
and error.response.status_code == 401
and error.response.headers.get(ERROR_HEADER) == SIGN_IN_REFUSED
):
return SIGN_IN_REFUSED
return None


def _open_websocket(url: str, headers: dict[str, str]) -> AbstractAsyncContextManager[Connection]:
return websocket_connect(
url,
additional_headers=headers,
user_agent_header=user_agent(),
ssl=_tls_context() if url.startswith("wss://") else None,
compression=None,
max_size=MAX_FRAME_LENGTH,
open_timeout=_OPEN_TIMEOUT_SECONDS,
)


@functools.cache
def _tls_context() -> ssl.SSLContext:
return ssl.create_default_context(cafile=certifi.where())
4 changes: 2 additions & 2 deletions src/gumloop/linked_proxy/frames.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

_HEADER = struct.Struct(">BI")
_WINDOW = struct.Struct(">I")
_MAX_FRAME_LENGTH = _HEADER.size + MAX_DATA_LENGTH
MAX_FRAME_LENGTH = _HEADER.size + MAX_DATA_LENGTH
_MAX_TARGET_LENGTH = 253 + len(":65535")
_MAX_REASON_LENGTH = 32
_MAX_GATEWAY_TOKEN_LENGTH = 1024
Expand Down Expand Up @@ -59,7 +59,7 @@ def encode(self) -> bytes:
@classmethod
def decode(cls, data: bytes) -> Frame:
"""Checks the layout only; whether the frame fits its stream is the tunnel's check."""
if not _HEADER.size <= len(data) <= _MAX_FRAME_LENGTH:
if not _HEADER.size <= len(data) <= MAX_FRAME_LENGTH:
raise ProtocolError(f"a {len(data)}-byte frame")
type_byte, stream_id = _HEADER.unpack_from(data)
payload = data[_HEADER.size :]
Expand Down
49 changes: 49 additions & 0 deletions src/gumloop/linked_proxy/sign_in.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""The token the CLI signs in to the linked proxy gateway with: a compact EdDSA JWS
signed by this machine's linked proxy key. The gateway accepts a token only for its
own URL, for at most a minute, and only once."""

from __future__ import annotations

import base64
import json
import secrets
import time
from collections.abc import Mapping

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives.serialization import Encoding
from cryptography.hazmat.primitives.serialization import PublicFormat

TOKEN_LIFETIME_SECONDS = 60


def public_key_text(key: Ed25519PrivateKey) -> str:
"""The raw public key in unpadded base64url, the form the backend registers."""
return _encode(key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw))


def sign_in_token(
key: Ed25519PrivateKey, *, linked_proxy_id: str, audience: str, gateway_token: str, now: float | None = None
) -> str:
"""``gateway_token`` is the backend's token for this linked proxy. The
gateway learns the key to verify the sign-in token with from it."""
issued_at = int(time.time() if now is None else now)
header = {"alg": "EdDSA", "typ": "JWT"}
claims = {
"sub": linked_proxy_id,
"aud": audience,
"iat": issued_at,
"exp": issued_at + TOKEN_LIFETIME_SECONDS,
"jti": secrets.token_urlsafe(16),
"gateway_token": gateway_token,
}
signing_input = f"{_encode_json(header)}.{_encode_json(claims)}"
return f"{signing_input}.{_encode(key.sign(signing_input.encode()))}"


def _encode_json(value: Mapping[str, str | int]) -> str:
return _encode(json.dumps(value, separators=(",", ":")).encode())


def _encode(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
4 changes: 4 additions & 0 deletions src/gumloop/resources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
from gumloop.resources.browser_profiles import BrowserProfiles
from gumloop.resources.chat import AsyncChat
from gumloop.resources.chat import Chat
from gumloop.resources.custom_proxies import AsyncCustomProxies
from gumloop.resources.custom_proxies import CustomProxies
from gumloop.resources.decisions import AsyncDecisions
from gumloop.resources.decisions import Decisions
from gumloop.resources.evaluations import AsyncEvaluations
Expand Down Expand Up @@ -41,6 +43,7 @@
"AsyncBrain",
"AsyncBrowserProfiles",
"AsyncChat",
"AsyncCustomProxies",
"AsyncDecisions",
"AsyncEvaluations",
"AsyncMCP",
Expand All @@ -52,6 +55,7 @@
"Brain",
"BrowserProfiles",
"Chat",
"CustomProxies",
"Decisions",
"Evaluations",
"Models",
Expand Down
Loading
Loading