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
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,39 @@ The field is inside the encrypted body, so nothing between the client and the
enclave can add or remove it, and a Gateway that predates it rejects the
envelope rather than ignoring it.

Every successful confidential response declares where the enclave sent the
request, in a top-level `nexus_route` object: in the JSON body, or in the
first event of a stream.

```json
"nexus_route": {
"version": 1,
"request_id": "6f1c1d2e-8a51-4c6b-9a43-0d2f7f0b9b11",
"requested_model": "nexus/auto",
"model": "minimax/minimax-m2.7",
"router": "nexus/auto",
"provider": "novita",
"upstream_host": "api.novita.ai",
"upstream_model": "minimax/minimax-m2.7",
"fallback": false
}
```

`request_id` repeats the envelope's. `model` is the public model that
answered, `router` is set when a router chose it, and `fallback` when the
model's fallback provider served the request. `upstream_host` is the host the
request went to (for Tinfoil, the enclave the Gateway verified) and
`upstream_model` the exact model name sent there; the response's own `model`
field names the public model. Which provider and upstream model serve a public
model is catalog data from Metering, outside the enclave's measurements. The
declaration doesn't fix that mapping. It makes the mapping visible on every
response. The response is encrypted to keys only the client and the enclave
hold, so the attested code writes the declaration and nothing outside the
enclave can change it. A provider's own `nexus_route` field is replaced. A
request whose route can't be declared fails rather than answering without it.
It declares where the request went, not what the provider ran: that needs the
provider's own attestation, as with Tinfoil.

PII masking covers conversation text, tool results, assistant reasoning, tool-call
argument string values, and `user`. Tool definitions, names, IDs, schemas,
metadata, provider options, and image/audio content are not scanned. Keep
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,9 +200,11 @@ func (h *ConfidentialChatCompletionsHandler) handleDecrypted(w http.ResponseWrit
// The downstream handler rechecks authentication and remains responsible for
// OpenAI validation, generation, and streaming. Only replace the
// decrypted envelope with its exact nested OpenAI request object.
ctx := domain.WithRouteDeclaration(r.Context(), envelope.RequestID)
if envelope.RequireAttestedInference {
r = r.WithContext(domain.WithAttestedInference(r.Context()))
ctx = domain.WithAttestedInference(ctx)
}
r = r.WithContext(ctx)
r.Body = io.NopCloser(bytes.NewReader(envelope.Request))
r.ContentLength = int64(len(envelope.Request))
r.Header.Del("Content-Length")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
package handlers_test

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"

"github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/adapters/http/handlers"
"github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/adapters/providers/openai"
"github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/adapters/providers/registry"
"github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/application/services"
"github.com/dappnode/dappnode-nexus-gateway/pkg/domain"
"github.com/google/uuid"
"github.com/tinfoilsh/encrypted-http-body-protocol/identity"
)

// End to end through the confidential endpoint, the chat handler, the
// service and the production OpenAI adapter against a local upstream: the
// decrypted response declares where the request went. Only auth, catalog and
// metering are faked.
func TestConfidentialResponseDeclaresRoute(t *testing.T) {
t.Setenv("NEXUS_ROUTE_TEST_PROVIDER_API_KEY", "local-test-only")
for _, stream := range []bool{false, true} {
t.Run(fmt.Sprintf("stream=%v", stream), func(t *testing.T) {
var upstreamModel string
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var request struct {
Model string `json:"model"`
}
_ = json.NewDecoder(r.Body).Decode(&request)
upstreamModel = request.Model
if !stream {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"id":"chatcmpl-1","model":"local-upstream","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`)
return
}
w.Header().Set("Content-Type", "text/event-stream")
_, _ = io.WriteString(w, "data: {\"id\":\"chatcmpl-1\",\"model\":\"local-upstream\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"ok\"}}]}\n\n"+
"data: {\"id\":\"chatcmpl-1\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n"+
"data: {\"id\":\"chatcmpl-1\",\"choices\":[],\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":1,\"total_tokens\":2}}\n\n"+
"data: [DONE]\n\n")
}))
defer upstream.Close()
upstreamURL, err := url.Parse(upstream.URL)
if err != nil {
t.Fatal(err)
}

model := domain.PublicModel{
PublicModelID: "vendor/model", ProviderModelID: "provider-model", UpstreamModelName: "local-upstream", Active: true,
SupportsChatCompletions: true,
ProviderConfig: domain.ProviderConfig{
ProviderName: "novita", BaseURL: upstream.URL + "/openai",
APIKeySecretRef: "NEXUS_ROUTE_TEST_PROVIDER_API_KEY",
},
}
logger := &mockLogger{}
providers := registry.NewRegistry()
providers.Register("novita", openai.NewAdapter(5*time.Second))
auth := &mockAuthService{authCtx: domain.AuthContext{
Account: domain.Account{ID: "account-1", Status: domain.AccountStatusActive},
APIKey: domain.APIKey{ID: "key-1", Active: true},
}}
generate := services.NewGenerateService(auth, &mockModelCatalog{model: model}, nil, providers, &mockUsageMeter{}, nil, logger)
chat := handlers.NewChatCompletionsHandler(services.NewChatCompletionsService(generate, logger), logger)
serverIdentity, err := identity.NewIdentity()
if err != nil {
t.Fatal(err)
}
confidential, err := handlers.NewConfidentialChatCompletionsHandler(serverIdentity, auth, http.HandlerFunc(chat.Handle), logger)
if err != nil {
t.Fatal(err)
}
clientIdentity, err := identity.FromPublicKeyBytes(serverIdentity.MarshalPublicKey())
if err != nil {
t.Fatal(err)
}

requestID := uuid.NewString()
envelope := fmt.Sprintf(`{"schema_version":1,"request_id":%q,"issued_at":%q,"request":{"model":"vendor/model","stream":%v,"messages":[{"role":"user","content":"hi"}]}}`,
requestID, time.Now().UTC().Format(time.RFC3339), stream)
request := httptest.NewRequest(http.MethodPost, "/v1/confidential/chat/completions", strings.NewReader(envelope))
request.Header.Set("Authorization", "Bearer local-test-only")
request.Header.Set("Content-Type", "application/json")
requestContext, err := clientIdentity.EncryptRequestWithContext(request)
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
confidential.Handle(recorder, request)

if bytes.Contains(recorder.Body.Bytes(), []byte(domain.RouteDeclarationField)) {
t.Fatal("the declaration is visible outside the encrypted response")
}
response := recorder.Result()
if err := requestContext.DecryptResponse(response); err != nil {
t.Fatalf("decrypt response: %v (status %d)", err, recorder.Code)
}
body, err := io.ReadAll(response.Body)
if err != nil {
t.Fatal(err)
}
if recorder.Code != http.StatusOK {
t.Fatalf("status %d: %s", recorder.Code, body)
}
if upstreamModel != "local-upstream" {
t.Fatalf("upstream got model %q", upstreamModel)
}

object := body
if stream {
if got := bytes.Count(body, []byte(domain.RouteDeclarationField)); got != 1 {
t.Fatalf("declarations in stream = %d, want 1:\n%s", got, body)
}
line, _, _ := strings.Cut(string(body), "\n")
first, ok := strings.CutPrefix(line, "data: ")
if !ok {
t.Fatalf("first line = %q", line)
}
object = []byte(first)
}
var decoded struct {
Model string `json:"model"`
Route struct {
Version int `json:"version"`
RequestID string `json:"request_id"`
RequestedModel string `json:"requested_model"`
Model string `json:"model"`
Router string `json:"router"`
Provider string `json:"provider"`
UpstreamHost string `json:"upstream_host"`
UpstreamModel string `json:"upstream_model"`
Fallback bool `json:"fallback"`
} `json:"nexus_route"`
}
if err := json.Unmarshal(object, &decoded); err != nil {
t.Fatalf("decode %s: %v", object, err)
}
route := decoded.Route
if decoded.Model != "vendor/model" || route.Version != 1 || route.RequestID != requestID ||
route.RequestedModel != "vendor/model" || route.Model != "vendor/model" || route.Router != "" ||
route.Provider != "novita" || route.UpstreamHost != upstreamURL.Host ||
route.UpstreamModel != "local-upstream" || route.Fallback {
t.Fatalf("response %s does not declare the route it took", object)
}
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ import (

// attestedStubProvider is a provider whose adapter verifies its upstream's
// attestation, like the Tinfoil adapter. withoutProof models an adapter that
// sends a request but returns no proof of the transport it used.
// sends a request but returns no proof of the transport it used; enclaveHost
// is the host its proof names.
type attestedStubProvider struct {
stubProvider
withoutProof bool
enclaveHost string
}

func (*attestedStubProvider) AttestedTransport() bool { return true }
Expand All @@ -25,7 +27,11 @@ func (p *attestedStubProvider) proof() *domain.TinfoilTransportProof {
if p.withoutProof {
return nil
}
return &domain.TinfoilTransportProof{Provider: "attested", Status: domain.ProofStatusVerified}
proof := &domain.TinfoilTransportProof{Provider: "attested", Status: domain.ProofStatusVerified}
if p.enclaveHost != "" {
proof.EnclaveHost = &p.enclaveHost
}
return proof
}

func (p *attestedStubProvider) Complete(ctx context.Context, raw []byte, model domain.PublicModel) ([]byte, *domain.TinfoilTransportProof, error) {
Expand Down
50 changes: 44 additions & 6 deletions apps/gateway/internal/application/services/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,11 @@ func (s *GenerateService) Proxy(ctx context.Context, endpoint string, raw []byte
"provider", target.ProviderConfig.ProviderName, "pii_mode", authCtx.APIKey.PIIMode)
}

attempt := func(target domain.PublicModel) (*ProxyCall, error) {
// A confidential request gets, inside its encrypted response, where the
// enclave sent it; see domain.WithRouteDeclaration.
declarer := newRouteDeclarer(ctx, req, execReq)

attempt := func(target domain.PublicModel, fallback bool) (*ProxyCall, error) {
if err := s.validateRequest(endpoint, execReq, target); err != nil {
return nil, err
}
Expand All @@ -173,10 +177,14 @@ func (s *GenerateService) Proxy(ctx context.Context, endpoint string, raw []byte
return nil, domain.ErrProviderUnavailable(target.ProviderConfig.ProviderName).WithMeta(
"fault", domain.FaultNexus, "cause", domain.CauseProviderNotRegistered)
}
if attested && !attestedTransport(provider) {
verified := attestedTransport(provider)
if attested && !verified {
return nil, domain.ErrAttestedInferenceUnavailable(execReq.PublicModelID).WithMeta(
"provider", target.ProviderConfig.ProviderName)
}
if err := declarer.check(target, verified); err != nil {
return nil, errRouteDeclaration(target, err)
}
upstreamStart := time.Now()
if !execReq.Stream {
body, proof, err := provider.Complete(ctx, masked, target)
Expand All @@ -197,6 +205,13 @@ func (s *GenerateService) Proxy(ctx context.Context, endpoint string, raw []byte
if err != nil {
return nil, err
}
declaration, err := declarer.declare(target, verified, proof, fallback)
if err == nil && declaration != nil {
rewritten, err = addRouteDeclaration(rewritten, declaration)
}
if err != nil {
return nil, errRouteDeclaration(target, err)
}
o.proof = proof
finish(target, o)
return &ProxyCall{Model: target, Body: rewritten}, nil
Expand All @@ -210,8 +225,14 @@ func (s *GenerateService) Proxy(ctx context.Context, endpoint string, raw []byte
resp.Body.Close()
return nil, errMissingTransportProof(target)
}
declaration, err := declarer.declare(target, verified, resp.Proof, fallback)
if err != nil {
resp.Body.Close()
return nil, errRouteDeclaration(target, err)
}
stream := newProxyStream(resp.Body, target.PublicModelID)
stream.proof = resp.Proof
stream.route = declaration
stream.hideUsage = !wantsUsage(raw)
stream.unmask = unmask(target)
// Nothing has reached the client yet: an upstream that fails before its
Expand All @@ -224,15 +245,15 @@ func (s *GenerateService) Proxy(ctx context.Context, endpoint string, raw []byte
return &ProxyCall{Model: target, Stream: stream}, nil
}

call, err := attempt(model)
call, err := attempt(model, false)
executed := model
if err != nil && clientCtx.Err() == nil && shouldTryFallback(ctx, err, model.Fallback) &&
withProviderTarget(model, *model.Fallback).SupportsEndpoint(endpoint) &&
(!attested || s.attestedTarget(model.Fallback.ProviderConfig.ProviderName)) {
executed = withProviderTarget(model, *model.Fallback)
s.logFallback(requestID, model, executed, sanitizeErrorWithPIIMapping(err, mapping))
metrics.RecordFallback(endpoint, model.PublicModelID, model.ProviderConfig.ProviderName, executed.ProviderConfig.ProviderName, err)
call, err = attempt(executed)
call, err = attempt(executed, true)
}
if err != nil {
defer stopLease()
Expand Down Expand Up @@ -475,6 +496,10 @@ type ProxyStream struct {
skipBlank bool
// unmask restores PII placeholders, for keys that mask.
unmask *unmasker
// route is the route declaration, added to the first event the client
// gets; routeSent records that it was.
route []byte
routeSent bool

o outcome
sawDone bool
Expand Down Expand Up @@ -575,7 +600,14 @@ func (p *ProxyStream) observe(raw []byte) ([][]byte, *chunk) {
if p.unmask != nil && len(c.Choices) > 0 {
data = p.unmask.event(data)
}
return [][]byte{append(append([]byte(nil), prefix...), rewriteModel(data, &c, p.public)...)}, &c
data = rewriteModel(data, &c, p.public)
if p.route != nil && !p.routeSent && !p.hides(&c) {
if declared, err := addRouteDeclaration(data, p.route); err == nil {
data = declared
p.routeSent = true
}
}
return [][]byte{append(append([]byte(nil), prefix...), data...)}, &c
}

// dropRepeatedRole removes a role the stream already sent for a choice, as
Expand Down Expand Up @@ -639,13 +671,19 @@ func (p *ProxyStream) keep(line []byte, c *chunk) bool {
return false
}
p.skipBlank = false
if p.hideUsage && c != nil && len(c.Choices) == 0 && c.Usage != nil && len(c.Error) == 0 {
if c != nil && p.hides(c) {
p.skipBlank = true
return false
}
return true
}

// hides reports whether an event is a usage-only one the client didn't ask
// for.
func (p *ProxyStream) hides(c *chunk) bool {
return p.hideUsage && len(c.Choices) == 0 && c.Usage != nil && len(c.Error) == 0
}

// Next returns the next line to send, without its newline. At the end it
// returns io.EOF (clean) or the read error.
func (p *ProxyStream) Next() ([]byte, error) {
Expand Down
Loading
Loading