Files
traefik-llmgateway/messages_passthrough_cache_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

89 lines
2.7 KiB
Go

package traefikllmgateway
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
)
type rawCacheFixture struct {
gw *Gateway
calls atomic.Int32
}
func newRawCacheFixture(t *testing.T, body string) *rawCacheFixture {
t.Helper()
f := &rawCacheFixture{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
f.calls.Add(1)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(body))
}))
t.Cleanup(srv.Close)
redisLn := newBehavioralRedisServer(t)
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{
"anthropic": {Type: providerTypeAnthropic, BaseURL: srv.URL, APIKey: "k", Models: []string{"claude-test"}},
}
cfg.Groups = map[string]*GroupConfig{"default": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{}}}}
cfg.Redis = &RedisConfig{Address: redisLn.Addr().String()}
cfg.Cache = CacheConfig{Enabled: true, TTL: "1m"}
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")
}
f.gw = gw
return f
}
func (f *rawCacheFixture) send(t *testing.T) *httptest.ResponseRecorder {
t.Helper()
body := map[string]any{"model": "claude-test", "max_tokens": 10, "messages": []any{map[string]any{"role": "user", "content": "hello"}}}
rec := httptest.NewRecorder()
f.gw.ServeHTTP(rec, newMessagesRequest(t, body, "x-api-key", "sk-alice"))
return rec
}
func TestMessagesPassthrough_UnrewrittenBodyHandling(t *testing.T) {
overCap := "[" + strings.Repeat("0,", maxResponseBytes/2+10) + "0]"
cases := []struct {
name string
body string
wantCode int
}{
{"truncated over cap", overCap, http.StatusBadGateway},
{"malformed", `{"id":`, http.StatusBadGateway},
{"empty", ``, http.StatusBadGateway},
{"html", `<html>oops</html>`, http.StatusBadGateway},
{"valid array", `[1,2,3]`, http.StatusOK},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
f := newRawCacheFixture(t, tc.body)
for i := 0; i < 2; i++ {
rec := f.send(t)
if rec.Code != tc.wantCode {
t.Fatalf("send %d: status = %d, want %d", i, rec.Code, tc.wantCode)
}
if tc.wantCode == http.StatusOK && rec.Body.String() != tc.body {
t.Fatalf("body = %q, want verbatim", rec.Body.String())
}
if rec.Header().Get("X-Llmgw-Cache") == "hit" {
t.Fatalf("send %d: an unrewritten reply was served from the cache", i)
}
}
if got := f.calls.Load(); got != 2 {
t.Fatalf("upstream calls = %d, want 2 (nothing cached)", got)
}
})
}
}