diff --git a/README.md b/README.md index 8d76e1f..929e845 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ 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. +**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`, where it reads which enclaves to trust. If the network inspects TLS, exempt the second one: ghost won't take that from an intercepted connection, and falls back to an enclave built into the release. @@ -143,7 +143,7 @@ The model's host is NEAR AI for DeepSeek V4.1 Flash Abliterated (served from TEE ## Honest limits -- **Hosted models cost credits.** `ghost usage` shows what you've spent, and ghost pauses itself after $5 in an hour so nothing runs away with your balance; change that with `ghost budget 20` or `ghost budget off`. A reply is never paid for twice: what comes back unusable is reported, not retried. +- **Hosted models cost credits.** `ghost usage` shows what you've spent, and ghost pauses itself after $5 in an hour so nothing runs away with your balance; change that with `ghost budget 20` or `ghost budget off`. What comes back unusable is reported, not paid for again: at most one retry, when the connection broke. - **Replies arrive whole.** The signature covers the complete reply, so ghost shows it once it's verified rather than word by word. - **The local model is opt-in and weaker.** Off by default (`GHOST_LOCAL`); it's a weaker agentic searcher and may still lean on the hosted gateway for tool orchestration. - **The engine is forked, not rewritten.** It's one pinned Hermes release ([`engine.pin`](engine.pin)), patched and self-contained: no separate Hermes install is needed or touched, and `ghost update` is what moves it. Internal package names stay `hermes_cli`. diff --git a/privacy/bridge.py b/privacy/bridge.py index 9919ead..0d3095a 100755 --- a/privacy/bridge.py +++ b/privacy/bridge.py @@ -14,6 +14,7 @@ import json import os import random +import re import threading import time import warnings @@ -25,6 +26,7 @@ import ghost_auth import outbound import spend +from enclaves import REGISTRY, Enclaves from ghost_auth import AuthError from localhttp import LocalServer @@ -155,7 +157,7 @@ def _apply_model_steer(obj): def _apply_limits(obj): asked = obj.get("max_tokens") or obj.get("max_completion_tokens") obj.pop("max_completion_tokens", None) - obj["max_tokens"] = min(int(asked), MAX_TOKENS) if asked else MAX_TOKENS + obj["max_tokens"] = min(asked, MAX_TOKENS) if isinstance(asked, int) and asked > 0 else MAX_TOKENS effort = str(obj.get("reasoning_effort") or DEFAULT_EFFORT).lower() effort = _EFFORT_ALIASES.get(effort, effort) obj["reasoning_effort"] = effort if effort in _EFFORTS else DEFAULT_EFFORT @@ -169,10 +171,10 @@ 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}) +_RETRY_STATUS = frozenset({500, 502, 503}) # (a 504 is a load balancer giving up on a request that goes on running) +_NEVER_ARRIVED = (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout, httpx.WriteError, httpx.WriteTimeout, httpx.ProxyError) _MAX_TRIES = 3 _BUSY_WAITS = (5, 10, 20, 30) # seconds: the relay takes 40 requests a minute, which a quick agent can reach _BREAK_WINDOW = 300.0 @@ -200,8 +202,8 @@ def _upstream(): key = (relay, outbound.proxy(relay)) # a laptop changes networks with _lock: 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)) + transport = OHTTPTransport(relay_url=relay, verify_before_release=True, timeout=TIMEOUT, transport=outbound.transport(relay)) + transport._resolver = Enclaves(outbound.transport(REGISTRY, public_only=True), log) _clients[key] = httpx.Client(transport=transport, timeout=TIMEOUT) return _clients[key], {"Authorization": f"Bearer {token}"} @@ -221,19 +223,22 @@ def _open(obj): client, headers = _upstream() try: resp = client.send(client.build_request("POST", UPSTREAM, json=obj, headers=headers), stream=True) - except (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout) as e: + except _NEVER_ARRIVED as e: tries += 1 if tries == _MAX_TRIES: - raise Refused(502, f"couldn't reach DreamFort ({type(e).__name__}); check your connection and try again") from e + why = f"your proxy said: {e}" if isinstance(e, httpx.ProxyError) else type(e).__name__ + raise Refused(502, f"couldn't reach DreamFort ({why}); check your connection and try again") from e log(f"relay unreachable (try {tries}): {e}; retrying") _backoff(tries - 1) continue if resp.status_code < 400: return resp try: - message = _decode_error(resp.read()) + message = _decode_error(resp.read(), resp.status_code) finally: resp.close() + if resp.status_code == 504: + raise httpx.ReadTimeout(message) if resp.status_code == 429 and waits: log(f"too many requests this minute; waiting {waits[0]}s") _wait(waits.pop(0)) @@ -318,6 +323,15 @@ def completion(self): return body +def _host_failed(error): + """What the enclave says when the model's host failed it. Nothing is billed: it settles a finished reply.""" + message = str(error.get("message") or error) if isinstance(error, dict) else str(error) + status = int(next(iter(re.findall(r"Error code: (\d{3})", message)), 502)) + if status not in (400, 404, 413, 422): # those are about the request (too long, say), which the engine can act on + status = 502 + return Refused(status, f"the model's host answered: {message[:600]}") + + def _generate(obj): """One generation, verified and whole. Always streamed from the enclave: its buffered form cuts long replies off at the relay's timeout and quietly 'repairs' a truncated tool call into valid JSON.""" @@ -325,10 +339,9 @@ def _generate(obj): why = spend.paused() if why: raise Refused(422, why) - reply = Reply(obj["max_tokens"]) - resp = _open({**obj, "stream": True}) - ended = False + reply, resp, ended = Reply(obj["max_tokens"]), None, False try: + resp = _open({**obj, "stream": True}) for line in resp.iter_lines(): if not line.startswith("data:"): continue @@ -338,23 +351,28 @@ def _generate(obj): break event = json.loads(data) if event.get("error"): - raise httpx.RemoteProtocolError(str(event["error"])[:200]) + raise _host_failed(event["error"]) reply.feed(event) ended = ended or reply.finish is not None if not ended: raise httpx.RemoteProtocolError("the reply stopped early") - except (httpx.HTTPError, TeeVerificationError, ValueError) as e: - # Accepted, so billed, but we never got it. One engine retry is fair; a second break in a row is not. + except (AuthError, Refused): # never accepted, or never billed + raise + except Exception as e: + # Accepted, so billed, but we never got it (cut off, unverifiable, unreadable). One engine retry is fair; + # a second break in a row is not. tokens_in = len(json.dumps(obj)) // 4 spend.record(obj.get("model"), tokens_in, 2000, spend.estimate(obj.get("model"), tokens_in, 2000)) again, _last_break = time.time() - _last_break < _BREAK_WINDOW, time.time() log(f"reply lost after it was accepted: {type(e).__name__}: {e}") - message = f"the connection to the enclave broke before the reply arrived ({type(e).__name__})" + message = ("a reply came back without the enclave's signature on it, so it was thrown away" if isinstance(e, TeeVerificationError) + else f"the connection to the enclave broke before the reply arrived ({type(e).__name__})") if again: - raise Unusable(message + " twice in a row; each attempt is billed, so ghost stopped retrying. Try again in a moment.") from e + raise Unusable(message + ", twice in a row; each attempt is billed, so ghost stopped retrying. Try again in a moment.") from e raise Refused(502, message) from e finally: - resp.close() + if resp is not None: + resp.close() tokens_in = int(reply.usage.get("prompt_tokens") or 0) cost = reply.cost if reply.cost is not None else spend.estimate(obj.get("model"), tokens_in, reply.tokens_out) spend.record(obj.get("model"), tokens_in, reply.tokens_out, cost) @@ -363,17 +381,21 @@ def _generate(obj): return reply -def _decode_error(raw: bytes) -> str: +def _decode_error(raw: bytes, status) -> str: + """What an error reply says, in a line for people.""" try: data = json.loads(raw) - if isinstance(data, dict): - err = data.get("error") - if isinstance(err, dict): - return str(err.get("message") or err) - return str(err or data.get("detail") or "the relay returned an error") - except Exception: - pass - return raw.decode("utf-8", errors="ignore")[:300] or "the relay returned an error" + error = data.get("error") if isinstance(data, dict) else None + if isinstance(error, dict) and error.get("code") == "tee_not_active": + return "the enclave ghost picked isn't active any more; if this keeps happening, run `ghost update`" + message = str((error.get("message") or error) if isinstance(error, dict) else error or data.get("detail") or "") + except (ValueError, AttributeError): + message = raw.decode("utf-8", errors="ignore") + quoted = re.search(r"\(relay: (.*)\)\s*$", message, re.S) # opengradient-ohttp's own words are about API keys + message = (quoted.group(1) if quoted else message).strip() + if not message or message.startswith("<"): # some proxy's page + return f"DreamFort isn't answering properly ({status}); try again in a moment" + return message[:600] class Handler(BaseHTTPRequestHandler): @@ -457,7 +479,9 @@ def do_POST(self): return try: obj = json.loads(raw) - except Exception as e: + if not isinstance(obj, dict): + raise ValueError("not an object") + except ValueError as e: self._error(400, f"invalid JSON body: {e}") return diff --git a/privacy/doctor.py b/privacy/doctor.py index 406a432..ae8cbd5 100644 --- a/privacy/doctor.py +++ b/privacy/doctor.py @@ -1,4 +1,4 @@ -"""ghost doctor: is everything between you and a model in order? Contacts DreamFort only, and no model.""" +"""ghost doctor: is everything between you and a model in order? Contacts DreamFort and the TEE registry, and no model.""" import subprocess import sys import time @@ -52,6 +52,16 @@ def relay(): return True, f"reachable, login accepted ({(time.monotonic() - started) * 1000:.0f} ms)", None +def enclaves(): + """The registry says which enclaves there are. Without it, ghost has some built in.""" + import outbound + from enclaves import REGISTRY, Enclaves, RegistryError + try: + return True, f"{Enclaves(outbound.transport(REGISTRY, public_only=True)).listed()} in the registry", None + except RegistryError: + return None, "the registry can't be read right now, so the one built into ghost is used", None + + def credits(): if ghost_auth.api_key(): return True, "see https://api.dreamfort.ai", None @@ -77,7 +87,7 @@ def style(text, code): failed = False checks = [("Engine", engine), ("Login", login), ("Bridge", bridge)] if ghost_auth.mode(): # nothing is contacted before you log in - checks += [("DreamFort", relay), ("Credits", credits)] + checks += [("DreamFort", relay), ("Enclaves", enclaves), ("Credits", credits)] print() for name, check in (*checks, ("Spending", spending)): ok, detail, fix = check() diff --git a/privacy/enclaves.py b/privacy/enclaves.py new file mode 100644 index 0000000..53e7ffd --- /dev/null +++ b/privacy/enclaves.py @@ -0,0 +1,59 @@ +"""Which enclaves a request may be sealed to: the ones the on-chain TEE registry lists. + +The chain it lives on has been down (25 November 2026), and a network that inspects TLS can't be believed about +it. When it can't be read, ghost uses the enclaves below instead. Their keys are fixed here, as the registry's +address is, so cutting ghost off from the registry can't point it at an impostor. DreamFort's apps fall back to +the same list (chat-app's lib/api/backupTees.ts, chat-api's src/core/backup_tees.py): keep the three in step. +""" +import random + +from cryptography.hazmat.primitives import serialization +from eth_hash.auto import keccak +from opengradient_ohttp import DEFAULT_RPC_URL as REGISTRY, RegistryError, TeeTarget +from opengradient_ohttp._registry import TeeResolver, parse_active_tees + + +def _enclave(endpoint, signing_key_pem, hpke_public_key): + der = serialization.load_pem_public_key(signing_key_pem.encode()).public_bytes( + serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo) + return TeeTarget(tee_id="0x" + keccak(der).hex(), endpoint=endpoint, signing_key_pem=signing_key_pem, + ohttp_public_key=bytes.fromhex(hpke_public_key), key_id=1) + + +BUILT_IN = ( + _enclave("https://3.147.79.53", """\ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxTFaCi3JXAOp1LxpjZxT +KZPGMGNzjtRIaC73KnMZOIm/rJoM6x+kqLrocQKU2ATfGi7tuiB06AirJaM31CiQ +yBBc9/qCkQj6i+zudQZCFkPIDgn34hpgL6nc2jXJAlhV7zHdpg2ieSjtBh8D+tSH +MYmrg32WY4SGxPiRPo8FnYITkOl8ZWjDi85Yi21ztWgY70Ck5j+UfzNa96ceObR/ +YGxPGLwMuon/N1LmZ2q+H6sPbHI6Sxeb5b33Kpe4wRwqkUkRw49Do/1iwY5pPJIc +OzkyDBXXQXl9EOZAhP5ug423H2dcwobkq3QEV+fW2EIHouDNR1lei0RwNCPlWPnj +LwIDAQAB +-----END PUBLIC KEY----- +""", "ba5c847114ffc09e387b2b9946b1ab8e91528a308137fdb160f59ea9e1717112"), +) + + +class Enclaves(TeeResolver): + """Picks one, and keeps it for as long as a registry read is kept.""" + + def __init__(self, transport=None, log=lambda message: None): + super().__init__(transport=transport) + self._log = log + + def get(self): + try: + return super().get() + except RegistryError as e: + self._log(f"the TEE registry can't be read, using a built-in enclave: {e}") + with self._lock: + self._cache.put(random.choice(BUILT_IN)) + return self._cache.get() + + def listed(self): + """How many enclaves the registry lists. Raises RegistryError when it can't be read.""" + found = len(parse_active_tees(self._fetch(), self._excluded)) + if not found: + raise RegistryError("the registry lists no enclave") + return found diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..90a1898 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,7 @@ +"""Tests run on people's own machines: whatever one forgets to replace must not be their ghost.""" +import os +import tempfile + +_home = tempfile.mkdtemp(prefix="ghost-tests-") +for name in ("GHOST_HOME", "OG_VEIL_HOME"): # (CI points them at the ghost it has just installed) + os.environ.setdefault(name, _home) diff --git a/tests/fake_dreamfort.py b/tests/fake_dreamfort.py new file mode 100644 index 0000000..3cad774 --- /dev/null +++ b/tests/fake_dreamfort.py @@ -0,0 +1,238 @@ +"""A stand-in for DreamFort on one local port: logins, the relay, the TEE registry and an enclave behind it. + +It is real HTTP, real OHTTP and real signatures, so ghost's own code runs against it unchanged. What its "model" +does is written in the newest user message: + + [[say TEXT]] answer TEXT (the default answer is "a fake reply") + [[run COMMAND]] call the terminal tool, then answer "ran: " + [[fail KIND N]] fail the first N attempts (every one, without N) at this message; KINDs are in FAILURES + + python tests/fake_dreamfort.py PORT LOG the service; LOG gets a line of JSON per request + python tests/fake_dreamfort.py PORT --bridge FILE ghost's bridge (FILE is its bridge.py), talking to it +""" +import base64 +import json +import os +import re +import struct +import sys +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import httpx +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import padding, rsa +from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 +from eth_abi import encode +from eth_hash.auto import keccak +from opengradient_ohttp._hpke import _LABEL_CHUNKED_RESPONSE, _LABEL_REQUEST, _SUITE, _derive_response_keys, _header_bytes +from opengradient_ohttp._registry import TEE_INFO_ARRAY_TYPE +from opengradient_ohttp._verify import build_inner_request + +API_KEY, NO_CREDITS_KEY = "df_sk_good0000", "df_sk_broke0000" +FAILURES = { + # refused, so never billed + "402": (402, {"detail": "Insufficient credits"}), "429": (429, {"error": "Rate limit exceeded: 40 per 1 minute"}), + "503": (503, {"detail": {"code": "tee_unreachable", "message": "TEE OHTTP request failed"}}), + "retired": (502, {"detail": {"code": "tee_not_active", "message": "Selected TEE is not active"}}), + "page": (502, b"

502 Bad Gateway

"), "451": (451, {"error": "Content policy violation"}), + # accepted, and then not delivered + "504": (504, b"

504 Gateway Time-out

"), "silent": None, "empty": None, "cut": None, "drop": None, + "forged": None, "unsigned": None, + # the model's host failed the enclave, which says so in the reply and bills nothing + "host400": "Error code: 400 - {'error': {'message': \"This model's maximum context length is 131072 tokens.\"}}", + "host503": "Error code: 503 - {'error': {'message': 'overloaded'}}", +} + + +class Enclave: + def __init__(self): + pair = _SUITE.kem.derive_key_pair(os.urandom(32)) + self.private, self.public = pair.private_key, pair.public_key.to_public_bytes() + self.rsa = rsa.generate_private_key(public_exponent=65537, key_size=2048) + self.der = self.rsa.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo) + self.tee_id = "0x" + keccak(self.der).hex() + + def registry_entry(self): + return ("0x" + "11" * 20, "0x" + "22" * 20, "https://enclave.test", self.der, b"", b"\0" * 32, 0, True, 1, 1, + (1, 0x20, 1, 3, self.public, b"", 1)) + + def open(self, wire): + """The request inside, and the function that seals a reply to it chunk by chunk.""" + enc = wire[7:39] + context = _SUITE.create_recipient_context(enc, self.private, info=_LABEL_REQUEST + b"\0" + _header_bytes(wire[0])) + inner, nonce = json.loads(context.open(wire[39:], aad=b"")), os.urandom(32) + key, base = _derive_response_keys(context.export(_LABEL_CHUNKED_RESPONSE, 32), enc, nonce) + + def seal(pieces): + yield nonce + for i, piece in enumerate(pieces): + final = i == len(pieces) - 1 + sealed = ChaCha20Poly1305(key).encrypt(bytes(a ^ b for a, b in zip(base, i.to_bytes(12, "big"))), piece, b"final" if final else b"") + yield (b"\0" if final else struct.pack(">I", 0x80000000 | len(sealed))) + sealed + return inner, seal + + def sign(self, inner, output): + _, canonical = build_inner_request({k: v for k, v in inner.items() if k != "stream"}) + asked, answered, now = keccak(json.dumps(canonical, sort_keys=True).encode()), keccak(output.encode()), int(time.time()) + signature = self.rsa.sign(keccak(asked + answered + now.to_bytes(32, "big")), + padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=32), hashes.SHA256()) + return {"tee_signature": base64.b64encode(signature).decode(), "tee_request_hash": asked.hex(), "tee_output_hash": answered.hex(), + "tee_timestamp": now, "tee_id": self.tee_id} + + +class DreamFort: + def __init__(self, log=None): + self.enclave, self.log, self.registry_up, self.attempts = Enclave(), log, True, {} + self.accepted, self.billed = [], [] # the requests the enclave opened, and the ones the account paid for + + def note(self, **row): + if self.log: + with open(self.log, "a", encoding="utf-8") as fh: + fh.write(json.dumps(row) + "\n") + + @staticmethod + def asked(inner): + """The newest user message, and the tool output that came after it.""" + text, after = "", [] + for message in inner["messages"]: + content = message.get("content") + content = content if isinstance(content, str) else " ".join(p.get("text", "") for p in content or [] if isinstance(p, dict)) + if message["role"] == "user": + text, after = content, [] + elif message["role"] == "tool": + after.append(content) + return text, after + + def failure(self, text): + found = re.search(r"\[\[fail (\w+) ?(\d*)\]\]", text) + if not found: + return None + seen = self.attempts[text] = self.attempts.get(text, 0) + 1 + return found[1] if not found[2] or seen <= int(found[2]) else None + + def reply(self, inner, kind): + """The reply's events, as the gateway streams them.""" + text, after = self.asked(inner) + command, say = re.search(r"\[\[run (.*?)\]\]", text, re.S), re.search(r"\[\[say (.*?)\]\]", text, re.S) + call = command and not after and any(t["function"]["name"] == "terminal" for t in inner.get("tools") or []) + calls = [{"id": "call_1", "type": "function", "function": {"name": "terminal", "arguments": json.dumps({"command": command[1]})}}] if call else [] + output = "" if calls else "ran: " + after[-1] if command and after else say[1] if say else "a fake reply" + signed = self.enclave.sign(inner, json.dumps(calls, sort_keys=True) if calls else output + ("!" if kind == "forged" else "")) + usage = {"prompt_tokens": len(json.dumps(inner)) // 4, "completion_tokens": 20} + + def event(delta, finish=None, **more): + return b"data: " + json.dumps({"id": "chatcmpl-1", "model": inner["model"], "choices": [{"index": 0, "delta": delta, "finish_reason": finish}], **more}).encode() + b"\n\n" + pieces = [event({"tool_calls": [{"index": 0, **calls[0]}]})] if calls else [event({"content": word}) for word in re.findall(r"\S+\s*|\s+", output)] + if kind and isinstance(FAILURES[kind], str): + return pieces[:1] + [b"data: " + json.dumps({"error": FAILURES[kind], "source": "provider"}).encode() + b"\n\n"] + if kind == "unsigned": + signed = {} + pieces.append(event({}, "tool_calls" if calls else "stop", usage=usage, opengradient={"cost_usd": "0.001"}, **signed)) + return pieces + [b"data: [DONE]\n\n"] + + +def handler(service): + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args): + pass + + def send(self, status, body=None, kind="application/json"): + body = body if isinstance(body, bytes) else json.dumps(body or {}).encode() + self.send_response(status) + self.send_header("Content-Type", kind) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def key(self): + return (self.headers.get("Authorization") or "").removeprefix("Bearer ") + + def do_GET(self): + known = self.key() in (API_KEY, NO_CREDITS_KEY, "account-token") + if self.path.endswith("/ohttp/config"): + return self.send(200 if known else 401) + if self.path.endswith("/credits/balance"): + return self.send(200 if known else 401, {"balanceUsd": 12.5}) + self.send(404) + + def do_POST(self): + body = self.rfile.read(int(self.headers.get("Content-Length") or 0)) + if self.path.endswith("/ohttp"): + return self.relay(body) + if self.path == "/": # the chain's JSON-RPC + if not service.registry_up: + return self.send(502, b"

502 Bad Gateway

", "text/html") + return self.send(200, {"result": "0x" + encode([TEE_INFO_ARRAY_TYPE], [[service.enclave.registry_entry()]]).hex()}) + self.send(404) # (code logins, which DreamFort doesn't offer yet) + + def relay(self, body): + if self.key() == NO_CREDITS_KEY: + return self.send(*FAILURES["402"]) + if self.key() not in (API_KEY, "account-token"): + return self.send(401, {"detail": "Invalid API key"}) + if not body: + return self.send(400, {"detail": "OHTTP request body is required"}) + if self.headers.get("X-TEE-ID") != service.enclave.tee_id: + return self.send(*FAILURES["retired"]) + inner, seal = service.enclave.open(body) + kind = service.failure(service.asked(inner)[0]) + refused = FAILURES.get(kind) if kind else None + if isinstance(refused, tuple) and kind != "504": + service.note(refused=kind) + return self.send(*refused, *(["text/html"] if isinstance(refused[1], bytes) else [])) + service.accepted.append(inner) + billed = not (kind and isinstance(refused, str)) + if billed: + service.billed.append(inner) + service.note(accepted=inner["model"], billed=billed, kind=kind, max_tokens=inner.get("max_tokens"), effort=inner.get("reasoning_effort"), + tools=len(inner.get("tools") or []), asked=service.asked(inner)[0][:80]) + if kind == "504": + return self.send(*refused, "text/html") + self.close_connection = True + if kind == "silent": + return None + chunks = [] if kind == "empty" else list(seal(service.reply(inner, kind))) + self.send_response(200) + self.send_header("Content-Type", "message/ohttp-chunked-res") + self.send_header("Transfer-Encoding", "chunked") + self.end_headers() + for chunk in chunks[:2] if kind in ("cut", "drop") else chunks: + self.wfile.write(b"%x\r\n" % len(chunk) + chunk + b"\r\n") + self.wfile.flush() + if kind != "drop": # (or the connection just ends) + self.wfile.write(b"0\r\n\r\n") + return Handler + + +def serve(service, port=0): + server = ThreadingHTTPServer(("127.0.0.1", port), handler(service)) + server.daemon_threads = True + return server + + +class Redirected(httpx.HTTPTransport): + """What ghost sends anywhere goes to the stand-in.""" + + def __init__(self, port): + super().__init__() + self.port = port + + def handle_request(self, request): + request.url = request.url.copy_with(scheme="http", host="127.0.0.1", port=self.port) + return super().handle_request(request) + + +if __name__ == "__main__": + port = int(sys.argv[1]) + if sys.argv[2] == "--bridge": + import runpy + sys.path.insert(0, os.path.dirname(os.path.abspath(sys.argv[3]))) + import outbound + outbound.transport = lambda url, public_only=False: Redirected(port) + os.environ["GHOST_CHAT_API_URL"] = f"http://127.0.0.1:{port}" + runpy.run_path(sys.argv[3], run_name="__main__") + else: + serve(DreamFort(sys.argv[2]), port).serve_forever() diff --git a/tests/test_bridge.py b/tests/test_bridge.py index 28b4beb..80e72a8 100644 --- a/tests/test_bridge.py +++ b/tests/test_bridge.py @@ -15,9 +15,12 @@ import httpx import pytest -sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "privacy")) +sys.path[:0] = [os.path.join(os.path.dirname(__file__), "..", "privacy"), os.path.dirname(__file__)] pytest.importorskip("opengradient_ohttp") import bridge as sp # noqa: E402 +import enclaves # noqa: E402 +import fake_dreamfort # noqa: E402 +import outbound # noqa: E402 import spend # noqa: E402 REAL_UPSTREAM = sp._upstream @@ -61,21 +64,22 @@ def __call__(self, request): @pytest.fixture -def enclave(monkeypatch, tmp_path): +def enclave(monkeypatch): enclave = Enclave() client = httpx.Client(transport=httpx.MockTransport(enclave)) monkeypatch.setattr(sp, "_upstream", lambda: (client, {"Authorization": "Bearer t"})) + return enclave + + +@pytest.fixture +def bridge(monkeypatch, tmp_path): monkeypatch.setattr(sp, "_backoff", lambda attempt: None) + monkeypatch.setattr(sp, "_wait", lambda seconds: None) monkeypatch.setattr(sp, "_last_break", 0.0) monkeypatch.setattr(sp, "LOG", str(tmp_path / "log")) for name, value in (("DIR", tmp_path), ("LEDGER", tmp_path / "spend.jsonl"), ("BUDGET_FILE", tmp_path / "budget")): monkeypatch.setattr(spend, name, value) monkeypatch.setattr(spend, "_entries", None) - return enclave - - -@pytest.fixture -def bridge(enclave): server = ThreadingHTTPServer(("127.0.0.1", 0), sp.Handler) threading.Thread(target=server.serve_forever, daemon=True).start() @@ -119,7 +123,7 @@ def test_the_enclave_is_always_streamed(enclave, bridge, stream): # ── good replies ────────────────────────────────────────────────────────────── -def test_streamed_reply(bridge): +def test_streamed_reply(enclave, bridge): status, body = bridge() assert status == 200 and '"content": "hi"' in body and body.rstrip().endswith("data: [DONE]") @@ -183,7 +187,7 @@ def test_refusals_are_passed_on(enclave, bridge, failure, status, words): assert got[0] == status and words in got[1] and enclave.accepted == [] -def test_a_busy_relay_is_waited_out(monkeypatch, enclave, bridge): +def test_a_busy_relay_is_waited_out(enclave, bridge, monkeypatch): """It limits requests per minute, and a request it turned away was never accepted.""" waits = [] monkeypatch.setattr(sp, "_wait", waits.append) @@ -211,7 +215,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, transport, registry_transport): # and no registry of ours + def __init__(self, relay_url, verify_before_release, timeout, transport): # and no registry of ours assert verify_before_release is True self.relay = relay_url @@ -240,6 +244,84 @@ def slow(*args): server.server_close() +# ── through the real sealing, against a stand-in DreamFort ──────────────────── +@pytest.fixture +def dream(monkeypatch): + service = fake_dreamfort.DreamFort() + server = fake_dreamfort.serve(service) + threading.Thread(target=server.serve_forever, daemon=True).start() + url = f"http://127.0.0.1:{server.server_port}" + monkeypatch.setattr(outbound, "transport", lambda url, public_only=False: fake_dreamfort.Redirected(server.server_port)) + monkeypatch.setattr(sp.ghost_auth, "credentials", lambda: (url + sp.ghost_auth.API_KEY_RELAY, fake_dreamfort.API_KEY)) + monkeypatch.setattr(sp.ghost_auth, "api_key", lambda: fake_dreamfort.API_KEY) + monkeypatch.setattr(sp, "_clients", {}) + yield service + server.shutdown() + server.server_close() + + +def says(content): + return {"messages": [{"role": "user", "content": content}]} + + +def test_a_sealed_request_is_answered(dream, bridge): + status, body = bridge(stream=False, **says("[[say hello there]]")) + assert status == 200 and json.loads(body)["choices"][0]["message"]["content"] == "hello there" and len(dream.billed) == 1 + assert dream.accepted[0]["messages"] == [{"role": "user", "content": "[[say hello there]]"}] and spend.spent(3600) == pytest.approx(0.001) + + +BROKE = ("the connection to the enclave broke", "twice in a row") +@pytest.mark.parametrize("kind, statuses, billed, words", [ + # refused: not billed, and said plainly + ("402", (402, 402), 0, ("out of credits",)), ("429", (429, 429), 0, ("Rate limit exceeded: 40 per 1 minute",)), + ("451", (451, 451), 0, ("Content policy violation",)), ("503", (503, 503), 0, ("TEE OHTTP request failed",)), + ("page", (502, 502), 0, ("DreamFort isn't answering properly (502)",)), ("retired", (502, 502), 0, ("isn't active any more",)), + # billed, maybe, but never delivered: the engine may try once more, and that's all + ("504", (502, 422), 2, BROKE), ("silent", (502, 422), 2, BROKE), ("empty", (502, 422), 2, BROKE), ("cut", (502, 422), 2, BROKE), + ("drop", (502, 422), 2, BROKE), ("forged", (502, 422), 2, ("without the enclave's signature", "twice in a row")), ("unsigned", (502, 422), 2, BROKE), + # the model's host failed: not billed, and it says why (a prompt that's too long is the engine's to shorten) + ("host400", (400, 400), 0, ("maximum context length",)), ("host503", (502, 502), 0, ("overloaded",)), +]) +def test_however_a_request_fails(dream, bridge, kind, statuses, billed, words): + got = [bridge(**says(f"[[fail {kind}]] {i}")) for i in range(2)] + assert tuple(status for status, _ in got) == statuses and len(dream.billed) == billed + assert all(any(word in message for _, message in got) for word in words) + assert len(dream.accepted) <= 2 and (spend.spent(3600) > 0) == bool(billed) # what may have been billed counts + + +def test_when_the_registry_cannot_be_read(monkeypatch, dream, bridge): + """Its chain has gone down; DreamFort's apps fall back to enclaves they know, and so does ghost.""" + ours = fake_dreamfort.Enclave() + pem = ours.rsa.public_key().public_bytes(fake_dreamfort.serialization.Encoding.PEM, fake_dreamfort.serialization.PublicFormat.SubjectPublicKeyInfo).decode() + dream.registry_up, listed, dream.enclave = False, dream.enclave, ours + monkeypatch.setattr(enclaves, "BUILT_IN", (enclaves._enclave("https://ours.test", pem, ours.public.hex()),)) + assert bridge(**says("[[say one]]"))[0] == bridge(**says("[[say two]]"))[0] == 200 + with open(sp.LOG) as fh: + assert fh.read().count("the TEE registry can't be read") == 1 # and it isn't asked again each time + dream.registry_up, dream.enclave = True, listed # back, and the built-in one retired: the registry decides again + assert bridge(**says("[[say three]]"))[0] == 200 and len(dream.billed) == 3 + + +def test_the_built_in_enclaves_are_the_apps_own(): + """chat-app's lib/api/backupTees.ts and chat-api's src/core/backup_tees.py list the same one.""" + assert [t.tee_id for t in enclaves.BUILT_IN] == ["0xe1443d7ed558fbd19117c4dc70e6245fc71d6063d64af3bc3f790081bc94e9aa"] + assert all(len(t.ohttp_public_key) == 32 for t in enclaves.BUILT_IN) + + +# ── what else the bridge answers ────────────────────────────────────────────── +@pytest.mark.parametrize("body", [b"", b"[]", b'"hi"', b"{", b"null"]) +def test_nonsense_is_turned_away(enclave, bridge, body): + req = urllib.request.Request(f"{bridge.url}/v1/chat/completions", body, {"Content-Type": "application/json"}) + with pytest.raises(urllib.error.HTTPError) as failed: + urllib.request.urlopen(req, timeout=5) + assert failed.value.code == 400 and enclave.seen == 0 + + +@pytest.mark.parametrize("asked", ["lots", -1, 0, 1.5, [], None]) +def test_a_nonsense_limit_is_the_usual_one(enclave, bridge, asked): + assert bridge(max_tokens=asked)[0] == 200 and enclave.accepted[0]["max_tokens"] == 32000 + + def test_the_bridge_says_which_process_it_is(bridge): with urllib.request.urlopen(bridge.url + "/healthz", timeout=5) as resp: assert (resp.read(), resp.headers["X-Ghost-Pid"]) == (b"ok", str(os.getpid())) @@ -315,5 +397,5 @@ def test_budget_survives_a_restart(monkeypatch, enclave, bridge): (["budget"], 0, "$5.00 per hour"), (["budget", "20"], 0, "$20.00 per hour"), (["budget", "off"], 0, "no limit"), (["budget", "-3"], 2, ""), (["usage"], 0, "Last hour"), ]) -def test_usage_commands(enclave, capsys, argv, code, words): +def test_usage_commands(bridge, capsys, argv, code, words): assert spend.main(argv) == code and words in capsys.readouterr().out diff --git a/tests/test_install.py b/tests/test_install.py index 90615e5..3fdf814 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", "outbound.py", "spend.py"] + assert sorted(p.name for p in privacy.iterdir() if p.suffix == ".py") == ["bridge.py", "doctor.py", "enclaves.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_login.py b/tests/test_login.py index 98ecfad..a160121 100644 --- a/tests/test_login.py +++ b/tests/test_login.py @@ -294,6 +294,7 @@ def machine(dream, tmp_path, monkeypatch): monkeypatch.setattr(spend, "_entries", [(time.time(), 0.21)]) monkeypatch.setattr(spend, "BUDGET_FILE", tmp_path / "budget") monkeypatch.setattr(spend, "LEDGER", tmp_path / "spend.jsonl") + monkeypatch.setattr("enclaves.Enclaves.listed", lambda self: 3) return doctor @@ -301,7 +302,7 @@ def test_doctor_when_all_is_well(dream, machine, capsys): ghost_auth.save_account(dream.bundle()) assert machine.main() == 0 out = capsys.readouterr().out - for words in ("✓ Engine Ghost v9 (stub)", "✓ Login DreamFort account (mara@example.com)", "✓ Bridge running", "✓ DreamFort reachable", + for words in ("✓ Engine Ghost v9 (stub)", "✓ Login DreamFort account (mara@example.com)", "✓ Bridge running", "✓ DreamFort reachable", "✓ Enclaves 3 in the registry", "✓ Credits $12.50 left", "✓ Spending $0.21 of $5.00"): assert words in out assert [s[1] for s in dream.seen] == ["/api/v1/chat/ohttp/config", "/api/v1/credits/balance"] # and no model @@ -328,6 +329,17 @@ def test_doctor_says_what_is_wrong_and_what_to_do(dream, machine, monkeypatch, c assert machine.main() == 1 and words in capsys.readouterr().out +def test_doctor_when_the_registry_is_down(dream, machine, monkeypatch, capsys): + """Nothing to fix here: ghost has a fallback.""" + import enclaves + + def down(self): + raise enclaves.RegistryError("502") + monkeypatch.setattr("enclaves.Enclaves.listed", down) + ghost_auth.save_account(dream.bundle()) + assert machine.main() == 0 and "· Enclaves the registry can't be read right now" in capsys.readouterr().out + + def test_usage_shows_what_is_left(dream, machine, capsys): import spend spend.main(["usage"]) diff --git a/tests/test_outbound.py b/tests/test_outbound.py index 46c3ff4..7f16999 100644 --- a/tests/test_outbound.py +++ b/tests/test_outbound.py @@ -71,11 +71,20 @@ def test_the_bridge_reads_the_registry_that_way(monkeypatch): 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)) + sealing = httpx.MockTransport(lambda request: None) + monkeypatch.setattr(bridge, "OHTTPTransport", lambda **options: made.update(options) or sealing) 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 + from opengradient_ohttp import DEFAULT_RPC_URL + assert made["transport"] == ("https://relay.example/x", {}) + assert sealing._resolver._transport == (DEFAULT_RPC_URL, {"public_only": True}) and sealing._resolver._rpc_url == DEFAULT_RPC_URL + + +def test_the_sealing_takes_its_enclaves_from_there(): + """ghost sets this attribute of opengradient-ohttp's transport; a release that moves it must not go unnoticed.""" + pytest.importorskip("opengradient_ohttp") + from opengradient_ohttp import OHTTPTransport + from opengradient_ohttp._registry import TeeResolver + assert type(OHTTPTransport()._resolver) is TeeResolver def test_an_engine_reaches_the_bridge_without_the_proxy(monkeypatch):