Files
traefik-llmgateway/passthrough_unpriced_gate_test.go
T
lukaszraczylo a11e640230 fix(passthrough): gate and bill passthrough requests by cost budget
Refusal text stays under 128 bytes, and only models the provider serves get a per-model counter. When the first 64 KiB does not settle the model, the gate reads the body up to the smaller of maxRequestBytes and the passthrough cap, inside a body-admission slot. It refuses with 402 if the model is missing, repeated, or in a malformed or unterminated object, with 413 if the object does not close within the bound, and with 400 if the body read fails. A priced model after 64 KiB passes and the body reaches the upstream unchanged. A 2xx event stream with no completion usage bills one estimated token per data event.
2026-11-29 00:23:09 +00:00

317 lines
11 KiB
Go

package traefikllmgateway
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
const gateUpstreamReply = `{"model":"gpt-5","usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}`
// gateEnv is a gateway with a cost-budgeted user "alice" in front of an
// upstream that records how many requests reached it and how many body
// bytes it received.
type gateEnv struct {
gw *Gateway
h http.Handler
calls *int32
lastBody *atomic.Value
}
func newGateEnv(t *testing.T, mutate func(*Config)) *gateEnv {
t.Helper()
var calls int32
var lastBody atomic.Value
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&calls, 1)
b, _ := io.ReadAll(r.Body)
lastBody.Store(string(b))
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, gateUpstreamReply)
}))
t.Cleanup(srv.Close)
cfg := CreateConfig()
cfg.Admin = &AdminConfig{Enabled: true}
cfg.Providers = map[string]*ProviderConfig{
"openai": {Type: "openai", BaseURL: srv.URL, APIKey: "sk-up", Models: []string{"cat-unpriced"}},
}
cfg.Groups = map[string]*GroupConfig{"default": {}, "public": {Limits: &LimitsConfig{CostPerDayUSD: 5}}}
cfg.Users = &UsersConfig{
AnonymousGroup: "public",
Inline: []*UserConfig{
{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{CostPerDayUSD: 5}},
{Name: "admin1", Group: "default", APIKey: "sk-admin1", Admin: true},
},
}
if mutate != nil {
mutate(cfg)
}
h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw")
if err != nil {
t.Fatalf("New: %v", err)
}
gw, ok := h.(*Gateway)
if !ok {
t.Fatal("handler is not *Gateway")
}
gw.limiter.spawn = func(f func()) { f() }
return &gateEnv{gw: gw, h: h, calls: &calls, lastBody: &lastBody}
}
func (e *gateEnv) post(body, key string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", strings.NewReader(body))
if key != "" {
req.Header.Set("Authorization", "Bearer "+key)
}
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
e.h.ServeHTTP(rec, req)
return rec
}
func (e *gateEnv) upstreamCalls() int { return int(atomic.LoadInt32(e.calls)) }
func (e *gateEnv) aliceTokOut() int64 {
v, _ := e.gw.limiter.getCounter("user", "alice", metricTokOut, windowDay, time.Now())
return v
}
// padThenModel puts the model after more than maxModelPeekBytes of prompt.
func padThenModel(model string) string {
return `{"messages":[{"role":"user","content":"` + strings.Repeat("a", maxModelPeekBytes+1024) + `"}],"model":"` + model + `"}`
}
func TestPassthroughCostGate_UnpricedModelBeyondPeekWindowRefused(t *testing.T) {
e := newGateEnv(t, nil)
rec := e.post(padThenModel("cat-unpriced"), "sk-alice")
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String())
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
if got := e.aliceTokOut(); got != 0 {
t.Errorf("tokout = %d, want 0", got)
}
}
func TestPassthroughCostGate_PricedModelBeyondPeekWindowServedWithFullBody(t *testing.T) {
e := newGateEnv(t, nil)
body := padThenModel("gpt-5")
rec := e.post(body, "sk-alice")
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200, body=%.200s", rec.Code, rec.Body.String())
}
if got, _ := e.lastBody.Load().(string); got != body {
t.Errorf("upstream body differs from the request body (got %d bytes, want %d)", len(got), len(body))
}
if got := e.aliceTokOut(); got != 5 {
t.Errorf("tokout = %d, want 5", got)
}
}
func TestPassthroughCostGate_LargeBodyWithoutModelRefused(t *testing.T) {
e := newGateEnv(t, nil)
body := `{"messages":[{"role":"user","content":"` + strings.Repeat("a", maxModelPeekBytes+1024) + `"}]}`
rec := e.post(body, "sk-alice")
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String())
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
}
func TestPassthroughCostGate_DuplicateModelKeyRefused(t *testing.T) {
e := newGateEnv(t, nil)
rec := e.post(`{"model":"gpt-5","model":"cat-unpriced"}`, "sk-alice")
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String())
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
}
func TestPassthroughCostGate_DuplicateModelBeyondPeekWindowRefused(t *testing.T) {
e := newGateEnv(t, nil)
body := `{"model":"gpt-5","pad":"` + strings.Repeat("a", maxModelPeekBytes+1024) + `","model":"cat-unpriced"}`
rec := e.post(body, "sk-alice")
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String())
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
}
func TestPassthroughCostGate_BodylessGetStillServed(t *testing.T) {
e := newGateEnv(t, nil)
req := httptest.NewRequest(http.MethodGet, "/openai/v1/models", nil)
req.Header.Set("Authorization", "Bearer sk-alice")
rec := httptest.NewRecorder()
e.h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200, body=%.200s", rec.Code, rec.Body.String())
}
}
func TestPassthroughCostGate_ModelFirstPricedStillServed(t *testing.T) {
e := newGateEnv(t, nil)
body := `{"model":"gpt-5","messages":[{"role":"user","content":"` + strings.Repeat("a", maxModelPeekBytes+1024) + `"}]}`
rec := e.post(body, "sk-alice")
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200, body=%.200s", rec.Code, rec.Body.String())
}
if got := e.aliceTokOut(); got != 5 {
t.Errorf("tokout = %d, want 5", got)
}
}
func TestPassthroughCostGate_AllowUnpricedOptInServesAllShapes(t *testing.T) {
e := newGateEnv(t, func(c *Config) { c.AllowUnpricedWithCostBudget = true })
for name, body := range map[string]string{
"padded": padThenModel("cat-unpriced"),
"duplicate": `{"model":"gpt-5","model":"cat-unpriced"}`,
} {
if rec := e.post(body, "sk-alice"); rec.Code != http.StatusOK {
t.Errorf("%s: status = %d, want 200, body=%.200s", name, rec.Code, rec.Body.String())
}
}
}
func TestPassthroughCostGate_NoCostBudgetUnchanged(t *testing.T) {
e := newGateEnv(t, func(c *Config) {
c.Users.Inline[0].Limits = &LimitsConfig{}
})
for name, body := range map[string]string{
"padded": padThenModel("cat-unpriced"),
"duplicate": `{"model":"gpt-5","model":"cat-unpriced"}`,
} {
if rec := e.post(body, "sk-alice"); rec.Code != http.StatusOK {
t.Errorf("%s: status = %d, want 200, body=%.200s", name, rec.Code, rec.Body.String())
}
}
}
func TestPassthroughCostGate_OverCapBodyIs413(t *testing.T) {
e := newGateEnv(t, nil)
req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", strings.NewReader(padThenModel("gpt-5")))
req.ContentLength = maxPassthroughBytes + 1
req.Header.Set("Authorization", "Bearer sk-alice")
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
e.h.ServeHTTP(rec, req)
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("status = %d, want 413", rec.Code)
}
}
func TestPassthroughCostGate_ObjectUnclosedWithinBoundIs413(t *testing.T) {
e := newGateEnv(t, func(c *Config) { c.MaxRequestBytes = 1 << 20 })
body := `{"model":"gpt-5"` + strings.Repeat(" ", 1<<20) + `,"model":"cat-unpriced"}`
rec := e.post(body, "sk-alice")
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("status = %d, want 413, body=%.200s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "maxRequestBytes") {
t.Errorf("body does not name maxRequestBytes: %.200s", rec.Body.String())
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
}
func TestPassthroughCostGate_ChunkedOverCapBodyIs413(t *testing.T) {
e := newGateEnv(t, func(c *Config) { c.MaxRequestBytes = maxExplicitUnifiedRequestBytes })
body := `{"pad":"` + strings.Repeat("a", maxPassthroughBytes) + `"}`
req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", strings.NewReader(body))
req.ContentLength = -1
req.Header.Set("Authorization", "Bearer sk-alice")
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
e.h.ServeHTTP(rec, req)
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("status = %d, want 413", rec.Code)
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
}
func TestPassthroughCostGate_HugeNonStringModelValueRefused(t *testing.T) {
e := newGateEnv(t, nil)
body := `{"model":[` + strings.Repeat("1,", 100_000) + `1],"x":1}`
body = strings.Replace(body, `"x":1`, `"pad":"`+strings.Repeat("a", maxModelPeekBytes)+`"`, 1)
rec := e.post(body, "sk-alice")
if rec.Code != http.StatusPaymentRequired {
t.Fatalf("status = %d, want 402, body=%.200s", rec.Code, rec.Body.String())
}
}
func TestPassthroughCostGate_ModelBeyondMaxRequestBytesIs413(t *testing.T) {
e := newGateEnv(t, func(c *Config) { c.MaxRequestBytes = 1 << 20 })
body := `{"pad":"` + strings.Repeat("a", 2<<20) + `","model":"gpt-5"}`
rec := e.post(body, "sk-alice")
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("status = %d, want 413", rec.Code)
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
}
func TestPassthroughCostGate_UnparseableObjectRefused(t *testing.T) {
for name, body := range map[string]string{
"nan between duplicates": `{"model":"gpt-5","a":NaN,"model":"cat-unpriced"}`,
"truncated mid-object": `{"model":"gpt-5","messages":[{"role":"user"`,
} {
e := newGateEnv(t, nil)
rec := e.post(body, "sk-alice")
if rec.Code != http.StatusPaymentRequired {
t.Errorf("%s: status = %d, want 402, body=%.200s", name, rec.Code, rec.Body.String())
}
if e.upstreamCalls() != 0 {
t.Errorf("%s: upstream calls = %d, want 0", name, e.upstreamCalls())
}
}
}
type failingReader struct{}
func (failingReader) Read([]byte) (int, error) { return 0, errors.New("client reset") }
func TestPassthroughCostGate_WidenedReadErrorIs400(t *testing.T) {
e := newGateEnv(t, nil)
body := io.MultiReader(strings.NewReader(`{"pad":"`+strings.Repeat("a", maxModelPeekBytes+1024)), failingReader{})
req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", body)
req.ContentLength = -1
req.Header.Set("Authorization", "Bearer sk-alice")
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
e.h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400, body=%.200s", rec.Code, rec.Body.String())
}
if e.upstreamCalls() != 0 {
t.Errorf("upstream calls = %d, want 0", e.upstreamCalls())
}
}
func BenchmarkScanTopLevelModelLargeBody(b *testing.B) {
body := []byte(`{"messages":[` + strings.Repeat(`{"role":"user","content":"hello"},`, 1<<17) + `{}],"model":"gpt-5"}`)
b.SetBytes(int64(len(body)))
for i := 0; i < b.N; i++ {
if m, ok, _, _ := scanTopLevelModel(body); !ok || m != "gpt-5" {
b.Fatal("model not found")
}
}
}