Files
traefik-llmgateway/passthrough_model_key_test.go
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

164 lines
5.8 KiB
Go

package traefikllmgateway
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
)
// modelKeyEnv fronts an upstream that decodes the body into a Go struct,
// the way a case-folding, last-wins upstream does, and records the model
// it would have run.
type modelKeyEnv struct {
h http.Handler
models []string
mu sync.Mutex
}
func (e *modelKeyEnv) seen() []string {
e.mu.Lock()
defer e.mu.Unlock()
return append([]string(nil), e.models...)
}
func newModelKeyEnv(t *testing.T, mutate func(*Config)) *modelKeyEnv {
t.Helper()
e := &modelKeyEnv{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
var s struct {
Model string `json:"model"`
}
_ = json.Unmarshal(b, &s)
e.mu.Lock()
e.models = append(e.models, s.Model)
e.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"model":"gpt-5","usage":{"prompt_tokens":1,"completion_tokens":1}}`)
}))
t.Cleanup(srv.Close)
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{"openai": {Type: "openai", BaseURL: srv.URL, APIKey: "sk-up", Models: []string{"cat-unpriced"}}}
cfg.Groups = map[string]*GroupConfig{"default": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{CostPerDayUSD: 5}}}}
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)
}
e.h = h
return e
}
func (e *modelKeyEnv) post(body, contentType string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/openai/v1/native-endpoint", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer sk-alice")
req.Header.Set("Content-Type", contentType)
rec := httptest.NewRecorder()
e.h.ServeHTTP(rec, req)
return rec
}
func restrictToAllowed(c *Config) {
c.Groups = map[string]*GroupConfig{"default": {Models: []string{"gpt-allowed"}}}
c.Users.Inline[0].Limits = &LimitsConfig{}
}
func TestPassthroughCostGate_BOMPrefixedUnpricedModelRefused(t *testing.T) {
e := newModelKeyEnv(t, nil)
rec := e.post("\xef\xbb\xbf"+`{"model":"cat-unpriced"}`, "application/json")
if rec.Code != http.StatusPaymentRequired || len(e.seen()) != 0 {
t.Fatalf("status = %d, upstream saw %v, want 402 and no upstream call", rec.Code, e.seen())
}
}
func TestPassthroughCostGate_CaseVariantSecondModelKeyRefused(t *testing.T) {
e := newModelKeyEnv(t, nil)
rec := e.post(`{"model":"gpt-5","MODEL":"cat-unpriced"}`, "application/json")
if rec.Code != http.StatusPaymentRequired || len(e.seen()) != 0 {
t.Fatalf("status = %d, upstream saw %v, want 402 and no upstream call", rec.Code, e.seen())
}
}
func TestPassthroughModelRestriction_CaseVariantSecondModelKeyRefused(t *testing.T) {
e := newModelKeyEnv(t, restrictToAllowed)
rec := e.post(`{"model":"gpt-allowed","Model":"gpt-forbidden"}`, "application/json")
if rec.Code != http.StatusForbidden || len(e.seen()) != 0 {
t.Fatalf("status = %d, upstream saw %v, want 403 and no upstream call", rec.Code, e.seen())
}
}
func TestPassthroughModelRestriction_LoneCaseVariantAllowedModelRefused(t *testing.T) {
e := newModelKeyEnv(t, restrictToAllowed)
for _, body := range []string{`{"Model":"gpt-allowed"}`, `{"model":"gpt-allowed","MODEL":"gpt-allowed"}`, `{"Model":"gpt-allowed","model":"gpt-allowed"}`} {
if rec := e.post(body, "application/json"); rec.Code != http.StatusForbidden {
t.Errorf("%s: status = %d, want 403", body, rec.Code)
}
}
if len(e.seen()) != 0 {
t.Errorf("upstream saw %v, want no call", e.seen())
}
}
func TestPassthroughCostGate_LoneCaseVariantPricedModelRefused(t *testing.T) {
e := newModelKeyEnv(t, nil)
rec := e.post(`{"Model":"gpt-5"}`, "application/json")
if rec.Code != http.StatusPaymentRequired || len(e.seen()) != 0 {
t.Fatalf("status = %d, upstream saw %v, want 402 and no upstream call", rec.Code, e.seen())
}
}
func TestPassthroughModelRestriction_LoneCaseVariantForbiddenModelDenied(t *testing.T) {
e := newModelKeyEnv(t, restrictToAllowed)
for _, body := range []string{`{"Model":"gpt-forbidden"}`, `{"MODEL":"gpt-forbidden"}`} {
if rec := e.post(body, "application/json"); rec.Code != http.StatusForbidden {
t.Errorf("%s: status = %d, want 403", body, rec.Code)
}
}
if len(e.seen()) != 0 {
t.Errorf("upstream saw %v, want no call", e.seen())
}
}
func TestPassthroughCostGate_BinaryContentTypeStillUngated(t *testing.T) {
e := newModelKeyEnv(t, nil)
rec := e.post(`{"model":"cat-unpriced"}`, "application/octet-stream")
if rec.Code != http.StatusOK || len(e.seen()) != 1 {
t.Fatalf("status = %d, upstream calls = %d, want 200 and 1 (documented ungated shape)", rec.Code, len(e.seen()))
}
}
func TestScanTopLevelModel_FoldsKeyCase(t *testing.T) {
cases := []struct {
name string
body string
model string
found bool
duplicate bool
}{
{"exact", `{"model":"a"}`, "a", true, false},
{"Model", `{"Model":"a"}`, "", false, true},
{"MODEL", `{"MODEL":"a"}`, "", false, true},
{"mOdEl", `{"mOdEl":"a"}`, "", false, true},
{"escaped key", `{"model":"a"}`, "a", true, false},
{"variant then exact", `{"Model":"a","model":"a"}`, "", false, true},
{"exact then variant", `{"model":"a","MODEL":"b"}`, "", false, true},
{"unrelated key", `{"models":"a","modelx":"b"}`, "", false, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
model, found, closed, dup := scanTopLevelModel([]byte(c.body))
if model != c.model || found != c.found || dup != c.duplicate || (!dup && !closed) {
t.Errorf("got (%q, found=%v, closed=%v, dup=%v), want (%q, %v, dup=%v)", model, found, closed, dup, c.model, c.found, c.duplicate)
}
})
}
}