fix(proxy): do not relay a redirect that carries a configured target query

proxyUpstream answers 502 when an upstream replies with a 3xx Location
and the upstream URL holds a query the client did not send. Targets
without a configured query still relay redirects.
This commit is contained in:
2026-11-29 00:23:11 +00:00
parent 7d43366324
commit 4e87b61932
3 changed files with 121 additions and 0 deletions
+19
View File
@@ -371,3 +371,22 @@ func validateTargetURL(raw string) error {
}
return nil
}
// queryAddedByGateway reports whether upstreamURL's query holds a pair that
// the client's own query lacks, which means the gateway added it from config.
func queryAddedByGateway(upstreamURL, clientRawQuery string) bool {
i := strings.Index(upstreamURL, "?")
if i < 0 || i == len(upstreamURL)-1 {
return false
}
have := make(map[string]bool)
for _, p := range strings.Split(clientRawQuery, "&") {
have[p] = true
}
for _, p := range strings.Split(upstreamURL[i+1:], "&") {
if p != "" && !have[p] {
return true
}
}
return false
}
+10
View File
@@ -1919,6 +1919,16 @@ func (g *Gateway) proxyUpstream(w http.ResponseWriter, r *http.Request, upstream
writeOAIError(w, http.StatusBadGateway, "server_error", "upstream connection error")
return proxyResult{}, false
}
// A redirect Location commonly echoes the request query, so one that
// answers a request carrying a gateway-added query would hand the
// configured credential to the client.
if resp.StatusCode >= 300 && resp.StatusCode < 400 && resp.Header.Get("Location") != "" && queryAddedByGateway(upstreamURL, r.URL.RawQuery) {
_ = resp.Body.Close()
cancel()
g.errorf("%s: upstream answered %d with a redirect; not relaying it because the upstream URL carries a configured query", logPrefix, resp.StatusCode)
writeOAIError(w, http.StatusBadGateway, "server_error", "upstream answered with a redirect, which the gateway does not relay")
return proxyResult{}, false
}
// logPrefix, not a hardcoded "provider %q": handleTargetProxy's own
// calls here (mcp_a2a.go) pass "mcp target (name ...)"/"a2a target
// (name ...)" — an MCP/A2A target is not a provider, and the watchdog
+92
View File
@@ -0,0 +1,92 @@
package traefikllmgateway
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
const redirectSecret = "SECRETQUERYTOKEN"
func newTargetRedirectGateway(t *testing.T, mcpURL, agentURL string) http.Handler {
t.Helper()
cfg := CreateConfig()
cfg.Providers = map[string]*ProviderConfig{"openai": {Type: "openai", APIKey: "k"}}
cfg.MCPServers = map[string]*TargetConfig{"alpha": {URL: mcpURL}}
cfg.Agents = map[string]*AgentConfig{"ag": {URL: agentURL}}
cfg.Groups = map[string]*GroupConfig{"default": {}}
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice"}}}
h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw")
if err != nil {
t.Fatalf("New: %v", err)
}
return h
}
func redirectingUpstream() *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/tools") {
_, _ = w.Write([]byte("ok"))
return
}
http.Redirect(w, r, "http://elsewhere.invalid/x?"+r.URL.RawQuery, http.StatusTemporaryRedirect) //nolint:gosec // test upstream echoing the query
}))
}
func doTarget(h http.Handler, path string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, path, nil)
req.Header.Set("Authorization", "Bearer sk-alice")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func TestTargetProxy_RedirectWithTargetQueryNotRelayed(t *testing.T) {
up := redirectingUpstream()
defer up.Close()
h := newTargetRedirectGateway(t, up.URL+"/mcp?token="+redirectSecret, up.URL+"/a2a?token="+redirectSecret)
for _, path := range []string{"/mcp/alpha", "/a2a/ag"} {
rec := doTarget(h, path)
if rec.Code != http.StatusBadGateway {
t.Errorf("%s: status = %d, want 502", path, rec.Code)
}
if loc := rec.Header().Get("Location"); loc != "" {
t.Errorf("%s: Location relayed: %q", path, loc)
}
if strings.Contains(rec.Body.String(), redirectSecret) || strings.Contains(rec.Header().Get("Location"), redirectSecret) {
t.Errorf("%s: secret reached the client", path)
}
}
}
func TestTargetProxy_RedirectWithoutTargetQueryStillRelayed(t *testing.T) {
up := redirectingUpstream()
defer up.Close()
h := newTargetRedirectGateway(t, up.URL+"/mcp", up.URL+"/a2a")
rec := doTarget(h, "/mcp/alpha")
if rec.Code != http.StatusTemporaryRedirect || rec.Header().Get("Location") == "" {
t.Errorf("status = %d, Location = %q, want 307 relayed", rec.Code, rec.Header().Get("Location"))
}
}
func TestTargetProxy_ClientOnlyQueryRedirectStillRelayed(t *testing.T) {
up := redirectingUpstream()
defer up.Close()
h := newTargetRedirectGateway(t, up.URL+"/mcp", up.URL+"/a2a")
rec := doTarget(h, "/mcp/alpha?x=1")
if rec.Code != http.StatusTemporaryRedirect || rec.Header().Get("Location") == "" {
t.Errorf("status = %d, Location = %q, want 307 relayed", rec.Code, rec.Header().Get("Location"))
}
}
func TestTargetProxy_NonRedirectUnchanged(t *testing.T) {
up := redirectingUpstream()
defer up.Close()
h := newTargetRedirectGateway(t, up.URL+"/mcp?token="+redirectSecret, up.URL+"/a2a")
rec := doTarget(h, "/mcp/alpha/tools")
if rec.Code != http.StatusOK || rec.Body.String() != "ok" {
t.Errorf("status = %d body = %q, want 200 ok", rec.Code, rec.Body.String())
}
}