Files
traefik-llmgateway/sanitize_provider_err_reserialised_test.go
T
lukaszraczylo 7d43366324 fix(admin): scrub the re-serialised base URL from provider errors
sanitizeProviderErr now also replaces the URL as net/url writes it.
A provider baseUrl with userinfo, a query or a fragment logs one
construction warning. The config still loads.
2026-11-29 00:23:11 +00:00

80 lines
2.3 KiB
Go

package traefikllmgateway
import (
"context"
"net"
"net/http"
"strings"
"testing"
)
func closedLoopbackAddr(t *testing.T) string {
t.Helper()
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := l.Addr().String()
_ = l.Close()
return addr
}
func TestSanitizeProviderErr_ReserialisedForms(t *testing.T) {
const tok = "DUMMYTOKEN123"
addr := closedLoopbackAddr(t)
cases := []struct {
name string
base string
}{
{"upper-case scheme with userinfo", "HTTP://" + tok + "@" + addr + "/v1"},
{"escaped userinfo, no password", "http://us%40" + tok + "@" + addr + "/v1"},
{"upper-case scheme with query credential", "HTTP://" + addr + "/v1?key=" + tok},
{"lower-case userinfo", "http://" + tok + "@" + addr + "/v1"},
{"user and password", "http://user:" + tok + "@" + addr + "/v1"},
{"lower-case query", "http://" + addr + "/v1?key=" + tok},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
resp, err := http.Get(tc.base) //nolint:gosec,noctx // loopback closed port, error text is the subject
if err == nil {
_ = resp.Body.Close()
t.Fatal("expected a dial error")
}
if !strings.Contains(err.Error(), tok) && !strings.Contains(err.Error(), "***") {
t.Fatalf("precondition: error text does not carry the credential: %v", err)
}
got := sanitizeProviderErr(err.Error(), tc.base)
if strings.Contains(got, tok) {
t.Fatalf("credential leaked: %q", got)
}
})
}
}
func TestNew_WarnsOnceForCredentialBearingBaseURL(t *testing.T) {
const tok = "DUMMYTOKEN123"
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{
"bad": {Type: "openai", APIKey: "k", BaseURL: "https://" + tok + "@example.invalid/v1"},
"good": {Type: "openai", APIKey: "k", BaseURL: "https://example.invalid/v1"},
}
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
h, err := New(context.Background(), next, cfg, "llmgw")
if err != nil {
t.Fatalf("New must keep accepting the config: %v", err)
}
warnings, _ := h.(*Gateway).configWarningsSnapshot()
var n int
for _, w := range warnings {
if strings.Contains(w, "userinfo") {
n++
if strings.Contains(w, tok) || !strings.Contains(w, `"bad"`) {
t.Errorf("warning must name the provider and never the credential: %q", w)
}
}
}
if n != 1 {
t.Errorf("userinfo warnings = %d, want 1 (%v)", n, warnings)
}
}