-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathproxy.go
More file actions
2314 lines (2120 loc) · 82 KB
/
Copy pathproxy.go
File metadata and controls
2314 lines (2120 loc) · 82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package proxy implements the teep HTTP proxy server. It sits between an
// OpenAI-compatible client and a TEE-capable AI backend (Venice, NEAR AI),
// performing attestation verification and optional E2EE on every request.
//
// Request flow for POST /v1/chat/completions:
//
// 1. Parse model name from request body.
// 2. Resolve model → provider. Unknown model → 400.
// 3. Check negative cache. Blocked → 503.
// 4. Check attestation cache. On miss, fetch + verify + cache.
// 5. Any enforced factor Fail (not in allow_fail) → 502 with report JSON.
// 6. If E2EE and tdx_reportdata_binding Pass: encrypt messages, set headers.
// If E2EE required but binding fails: block request (no plaintext fallback).
// 7. Forward to upstream. Parse streaming SSE or buffer non-streaming body.
// 8. Decrypt each chunk (E2EE). Abort on any decryption failure.
// 9. Re-emit SSE to client (streaming) or return assembled JSON (non-streaming).
//
// 10. Zero session key material.
package proxy
import (
"bytes"
"context"
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"mime"
"mime/multipart"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/13rac1/teep/internal/attestation"
"github.com/13rac1/teep/internal/config"
"github.com/13rac1/teep/internal/defaults"
"github.com/13rac1/teep/internal/e2ee"
"github.com/13rac1/teep/internal/multi"
"github.com/13rac1/teep/internal/provider"
chutesProvider "github.com/13rac1/teep/internal/provider/chutes"
"github.com/13rac1/teep/internal/provider/nanogpt"
"github.com/13rac1/teep/internal/provider/nearcloud"
"github.com/13rac1/teep/internal/provider/neardirect"
"github.com/13rac1/teep/internal/provider/phalacloud"
"github.com/13rac1/teep/internal/provider/venice"
"github.com/13rac1/teep/internal/reqid"
"github.com/13rac1/teep/internal/tlsct"
"github.com/google/go-tdx-guest/verify/trust"
)
const (
// attestationCacheTTL is how long a VerificationReport is considered fresh.
// Uses the shared AttestationCacheTTL so all attestation caches expire together.
attestationCacheTTL = attestation.AttestationCacheTTL
// negativeCacheTTL is how long a failed attestation blocks retries.
negativeCacheTTL = 30 * time.Second
// signingKeyCacheTTL is how long a REPORTDATA-verified signing key is
// reused for E2EE without re-fetching attestation. Uses the shared
// AttestationCacheTTL so all attestation caches expire together.
signingKeyCacheTTL = attestation.AttestationCacheTTL
// upstreamNonStreamTimeout is the context deadline for non-streaming
// upstream requests. Must be generous — attestation + E2EE setup can
// consume 20+ seconds before the upstream request even starts, and
// large models may need minutes to generate a full response.
upstreamNonStreamTimeout = 5 * time.Minute
// upstreamStreamTimeout is the context deadline for streaming upstream
// requests. Streaming responses can run for a long time.
upstreamStreamTimeout = 30 * time.Minute
// chutesMaxAttempts is the maximum number of Chutes E2EE upstream
// attempts. Retries attempt failover to a different instance from the
// nonce pool when available, with full E2EE re-encryption. Failover is
// acceptable because every instance's key is verified via TDX attestation
// before use.
chutesMaxAttempts = 3
)
// stats holds live operational counters for the status page.
// All fields are read/written atomically — no mutex needed.
type stats struct {
startTime time.Time
requests atomic.Int64
errors atomic.Int64
streaming atomic.Int64
nonStream atomic.Int64
e2ee atomic.Int64
plaintext atomic.Int64
cacheHits atomic.Int64
cacheMisses atomic.Int64
// HTTP transport counters (reported by countingTransport callbacks).
httpRequests atomic.Int64
httpErrors atomic.Int64
modelsMu sync.RWMutex
models map[string]*modelStats
}
// modelStats holds per-model counters.
type modelStats struct {
requests atomic.Int64
errors atomic.Int64
lastVerifyMs atomic.Int64 // last verification duration in ms
lastRequestAt atomic.Int64 // unix timestamp
lastTokCount atomic.Int64 // effective tokens from last request
lastTokDurMs atomic.Int64 // stream duration in milliseconds
}
// getModelStats returns (or creates) the modelStats for a provider/model key.
func (st *stats) getModelStats(prov, model string) *modelStats {
key := prov + "/" + model
st.modelsMu.RLock()
if ms, ok := st.models[key]; ok {
st.modelsMu.RUnlock()
return ms
}
st.modelsMu.RUnlock()
st.modelsMu.Lock()
defer st.modelsMu.Unlock()
if ms, ok := st.models[key]; ok {
return ms
}
ms := &modelStats{}
st.models[key] = ms
return ms
}
// recordTokPerSec stores raw token count and duration from StreamStats.
// Tokens/sec is computed at render time in buildDashboardData.
func recordTokPerSec(ms *modelStats, ss e2ee.StreamStats) {
if ss.Duration <= 0 {
return
}
ms.lastTokCount.Store(int64(ss.EffectiveTokens()))
ms.lastTokDurMs.Store(ss.Duration.Milliseconds())
}
// fmtDur formats a duration as seconds with 3 decimal places (e.g. "4.200s").
func fmtDur(d time.Duration) string {
return fmt.Sprintf("%.3fs", d.Seconds())
}
// extractMultipartField reads a single text field from multipart/form-data
// body bytes without consuming an http.Request body. Returns the field value
// or an error if the content-type is not multipart or the field is absent.
func extractMultipartField(contentType string, body []byte, fieldName string) (string, error) {
mediaType, params, err := mime.ParseMediaType(contentType)
if err != nil || !strings.HasPrefix(mediaType, "multipart/") {
return "", fmt.Errorf("not multipart content-type: %s", contentType)
}
boundary := params["boundary"]
if boundary == "" {
return "", errors.New("missing boundary in content-type")
}
mr := multipart.NewReader(bytes.NewReader(body), boundary)
for {
p, err := mr.NextPart()
if err != nil {
if errors.Is(err, io.EOF) {
return "", fmt.Errorf("field %q not found in multipart body", fieldName)
}
return "", err
}
if p.FormName() == fieldName {
const maxFieldSize = 1024
val, err := io.ReadAll(io.LimitReader(p, maxFieldSize+1))
if err != nil {
_ = p.Close()
return "", err
}
if err := p.Close(); err != nil {
return "", err
}
if len(val) > maxFieldSize {
return "", fmt.Errorf("field %q exceeds %d bytes", fieldName, maxFieldSize)
}
return string(val), nil
}
if err := p.Close(); err != nil {
return "", err
}
}
}
// chutesRetryableError returns true if the upstream error or response status
// indicates a Chutes instance-level failure that warrants failover to a
// different instance. Returns false for client-induced cancellations
// (context.Canceled) so we don't burn retries after the caller is gone.
//
// Note: 429 (Too Many Requests) is explicitly NOT retried. Chutes rate
// limits are account-level, not instance-level, so retrying with a
// different instance amplifies the rate limit and burns nonces uselessly.
func chutesRetryableError(err error, resp *http.Response) bool {
if err != nil {
if errors.Is(err, context.Canceled) {
return false // client disconnected; retrying is pointless
}
return true // connection error, timeout, etc.
}
if resp == nil {
return true
}
switch resp.StatusCode {
case http.StatusInternalServerError,
http.StatusBadGateway,
http.StatusServiceUnavailable,
http.StatusGatewayTimeout:
return true
}
return false
}
// respStatusCode returns the HTTP status code from a response, or 0 if nil.
func respStatusCode(resp *http.Response) int {
if resp == nil {
return 0
}
return resp.StatusCode
}
// upstreamBody holds the result of buildUpstreamBody: the encrypted (or
// plaintext) body, any E2EE session state, and Chutes instance tracking IDs
// for the retry loop's MarkFailed calls.
type upstreamBody struct {
Body []byte
Session e2ee.Decryptor
Meta *e2ee.ChutesE2EE
ChuteID string // For MarkFailed (from raw attestation, not meta)
InstanceID string // For MarkFailed (from raw attestation, not meta)
}
// zeroE2EESessions zeroes crypto material from a failed E2EE attempt.
func zeroE2EESessions(session e2ee.Decryptor, meta *e2ee.ChutesE2EE) {
if session != nil {
session.Zero()
}
if meta != nil && meta.Session != nil {
meta.Session.Zero()
}
}
// chatRequest is a minimal parse of an OpenAI chat completions request.
// Only fields the proxy needs to inspect or rewrite are decoded here.
type chatRequest struct {
Model string `json:"model"`
Messages []chatMessage `json:"messages"`
Stream bool `json:"stream"`
}
// chatMessage is one message in the chat history.
// Content is json.RawMessage because it may be a string (text) or an array
// (multimodal / vision-language). The proxy never inspects message content.
type chatMessage struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
}
// providerModelKey is used as the key in the e2eeFailed sync.Map.
type providerModelKey struct {
provider string
model string
}
// Server is the teep proxy HTTP server.
type Server struct {
cfg *config.Config
providers map[string]*provider.Provider // provider name → Provider
cache *attestation.Cache
negCache *attestation.NegativeCache
signingKeyCache *attestation.SigningKeyCache
spkiCache *attestation.SPKICache
rekorClient *attestation.RekorClient
nvidiaVerifier *attestation.NVIDIAVerifier
mux *http.ServeMux
attestClient *http.Client // for attestation fetches
collateral trust.HTTPSGetter // for Intel PCS collateral fetches
verifyQuote attestation.TDXVerifier // constructed from cfg.Offline + collateral
upstreamClient *http.Client // for chat completions forwards
sseConns atomic.Int64 // active SSE /events connections
e2eeFailed sync.Map // cacheKey → true; tracks provider+model pairs with E2EE decryption failures
breakers map[string]*circuitBreaker // provider name → circuit breaker; fixed at startup, no sync needed
stats stats
}
// New builds a Server from cfg. Providers are wired with their Attester and
// Preparer implementations based on provider name.
func New(cfg *config.Config) (*Server, error) {
spkiCache := attestation.NewSPKICache()
attestClient := tlsct.NewHTTPClientWithTransport(config.AttestationTimeout, &http.Transport{
MaxIdleConnsPerHost: 10,
IdleConnTimeout: 90 * time.Second,
}, !cfg.Offline)
s := &Server{
cfg: cfg,
providers: make(map[string]*provider.Provider, len(cfg.Providers)),
cache: attestation.NewCache(attestationCacheTTL),
negCache: attestation.NewNegativeCache(negativeCacheTTL),
signingKeyCache: attestation.NewSigningKeyCache(signingKeyCacheTTL),
spkiCache: spkiCache,
mux: http.NewServeMux(),
attestClient: attestClient,
stats: stats{startTime: time.Now(), models: make(map[string]*modelStats)},
}
onReq := func() { s.stats.httpRequests.Add(1) }
onErr := func() { s.stats.httpErrors.Add(1) }
attestClient.Transport = tlsct.WrapCounting(
tlsct.WrapLogging(attestClient.Transport),
onReq, onErr)
upstreamClient := tlsct.NewHTTPClientWithTransport(0, &http.Transport{
MaxIdleConnsPerHost: 10,
IdleConnTimeout: 90 * time.Second,
}, !cfg.Offline)
upstreamClient.Transport = tlsct.WrapCounting(
tlsct.WrapLogging(upstreamClient.Transport),
onReq, onErr)
s.upstreamClient = upstreamClient
s.rekorClient = attestation.NewRekorClient(attestClient)
s.nvidiaVerifier = attestation.DefaultNVIDIAVerifier()
s.collateral = attestation.NewCollateralGetter(s.attestClient)
s.verifyQuote = attestation.NewTDXVerifier(cfg.Offline, s.collateral)
for name, cp := range cfg.Providers {
mDefaults, gwDefaults := defaults.MeasurementDefaults(name)
mergedPolicy := config.MergedMeasurementPolicy(name, cfg, mDefaults)
mergedGWPolicy := config.MergedGatewayMeasurementPolicy(name, cfg, gwDefaults)
p, err := fromConfig(cp, spkiCache, cfg.Offline, config.MergedAllowFail(name, cfg, cfg.Offline), mergedPolicy, mergedGWPolicy, s.rekorClient, s.nvidiaVerifier, s.collateral)
if err != nil {
return nil, fmt.Errorf("provider %q: %w", name, err)
}
s.providers[name] = p
slog.Info("registered provider", "provider", name, "base_url", cp.BaseURL, "api_key", config.RedactKey(cp.APIKey), "e2ee", cp.E2EE)
}
if len(s.providers) == 0 {
return nil, errors.New("no providers configured")
}
s.breakers = make(map[string]*circuitBreaker, len(s.providers))
for name := range s.providers {
s.breakers[name] = &circuitBreaker{
threshold: defaultBreakerThreshold,
resetTimeout: defaultBreakerResetTimeout,
now: time.Now,
}
}
s.mux.HandleFunc("GET /{$}", s.handleIndex)
s.mux.HandleFunc("GET /events", s.handleEvents)
s.mux.HandleFunc("POST /v1/chat/completions", s.handleEndpoint(&chatEndpoint))
s.mux.HandleFunc("POST /v1/embeddings", s.handleEndpoint(&embeddingsEndpoint))
s.mux.HandleFunc("POST /v1/audio/transcriptions", s.handleEndpoint(&audioEndpoint))
s.mux.HandleFunc("POST /v1/images/generations", s.handleEndpoint(&imagesEndpoint))
s.mux.HandleFunc("POST /v1/rerank", s.handleEndpoint(&rerankEndpoint))
s.mux.HandleFunc("GET /v1/models", s.handleModels)
s.mux.HandleFunc("GET /v1/tee/report", s.handleReport)
return s, nil
}
// ListenAndServe starts the proxy HTTP server on the configured listen address.
// It blocks until ctx is cancelled (e.g. via signal.NotifyContext), then
// initiates a graceful shutdown with a 5-second deadline to drain in-flight
// requests (which zeros any active E2EE sessions via their defers).
func (s *Server) ListenAndServe(ctx context.Context) error {
srv := &http.Server{
Addr: s.cfg.ListenAddr,
Handler: s,
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 10 * time.Minute,
IdleTimeout: 120 * time.Second,
}
slog.Info("teep proxy listening", "addr", s.cfg.ListenAddr)
errCh := make(chan error, 1)
go func() { errCh <- srv.ListenAndServe() }()
select {
case err := <-errCh:
return err
case <-ctx.Done():
slog.Info("shutting down")
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
return srv.Shutdown(shutdownCtx)
}
}
// ServeHTTP implements http.Handler so Server can be used with httptest.NewServer.
// Unmatched routes are logged before returning 404.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
rec := &statusRecorder{ResponseWriter: w}
s.mux.ServeHTTP(rec, r)
if rec.status == http.StatusNotFound {
ctx := reqid.WithID(r.Context(), reqid.New())
slog.WarnContext(ctx, "unmatched route", "method", r.Method, "path", r.URL.Path)
}
}
// statusRecorder wraps http.ResponseWriter to capture the status code.
// It implements http.Flusher by delegating to the underlying writer.
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) Write(b []byte) (int, error) {
if r.status == 0 {
r.status = http.StatusOK
}
return r.ResponseWriter.Write(b)
}
func (r *statusRecorder) WriteHeader(code int) {
r.status = code
r.ResponseWriter.WriteHeader(code)
}
func (r *statusRecorder) Flush() {
if f, ok := r.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}
// fromConfig constructs a provider.Provider from a config.Provider, attaching
// the correct Attester, Preparer, and PinnedHandler for the known provider names.
func fromConfig(
cp *config.Provider,
spkiCache *attestation.SPKICache,
offline bool,
allowFail []string,
policy attestation.MeasurementPolicy,
gatewayPolicy attestation.MeasurementPolicy,
rekorClient *attestation.RekorClient,
nvidiaVerifier *attestation.NVIDIAVerifier,
getter trust.HTTPSGetter,
) (*provider.Provider, error) {
p := &provider.Provider{
Name: cp.Name,
BaseURL: cp.BaseURL,
APIKey: cp.APIKey,
E2EE: cp.E2EE,
MeasurementPolicy: policy,
GatewayMeasurementPolicy: gatewayPolicy,
}
switch cp.Name {
case "venice":
p.ChatPath = "/api/v1/chat/completions"
p.Attester = venice.NewAttester(cp.BaseURL, cp.APIKey, offline)
p.Preparer = venice.NewPreparer(cp.APIKey)
p.Encryptor = venice.NewE2EE()
p.ReportDataVerifier = venice.ReportDataVerifier{}
p.SupplyChainPolicy = venice.SupplyChainPolicy()
p.ModelLister = venice.NewModelLister(cp.BaseURL, cp.APIKey, config.NewAttestationClient(offline))
case "neardirect":
p.ChatPath = "/v1/chat/completions"
p.EmbeddingsPath = "/v1/embeddings"
p.AudioPath = "/v1/audio/transcriptions"
p.ImagesPath = "/v1/images/generations"
p.RerankPath = "/v1/rerank"
rdVerifier := neardirect.ReportDataVerifier{}
p.Attester = neardirect.NewAttester(cp.BaseURL, cp.APIKey, offline)
p.Preparer = neardirect.NewPreparer(cp.APIKey)
p.ReportDataVerifier = rdVerifier
p.SupplyChainPolicy = neardirect.SupplyChainPolicy()
resolver := neardirect.NewEndpointResolver(offline)
p.PinnedHandler = neardirect.NewPinnedHandler(
resolver,
spkiCache,
cp.APIKey,
offline,
allowFail,
policy,
rdVerifier,
rekorClient,
nvidiaVerifier,
getter,
)
p.SPKIDomainForModel = func(ctx context.Context, model string) (string, bool) {
d, err := resolver.Resolve(ctx, model)
if err != nil {
return "", false
}
return d, true
}
p.ModelLister = provider.NewFilteredModelLister(
"https://"+nearcloud.GatewayHost(), cp.APIKey,
config.NewAttestationClient(offline), resolver,
)
case "nearcloud":
p.ChatPath = "/v1/chat/completions"
p.ImagesPath = "/v1/images/generations"
// nearcloud non-chat E2EE: the gateway only forwards E2EE headers for
// chat completions and image generations. Embeddings (input), audio,
// and rerank fields would be sent in plaintext through a channel the
// user believes is E2EE. Non-chat paths (other than images) are not
// wired until the gateway is fixed to forward E2EE headers.
p.Encryptor = neardirect.NewE2EE()
rdVerifier := neardirect.ReportDataVerifier{}
p.Attester = nearcloud.NewAttester(cp.APIKey, offline)
p.Preparer = neardirect.NewPreparer(cp.APIKey)
p.ReportDataVerifier = rdVerifier
p.SupplyChainPolicy = nearcloud.SupplyChainPolicy()
p.PinnedHandler = nearcloud.NewPinnedHandler(
spkiCache,
cp.APIKey,
offline,
allowFail,
policy,
gatewayPolicy,
rdVerifier,
rekorClient,
nvidiaVerifier,
getter,
)
p.SPKIDomainForModel = func(_ context.Context, _ string) (string, bool) {
return nearcloud.GatewayHost(), true
}
p.ModelLister = provider.NewFilteredModelLister(
"https://"+nearcloud.GatewayHost(), cp.APIKey,
config.NewAttestationClient(offline), neardirect.NewEndpointResolver(offline),
)
case "nanogpt":
p.ChatPath = "/v1/chat/completions"
p.Attester = nanogpt.NewAttester(cp.BaseURL, cp.APIKey, offline)
p.ReportDataVerifier = multi.Verifier{
Verifiers: map[attestation.BackendFormat]provider.ReportDataVerifier{
attestation.FormatDstack: venice.ReportDataVerifier{},
},
}
p.SupplyChainPolicy = nanogpt.SupplyChainPolicy()
case "phalacloud":
p.ChatPath = "/chat/completions"
p.EmbeddingsPath = "/embeddings"
p.Attester = phalacloud.NewAttester(cp.BaseURL, cp.APIKey, offline)
p.Preparer = phalacloud.NewPreparer(cp.APIKey)
p.ModelLister = provider.NewModelLister(cp.BaseURL, cp.APIKey, config.NewAttestationClient(offline))
p.ReportDataVerifier = multi.Verifier{
Verifiers: map[attestation.BackendFormat]provider.ReportDataVerifier{
attestation.FormatDstack: venice.ReportDataVerifier{},
},
}
p.SupplyChainPolicy = nil // no supply chain policy yet
case "chutes":
p.BaseURL = chutesProvider.DefaultLLMBaseURL
p.ChatPath = "/v1/chat/completions"
p.EmbeddingsPath = "/v1/embeddings"
p.SkipSigningKeyCache = true
attester := chutesProvider.NewAttester(cp.BaseURL, cp.APIKey, offline)
p.Attester = attester
p.Encryptor = chutesProvider.NewE2EE()
p.Preparer = chutesProvider.NewPreparer(cp.APIKey, cp.BaseURL)
p.ReportDataVerifier = chutesProvider.ReportDataVerifier{}
p.SupplyChainPolicy = nil // cosign+IMA model, no docker-compose
p.ModelLister = chutesProvider.NewModelLister(chutesProvider.DefaultModelsBaseURL, cp.APIKey, config.NewAttestationClient(offline))
p.E2EEMaterialFetcher = chutesProvider.NewNoncePool(
cp.BaseURL, cp.APIKey, attester.Resolver(), config.NewAttestationClient(offline),
)
default:
return nil, fmt.Errorf("unknown provider %q (supported: venice, neardirect, nearcloud, nanogpt, phalacloud, chutes)", cp.Name)
}
// Invariant: any provider with a PinnedHandler must have SPKIDomainForModel
// so the proxy can evict SPKI entries when the attestation cache expires.
// This check prevents future providers from silently omitting the resolver.
if p.PinnedHandler != nil && p.SPKIDomainForModel == nil {
return nil, fmt.Errorf("provider %q has PinnedHandler but no SPKIDomainForModel; SPKI eviction would fail", cp.Name)
}
return p, nil
}
// resolveModel returns the provider for a client model. The model name is
// passed through to the upstream unchanged. With a single provider (the
// current production configuration), this is deterministic. Multi-provider
// routing by model name is not yet implemented; the first provider is returned.
func (s *Server) resolveModel(clientModel string) (*provider.Provider, string, bool) {
for _, p := range s.providers {
return p, clientModel, true
}
return nil, "", false
}
// fetchAndVerify fetches attestation from the provider and runs all
// verification factors. On failure it records the provider/model in the
// negative cache. Returns (nil, nil) on fetch error.
//
// The raw attestation is returned alongside the report so callers can reuse
// it for E2EE key exchange without a second round-trip. The REPORTDATA
// binding has already been verified against the raw's signing key.
func (s *Server) fetchAndVerify(ctx context.Context, prov *provider.Provider, upstreamModel string) (*attestation.VerificationReport, *attestation.RawAttestation) {
if prov.Attester == nil {
slog.ErrorContext(ctx, "provider has no Attester", "provider", prov.Name, "model", upstreamModel)
s.negCache.Record(prov.Name, upstreamModel)
return nil, nil
}
cb := s.breakers[prov.Name]
if !cb.allow() {
slog.WarnContext(ctx, "circuit breaker open; skipping attestation fetch", "provider", prov.Name)
// Also record in negCache so that the next request for this specific
// (provider, model) pair is rejected at the negCache.IsBlocked check
// before it even reaches fetchAndVerify. This avoids repeated mutex
// acquisitions on the circuit breaker for the same model while the
// circuit is open.
s.negCache.Record(prov.Name, upstreamModel)
return nil, nil
}
totalStart := time.Now()
nonce := attestation.NewNonce()
slog.DebugContext(ctx, "attestation fetch starting", "provider", prov.Name, "model", upstreamModel)
fetchStart := time.Now()
raw, err := prov.Attester.FetchAttestation(ctx, upstreamModel, nonce)
if err != nil {
slog.ErrorContext(ctx, "attestation fetch failed", "provider", prov.Name, "model", upstreamModel, "err", err)
// Do not count client-driven context terminations as provider failures.
// context.Canceled (client disconnect) and context.DeadlineExceeded
// (client-imposed timeout) both say nothing about provider health —
// the provider may be perfectly healthy. Counting them would let an
// attacker trip the circuit with threshold fire-and-disconnect or
// short-deadline requests. Use ctx.Err() to catch all context-error
// variants rather than enumerating specific sentinel values.
if ctx.Err() == nil {
cb.failure()
}
s.negCache.Record(prov.Name, upstreamModel)
return nil, nil
}
// success() is called on a clean network fetch, not contingent on
// verification passing. Verification failure (bad TDX quote, failed
// supply-chain check) means the TEE returned wrong content, not that
// the endpoint is unavailable. Requiring a non-blocked report before
// closing the circuit would keep it open indefinitely for a provider
// that consistently fails verification — which is a policy problem,
// not a reliability problem.
cb.success()
fetchDur := time.Since(fetchStart)
slog.DebugContext(ctx, "attestation fetch complete", "provider", prov.Name, "elapsed", fetchDur)
tdxResult, tdxDur := s.verifyTDX(ctx, raw, nonce, prov)
nvidiaResult, nvidiaDur := verifyNVIDIA(ctx, raw, nonce, prov.Name)
nrasResult, nrasDur := s.verifyNVIDIAOnline(ctx, raw, prov.Name)
pocResult, pocDur := s.verifyPoC(ctx, raw, prov.Name)
sc, composeDur := s.verifySupplyChain(ctx, raw, tdxResult)
totalDur := time.Since(totalStart)
slog.InfoContext(ctx, "verification complete",
"provider", prov.Name,
"model", upstreamModel,
"total", fmtDur(totalDur),
"fetch", fmtDur(fetchDur),
"tdx", fmtDur(tdxDur),
"nvidia", fmtDur(nvidiaDur),
"nras", fmtDur(nrasDur),
"poc", fmtDur(pocDur),
"compose", fmtDur(composeDur),
)
ms := s.stats.getModelStats(prov.Name, upstreamModel)
ms.lastVerifyMs.Store(totalDur.Milliseconds())
report := attestation.BuildReport(&attestation.ReportInput{
Provider: prov.Name,
Model: upstreamModel,
Raw: raw,
Nonce: nonce,
AllowFail: config.MergedAllowFail(prov.Name, s.cfg, s.cfg.Offline),
Policy: prov.MeasurementPolicy,
GatewayPolicy: prov.GatewayMeasurementPolicy,
SupplyChainPolicy: prov.SupplyChainPolicy,
ImageRepos: sc.ImageRepos,
DigestToRepo: sc.DigestToRepo,
TDX: tdxResult,
Nvidia: nvidiaResult,
NvidiaNRAS: nrasResult,
PoC: pocResult,
Compose: sc.Compose,
Sigstore: sc.Sigstore,
Rekor: sc.Rekor,
E2EEConfigured: prov.E2EE,
})
return report, raw
}
// verifyTDX runs TDX quote verification and REPORTDATA binding.
func (s *Server) verifyTDX(
ctx context.Context,
raw *attestation.RawAttestation,
nonce attestation.Nonce,
prov *provider.Provider,
) (*attestation.TDXVerifyResult, time.Duration) {
if raw.IntelQuote == "" {
return nil, 0
}
slog.DebugContext(ctx, "TDX verification starting", "provider", prov.Name)
start := time.Now()
result := s.verifyQuote(ctx, raw.IntelQuote)
if prov.ReportDataVerifier != nil && result.ParseErr == nil {
detail, err := prov.ReportDataVerifier.VerifyReportData(result.ReportData, raw, nonce)
if errors.Is(err, multi.ErrNoVerifier) {
slog.DebugContext(ctx, "no REPORTDATA verifier for backend format", "format", raw.BackendFormat)
} else {
result.ReportDataBindingErr = err
result.ReportDataBindingDetail = detail
}
}
dur := time.Since(start)
slog.DebugContext(ctx, "TDX verification complete", "provider", prov.Name, "elapsed", dur)
return result, dur
}
// verifyNVIDIA runs offline NVIDIA payload or GPU direct verification.
func verifyNVIDIA(
ctx context.Context,
raw *attestation.RawAttestation,
nonce attestation.Nonce,
provName string,
) (*attestation.NvidiaVerifyResult, time.Duration) {
if raw.NvidiaPayload != "" {
slog.DebugContext(ctx, "NVIDIA verification starting", "provider", provName)
start := time.Now()
result := attestation.VerifyNVIDIAPayload(ctx, raw.NvidiaPayload, nonce)
dur := time.Since(start)
slog.DebugContext(ctx, "NVIDIA verification complete", "provider", provName, "elapsed", dur)
return result, dur
}
if len(raw.GPUEvidence) > 0 {
slog.DebugContext(ctx, "NVIDIA GPU direct verification starting", "provider", provName, "gpus", len(raw.GPUEvidence))
serverNonce, err := attestation.ParseNonce(raw.Nonce)
if err != nil {
return &attestation.NvidiaVerifyResult{
SignatureErr: fmt.Errorf("parse server nonce: %w", err),
}, 0
}
start := time.Now()
result := attestation.VerifyNVIDIAGPUDirect(ctx, raw.GPUEvidence, serverNonce)
dur := time.Since(start)
slog.DebugContext(ctx, "NVIDIA GPU direct verification complete", "provider", provName, "elapsed", dur)
return result, dur
}
return nil, 0
}
// verifyNVIDIAOnline runs NVIDIA NRAS online verification.
func (s *Server) verifyNVIDIAOnline(
ctx context.Context,
raw *attestation.RawAttestation,
provName string,
) (*attestation.NvidiaVerifyResult, time.Duration) {
if s.cfg.Offline {
return nil, 0
}
if raw.NvidiaPayload != "" && raw.NvidiaPayload[0] == '{' {
slog.DebugContext(ctx, "NVIDIA NRAS verification starting", "provider", provName)
start := time.Now()
result := s.nvidiaVerifier.VerifyNRAS(ctx, raw.NvidiaPayload, s.attestClient)
dur := time.Since(start)
slog.DebugContext(ctx, "NVIDIA NRAS verification complete", "provider", provName, "elapsed", dur)
return result, dur
}
if len(raw.GPUEvidence) > 0 {
slog.DebugContext(ctx, "NVIDIA NRAS verification starting (synthesized EAT)", "provider", provName)
eatJSON := attestation.GPUEvidenceToEAT(raw.GPUEvidence, raw.Nonce)
start := time.Now()
result := s.nvidiaVerifier.VerifyNRAS(ctx, eatJSON, s.attestClient)
dur := time.Since(start)
slog.DebugContext(ctx, "NVIDIA NRAS verification complete (synthesized EAT)", "provider", provName, "elapsed", dur)
return result, dur
}
return nil, 0
}
// verifyPoC runs the Proof of Cloud check against quorum peers.
func (s *Server) verifyPoC(
ctx context.Context,
raw *attestation.RawAttestation,
provName string,
) (*attestation.PoCResult, time.Duration) {
if s.cfg.Offline || raw.IntelQuote == "" {
return nil, 0
}
slog.DebugContext(ctx, "Proof of Cloud check starting", "provider", provName)
start := time.Now()
poc := attestation.NewPoCClient(attestation.PoCPeers, attestation.PoCQuorum, s.attestClient)
result := poc.CheckQuote(ctx, raw.IntelQuote)
dur := time.Since(start)
slog.DebugContext(ctx, "Proof of Cloud check complete", "provider", provName, "elapsed", dur,
"registered", result != nil && result.Registered)
return result, dur
}
// supplyChainResult holds the outputs of compose binding, sigstore, and rekor
// verification. Zero value is safe to use (nil slices/maps/pointers).
type supplyChainResult struct {
Compose *attestation.ComposeBindingResult
Sigstore []attestation.SigstoreResult
ImageRepos []string
DigestToRepo map[string]string
Rekor []attestation.RekorProvenance
}
// verifySupplyChain runs compose binding, sigstore digest, and rekor provenance checks.
func (s *Server) verifySupplyChain(
ctx context.Context,
raw *attestation.RawAttestation,
tdxResult *attestation.TDXVerifyResult,
) (supplyChainResult, time.Duration) {
if raw.AppCompose == "" || tdxResult == nil || tdxResult.ParseErr != nil {
if tdxResult != nil && tdxResult.ParseErr != nil {
slog.WarnContext(ctx, "supply chain verification skipped: TDX quote parse failed",
"parse_err", tdxResult.ParseErr)
} else {
slog.DebugContext(ctx, "supply chain verification skipped",
"has_compose", raw.AppCompose != "",
"has_tdx", tdxResult != nil)
}
return supplyChainResult{}, 0
}
start := time.Now()
sc := supplyChainResult{
Compose: &attestation.ComposeBindingResult{Checked: true},
}
sc.Compose.Err = attestation.VerifyComposeBinding(raw.AppCompose, tdxResult.MRConfigID)
if sc.Compose.Err == nil {
cd := attestation.ExtractComposeDigests(raw.AppCompose)
sc.ImageRepos = cd.Repos
sc.DigestToRepo = cd.DigestToRepo
if len(cd.Digests) > 0 && !s.cfg.Offline {
sc.Sigstore = s.rekorClient.CheckSigstoreDigests(ctx, cd.Digests)
}
}
if len(sc.Sigstore) > 0 && !s.cfg.Offline {
for _, sr := range sc.Sigstore {
if sr.OK {
sc.Rekor = append(sc.Rekor, s.rekorClient.FetchRekorProvenance(ctx, sr.Digest))
}
}
}
return sc, time.Since(start)
}
// --------------------------------------------------------------------------
// Endpoint handler factory
// --------------------------------------------------------------------------
// endpointConfig configures a proxy endpoint handler via the handleEndpoint factory.
type endpointConfig struct {
// name is the endpoint name for logging (e.g. "chat", "embeddings").
name string
// endpointPath returns the upstream API path for this endpoint type from
// the given provider. Returns "" if the provider doesn't support this endpoint.
endpointPath func(*provider.Provider) string
// unsupported is the human-readable description of this endpoint type,
// used in error messages when the provider doesn't support it.
// Empty string means the path is always required (chat).
unsupported string
// parseRequest extracts the model name and streaming flag from the request
// body. For JSON endpoints, this unmarshals and reads the model field.
// For multipart (audio), this extracts the model from form data.
parseRequest func(r *http.Request, body []byte) (model string, stream bool, err error)
// contentType is the default Content-Type for upstream requests.
// If empty, the original request's Content-Type is preserved.
contentType string
// preRouteGuard is an optional check run after model resolution but before
// routing. Returns an error message and true to block the request.
// Nil means no guard.
preRouteGuard func(prov *provider.Provider) (errMsg string, block bool)
// canStream indicates whether this endpoint type supports SSE streaming.
// When true, the pinned path uses handlePinnedChat (which supports
// streaming + E2EE session decryption); otherwise handlePinnedNonChat.
canStream bool
}
// parseChatRequest extracts model and stream flag from a chat completions JSON body.
func parseChatRequest(_ *http.Request, body []byte) (model string, stream bool, err error) {
var req chatRequest
if err := json.Unmarshal(body, &req); err != nil {
return "", false, errors.New("invalid JSON body")
}
return req.Model, req.Stream, nil
}
// parseJSONModelRequest extracts only the model field from a JSON body.
// Used for embeddings, images, and rerank endpoints that don't support streaming.
func parseJSONModelRequest(_ *http.Request, body []byte) (model string, stream bool, err error) {
var req struct {
Model string `json:"model"`
}
if err := json.Unmarshal(body, &req); err != nil {
return "", false, errors.New("invalid JSON body")
}
return req.Model, false, nil
}
// parseAudioModelRequest extracts the model field from a multipart/form-data body.
func parseAudioModelRequest(r *http.Request, body []byte) (model string, stream bool, err error) {
model, err = extractMultipartField(r.Header.Get("Content-Type"), body, "model")
if err != nil {
return "", false, fmt.Errorf("extracting model from multipart body: %w", err)
}
if model == "" {
return "", false, errors.New(`"model" form field is empty`)
}
return model, false, nil
}
// Endpoint configurations for each proxy route.
var (
chatEndpoint = endpointConfig{
name: "chat",
endpointPath: func(p *provider.Provider) string { return p.ChatPath },
parseRequest: parseChatRequest,
contentType: "application/json",
canStream: true,
}
embeddingsEndpoint = endpointConfig{
name: "embeddings",
endpointPath: func(p *provider.Provider) string { return p.EmbeddingsPath },
unsupported: "embeddings",
parseRequest: parseJSONModelRequest,
contentType: "application/json",
}
imagesEndpoint = endpointConfig{
name: "images",
endpointPath: func(p *provider.Provider) string { return p.ImagesPath },
unsupported: "image generation",
parseRequest: parseJSONModelRequest,
contentType: "application/json",
}
rerankEndpoint = endpointConfig{
name: "rerank",
endpointPath: func(p *provider.Provider) string { return p.RerankPath },
unsupported: "reranking",
parseRequest: parseJSONModelRequest,
contentType: "application/json",
}
audioEndpoint = endpointConfig{
name: "audio",
endpointPath: func(p *provider.Provider) string { return p.AudioPath },
unsupported: "audio transcription",
parseRequest: parseAudioModelRequest,
preRouteGuard: func(prov *provider.Provider) (string, bool) {
// Non-pinned E2EE providers (Chutes, nearcloud) require body encryption,
// which doesn't support multipart. Fail closed to prevent silently
// sending plaintext.
if prov.E2EE && prov.PinnedHandler == nil {
return "audio transcription requires TLS-level E2EE (pinned provider)", true
}
return "", false
},
}
)
// handleEndpoint returns an http.HandlerFunc that handles requests for the
// given endpoint configuration. The returned handler performs:
// body reading → model parsing → provider resolution → attestation → E2EE → relay.
func (s *Server) handleEndpoint(ep *endpointConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := reqid.WithID(r.Context(), reqid.New())
requestStart := time.Now()
r.Body = http.MaxBytesReader(w, r.Body, 50<<20) // 50 MiB max
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "request body too large or unreadable", http.StatusBadRequest)
return
}
model, stream, err := ep.parseRequest(r, body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return