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
4 changes: 2 additions & 2 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- run: pip install pytest httpx "opengradient-ohttp>=0.1,<0.2"
- run: pip install pytest httpx truststore "opengradient-ohttp>=0.1,<0.2"
- run: pytest tests/ -q

# The real thing: install ghost the way a user does, use it before logging in, and check the engine it built.
Expand All @@ -33,7 +33,7 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- run: pip install pytest uv httpx "opengradient-ohttp>=0.1,<0.2"
- run: pip install pytest uv httpx truststore "opengradient-ohttp>=0.1,<0.2"
- name: Install ghost
if: runner.os != 'Windows'
run: set -o pipefail; ./install.sh | tee "$HOME/install.txt"
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ On Windows, from a clone: `.\install.ps1 -Local -NoBrowser`.

An update installs that release's `config.yaml` and `SOUL.md`; if you changed yours, they're kept beside them as `.prev`.

**On a company network**, ghost uses the system's proxy (or `HTTPS_PROXY`) and the certificates the system trusts. It needs to reach `chat-api.memchat.io` and `ogevmdevnet.opengradient.ai`. If the network inspects TLS, the second one has to be exempt: that's where ghost reads which enclaves to trust, and it won't take that from an intercepted connection.

</details>

## Why ghost exists
Expand Down
8 changes: 7 additions & 1 deletion install.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,13 @@ foreach ($task in "ghost-scrubber", "ghost-veil") { Unregister-ScheduledTask -Ta

$env:UV_PROJECT_ENVIRONMENT = $Venv
Push-Location $Repo
try { & uv sync --quiet --python 3.11 --frozen; Check "uv sync" } finally { Pop-Location }
try {
& uv sync --quiet --python 3.11 --frozen
if ($LASTEXITCODE -ne 0) { # again with the system's certificates, for a network that has one of its own
$env:UV_SYSTEM_CERTS = "1"; $env:UV_NATIVE_TLS = "1"
& uv sync --quiet --python 3.11 --frozen; Check "uv sync"
}
} finally { Pop-Location }
Remove-Item Env:UV_PROJECT_ENVIRONMENT
if (Test-Path "$Priv\.scrub") { # someone relied on it: say so rather than let them find out
Write-Host " Redaction was removed. What you send is sealed to a TEE enclave, but no longer redacted first."
Expand Down
4 changes: 3 additions & 1 deletion install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,9 @@ check_machine() {
}

install_bridge() {
( cd "$REPO" && UV_PROJECT_ENVIRONMENT="$GHOST_HOME/venv" uv sync --python 3.11 --frozen )
# (Again with the system's certificates, for a network that has one of its own.)
( cd "$REPO" && export UV_PROJECT_ENVIRONMENT="$GHOST_HOME/venv" \
&& { uv sync --python 3.11 --frozen || UV_SYSTEM_CERTS=1 UV_NATIVE_TLS=1 uv sync --python 3.11 --frozen; } )
mkdir -p "$PRIV"
if [ -e "$PRIV/.scrub" ]; then # someone relied on it: say so rather than let them find out
NOTES+=("Redaction was removed. What you send is sealed to a TEE enclave, but no longer redacted first.")
Expand Down
12 changes: 8 additions & 4 deletions privacy/bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from opengradient_ohttp import OHTTPTransport, TeeVerificationError

import ghost_auth
import outbound
import spend
from ghost_auth import AuthError
from localhttp import LocalServer
Expand Down Expand Up @@ -168,6 +169,7 @@ def _apply_limits(obj):
# retried only while it has not been accepted, and a reply that comes back unusable is reported as that
# instead of being quietly paid for again.
UPSTREAM = "https://ohttp.invalid/v1/chat/completions" # routed by the transport; never contacted
REGISTRY = "https://ogevmdevnet.opengradient.ai" # only to look up its proxy; the transport has its own
# Hidden reasoning is silent, sometimes for minutes: giving up on it only means paying twice.
TIMEOUT = httpx.Timeout(1200.0, connect=15.0, pool=60.0)
_RETRY_STATUS = frozenset({500, 502, 503, 504})
Expand Down Expand Up @@ -195,11 +197,13 @@ def __init__(self, status, message):
def _upstream():
"""(client, headers) for the login in use. Raises AuthError when nobody is logged in."""
relay, token = ghost_auth.credentials()
key = (relay, outbound.proxy(relay)) # a laptop changes networks
with _lock:
if relay not in _clients:
transport = OHTTPTransport(relay_url=relay, verify_before_release=True, timeout=TIMEOUT)
_clients[relay] = httpx.Client(transport=transport, timeout=TIMEOUT)
return _clients[relay], {"Authorization": f"Bearer {token}"}
if key not in _clients:
transport = OHTTPTransport(relay_url=relay, verify_before_release=True, timeout=TIMEOUT, transport=outbound.transport(relay),
registry_transport=outbound.transport(REGISTRY, public_only=True))
_clients[key] = httpx.Client(transport=transport, timeout=TIMEOUT)
return _clients[key], {"Authorization": f"Bearer {token}"}


def _backoff(attempt):
Expand Down
3 changes: 2 additions & 1 deletion privacy/doctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,11 @@ def bridge():
def relay():
"""The relay's own config document: it answers only a login it accepts, and nothing is run or billed."""
import httpx
import outbound
started = time.monotonic()
try:
address, token = ghost_auth.credentials()
resp = httpx.get(f"{address}/config", headers={"Authorization": f"Bearer {token}"}, timeout=20)
resp = httpx.get(f"{address}/config", headers={"Authorization": f"Bearer {token}"}, timeout=20, verify=outbound.trust())
except AuthError as e:
return False, str(e), "ghost login"
except httpx.HTTPError as e:
Expand Down
7 changes: 5 additions & 2 deletions privacy/ghost_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,10 @@ def _refresh(session):
if not session.get("refresh_token") or not config.get("supabase_url"):
raise AuthError(EXPIRED)
import httpx # only here: the launcher reads this module on every start
import outbound
try:
resp = httpx.post(f"{config['supabase_url']}/auth/v1/token", params={"grant_type": "refresh_token"},
json={"refresh_token": session["refresh_token"]},
json={"refresh_token": session["refresh_token"]}, verify=outbound.trust(),
headers={"apikey": config.get("supabase_anon_key") or ""}, timeout=15)
except httpx.HTTPError as e:
raise AuthError(f"couldn't reach DreamFort to renew your login ({type(e).__name__}); check your connection") from e
Expand Down Expand Up @@ -169,8 +170,10 @@ def balance():
if api_key() or not account():
return None
import httpx
import outbound
try:
resp = httpx.get(f"{CHAT_API_URL}/api/v1/credits/balance", headers={"Authorization": f"Bearer {credentials()[1]}"}, timeout=10)
resp = httpx.get(f"{CHAT_API_URL}/api/v1/credits/balance", headers={"Authorization": f"Bearer {credentials()[1]}"},
verify=outbound.trust(), timeout=10)
return float(resp.json()["balanceUsd"]) if resp.status_code == 200 else None
except (AuthError, httpx.HTTPError, ValueError, KeyError, TypeError):
return None
Expand Down
12 changes: 7 additions & 5 deletions privacy/ghost_login.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import httpx

import ghost_auth
import outbound
from ghost_auth import AuthError
from localhttp import LocalServer

Expand Down Expand Up @@ -246,7 +247,7 @@ def parse_pasted(text):

def device_code():
"""Ask DreamFort for a login code. None when this server doesn't do code logins."""
resp = httpx.post(f"{ghost_auth.CHAT_API_URL}/api/v1/cli-auth/device/code", timeout=TIMEOUT)
resp = httpx.post(f"{ghost_auth.CHAT_API_URL}/api/v1/cli-auth/device/code", timeout=TIMEOUT, verify=outbound.trust())
if resp.status_code in (404, 405, 501):
return None
resp.raise_for_status()
Expand All @@ -268,7 +269,7 @@ def device_login(handshake):
spin = Spinner(f"Waiting for you to approve it… {dim('(Esc to cancel)')}")
if not COLOR:
say("Waiting for you to approve it…")
deadline = time.monotonic() + float(handshake["expiresIn"])
deadline, trust = time.monotonic() + float(handshake["expiresIn"]), outbound.trust()
interval = max(MIN_POLL, float(handshake["interval"]))
next_poll = time.monotonic() + interval
with Keys() as keys:
Expand All @@ -282,7 +283,7 @@ def device_login(handshake):
next_poll = time.monotonic() + interval
try:
poll = httpx.post(f"{ghost_auth.CHAT_API_URL}/api/v1/cli-auth/device/token",
json={"deviceCode": handshake["deviceCode"]}, timeout=TIMEOUT)
json={"deviceCode": handshake["deviceCode"]}, timeout=TIMEOUT, verify=trust)
except httpx.HTTPError:
continue # a network blip; keep waiting
if poll.status_code == 200:
Expand Down Expand Up @@ -419,13 +420,14 @@ def check_key(key):
headers = {"Authorization": f"Bearer {key}"}
relay = ghost_auth.CHAT_API_URL + ghost_auth.API_KEY_RELAY
try:
resp = httpx.get(f"{relay}/config", headers=headers, timeout=TIMEOUT)
trust = outbound.trust()
resp = httpx.get(f"{relay}/config", headers=headers, timeout=TIMEOUT, verify=trust)
if resp.status_code in (401, 403):
raise AuthError("DreamFort doesn't accept that key; check it was copied whole and hasn't been revoked")
if resp.status_code >= 400:
raise AuthError(f"DreamFort couldn't check that key right now ({resp.status_code}); try again in a moment")
# An empty request is refused before anything runs, but only after the balance is checked.
probe = httpx.post(relay, headers={**headers, "Content-Type": "message/ohttp-req", "X-TEE-ID": "0x0"}, timeout=TIMEOUT)
probe = httpx.post(relay, headers={**headers, "Content-Type": "message/ohttp-req", "X-TEE-ID": "0x0"}, timeout=TIMEOUT, verify=trust)
except httpx.HTTPError as e:
raise AuthError(f"couldn't reach DreamFort ({type(e).__name__}); check your connection and try again") from e
return "This key works, but its account has no credits yet." if probe.status_code == 402 else None
Expand Down
12 changes: 12 additions & 0 deletions privacy/launch.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import subprocess
import sys
import time
import urllib.request
from pathlib import Path

PRIV = Path(__file__).resolve().parent
Expand Down Expand Up @@ -168,13 +169,24 @@ def engine_binary():
return next((bin_dir / n for n in names if (bin_dir / n).exists()), None)


def engine_proxies():
"""What an engine needs to reach the world through this machine's proxy, and the bridge without it."""
found = urllib.request.getproxies() # the environment's, or the system's settings
env = {f"{scheme}_proxy": found[scheme] for scheme in ("http", "https", "all") if found.get(scheme)}
if env:
direct = [h.strip() for h in (found.get("no") or "").split(",") if h.strip()]
env["no_proxy"] = ",".join(direct + [h for h in ("127.0.0.1", "localhost", "::1") if h not in direct])
return {name: value for lower, value in env.items() for name in (lower, lower.upper())}


def run_engine(args):
engine = engine_binary()
if engine is None:
say(f"the engine isn't installed ({ENGINE}). Put it back with: ghost update")
return 1
# An ambient ANTHROPIC_API_KEY would make any `claude` the agent runs bill that key instead of your plan.
os.environ.pop("ANTHROPIC_API_KEY", None)
os.environ.update(engine_proxies())
command = [str(engine), "-p", "uncensored", *args]
sys.stdout.flush()
if os.name != "nt":
Expand Down
43 changes: 43 additions & 0 deletions privacy/outbound.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""How ghost's own requests leave this machine: through its proxy, if it has one, and trusting the certificates
it trusts, as a company laptop needs.

With one exception. Which enclaves to trust is read from the TEE registry, so on a network that inspects TLS
that read must fail rather than believe the network: it trusts the public authorities only.
"""
import ssl
import sys
import urllib.request
from urllib.parse import urlsplit

import certifi
import httpx
import truststore


def trust():
"""Certificates the system trusts (and the public ones, for a Linux without a store of its own)."""
context = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
if sys.platform.startswith("linux"):
context.load_verify_locations(certifi.where())
return context


def proxy(url):
"""The proxy for `url`, from the environment or the system's settings. None for a direct connection."""
parts = urlsplit(url)
try:
if urllib.request.proxy_bypass(parts.hostname):
return None
found = urllib.request.getproxies()
except OSError:
return None
address = found.get(parts.scheme) or found.get("all")
if address and "://" not in address:
return f"http://{address}"
return address if address and urlsplit(address).scheme in ("http", "https") else None


def transport(url, *, public_only=False):
verify = ssl.create_default_context(cafile=certifi.where()) if public_only else trust()
return httpx.HTTPTransport(verify=verify, proxy=proxy(url))

3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ dependencies = [
# signature on every reply. Pinned so a re-install can't silently change the verification protocol.
"opengradient-ohttp>=0.1,<0.2",
"httpx>=0.27",
# The certificates this machine trusts, for networks with one of their own.
"truststore>=0.10",
"certifi",
]

[tool.uv]
Expand Down
2 changes: 1 addition & 1 deletion tests/test_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ def test_each_login_has_its_own_relay(monkeypatch, bridge, login, relay, token,
seen = []

class Transport(httpx.BaseTransport):
def __init__(self, relay_url, verify_before_release, timeout): # and no registry: the library's own is used
def __init__(self, relay_url, verify_before_release, timeout, transport, registry_transport): # and no registry of ours
assert verify_before_release is True
self.relay = relay_url

Expand Down
2 changes: 1 addition & 1 deletion tests/test_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ def test_what_older_releases_left_behind_is_removed(machine):
(privacy / name).touch()
(privacy / "pii_denylist.txt").write_text("my terms")
assert "Redaction was removed" not in m.install().stdout
assert sorted(p.name for p in privacy.iterdir() if p.suffix == ".py") == ["bridge.py", "doctor.py", "ghost_auth.py", "ghost_login.py", "launch.py", "localhttp.py", "spend.py"]
assert sorted(p.name for p in privacy.iterdir() if p.suffix == ".py") == ["bridge.py", "doctor.py", "ghost_auth.py", "ghost_login.py", "launch.py", "localhttp.py", "outbound.py", "spend.py"]
assert not (privacy / ".presidio").exists() and (privacy / "pii_denylist.txt").read_text() == "my terms" # yours


Expand Down
88 changes: 88 additions & 0 deletions tests/test_outbound.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
"""Company networks: the system's proxy and certificates, and the one read that trusts neither."""
import socket
import ssl
import sys
import threading
from pathlib import Path

import httpx
import pytest

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "privacy"))
truststore = pytest.importorskip("truststore")
import outbound # noqa: E402

PROXY_VARIABLES = [v for name in ("http", "https", "all", "no") for v in (f"{name}_proxy", f"{name.upper()}_PROXY")]


@pytest.fixture(autouse=True)
def no_proxy_of_this_machine(monkeypatch):
for name in PROXY_VARIABLES:
monkeypatch.delenv(name, raising=False)
monkeypatch.setattr(outbound.urllib.request, "getproxies", outbound.urllib.request.getproxies_environment)
monkeypatch.setattr(outbound.urllib.request, "proxy_bypass", outbound.urllib.request.proxy_bypass_environment)


@pytest.mark.parametrize("env, url, expect", [
({}, "https://chat-api.example/x", None),
({"HTTPS_PROXY": "http://proxy.corp:8080"}, "https://chat-api.example/x", "http://proxy.corp:8080"),
({"https_proxy": "proxy.corp:8080"}, "https://chat-api.example/x", "http://proxy.corp:8080"),
({"ALL_PROXY": "http://proxy.corp:8080"}, "https://chat-api.example/x", "http://proxy.corp:8080"),
({"HTTP_PROXY": "http://proxy.corp:8080"}, "https://chat-api.example/x", None),
({"HTTPS_PROXY": "http://proxy.corp:8080", "NO_PROXY": ".example"}, "https://chat-api.example/x", None),
({"HTTPS_PROXY": "socks5://proxy.corp:1080"}, "https://chat-api.example/x", None),
])
def test_which_proxy(monkeypatch, env, url, expect):
for name, value in env.items():
monkeypatch.setenv(name, value)
assert outbound.proxy(url) == expect


@pytest.mark.parametrize("public_only", [False, True])
def test_the_relay_and_the_registry_are_reached_through_it(monkeypatch, public_only):
listener = socket.create_server(("127.0.0.1", 0))
asked = []

def refuse():
conn, _ = listener.accept()
asked.append(conn.recv(4096).split(b"\r\n")[0])
conn.sendall(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n")
conn.close()
threading.Thread(target=refuse, daemon=True).start()
monkeypatch.setenv("HTTPS_PROXY", f"http://127.0.0.1:{listener.getsockname()[1]}")
with httpx.Client(transport=outbound.transport("https://chat-api.example", public_only=public_only)) as client:
with pytest.raises(httpx.ProxyError):
client.get("https://chat-api.example/x")
assert asked == [b"CONNECT chat-api.example:443 HTTP/1.1"]


def test_the_registry_read_does_not_trust_the_systems_certificates():
"""A network that inspects TLS is trusted by the system. It must not get to say which enclaves to trust."""
def context(**options):
return outbound.transport("https://x.example", **options)._pool._ssl_context
assert isinstance(context(), truststore.SSLContext)
assert type(context(public_only=True)) is ssl.SSLContext and context(public_only=True).verify_mode == ssl.CERT_REQUIRED


def test_the_bridge_reads_the_registry_that_way(monkeypatch):
pytest.importorskip("opengradient_ohttp")
import bridge
made = {}
monkeypatch.setattr(bridge, "_clients", {})
monkeypatch.setattr(bridge.ghost_auth, "credentials", lambda: ("https://relay.example/x", "t"))
monkeypatch.setattr(bridge.outbound, "transport", lambda url, **options: (url, options))
monkeypatch.setattr(bridge, "OHTTPTransport", lambda **options: made.update(options) or httpx.MockTransport(lambda r: None))
bridge._upstream()
assert made["transport"] == ("https://relay.example/x", {}) and made["registry_transport"][1] == {"public_only": True}
from opengradient_ohttp._registry import DEFAULT_RPC_URL
assert made["registry_transport"][0] == DEFAULT_RPC_URL and "registry_rpc_url" not in made


def test_an_engine_reaches_the_bridge_without_the_proxy(monkeypatch):
import launch
assert launch.engine_proxies() == {}
monkeypatch.setenv("HTTPS_PROXY", "http://proxy.corp:8080")
monkeypatch.setenv("NO_PROXY", "intranet.corp, localhost")
env = launch.engine_proxies()
assert env["https_proxy"] == env["HTTPS_PROXY"] == "http://proxy.corp:8080" and "http_proxy" not in env
assert env["no_proxy"] == env["NO_PROXY"] == "intranet.corp,localhost,127.0.0.1,::1"
Loading
Loading