Repository navigation
fix(mcptoolset): keep the Config.Auth credential on the endpoint's origin across redirects - #1986
Conversation
…igin across redirects
…-hook chain authCheckRedirect ran the origin policy and then returned whatever the caller's CheckRedirect returned. net/http sends the request as that hook leaves it, so a hook that rewrote req.URL and returned nil sent the next hop, credential and JSON-RPC body included, to whatever origin it named. The hook also receives via, so re-running the policy on the live chain is not enough. Take copies of the original and previous URLs before the hook runs and judge the hop it leaves against those. Pin the rest of the policy's contract in TestAuthRedirectPolicy: the policy decides before the hook (a caller returning ErrUseLastResponse on a cross-host hop still gets the refusal), the hook's sentinel reaches net/http unwrapped on an allowed hop, and nothing is installed without Config.Auth. Bound TestAuthRedirectCap's redirect loop so a missing cap fails the hop count instead of hanging the package. Move the hop cap constant into credredirect as MaxRedirects, shared by both callers, prefix mcptoolset's cap error like remoteagent's, unexport sameTarget, and fix the TestSameTarget comment that still referred to end-to-end tests "above" from before the move.
karolpiotrowicz
left a comment
There was a problem hiding this comment.
Three things need to change before this merges. On MCP protocol versions older than 2026-07-28, go-sdk opens an optional server-to-client stream with a standalone SSE GET after the initialize request. A refused redirect on that GET now takes the whole MCP toolset down. No test lets a caller's CheckRedirect allow a redirect. The comment on authCheckRedirect promises more than the check enforces.
On this head (3ddfddd) and on its merge with current main (beea418), go build, go vet, gofmt, staticcheck and govulncheck report nothing. The apidiff check reports no change to the exported API. The full test suite passes, and the race detector is quiet on the three changed packages. Five of the nine new TestAuthRedirectPolicy cases fail on main, where the cross-host target receives the credential, and all nine pass here.
Must change before merge
1. A cross-host redirect on the standalone SSE GET makes every Tools() call fail after 16 to 21.5 seconds
Take a server, used with Config.Auth, that serves the MCP POSTs itself but answers go-sdk's standalone GET with a 302 to another host. go-sdk v1.8.0 (3f3b699) notes that some servers redirect that GET (streamable.go#L2190-L2196). authCheckRedirect refuses that 302 with an error, so client.Do fails. go-sdk retries the GET five more times, waiting longer before each attempt (streamable.go#L2754-L2760), and then fails the session (streamable.go#L2168-L2175). Tools() returns "failed to init MCP session: standalone SSE request failed … refusing redirect", and the next call starts over.
In the repro below, the first call failed after 21.5 s and the second after 19.2 s. Even with a 3 s context.WithTimeout around each call, they took 16 s and 17.7 s, so a caller cannot bound the wait with a deadline. On main the same server works. There the GET follows the redirect and carries the credential to the other host. go-sdk opens the standalone GET only when the session negotiates a protocol version older than 2026-07-28 (streamable.go#L2143-L2147), and its own v1.8.0 handler negotiated an older one in this repro.
The other host is never contacted on this branch, and that must stay true. Refusing a redirect on this optional stream must not fail the session. go-sdk already treats an answer to this GET that is not text/event-stream as "no stream" and carries on (streamable.go#L2190-L2196).
2. No test lets a caller's CheckRedirect allow a redirect
Every hook in TestAuthRedirectPolicy returns an error, returns ErrUseLastResponse, sits on a cross-host hop, or retargets the request and gets refused. So the return nil at set.go#L182 never runs. Changing it to return an error leaves the whole suite passing. That change would refuse every redirect for any caller that sets its own CheckRedirect, including the same-host /mcp to /mcp/ trailing-slash redirect this PR keeps working.
3. The comment on authCheckRedirect says a caller's hook can never widen the policy, but through an HTTP forward proxy a hook that sets req.Host does
The comment (set.go#L159-L161) says the hook "may refuse more but never allow more". The check after the hook (set.go#L179) reads only req.URL. Take an http endpoint behind an HTTP forward proxy, and a hook that leaves the URL alone but sets req.Host = "evil.test" on the allowed /mcp to /mcp/ hop. The proxy then receives POST http://evil.test/mcp/ carrying the credential, because net/http builds the proxied request target from req.Host. An https endpoint is not affected, since the CONNECT target and the TLS name come from the URL. On main the same hook also sends the credential toward evil.test, so that leak predates this PR. Either the check or the comment has to change.
Non-blocking
Two behaviors that work today have no test:
- The cap under a caller hook. When the caller sets a
CheckRedirect, that hook governs the chain length, and the 10-request cap (set.go#L167-L171) applies only when there is no hook. No case runs more than 10 requests with a hook. - The previous-hop comparison. The post-hook check compares against the previous hop (set.go#L175), which is what refuses an http hop after the chain has moved to https. No case runs even two hops with a hook, so a version that compared against the original URL would leave the suite passing.
Reproductions
Repro for the standalone GET redirect: go test -run TestStandaloneGETCrossHostRedirect -v ./tool/mcptoolset/
package mcptoolset_test
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/modelcontextprotocol/go-sdk/mcp"
"google.golang.org/adk/v2/auth"
icontext "google.golang.org/adk/v2/internal/context"
"google.golang.org/adk/v2/tool/mcptoolset"
)
func TestStandaloneGETCrossHostRedirect(t *testing.T) {
var mu sync.Mutex
var otherAuth []string
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock(); otherAuth = append(otherAuth, r.Method+" "+r.Header.Get("Authorization")); mu.Unlock()
w.Header().Set("Content-Type", "text/html"); io.WriteString(w, "<html>docs</html>")
}))
defer other.Close()
srv := mcp.NewServer(&mcp.Implementation{Name: "t", Version: "1"}, nil)
mcp.AddTool(srv, &mcp.Tool{Name: "ping", Description: "p"}, func(_ context.Context, req *mcp.CallToolRequest, in struct{}) (*mcp.CallToolResult, any, error) { return &mcp.CallToolResult{}, nil, nil })
h := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return srv }, nil)
var gets int
endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
mu.Lock(); gets++; mu.Unlock()
http.Redirect(w, r, other.URL+"/docs", http.StatusFound)
return
}
h.ServeHTTP(w, r)
}))
defer endpoint.Close()
ep := strings.Replace(endpoint.URL, "127.0.0.1", "localhost", 1) + "/mcp"
ts, err := mcptoolset.New(mcptoolset.Config{Endpoint: ep, Auth: auth.StaticToken("secret-tok")})
if err != nil { t.Fatal(err) }
defer ts.(io.Closer).Close()
for i := 0; i < 2; i++ {
start := time.Now()
tools, err := ts.Tools(icontext.NewReadonlyContext(icontext.NewInvocationContext(t.Context(), icontext.InvocationContextParams{})))
t.Logf("Tools call %d: %d tools, err=%v, took %v", i, len(tools), err, time.Since(start).Round(100*time.Millisecond))
}
mu.Lock(); defer mu.Unlock()
t.Logf("endpoint GETs=%d other host saw=%q", gets, otherAuth)
}Repro for the req.Host rewrite: go test -run TestHookHostRewriteViaProxy -v ./tool/mcptoolset/
package mcptoolset_test
import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"sync"
"testing"
"github.com/modelcontextprotocol/go-sdk/mcp"
"google.golang.org/adk/v2/auth"
icontext "google.golang.org/adk/v2/internal/context"
"google.golang.org/adk/v2/tool/mcptoolset"
)
// An HTTP forward proxy records the request target and Authorization of each request.
func TestHookHostRewriteViaProxy(t *testing.T) {
type seen struct{ uri, host, authz string }
var mu sync.Mutex
var got []seen
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock(); got = append(got, seen{r.RequestURI, r.Host, r.Header.Get("Authorization")}); mu.Unlock()
if r.Host == "endpoint.test" && r.URL.Path == "/mcp" {
http.Redirect(w, r, "/mcp/", http.StatusTemporaryRedirect)
return
}
http.Error(w, "x", http.StatusTeapot)
}))
defer proxy.Close()
pu, _ := url.Parse(proxy.URL)
hook := func(req *http.Request, via []*http.Request) error { req.Host = "evil.test"; return nil }
ts, err := mcptoolset.New(mcptoolset.Config{
Transport: &mcp.StreamableClientTransport{Endpoint: "http://endpoint.test/mcp", HTTPClient: &http.Client{
Transport: &http.Transport{Proxy: http.ProxyURL(pu)}, CheckRedirect: hook}},
Auth: auth.StaticToken("secret-tok"),
})
if err != nil { t.Fatal(err) }
defer ts.(io.Closer).Close()
_, err = ts.Tools(icontext.NewReadonlyContext(icontext.NewInvocationContext(t.Context(), icontext.InvocationContextParams{})))
mu.Lock(); defer mu.Unlock()
t.Logf("Tools err = %v", err)
for _, s := range got { t.Logf("proxy saw target=%q host=%q authz=%q", s.uri, s.host, s.authz) }
for _, s := range got { if s.host == "evil.test" && s.authz != "" { t.Errorf("credential sent toward evil.test: %+v", s) } }
}|
All three are fixed in a9ccdf41, and the two untested behaviors have tests now. 1. Refused redirect on the standalone GET. A hop the policy refuses on a GET chain now comes back to net/http as 2. A caller hook that allows a hop. Added as 3. The cap under a caller hook is pinned in The previous-hop comparison under a hook is pinned in The two inline notes on |
karolpiotrowicz
left a comment
There was a problem hiding this comment.
Six things still need to change before this merges. The most serious is that the new host comparison lets through some redirects that send the credential to a name other than the endpoint's, in the Host header or through a forward proxy.
Two of the three items from my earlier review are fixed on this head (a9ccdf4). They are the stalled standalone GET and the missing test for a hook that allows a redirect. The standalone GET is the request that go-sdk, the MCP Go SDK, sends to open its optional server-to-client stream. The third item is still open, though narrower. It is about a caller's CheckRedirect letting the token reach a host the endpoint check would refuse, and item 2 below covers it.
What I checked on this head:
- My standalone GET repro now gets the tool list back at once, and the host that the GET was redirected to sees no request.
- A
CheckRedirecthook that setsreq.Hostorreq.URL.Opaqueis refused. - Each of these now has a test that fails when I break the code it covers:
- a caller's hook that allows a redirect;
- a caller's hook, not the 10-redirect cap, deciding how long a chain may run;
- the comparison against the previous hop.
- The cases from my two inline notes now resolve as your replies say. A redirect between ß and ẞ, or between ς and σ, is refused. A Unicode name and its punycode form match. Both port forms,
http://h:443tohttps://handhttp://htohttps://h:80, are followed.
The checks from my earlier review still pass on this head and on its merge with current main (6d4199c).
Must change before merge
1. dialName matches the address net/http dials, but not the Host header or the proxy target
sameTarget now compares the idna.Lookup form of each host, through the new dialName helper (credredirect.go#L57, credredirect.go#L73-L84). net/http dials that form (Go 1.26.10, transport.go#L3029-L3043). But it writes the Host header, the HTTP/2 :authority and a forward proxy's request target from httpguts.PunycodeHostPort (request.go#L605-L612). That function calls idna.ToASCII, the Punycode profile, which encodes the name as written and does none of the character mapping idna.Lookup does (httplex.go#L324-L347). Lookup drops a soft hyphen (U+00AD), turns fullwidth letters into ASCII and turns ẞ into "ss". So a redirect to such a spelling of the endpoint's own name passes the check, while the request carries a different name.
I ran two cases through mcptoolset.New and Tools(), with Config.Auth set and no caller hook:
- Direct HTTPS. Endpoint
https://api.example.test/mcp, and aLocationthat puts a soft hyphen insideapi. The second request went to the same address with TLS server name (SNI)api.example.test, but withHost: xn--api-hfa.example.testand the bearer token. A front end that routes by Host sends that to whoever serves the other name. - HTTP forward proxy. Endpoint
http://fass.example/mcp, and aLocationofhttp://faẞ.example/mcp/orhttp://fass.example/mcp/(fullwidth f, U+FF46). The proxy receivedPOST http://xn--fa-64s.example/mcp/, orxn--ass-776s.example, with the token.
The previous head (3ddfddd) refused the soft-hyphen, ẞ and fullwidth spellings. It still had the same mismatch for some names, though. That head's EqualFold treats the long s (ſ, U+017F) as s and the Kelvin sign as k, so a redirect from fass.example to faſs.example sends the token to xn--fas-h3a.example on both heads. Switching to idna.Lookup widens that mismatch to endpoint names without an s or a k, since a soft hyphen fits into any label.
My earlier inline note asked for a comparison between the names net/http dials, and that was only half of it. Two URLs are the same target only when every name net/http derives from them matches: the one it dials and the one it writes into the Host header or the proxy target.
agent/remoteagent/v2 calls the same check from its own CheckRedirect (auth.go#L566-L574), so its credential follows the same redirects.
2. A caller's CheckRedirect can still widen the target through a forward proxy
This is the third item from my earlier review, now narrower. A hook that changes req.Host or req.URL.Opaque is now refused, but the path isn't checked after the hook runs. Behind a forward proxy, net/http writes the target as scheme, "://", host and then RequestURI() (request.go#L646-L648), and RequestURI() doesn't add a leading slash (url.go#L1151-L1157). These hooks all got the token to another host:
- A hook that sets
req.URL.Path = ".evil.test/mcp/"sent the token tohttp://endpoint.test.evil.test/mcp/. - On an endpoint with a port, a path of
"@evil.test/mcp/"turned the endpoint's host and port into userinfo and sent the token toevil.test. - A hook that sets
req.URL.Path = strings.TrimPrefix(req.URL.Path, "/api")sent the token tohttp://endpoint.test.evil.test/mcp/when the server's same-originLocationwas/api.evil.test/mcp/.
The previous head behaves the same, so this isn't new behavior. But the comments on authCheckRedirect still say the hook "may refuse more but never allow more" (set.go#L159-L161). They now also say a proxy "takes its target from Host and from an opaque URL" (set.go#L173-L177). Either the check or those comments have to change.
3. The Config.Auth sentence about the optional stream promises more than happens
The new doc says that after a refused redirect on the SDK's optional server-to-client stream, the toolset does without the stream (set.go#L253-L256). That holds for the first standalone GET when the 3xx isn't labelled text/event-stream (streamable.go#L2190-L2196, go-sdk v1.8.0). Two cases fail the session instead:
- A refused 3xx labelled
text/event-stream. It gets past the SDK's content-type check and reachescheckResponse, which fails the session (streamable.go#L2198-L2211).http.Redirectkeeps a Content-Type that the handler set before calling it, so a server only has to set that header before redirecting. I ran this, and everyTools()call failed at once with "standalone SSE stream: Found". The previous head failed the same way after about 20 seconds, and main followed the redirect with the token. - A refused redirect on a reconnect. This covers reconnecting an established stream and resuming a call's stream with Last-Event-ID. The SDK hands the unfollowed 3xx to
checkResponse, which fails the session for any status outside 2xx (streamable.go#L2553-L2568). The session error then reads only the status text, such as "Found" for a 302, and doesn't mention the refused redirect.
Neither case sends the credential anywhere new.
4. Three inline notes that also block merge
- The Host check refuses a hook that copies
req.Hostfrom the previous request. dialNamedrops an emptyxn--label from an ASCII name, and the comment above it says ASCII names are left alone.- The fallback branch in
dialNamehas no test.
The other inline notes don't block.
Reproductions
The Host header over direct HTTPS: go test -run TestHostHeaderAfterMappedRedirect -v ./tool/mcptoolset/
package mcptoolset_test
import (
"context"
"crypto/tls"
"io"
"net"
"net/http"
"net/http/httptest"
"testing"
"github.com/modelcontextprotocol/go-sdk/mcp"
"google.golang.org/adk/v2/auth"
icontext "google.golang.org/adk/v2/internal/context"
"google.golang.org/adk/v2/tool/mcptoolset"
)
func TestHostHeaderAfterMappedRedirect(t *testing.T) {
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Logf("path=%s host=%s sni=%s authz=%q", r.URL.Path, r.Host, r.TLS.ServerName, r.Header.Get("Authorization"))
if r.URL.Path == "/mcp" {
w.Header().Set("Location", "https://ap\u00adi.example.test/mcp/") // soft hyphen inside "api"
w.WriteHeader(http.StatusTemporaryRedirect)
return
}
http.Error(w, "x", http.StatusTeapot)
}))
defer srv.Close()
addr := srv.Listener.Addr().String()
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, network, addr) // every name resolves to the test server
},
}
ts, err := mcptoolset.New(mcptoolset.Config{
Transport: &mcp.StreamableClientTransport{Endpoint: "https://api.example.test/mcp", HTTPClient: &http.Client{Transport: tr}},
Auth: auth.StaticToken("secret-tok"),
})
if err != nil {
t.Fatal(err)
}
defer ts.(io.Closer).Close()
_, err = ts.Tools(icontext.NewReadonlyContext(icontext.NewInvocationContext(t.Context(), icontext.InvocationContextParams{})))
t.Logf("Tools err = %v", err)
}The path after a caller hook, through a forward proxy: go test -run TestHookPathThroughProxy -v ./tool/mcptoolset/
package mcptoolset_test
import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/modelcontextprotocol/go-sdk/mcp"
"google.golang.org/adk/v2/auth"
icontext "google.golang.org/adk/v2/internal/context"
"google.golang.org/adk/v2/tool/mcptoolset"
)
func TestHookPathThroughProxy(t *testing.T) {
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Logf("proxy saw target=%s host=%s authz=%q", r.RequestURI, r.Host, r.Header.Get("Authorization"))
if r.Host == "endpoint.test" && r.URL.Path == "/mcp" {
w.Header().Set("Location", "/api.evil.test/mcp/") // same origin
w.WriteHeader(http.StatusTemporaryRedirect)
return
}
http.Error(w, "x", http.StatusTeapot)
}))
defer proxy.Close()
pu, _ := url.Parse(proxy.URL)
hook := func(r *http.Request, _ []*http.Request) error { r.URL.Path = strings.TrimPrefix(r.URL.Path, "/api"); return nil }
ts, err := mcptoolset.New(mcptoolset.Config{
Transport: &mcp.StreamableClientTransport{Endpoint: "http://endpoint.test/mcp", HTTPClient: &http.Client{
Transport: &http.Transport{Proxy: http.ProxyURL(pu)}, CheckRedirect: hook}},
Auth: auth.StaticToken("secret-tok"),
})
if err != nil {
t.Fatal(err)
}
defer ts.(io.Closer).Close()
_, err = ts.Tools(icontext.NewReadonlyContext(icontext.NewInvocationContext(t.Context(), icontext.InvocationContextParams{})))
t.Logf("Tools err = %v", err)
}|
All six are addressed in 8499152f. 1. The Host header and the proxy target. 2. The path through a forward proxy. 3. The 4. The three inline notes are answered in their threads: a hook pinning On the two non-blocking inline notes: the fallback comparison you pointed at is gone with One more thing the change surfaced: with the port rule from your first review, |
…ion, and hold Host and Opaque through a caller hook On protocol versions before 2026-07-28 go-sdk opens its optional server-to-client stream with a GET after initialize. An error from client.Do on that GET is retried with growing delays and then fails the session, so a server that redirects the GET elsewhere made every Tools() call fail after about 20 seconds, while an answer that is not text/event-stream only means the server offers no stream. A refused hop on a GET chain now hands net/http the 3xx unfollowed instead of an error. The JSON-RPC traffic is POST and keeps the error. Through an HTTP forward proxy the request target comes from req.Host or an opaque URL rather than from req.URL, so a caller CheckRedirect that set either one sent the credential toward another host with the URL check passing. Both now have to stay as they were before the hook ran. In credredirect, compare the names net/http dials, the IDNA ASCII forms, instead of the written hostnames: ß and ẞ, or ς and σ, case-fold equal but map to different names, and a Unicode name and its punycode form map to the same one. Let the http to https upgrade keep a port that one side writes out and the other implies, which the Config.Auth doc already promised. Add the tests the review asked for: a caller hook that allows a hop, the cap under a caller hook, and the previous-hop comparison under a hook.
… and hold the wire target through a caller hook net/http derives two names from a URL's host. It dials the IDNA lookup form, which maps characters before encoding, and it writes the Host header and a forward proxy's request target from the punycode form of the name as written. The previous head compared the lookup form only, so a Location spelling the endpoint's name with a soft hyphen, a fullwidth letter, a long s or ẞ for ss passed while the request carried another Host. A redirect is now the same target only when both names agree. ASCII names are taken as written by both, as net/http does, so an empty punycode label is no longer dropped and a Unicode name still equals its punycode form. Check also refuses a request that would address another host on the wire than its URL names: a Host header for another host or port, an opaque URL, or a path without a leading slash, which a forward proxy turns into another target. That closes the path rewrites a caller CheckRedirect could make after the policy had passed the hop, and it accepts a hook that merely pins req.Host to the URL's host, which the previous head refused. State on Config.Auth what a refused redirect does on the SDK's optional server-to-client stream: the first stream request's 3xx reads as no stream unless it is labeled text/event-stream, and a labeled 3xx or one on a reconnect fails the session with the status text. Pin dialName and hostName each on their own, Check's chain and wire-target rules directly, and the GET-chain refusal after a hook.
8499152 to
2986d8d
Compare
wojtas000
left a comment
There was a problem hiding this comment.
Two things block: the description says agent/remoteagent/v2 keeps its behavior, and it does not, and a refused redirect now returns the server's Location query string inside the error. The redirect guard itself holds up. I disabled it and watched Bearer user-tok reach endpoint.test.evil.test through the proxy, so this is about what the change says and what it prints, not about the approach.
Must change before merge:
-
Say what changes for an A2A user, and pin it. The Summary says the rule "moved unchanged" and that
remoteagent/v2"keeps its behavior and error messages". I ran the same table of hops throughauthHTTPClient(nil).CheckRedirecton the merge base and on this head. Seven of eleven decisions differ:hop main this PR https://faß.exampletohttps://xn--fa-hia.examplerefused followed https://xn--fa-hia.exampletohttps://faß.examplerefused followed https://faß.exampletohttps://faẞ.examplefollowed refused https://MÜNCHEN.exampletohttps://münchen.examplefollowed refused http://htohttps://h:80refused followed http://h:443tohttps://hrefused followed a req.Hostnaming another hostfollowed refused, new message None of the loosened hops sends the credential anywhere new. In each one the dial address, the port and the
Hostheader are identical on both sides. The tightened ones close a hole, becausestrings.EqualFoldfolded ß with ẞ although the two carry differentHostheaders. The cross-host and downgrade message is byte-identical, so that part of the claim holds.The code looks right to me. The description is what needs fixing, and so does the test gap. With
if !addressesOwnHost(req)replaced byif false,internal/credredirectandtool/mcptoolsetgo red whileagent/remoteagent/v2stays green:TestSameCredentialTargetmoved out and nothing inremoteagent/v2replaced it. -
Keep the server's
Locationout of the error. Details inline on set.go:202. Short version: net/http overwritesurl.Error.URLwith the rawLocationheader, so a307to…/cb?code=…&state=…puts that query string in whatTools()returns. On main there is no refusal and no such error, so this is new here. -
The Summary's "The call fails with an error and the other host is never contacted" is not true of the stream GET. There the refusal is
http.ErrUseLastResponse, the session continues with no server-to-client stream, and nothing is logged. TheConfig.Authdoc comment describes this correctly, the Summary does not. The code is deliberate and well pinned, since I mutated the GET branch and six subtests went red, so this is a description fix too.
Non-blocking, all inline: the post-hook refusal reads via[0].Method off the live slice the hook may have edited (set.go:199). Config.Auth's doc states go-sdk behavior unconditionally where the private comment qualifies it, and does not say the redirect bound stops at a caller-supplied Transport (set.go:247, set.go:253). credredirect.go:85 is uncovered. The paragraph at credredirect.go:105 is attached to no declaration and go doc drops it, and the comment at credredirect.go:40 names the two checks in the opposite order from the loop. And no test distinguishes via[0].Method from another request in the chain (redirect_test.go:62).
One more, your call rather than mine: the two callers apply the hop cap in opposite order, so a cross-origin 10th hop reports differently from mcptoolset and from remoteagent/v2. Both stop the chain, and aligning them would change remoteagent/v2's error text, which is the thing you deliberately kept.
What I ran
Build, go vet, gofmt -l, go mod tidy -diff, the full test suite, -race on the three touched packages, staticcheck, govulncheck and golangci-lint run are all clean, in both modules. apidiff is empty for tool/mcptoolset and agent/remoteagent/v2. session/vertexai was excluded, because it hangs the same way on main. There are no fuzz targets in the touched packages.
Each gate was made to fail on purpose first: an injected exported symbol shows up in apidiff, an injected unsynchronized counter trips -race, an injected strings.Index(s, "x") > -1 trips staticcheck, and replacing if !addressesOwnHost(req) with if false turns two packages red.
Coverage: internal/credredirect 96.2% new, tool/mcptoolset 95.4% to 95.6%, agent/remoteagent/v2 92.7% to 92.6%.
Your set_test.go applied to the merge base fails 12 subtests that pass here, which covers the cross-host and hook-rewrite cases. It does not reach the https-to-http downgrade end to end, the IDNA comparison, the port rules, or anything in agent/remoteagent/v2.
Two things I could not settle. Nothing anywhere observes what net/http actually dials or writes as Host for an internationalized name, and TestHostNames asserts literal strings the implementation also computes, so a change in either derivation leaves every test green. And no changed remoteagent/v2 decision was driven through a real a2a-go client, so whether the new refusal message can occur there at all depends on whether a2a-go ever sets req.Host, which I did not establish.
…'s error, and decide the chain's method before the hook runs net/http wraps a CheckRedirect error in a *url.Error whose URL is the raw Location header, so a refused cross-host 307 to an SSO callback put its code and state into what Tools() returned. The refusal is now a typed error, and withRetry, the one place every session error leaves the toolset, replaces the *url.Error around it with the refusal itself, keeping the message of every layer above. The refusal already names both origins. refuseRedirect read via[0].Method off the slice after the caller's hook had run, so a hook that set it to GET on a POST chain turned the refusal into an unfollowed 3xx. The method is taken before the hook, with the URLs. Pin in remoteagent/v2's own table the decisions that change for the A2A path now that the host comparison is shared, check dialName and hostName against what net/http dials and sends as Host rather than against literals, cover the hostName failure branch, and fix the Check comment's order and the paragraph go doc dropped. The Config.Auth doc now says the bound stops at a supplied Transport and qualifies the stream behavior by protocol version and SDK release.
|
All three are addressed in f8956168 and in the description, plus the inline notes. 1. What changes for an A2A user. The description's Summary now says the host comparison changes on the move, lists the decisions that differ for 2. The 3. The stream GET sentence. The Summary now says what the code does: an error on the POSTs, the unfollowed 3xx on the stream GET, and what the SDK in Inline notes. The method is taken before the hook runs, with the URLs (set.go#L167), and two rows pin it, a chain a 303 turned from POST into GET and a hook that rewrites On the two things you could not settle: The cap order between the two callers I left as is, for the reason you gave. |
Everything this review asked for is fixed on the current head.
karolpiotrowicz
left a comment
There was a problem hiding this comment.
Three things still need to change before this merges. The withRetry redaction works: Tools() and tool-call errors no longer carry the Location, and the same-hop method rewrite is fixed.
Must change before merge:
Close()and the reconnect log line still carry a refused redirect'sLocation. Closing a session sends a DELETE through the same client. When the server answers it with a cross-host 307 to…/sso?code=…&state=…,Close()returnsDelete "…/sso?code=…&state=…": mcptoolset: refusing redirect …. After a failed call forces a reconnect,refreshConnectionwrites the same text withlog.Printf(client.go#L103, #L249-L250). Nothing the toolset returns or logs should carry the server'sLocation.- The Host check accepts a bracketed or unbracketed spelling of the endpoint's name (inline on
credredirect.go). - The GET sentence in the
Config.Authdoc and inrefuseRedirect's comment (inline onset.go).
Not from this PR: the redirect-cap error and the remoteagent/v2 refusal carry the Location the same way on main, which may be worth a follow-up.
The branch now conflicts with main in set.go's imports, and no CI has run on this head. On its merge with main the same checks are clean, apart from plugin/agentanalytics, which fails to build on main itself.
Close after a cross-host DELETE redirect: go test -run TestCloseRedirectLocation -v ./tool/mcptoolset/
package mcptoolset_test
import (
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/modelcontextprotocol/go-sdk/mcp"
"google.golang.org/adk/v2/auth"
icontext "google.golang.org/adk/v2/internal/context"
"google.golang.org/adk/v2/tool/mcptoolset"
)
func TestCloseRedirectLocation(t *testing.T) {
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("other host received %s", r.Method)
}))
defer other.Close()
srv := mcp.NewServer(&mcp.Implementation{Name: "t", Version: "1"}, nil)
h := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return srv }, nil)
endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodDelete {
http.Redirect(w, r, other.URL+"/sso?code=SECRET&state=xyz", http.StatusTemporaryRedirect)
return
}
h.ServeHTTP(w, r)
}))
defer endpoint.Close()
ts, err := mcptoolset.New(mcptoolset.Config{Endpoint: endpoint.URL + "/mcp", Auth: auth.StaticToken("secret-tok")})
if err != nil {
t.Fatal(err)
}
inv := icontext.NewInvocationContext(t.Context(), icontext.InvocationContextParams{})
if _, err := ts.Tools(icontext.NewReadonlyContext(inv)); err != nil {
t.Fatal(err)
}
t.Logf("Close err = %v", ts.(io.Closer).Close())
}A hook that brackets the Host: go test -run TestBracketedHostHeader -v ./tool/mcptoolset/
package mcptoolset_test
import (
"context"
"io"
"net"
"net/http"
"net/http/httptest"
"testing"
"github.com/modelcontextprotocol/go-sdk/mcp"
"google.golang.org/adk/v2/auth"
icontext "google.golang.org/adk/v2/internal/context"
"google.golang.org/adk/v2/tool/mcptoolset"
)
func TestBracketedHostHeader(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Logf("path=%s host=%s authz=%q", r.URL.Path, r.Host, r.Header.Get("Authorization"))
if r.URL.Path == "/mcp" {
http.Redirect(w, r, "/mcp/", http.StatusTemporaryRedirect)
return
}
http.Error(w, "x", http.StatusTeapot)
}))
defer srv.Close()
addr := srv.Listener.Addr().String()
tr := &http.Transport{DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, network, addr) // every name resolves to the test server
}}
hook := func(r *http.Request, _ []*http.Request) error { r.Host = "[endpoint.test]"; return nil }
ts, err := mcptoolset.New(mcptoolset.Config{
Transport: &mcp.StreamableClientTransport{Endpoint: "http://endpoint.test/mcp", HTTPClient: &http.Client{Transport: tr, CheckRedirect: hook}},
Auth: auth.StaticToken("secret-tok"),
})
if err != nil {
t.Fatal(err)
}
defer ts.(io.Closer).Close()
_, err = ts.Tools(icontext.NewReadonlyContext(icontext.NewInvocationContext(t.Context(), icontext.InvocationContextParams{})))
t.Logf("Tools err = %v", err)
}A refused redirect on a resumed tool call: go test -run TestResumeGETRedirect -v ./tool/mcptoolset/
package mcptoolset_test
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/modelcontextprotocol/go-sdk/mcp"
"google.golang.org/adk/v2/agent"
"google.golang.org/adk/v2/auth"
icontext "google.golang.org/adk/v2/internal/context"
"google.golang.org/adk/v2/internal/toolinternal"
"google.golang.org/adk/v2/tool/mcptoolset"
)
func TestResumeGETRedirect(t *testing.T) {
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Errorf("other host received %s", r.Method)
}))
defer other.Close()
srv := mcp.NewServer(&mcp.Implementation{Name: "t", Version: "1"}, nil)
mcp.AddTool(srv, &mcp.Tool{Name: "ping"}, func(context.Context, *mcp.CallToolRequest, struct{}) (*mcp.CallToolResult, any, error) {
return &mcp.CallToolResult{}, nil, nil
})
h := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return srv }, nil)
endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet && r.Header.Get("Last-Event-ID") != "" {
t.Logf("resume GET, Last-Event-ID=%s", r.Header.Get("Last-Event-ID"))
http.Redirect(w, r, other.URL, http.StatusFound)
return
}
body, _ := io.ReadAll(r.Body)
if strings.Contains(string(body), `"tools/call"`) {
// One event with an id, then the stream ends before the response.
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, "id: 1\ndata: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/message\",\"params\":{\"level\":\"info\",\"data\":\"x\"}}\n\n")
return
}
r.Body = io.NopCloser(strings.NewReader(string(body)))
h.ServeHTTP(w, r)
}))
defer endpoint.Close()
ts, err := mcptoolset.New(mcptoolset.Config{Endpoint: endpoint.URL + "/mcp", Auth: auth.StaticToken("secret-tok")})
if err != nil {
t.Fatal(err)
}
defer ts.(io.Closer).Close()
inv := icontext.NewInvocationContext(t.Context(), icontext.InvocationContextParams{})
tools, err := ts.Tools(icontext.NewReadonlyContext(inv))
if err != nil {
t.Fatal(err)
}
_, err = tools[0].(toolinternal.FunctionTool).Run(agent.NewToolContext(inv, "", nil, nil), map[string]any{})
t.Logf("Run err = %v", err)
}…, and compare the Host header net/http writes A refused redirect on the DELETE that closes a session, and on the close a reconnect performs, carried the server's Location through Close() and the "failed to close MCP session" log line. Both now go through the same redaction as a call's error. The redaction keeps every error a rebuilt layer wrapped beside the refusal, so errors.As for the SDK's typed error matches as before. addressesOwnHost parsed req.Host as a URL host, which let a respelling of the endpoint's own name through: brackets around it, a port folded into an IPv6 literal, the default port written out. net/http sends the string as given, so the check now compares the exact Host header net/http would write from the URL with the one it would write from req.Host. Say in refuseRedirect's comment and the Config.Auth doc that the SDK also sends a GET to resume a call's event stream, and what a refused redirect there does.
…-redirect # Conflicts: # tool/mcptoolset/set.go
|
All three are fixed in 9db4c6d8, and the branch is merged with current main (e11641c8) so CI runs on this head.
The Host check. It compares the exact string net/http writes, not a parsed host: the Host header net/http would derive from The GET sentence. On the follow-up you mention: the redirect-cap error and |
There was a problem hiding this comment.
Fix before merge: TestHostNames in internal/credredirect fails on Go 1.27. CI runs Go 1.26.10, the version in go.mod, and it passes there. The faẞ.example row expects net/http to dial fass.example, which is what Go 1.26 does. Go 1.27 dials xn--fa-hia.example, the punycode of faß.example. TestHostNamesMatchNetHTTP passes for that host on both versions, so dialName follows net/http on each, and only the hard-coded expectation is tied to one version. go.mod sets a minimum, so anyone running the suite on 1.27 gets a red test. Details are inline.
The redirect rule itself holds up. Every hop this change starts following keeps the same address, port and Host header. Every hop it starts refusing would send a different Host header. A hook that edits the request cannot widen the rule after the check has run. The Location stays out of every error the toolset returns and out of its log line.
I checked each point raised against the earlier commit:
- A2A users: the behavior change is real. A redirect from a Unicode host name to its punycode spelling used to be refused and is now followed with the token. The two written-out default-port upgrades are followed too. ß to ẞ, a difference in Unicode case, and a Host header naming another host are now refused.
TestCheckRedirectinagent/remoteagent/v2now pins all six of these, and they fail without the change. The thread says the description now lists them; please make sure it does. The new Host-header refusal cannot occur for an A2A user today, because net/http never sets that header when it follows a redirect. - adk-python follows a redirect to another host without the token, while this change refuses the hop, so a server that relies on that redirect now fails at tool discovery. The description argues for this on purpose. It is a product call, not a defect.
- Copying net/http's host-name rules by hand:
TestHostNamesMatchNetHTTPnow checks them against real requests, and it is what shows the hand-written table is wrong.golang.org/x/netgoes from indirect to direct ingo.modat the same version. - Guarding against the application's own redirect hook: the
Config.Authdoc says that a transport the application supplies sits below the credential and outside this rule. So the post-hook re-check guards against honest mistakes, not attackers. It is small and tested, and keeping it is reasonable. - The MCP SDK's own same-origin rule (modelcontextprotocol/go-sdk#1440) is not in the SDK version in
go.mod, so nothing changes today. The two hops it refuses and this rule allows, a method change and added user info, both stay on the same host and port. Revisit when the SDK is upgraded.
… literal TestHostNames expected net/http to dial fass.example for faẞ.example. That is what the IDNA tables of Go 1.26 give. Go 1.27 ships Unicode 17 tables, which map ẞ to ß, so the same name is dialed as xn--fa-hia.example and the row failed for anyone running the suite on 1.27, while CI, on the go.mod version, stayed green. dialName follows net/http on both, which TestHostNamesMatchNetHTTP shows by recording what a real client dials. The table keeps only the Host header name, which does not depend on the mapping tables, and the dial name is left to the net/http test. Removing the ASCII fast path, the lookup profile or the fallback from dialName still fails that test on both releases. Reword the comments that named which spellings share a dial address, since that also follows the Go release, and narrow the claim that a Unicode name equals its punycode form to a name already in its mapped form.
… a redirected reconnect withRetry redacted a refused redirect's Location at four return sites, and no test reached the two on the reconnect path: removing either left the suite green. A call's error now leaves through one deferred redaction, so there is no per-site call to forget. The reconnect's own error is formatted into the message rather than wrapped, so it keeps a redaction of its own. TestAuthRedirectLocationStaysOut gains a reconnect that is itself redirected to another host, which fails without that second redaction, and a call on a session that is already up.
|
Fixed in 7ecf887b and 29ab6d80. The three touched packages now pass on Go 1.27.3 as well as on 1.26.10. The Go 1.27 failure. Reproduced on 1.27.3: The description. It lists the six A2A decisions. Two of its sentences were wrong and are corrected. "A Unicode name and its punycode form are one target" holds only for a name already in its mapped form, since The three nits are answered in their threads. |
wojtas000
left a comment
There was a problem hiding this comment.
The Go 1.27 failure is fixed. The three touched packages pass on Go 1.27.3 and on 1.26.10, and on this head merged with main. With dialName returning the name as written, TestHostNamesMatchNetHTTP fails on both releases, so dropping the literal dial column lost nothing. The reworded comments hold on both releases. Taking the dial comparison out of sameTarget still fails the faẞ.example to xn--fa-64s.example row, which is the one case where only the dial name differs. The new reconnect case fails when its redaction is removed, and the established-session case fails without the deferred one.
Review was finalized with Jan, thank you for the previous comments.
Problem
With
Config.Authset,tool/mcptoolsethands the configured credential to whatever host a redirect names.httpClientinstallsauth.Transport, which applies the credential to every request it sends, redirect hops included. That runs below the layer where net/http stripsAuthorizationon a cross-host redirect, and the client never setsCheckRedirect, so net/http's default policy follows the redirect and the credential goes with it. Anhttpstohttpredirect sends it in cleartext.The
auth/gcpprovider already requires that the client carryingauth.Transportrefuse cross-host redirects, andagent/remoteagent/v2enforces the same forA2AConfig.Auth.modelcontextprotocol/go-sdk#1440 restricts redirects to the same origin in the SDK, but it is not in a release yet, and it steps aside whenever the
http.Clientsets its ownCheckRedirectorMCPGODEBUG=followallredirects=1is set. Either one lets the credential follow a cross-origin redirect again, which is the open question on #1965.Summary
Config.Authset, the toolset's HTTP client refuses a redirect unless it stays on the endpoint's host and port and either keeps the scheme or upgrades http to https. The other host is never contacted. On the JSON-RPC requests, which are POSTs, the call fails with an error that names both origins and nothing else from the server'sLocation. On a GET the unfollowed 3xx goes back to the SDK instead. go-sdk sends a GET for its optional server-to-client stream (protocol versions before 2026-07-28) and to resume a call's event stream withLast-Event-ID, and an error on the stream GET is retried with growing delays and then fails the session. With the SDK release ingo.mod, a 3xx on the first stream request that is not labeledtext/event-streammeans no stream and the session goes on, while one that is labeled, one on a stream reconnect, or one on a resume fails the session or the call with the status text as the reason. A same-origin redirect such as/mcpto/mcp/, which Starlette and FastMCP mounts send, is still followed with the credential.CheckRedirecton a caller-suppliedHTTPClientruns after this check, so it can refuse more redirects but cannot let the credential reach another origin, through the URL or through the request'sHostheader, path or opaque URL, which a forward proxy takes its target from. Without one, the client keeps net/http's limit of 10 requests per chain. Toolsets withoutConfig.Authare unchanged. ATransportsupplied through theHTTPClientsits below the credential and is outside the bound.agent/remoteagent/v2applied forA2AConfig.Authmoves intointernal/credredirect, and both auth paths share it. Its host comparison changes on the way: two URLs are the same target only when both names net/http derives from the host agree, the IDNA lookup form it dials and the punycode of the name as written, which it sends asHostand as a forward proxy's request target. Comparing the written hostnames withstrings.EqualFold, as before, folded ß with ẞ although the two carry differentHostheaders. Forremoteagent/v2that means: a Unicode name that is already in its mapped form, such asfaß.example, and its punycode form are now one target, two spellings that dial or sendHostdifferently (ß against ẞ, ς against σ, a soft hyphen, a fullwidth letter, Unicode case) are refused where some were followed, an upgrade whose port is written out on one side and implied on the other (http://htohttps://h:80,http://h:443tohttps://h) is followed where it was refused, and a request whoseHostheader names another host is refused with a new message. None of the loosened cases sends the credential anywhere new: the dial address, the port and theHostheader are the same on both sides. The cross-host and downgrade error text is unchanged.The redirect is refused rather than followed without the credential, for three reasons. It matches
remoteagent/v2and the MCP SDKs (modelcontextprotocol/go-sdk#1440, modelcontextprotocol/python-sdk#3397). Following it would still send the JSON-RPC request body, tool arguments included, to the other host. And an endpoint that requires the credential would answer the unauthenticated request with an error anyway. adk-python is closer to the second option:_RefreshableAsyncCredentialsskips the google-auth token when the redirect's host and port differ from the endpoint's, and httpx strips a staticAuthorizationheader on a cross-origin redirect. Both still follow the redirect.Once a go-sdk release with #1440 is picked up, a toolset with
Config.Authuses this policy instead of the SDK's, because the SDK defers to anyCheckRedirect. The SDK's policy also refuses a redirect that changes the HTTP method or the URL userinfo. Those two checks will not apply withConfig.Authunless they are added here too.Fixes #1965