mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-12-06 11:03:52 +00:00
Corrects passthrough metering, the cost gate, credential redaction, reload drain, response headers and the discovery cap.
179 lines
6.6 KiB
Go
179 lines
6.6 KiB
Go
package traefikllmgateway
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"errors"
|
||
"net/http"
|
||
"net/http/httptest"
|
||
"net/url"
|
||
"strings"
|
||
"testing"
|
||
)
|
||
|
||
const renderingMarker = "TOKEN123"
|
||
|
||
func auditPayloads(addr string) map[string]string {
|
||
return map[string]string{
|
||
"quote in query": "http://" + addr + "?api-key=DUMMY\"" + renderingMarker,
|
||
"backslash in query": "http://" + addr + "?api-key=DUMMY\\" + renderingMarker,
|
||
"nbsp in query": "http://" + addr + "?api-key=DUMMY " + renderingMarker,
|
||
"quote in password": "http://user:DUMMY\"" + renderingMarker + "@" + addr,
|
||
"trailing newline": "http://user:DUMMY" + renderingMarker + "@" + addr + "\n",
|
||
"run3 upper scheme": "HTTP://" + renderingMarker + "@" + addr + "/v1",
|
||
"run3 escaped userinf": "http://us%40" + renderingMarker + "@" + addr + "/v1",
|
||
"run3 upper query": "HTTP://" + addr + "/v1?key=" + renderingMarker,
|
||
"plain query": "http://" + addr + "/v1?key=" + renderingMarker,
|
||
}
|
||
}
|
||
|
||
func TestSanitizeProviderErr_QuotedRenderings(t *testing.T) {
|
||
addr := closedLoopbackAddr(t)
|
||
for name, base := range auditPayloads(addr) {
|
||
if !strings.HasPrefix(name, "quote") && !strings.HasPrefix(name, "backslash") && !strings.HasPrefix(name, "nbsp") && !strings.HasPrefix(name, "trailing") {
|
||
continue
|
||
}
|
||
t.Run(name, func(t *testing.T) {
|
||
resp, err := http.Get(base + "/v1/models") //nolint:gosec,noctx // closed loopback port, the error text is the subject
|
||
if err == nil {
|
||
_ = resp.Body.Close()
|
||
t.Fatal("expected an error")
|
||
}
|
||
if !strings.Contains(err.Error(), renderingMarker) {
|
||
t.Fatalf("precondition: error does not carry the marker: %v", err)
|
||
}
|
||
if got := sanitizeProviderErr(err.Error(), base); strings.Contains(got, renderingMarker) || strings.Contains(got, "DUMMY") {
|
||
t.Fatalf("credential leaked: %q", got)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
func TestSanitizeProviderErr_URLEncodedRendering(t *testing.T) {
|
||
base := "http://example.invalid/v1?api-key=DUMMY\"" + renderingMarker
|
||
for name, enc := range map[string]string{
|
||
"query escape": url.QueryEscape(base),
|
||
"path escape": url.PathEscape(base),
|
||
} {
|
||
t.Run(name, func(t *testing.T) {
|
||
got := sanitizeProviderErr("redirect_uri="+enc+" rejected", base)
|
||
if strings.Contains(got, renderingMarker) || strings.Contains(got, "DUMMY") {
|
||
t.Fatalf("credential leaked: %q", got)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
func withUserinfo(userinfo, path string) string {
|
||
return "http://" + userinfo + "@h.invalid:1" + path
|
||
}
|
||
|
||
func TestSanitizeProviderErr_SecretComponentBackstop(t *testing.T) {
|
||
cases := map[string][2]string{
|
||
"query value": {"http://h.invalid:1/v1?key=BACKSTOPSECRET", "http://h.invalid:1/inserted/v1?key=BACKSTOPSECRET"},
|
||
"quoted query": {"http://h.invalid:1/v1?key=BACK\"STOPSECRET", "http://h.invalid:1/inserted/v1?key=BACK\"STOPSECRET"},
|
||
"password": {withUserinfo("user:BACKSTOPSECRET", "/v1"), withUserinfo("user:BACKSTOPSECRET", "/inserted/v1")},
|
||
"token as user": {withUserinfo("BACKSTOPSECRET", "/v1"), withUserinfo("BACKSTOPSECRET", "/inserted/v1")},
|
||
"escaped password": {withUserinfo("user:BACK%22STOPSECRET", "/v1"), withUserinfo("user:BACK%22STOPSECRET", "/inserted/v1")},
|
||
}
|
||
for name, c := range cases {
|
||
t.Run(name, func(t *testing.T) {
|
||
msg := (&url.Error{Op: "Get", URL: c[1], Err: errors.New("refused")}).Error()
|
||
got := sanitizeProviderErr(msg, c[0])
|
||
if strings.Contains(got, "STOPSECRET") {
|
||
t.Fatalf("credential leaked: %q", got)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
func TestSanitizeProviderErr_ShortValuesNotBlanked(t *testing.T) {
|
||
got := sanitizeProviderErr("dial tcp: lookup v1 failed", "http://h.invalid/v1?a=v1")
|
||
if got != "dial tcp: lookup v1 failed" {
|
||
t.Errorf("short query value blanked an unrelated substring: %q", got)
|
||
}
|
||
}
|
||
|
||
func renderingsGateway(t *testing.T, base string) (http.Handler, string) {
|
||
t.Helper()
|
||
cfg := CreateConfig()
|
||
cfg.Admin = &AdminConfig{Enabled: true}
|
||
cfg.Providers = map[string]*ProviderConfig{"p": {Type: "openai", BaseURL: base, APIKey: "k", Discovery: true}}
|
||
cfg.Groups = map[string]*GroupConfig{"g": {}}
|
||
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "admin1", Group: "g", APIKey: "sk-admin1", Admin: true}}}
|
||
var h http.Handler
|
||
var gw *Gateway
|
||
log := captureStderr(t, func() { h, gw = newAdminGatewayHandle(t, cfg) })
|
||
// An armed warm-fill retry would log from its own goroutine during a later test.
|
||
st := gw.registry.states["p"]
|
||
st.mu.Lock()
|
||
st.inFlight = true
|
||
st.mu.Unlock()
|
||
return h, log
|
||
}
|
||
|
||
func TestAdminOverview_DiscoveryErrorScrubsQuotedCredential(t *testing.T) {
|
||
addr := closedLoopbackAddr(t)
|
||
for name, base := range auditPayloads(addr) {
|
||
t.Run(name, func(t *testing.T) {
|
||
h, _ := renderingsGateway(t, base)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, adminRequest(http.MethodGet, adminOverviewPath, "sk-admin1"))
|
||
var got adminOverviewResponse
|
||
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil || len(got.Providers) != 1 {
|
||
t.Fatalf("overview decode: %v, %s", err, rec.Body.String())
|
||
}
|
||
if le := got.Providers[0].LastErr; le == "" || strings.Contains(le, renderingMarker) {
|
||
t.Errorf("lastErr = %q, want a non-empty scrubbed error", le)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
func TestInitialDiscoveryLog_ScrubsQuotedCredential(t *testing.T) {
|
||
addr := closedLoopbackAddr(t)
|
||
for name, base := range auditPayloads(addr) {
|
||
t.Run(name, func(t *testing.T) {
|
||
_, log := renderingsGateway(t, base)
|
||
if !strings.Contains(log, "initial discovery") {
|
||
t.Fatalf("precondition: no discovery failure logged: %q", log)
|
||
}
|
||
if strings.Contains(log, renderingMarker) {
|
||
t.Errorf("log carries the credential: %q", log)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
func TestNew_CredentialBearingBaseURLStillLoads(t *testing.T) {
|
||
addr := closedLoopbackAddr(t)
|
||
for name, base := range auditPayloads(addr) {
|
||
t.Run(name, func(t *testing.T) {
|
||
cfg := CreateConfig()
|
||
cfg.Providers = map[string]*ProviderConfig{"p": {Type: "openai", BaseURL: base, APIKey: "k"}}
|
||
if _, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw"); err != nil {
|
||
t.Fatalf("New must keep accepting the config: %v", err)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
func TestSanitizeProviderErr_Run3SpellingsStillScrubbed(t *testing.T) {
|
||
addr := closedLoopbackAddr(t)
|
||
for name, base := range auditPayloads(addr) {
|
||
if !strings.HasPrefix(name, "run3") && name != "plain query" {
|
||
continue
|
||
}
|
||
t.Run(name, func(t *testing.T) {
|
||
resp, err := http.Get(base) //nolint:gosec,noctx // closed loopback port, the error text is the subject
|
||
if err == nil {
|
||
_ = resp.Body.Close()
|
||
t.Fatal("expected a dial error")
|
||
}
|
||
if got := sanitizeProviderErr(err.Error(), base); strings.Contains(got, renderingMarker) {
|
||
t.Fatalf("credential leaked: %q", got)
|
||
}
|
||
})
|
||
}
|
||
}
|