diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 87acedb..8c477c6 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -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. @@ -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" diff --git a/README.md b/README.md index bde391e..8d76e1f 100644 --- a/README.md +++ b/README.md @@ -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. + ## Why ghost exists diff --git a/install.ps1 b/install.ps1 index c6a4623..92613b5 100644 --- a/install.ps1 +++ b/install.ps1 @@ -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." diff --git a/install.sh b/install.sh index 347887a..5188f62 100755 --- a/install.sh +++ b/install.sh @@ -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.") diff --git a/privacy/bridge.py b/privacy/bridge.py index 81aaec2..9919ead 100755 --- a/privacy/bridge.py +++ b/privacy/bridge.py @@ -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 @@ -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}) @@ -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): diff --git a/privacy/doctor.py b/privacy/doctor.py index cd43380..406a432 100644 --- a/privacy/doctor.py +++ b/privacy/doctor.py @@ -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: diff --git a/privacy/ghost_auth.py b/privacy/ghost_auth.py index 86409d3..a3a3295 100644 --- a/privacy/ghost_auth.py +++ b/privacy/ghost_auth.py @@ -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 @@ -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 diff --git a/privacy/ghost_login.py b/privacy/ghost_login.py index d8126f3..9795c05 100644 --- a/privacy/ghost_login.py +++ b/privacy/ghost_login.py @@ -26,6 +26,7 @@ import httpx import ghost_auth +import outbound from ghost_auth import AuthError from localhttp import LocalServer @@ -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() @@ -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: @@ -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: @@ -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 diff --git a/privacy/launch.py b/privacy/launch.py index 7290186..7e5029e 100644 --- a/privacy/launch.py +++ b/privacy/launch.py @@ -15,6 +15,7 @@ import subprocess import sys import time +import urllib.request from pathlib import Path PRIV = Path(__file__).resolve().parent @@ -168,6 +169,16 @@ 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: @@ -175,6 +186,7 @@ def run_engine(args): 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": diff --git a/privacy/outbound.py b/privacy/outbound.py new file mode 100644 index 0000000..d8c7ff0 --- /dev/null +++ b/privacy/outbound.py @@ -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)) + diff --git a/pyproject.toml b/pyproject.toml index 0d1fcf3..2a70ea0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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] diff --git a/tests/test_bridge.py b/tests/test_bridge.py index e17661f..28b4beb 100644 --- a/tests/test_bridge.py +++ b/tests/test_bridge.py @@ -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 diff --git a/tests/test_install.py b/tests/test_install.py index a18fd02..90615e5 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -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 diff --git a/tests/test_outbound.py b/tests/test_outbound.py new file mode 100644 index 0000000..46c3ff4 --- /dev/null +++ b/tests/test_outbound.py @@ -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" diff --git a/uv.lock b/uv.lock index 13d5c7a..1102582 100644 --- a/uv.lock +++ b/uv.lock @@ -372,14 +372,18 @@ name = "ghost-privacy" version = "0.1.0" source = { virtual = "." } dependencies = [ + { name = "certifi" }, { name = "httpx" }, { name = "opengradient-ohttp" }, + { name = "truststore" }, ] [package.metadata] requires-dist = [ + { name = "certifi" }, { name = "httpx", specifier = ">=0.27" }, { name = "opengradient-ohttp", specifier = ">=0.1,<0.2" }, + { name = "truststore", specifier = ">=0.10" }, ] [[package]] @@ -737,6 +741,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fb/12/5911ae3eeec47800503a238d971e51722ccea5feb8569b735184d5fcdbc0/toolz-1.1.0-py3-none-any.whl", hash = "sha256:15ccc861ac51c53696de0a5d6d4607f99c210739caf987b5d2054f3efed429d8", size = 58093, upload-time = "2025-10-17T04:03:20.435Z" }, ] +[[package]] +name = "truststore" +version = "0.10.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ee/9f/c5201d42a484c061e528825fc8e2d565f5abd50a4ced6fb7d29c4ec99b2b/truststore-0.10.5.tar.gz", hash = "sha256:30d36967ccaded5cbb38d602c433f53600036c79d502f4533a49b60a03bbefcd", size = 28091, upload-time = "2026-10-12T22:27:31.808Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/e9/3a7820be2bb0fe53b6bc9c3be26d3d1158004e4c3ab953aa6840b955b1e9/truststore-0.10.5-py3-none-any.whl", hash = "sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c", size = 19017, upload-time = "2026-10-12T22:27:30.377Z" }, +] + [[package]] name = "typing-extensions" version = "4.15.0"