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
96 changes: 72 additions & 24 deletions tee_gateway/controllers/ohttp_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,16 @@
Billing channel for the relay (both modes settle the real cost via x402
against the relay's x-payment; the gateway is the source of truth for the
amount):
* stream=false: outer headers expose ONLY the settled cost —
* stream=false: outer headers expose the settled cost —
X-Inference-Cost-OPG (smallest units, the integer x402 actually charged)
and X-Inference-Cost-USD (the equivalent USD at the price used). No
model name, no token counts: those would be a fingerprint of the
inner request and have no role in billing.
and X-Inference-Cost-USD (the equivalent USD at the price used) — and
the request's usage, X-Inference-Model, X-Inference-Input-Tokens and
X-Inference-Output-Tokens, so the relay can report usage to its
customer.
* stream=true: outer response headers are flushed before any body chunk
is yielded, so cost isn't known at header-write time. The relay reads
the settled amount from x402: either by querying the facilitator with
its X-Upto-Session, or via X-Payment-Response on its next request. The
is yielded, so cost isn't known at header-write time. The gateway
splices a private plaintext billing frame (the same cost and usage
fields) in before the final sealed chunk, which the relay strips. The
client still sees cost in the final SSE event inside the encrypted
stream (the ``opengradient`` block written by the chat controller).

Expand All @@ -41,19 +42,20 @@
request.
* The ENCLAVE decrypts the inner payload, forwards the request to its own
chat endpoint with the relay's ``x-payment`` header, and returns. The
relay sees status and settlement headers and, for non-stream, the outer
``X-Inference-Cost-OPG`` / ``X-Inference-Cost-USD`` billing headers, but
relay sees status and settlement headers and the cost, model and token
counts (outer headers for non-stream, the billing frame for stream), but
never sees the inner prompt or completion.

Privacy properties:
* Relay (network position): terminates the client's TCP/TLS connection,
so the relay DOES see the client's IP at the network layer — that's
unavoidable. What the relay does NOT see is the request/response
content: it observes only the OHTTP-encapsulated ciphertext, its own
wallet's x-payment material, and (single-shot only) the settled-cost
outer headers it needs to bill its own customer. Model name and token
counts are deliberately NOT surfaced — they'd fingerprint the inner
request without adding anything billing-relevant.
wallet's x-payment material, and the settled cost, model and
input/output token counts it needs to bill and report usage to its own
customer. These say which model ran and how long the prompt and reply
were (which the ciphertext sizes already approximate); they say nothing
about content.
* Enclave (compute position): sees the plaintext prompt and completion
(they are decrypted inside the enclave to run the LLM call), but at
the network layer it only sees the RELAY's IP — never the client's.
Expand All @@ -80,6 +82,7 @@

from tee_gateway import ohttp
from tee_gateway.tee_manager import get_tee_keys
from tee_gateway.model_registry import get_model_config
from tee_gateway.pricing import SessionCost
from tee_gateway.body_preread import MAX_PAID_REQUEST_BYTES

Expand Down Expand Up @@ -230,9 +233,10 @@ def _build_outer_response(
inner_content_type: str,
) -> Response:
"""Single-shot OHTTP response. Seals the body on 2xx (contains user
prompts/completions) and surfaces only extracted cost/price headers as
outer headers for relay billing (including `X-Inference-Price-OPG-USD`);
usage details remain sealed in the encapsulated body. Non-2xx bodies
prompts/completions) and surfaces only extracted cost/price, model and
token count headers as outer headers for relay billing (including
`X-Inference-Price-OPG-USD`); everything else remains sealed in the
encapsulated body. Non-2xx bodies
(x402 payment requirements, validation errors) are forwarded as
plaintext so the relay can act on them."""
# Keep headers as a list of (name, value) tuples — WSGI gives us a list
Expand Down Expand Up @@ -351,9 +355,8 @@ def _drain(sub_iter: Iterator[bytes]) -> bytes:

def _extract_cost_headers(body_bytes: bytes) -> dict[str, str]:
"""Project the response's ``opengradient`` cost block onto outer headers
for the relay's billing pipeline. Cost is the only metadata the relay
needs — model name and token counts stay sealed (they'd fingerprint the
inner request without being billing-relevant). The price is surfaced too
for the relay's billing pipeline, with the model and token counts it
reports as usage when the response has them. The price is surfaced too
so the relay (and downstream auditors) can verify
``cost_usd == cost_opg / 10^decimals * opg_price_usd`` without trusting us.
"""
Expand All @@ -374,19 +377,64 @@ def _extract_cost_headers(body_bytes: bytes) -> dict[str, str]:
)
return {}
wire = cost.model_dump(mode="json")
return {
headers = {
"X-Inference-Cost-OPG": wire["cost_opg"],
"X-Inference-Cost-USD": wire["cost_usd"],
"X-Inference-Price-OPG-USD": wire["opg_price_usd"],
}
for key, value in _usage_fields(body).items():
headers[_USAGE_HEADERS[key]] = value
return headers


# Outer header for each usage field on the non-streaming path; the streaming
# billing frame carries the same fields under these keys.
_USAGE_HEADERS = {
"model": "X-Inference-Model",
"input_tokens": "X-Inference-Input-Tokens",
"output_tokens": "X-Inference-Output-Tokens",
}


def _usage_fields(response_json: dict[str, Any]) -> dict[str, str]:
"""What the relay reports as usage for this response: the model and the
input and output token counts. Strings, like the cost fields, so every
value on the billing channel has one type.

``model`` is the registry's name for the response's model (lowercased,
as pricing looks it up), and only a model the registry knows, so the
value is always one of a fixed set and safe as a header. Token counts come
from the OpenAI ``usage`` block, both or neither, so the relay never
records half a pair. Each is left out when the response doesn't carry it
(web search has neither).
"""
fields: dict[str, str] = {}
model = response_json.get("model")
if isinstance(model, str):
try:
get_model_config(model)
except ValueError:
pass
else:
fields["model"] = model.strip().lower()
usage = response_json.get("usage")
if isinstance(usage, dict):
counts = (usage.get("prompt_tokens"), usage.get("completion_tokens"))
if all(
isinstance(n, int) and not isinstance(n, bool) and n >= 0 for n in counts
):
fields["input_tokens"] = str(counts[0])
fields["output_tokens"] = str(counts[1])
return fields


def _build_billing_frame(response_json: dict[str, Any] | None) -> bytes:
"""Build the private gateway-to-relay billing frame for streaming OHTTP.

This plaintext frame carries only the same billing fields projected as
outer headers for non-streaming OHTTP. The relay strips it before forwarding
bytes to the browser.
This plaintext frame carries only the same fields projected as outer
headers for non-streaming OHTTP: the cost, and ``model`` /
``input_tokens`` / ``output_tokens`` when the response has them. The
relay strips it before forwarding bytes to the browser.
"""
if not isinstance(response_json, dict):
return b""
Expand All @@ -401,7 +449,7 @@ def _build_billing_frame(response_json: dict[str, Any] | None) -> bytes:
)
return b""
payload = json.dumps(
cost.model_dump(mode="json"),
cost.model_dump(mode="json") | _usage_fields(response_json),
separators=(",", ":"),
).encode("utf-8")
return OHTTP_BILLING_FRAME_MAGIC + len(payload).to_bytes(4, "big") + payload
Expand Down
144 changes: 141 additions & 3 deletions tee_gateway/test/test_ohttp_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@
* Non-2xx inner responses are forwarded as plaintext (no HPKE seal),
with the inner content-type and the x402-related headers preserved
* 2xx inner responses are sealed and the ``opengradient`` cost block is
projected onto outer X-Inference-Cost-* headers
projected onto outer X-Inference-Cost-* headers, with the registry model
name as X-Inference-Model and the ``usage`` token counts as
X-Inference-Input-Tokens / X-Inference-Output-Tokens
* The streaming billing frame carries the same cost, model and token counts
* Streaming inner responses emit exactly one AAD=b"final" chunk and
close the inner WSGI iterator (settles x402)
"""
Expand Down Expand Up @@ -271,7 +274,9 @@ def test_2xx_inner_response_is_sealed_with_cost_headers(monkeypatch):

inner_payload = {
"id": "chatcmpl-xyz",
"model": "GPT-4.1",
"choices": [{"message": {"role": "assistant", "content": "hi"}}],
"usage": {"prompt_tokens": 12, "completion_tokens": 34, "total_tokens": 46},
"opengradient": {
"cost_opg": 1234567890,
"cost_usd": "0.001234",
Expand Down Expand Up @@ -299,11 +304,14 @@ def inner():

assert resp.status_code == 200
assert resp.content_type.startswith(ohttp_controller.OHTTP_RESPONSE_MEDIA_TYPE)
# Cost is projected onto outer headers — relay-billable, no model name
# and no token counts leak.
# Cost, model and token counts are projected onto outer headers for the
# relay's billing and usage; the model as the registry names it.
assert resp.headers["X-Inference-Cost-OPG"] == "1234567890"
assert Decimal(resp.headers["X-Inference-Cost-USD"]) == Decimal("0.001234")
assert Decimal(resp.headers["X-Inference-Price-OPG-USD"]) == Decimal("1.234")
assert resp.headers["X-Inference-Input-Tokens"] == "12"
assert resp.headers["X-Inference-Output-Tokens"] == "34"
assert resp.headers["X-Inference-Model"] == "gpt-4.1"
# x402 / TEE headers still pass through.
assert resp.headers.get("X-Tee-Signature") == "sig"
assert resp.headers.get("X-Payment-Response") == "settled"
Expand Down Expand Up @@ -336,6 +344,136 @@ def inner():
assert resp.status_code == 200
assert "X-Inference-Cost-OPG" not in resp.headers
assert "X-Inference-Cost-USD" not in resp.headers
assert "X-Inference-Model" not in resp.headers
assert "X-Inference-Input-Tokens" not in resp.headers
assert "X-Inference-Output-Tokens" not in resp.headers


# ---------------------------------------------------------------------------
# Model and token counts on the relay's billing channel

_COST_BLOCK = {"cost_opg": "1000", "cost_usd": "0.001", "opg_price_usd": "1"}


def _frame_json(frame: bytes) -> dict:
magic = ohttp_controller.OHTTP_BILLING_FRAME_MAGIC
assert frame.startswith(magic)
length = int.from_bytes(frame[len(magic) : len(magic) + 4], "big")
payload = frame[len(magic) + 4 :]
assert len(payload) == length
return json.loads(payload)


def test_cost_headers_carry_token_counts_only_with_valid_usage():
def headers(usage):
body = {"opengradient": _COST_BLOCK}
if usage is not None:
body["usage"] = usage
return ohttp_controller._extract_cost_headers(json.dumps(body).encode())

with_usage = headers({"prompt_tokens": 7, "completion_tokens": 0})
assert with_usage["X-Inference-Input-Tokens"] == "7"
assert with_usage["X-Inference-Output-Tokens"] == "0"

# No usage (web search), half a pair, or junk: cost only, no token headers.
for usage in (
None,
{"prompt_tokens": 7},
{"prompt_tokens": -1, "completion_tokens": 2},
{"prompt_tokens": "7", "completion_tokens": 2},
{"prompt_tokens": True, "completion_tokens": 2},
[7, 2],
):
got = headers(usage)
assert got["X-Inference-Cost-OPG"] == "1000", usage
assert "X-Inference-Input-Tokens" not in got, usage
assert "X-Inference-Output-Tokens" not in got, usage


def test_cost_headers_carry_the_model_only_when_the_registry_knows_it():
def headers(model):
body = {"opengradient": _COST_BLOCK, "model": model}
return ohttp_controller._extract_cost_headers(json.dumps(body).encode())

assert headers(" GPT-4.1 ")["X-Inference-Model"] == "gpt-4.1"

# Unknown names, injected header text and non-strings never reach a header.
for model in ("not-a-model", "gpt-4.1\r\nX-Evil: 1", "", None, 4.1):
got = headers(model)
assert got["X-Inference-Cost-OPG"] == "1000", model
assert "X-Inference-Model" not in got, model


def test_billing_frame_carries_model_and_token_counts_as_strings():
frame = ohttp_controller._build_billing_frame(
{
"opengradient": _COST_BLOCK,
"model": "gpt-4.1",
"usage": {"prompt_tokens": 12, "completion_tokens": 34},
}
)

assert _frame_json(frame) == {
"cost_opg": "1000",
"cost_usd": "0.001",
"opg_price_usd": "1",
"model": "gpt-4.1",
"input_tokens": "12",
"output_tokens": "34",
}


def test_billing_frame_without_model_or_usage_carries_cost_only():
frame = ohttp_controller._build_billing_frame({"opengradient": _COST_BLOCK})

assert _frame_json(frame) == {
"cost_opg": "1000",
"cost_usd": "0.001",
"opg_price_usd": "1",
}


def test_streamed_response_splices_billing_frame_with_usage(monkeypatch):
sk, wire, _, _ = _encapsulate(b'{"model":"gpt-4.1","stream":true}')
final_event = {
"choices": [],
"model": "gpt-4.1",
"usage": {"prompt_tokens": 5, "completion_tokens": 9, "total_tokens": 14},
"opengradient": _COST_BLOCK,
}
sse_chunks = [
b'data: {"a":1}\n\n',
b"data: " + json.dumps(final_event).encode() + b"\n\n",
b"data: [DONE]\n\n",
]

def inner():
return (
"200 OK",
[("Content-Type", "text/event-stream")],
_CloseTrackingIter(sse_chunks),
)

app, _, fake_keys = _make_app(inner, sk)
monkeypatch.setattr(ohttp_controller, "get_tee_keys", fake_keys)

resp = app.test_client().post(
"/v1/ohttp", data=wire, content_type="message/ohttp-req"
)

body = resp.get_data()
start = body.index(ohttp_controller.OHTTP_BILLING_FRAME_MAGIC)
magic_len = len(ohttp_controller.OHTTP_BILLING_FRAME_MAGIC)
length = int.from_bytes(body[start + magic_len : start + magic_len + 4], "big")
frame = body[start : start + magic_len + 4 + length]
parsed = _frame_json(frame)
assert parsed["model"] == "gpt-4.1"
assert parsed["input_tokens"] == "5"
assert parsed["output_tokens"] == "9"
# Usage never rides the outer headers on the streaming path: those were
# flushed before the reply existed.
assert "X-Inference-Model" not in resp.headers
assert "X-Inference-Input-Tokens" not in resp.headers


# ---------------------------------------------------------------------------
Expand Down
Loading