Files
traefik-llmgateway/passthrough_usage_residual_test.go
T
lukaszraczyloandGitHub f1b198bce4 fix(security): audit run-4 fixes and run-3 leftovers (#26)
Corrects passthrough metering, the cost gate, credential redaction, reload drain, response headers and the discovery cap.
2026-11-29 10:50:36 +00:00

190 lines
8.3 KiB
Go

package traefikllmgateway
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
)
const (
residualPrompt = 700
residualCompletion = 30000
residualDailyLimit = 20000
)
func newResidualGateway(t *testing.T, providerType, model string, upstream http.HandlerFunc) *Gateway {
t.Helper()
srv := httptest.NewServer(upstream)
t.Cleanup(srv.Close)
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{"up": {Type: providerType, BaseURL: srv.URL, APIKey: "sk-up", Models: []string{model}}}
cfg.Groups = map[string]*GroupConfig{"default": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{TokensPerDay: residualDailyLimit}}}}
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 gw
}
func residualPost(gw *Gateway, path, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
req.Header.Set("Authorization", "Bearer sk-alice")
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
gw.ServeHTTP(rec, req)
return rec
}
func residualCounters(gw *Gateway) (int64, int64) {
in, _ := gw.limiter.getCounter("user", "alice", metricTokIn, windowDay, time.Now())
out, _ := gw.limiter.getCounter("user", "alice", metricTokOut, windowDay, time.Now())
return in, out
}
func jsonUpstream(body func() string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, body())
}
}
func overCapFiller() string { return strings.Repeat("a", maxAccountingTeeBytes+200<<10) }
func TestPassthroughJSON_OverTeeCapBillsReportedUsageFromTail(t *testing.T) {
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", jsonUpstream(func() string {
return `{"id":"c1","model":"gpt-5","choices":[{"message":{"content":"` + overCapFiller() + `"}}],"usage":{"prompt_tokens":700,"completion_tokens":30000}}`
}))
if rec := residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","messages":[]}`); rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
if rec := residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","messages":[]}`); rec.Code != http.StatusTooManyRequests {
t.Errorf("second request status = %d, want 429", rec.Code)
}
}
func TestPassthroughJSON_OverTeeCapGeminiUsageMetadataFromTail(t *testing.T) {
gw := newResidualGateway(t, providerTypeGemini, "gemini-x", jsonUpstream(func() string {
return `{"candidates":[{"content":{"parts":[{"text":"` + overCapFiller() + `"}]}}],"usageMetadata":{"promptTokenCount":700,"candidatesTokenCount":30000},"modelVersion":"gemini-x"}`
}))
if rec := residualPost(gw, "/up/v1beta/models/gemini-x:generateContent", `{"contents":[]}`); rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
}
func TestPassthroughJSON_UsageTextInsideStringNotParsed(t *testing.T) {
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", jsonUpstream(func() string {
fake := `{\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":1}}`
return `{"model":"gpt-5","choices":[{"message":{"content":"` + overCapFiller() + `"}}],"usage":{"prompt_tokens":700,"completion_tokens":30000},"note":"` + fake + `"}`
}))
residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","messages":[]}`)
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
}
func TestPassthroughJSON_OverTeeCapWithoutUsageKeepsPromptEstimate(t *testing.T) {
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", jsonUpstream(func() string {
return `{"model":"gpt-5","data":[{"b64_json":"` + overCapFiller() + `"}]}`
}))
body := `{"model":"gpt-5","prompt":"` + strings.Repeat("p", 400) + `"}`
residualPost(gw, "/up/v1/native-endpoint", body)
in, out := residualCounters(gw)
if want := estimatePromptTokens(int64(len(body))); in != want {
t.Errorf("tokin = %d, want request-size estimate %d", in, want)
}
if out != 0 {
t.Errorf("tokout = %d, want 0", out)
}
}
func TestPassthroughJSON_UsageStraddlingTeeCapBilled(t *testing.T) {
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", jsonUpstream(func() string {
pre := `{"model":"gpt-5","c":"` + strings.Repeat("a", maxAccountingTeeBytes-20-len(`{"model":"gpt-5","c":"`)) + `"`
return pre + `,"usage":{"prompt_tokens":700,"completion_tokens":30000}}`
}))
residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","messages":[]}`)
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
}
func TestPassthroughJSON_EchoedUsageAfterRealOneIgnored(t *testing.T) {
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", jsonUpstream(func() string {
return `{"model":"gpt-5","c":"` + overCapFiller() + `","usage":{"prompt_tokens":700,"completion_tokens":30000},"metadata":{"usage":"x"}}`
}))
residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","messages":[]}`)
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
}
func TestPassthroughJSON_EchoedObjectAfterRealUsageIgnored(t *testing.T) {
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", jsonUpstream(func() string {
return `{"model":"gpt-5","c":"` + overCapFiller() + `","usage":{"prompt_tokens":700,"completion_tokens":30000},"tool":{"usage":{"prompt_tokens":1,"completion_tokens":9000000}}}`
}))
residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","messages":[]}`)
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
}
func TestPassthroughJSON_UsageInHeadBilled(t *testing.T) {
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", jsonUpstream(func() string {
return `{"model":"gpt-5","usage":{"prompt_tokens":700,"completion_tokens":30000},"c":"` + overCapFiller() + `"}`
}))
residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","messages":[]}`)
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
}
func TestPassthroughJSON_HangupAfterEchoedObjectKeepsHeadUsage(t *testing.T) {
gw := newResidualGateway(t, providerTypeOpenAI, "gpt-5", func(w http.ResponseWriter, r *http.Request) {
body := `{"model":"gpt-5","usage":{"prompt_tokens":6,"completion_tokens":10000},"c":"` + overCapFiller() + `","echo":{"usage":{"prompt_tokens":1,"completion_tokens":0}}`
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(body)+1000))
_, _ = io.WriteString(w, body)
})
residualPost(gw, "/up/v1/native-endpoint", `{"model":"gpt-5","messages":[]}`)
in, out := residualCounters(gw)
if in != 6 || out != 10000 {
t.Fatalf("tokens in/out = %d/%d, want 6/10000", in, out)
}
}
func TestPassthroughJSON_OverTeeCapGeminiArrayReplyBilled(t *testing.T) {
gw := newResidualGateway(t, providerTypeGemini, "gemini-x", jsonUpstream(func() string {
return `[{"candidates":[{"content":{"parts":[{"text":"` + overCapFiller() + `"}]}}],"usageMetadata":{"promptTokenCount":700,"candidatesTokenCount":30000},"modelVersion":"gemini-x"}]`
}))
residualPost(gw, "/up/v1beta/models/gemini-x:streamGenerateContent", `{"contents":[]}`)
in, out := residualCounters(gw)
if in != residualPrompt || out != residualCompletion {
t.Fatalf("tokens in/out = %d/%d, want %d/%d", in, out, residualPrompt, residualCompletion)
}
}