Skip to content

fix(mcptoolset): keep the Config.Auth credential on the endpoint's origin across redirects - #1986

Merged
wolo-lab merged 12 commits into
mainfrom
wolo/mcptoolset-check-redirect
Nov 18, 2026
Merged

wolo-lab merged 12 commits into
mainfrom
wolo/mcptoolset-check-redirect

Conversation

@wolo-lab

@wolo-lab wolo-lab commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Problem

With Config.Auth set, tool/mcptoolset hands the configured credential to whatever host a redirect names. httpClient installs auth.Transport, which applies the credential to every request it sends, redirect hops included. That runs below the layer where net/http strips Authorization on a cross-host redirect, and the client never sets CheckRedirect, so net/http's default policy follows the redirect and the credential goes with it. An https to http redirect sends it in cleartext.

The auth/gcp provider already requires that the client carrying auth.Transport refuse cross-host redirects, and agent/remoteagent/v2 enforces the same for A2AConfig.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.Client sets its own CheckRedirect or MCPGODEBUG=followallredirects=1 is set. Either one lets the credential follow a cross-origin redirect again, which is the open question on #1965.

Summary

  • With Config.Auth set, 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's Location. 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 with Last-Event-ID, and an error on the stream GET is retried with growing delays and then fails the session. With the SDK release in go.mod, a 3xx on the first stream request that is not labeled text/event-stream means 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 /mcp to /mcp/, which Starlette and FastMCP mounts send, is still followed with the credential.
  • A CheckRedirect on a caller-supplied HTTPClient runs after this check, so it can refuse more redirects but cannot let the credential reach another origin, through the URL or through the request's Host header, 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 without Config.Auth are unchanged. A Transport supplied through the HTTPClient sits below the credential and is outside the bound.
  • The rule agent/remoteagent/v2 applied for A2AConfig.Auth moves into internal/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 as Host and as a forward proxy's request target. Comparing the written hostnames with strings.EqualFold, as before, folded ß with ẞ although the two carry different Host headers. For remoteagent/v2 that means: a Unicode name that is already in its mapped form, such as faß.example, and its punycode form are now one target, two spellings that dial or send Host differently (ß 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://h to https://h:80, http://h:443 to https://h) is followed where it was refused, and a request whose Host header 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 the Host header 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/v2 and 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: _RefreshableAsyncCredentials skips the google-auth token when the redirect's host and port differ from the endpoint's, and httpx strips a static Authorization header on a cross-origin redirect. Both still follow the redirect.

Once a go-sdk release with #1440 is picked up, a toolset with Config.Auth uses this policy instead of the SDK's, because the SDK defers to any CheckRedirect. The SDK's policy also refuses a redirect that changes the HTTP method or the URL userinfo. Those two checks will not apply with Config.Auth unless they are added here too.

Fixes #1965

@wolo-lab
wolo-lab marked this pull request as ready for review October 28, 2026 17:12
…-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 karolpiotrowicz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) } }
}

Comment thread internal/credredirect/credredirect.go Resolved
Comment thread internal/credredirect/credredirect.go Resolved
@wolo-lab
wolo-lab requested a review from a team as a code owner November 4, 2026 19:16
@wolo-lab

wolo-lab commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

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 http.ErrUseLastResponse instead of an error (refuseRedirect). go-sdk then sees a 3xx that is not text/event-stream, logs it and carries on without the stream, which is what it does for a server that offers none. The JSON-RPC traffic is POST and keeps the error, since that is the message a caller can act on. Your repro is TestAuthRedirectStandaloneStream now: Tools() returns the tool in about 10 ms, the endpoint's GET was redirected, and the other host saw no request. It took 21 s and failed before the change. The behavior is stated on Config.Auth.

2. A caller hook that allows a hop. Added as same origin with a permissive caller CheckRedirect: the trailing-slash hop is followed with the credential. Turning the return nil after the hook into an error fails it.

3. req.Host through a forward proxy. The post-hook check now also requires req.Host and req.URL.Opaque to be what they were before the hook ran (set.go#L176-L188). Opaque was a second way in: a hook setting req.URL.Opaque = "//evil.test/mcp/" made the proxy receive POST http://evil.test/mcp/ with the token too. Your proxy repro, with both variants, is TestAuthRedirectHookRewritesHost. Dropping either half of the guard fails the matching case.

The cap under a caller hook is pinned in TestAuthRedirectCap: with an allow-all hook the chain runs past 10 and ends where the server stops it, at hop 16.

The previous-hop comparison under a hook is pinned in TestAuthCheckRedirectChains: a hook that sets the scheme back to http after the chain moved to https is refused, and comparing against the original URL alone lets that one through, since the original was http as well.

The two inline notes on credredirect are answered in their threads. Both are in the same commit.

@karolpiotrowicz karolpiotrowicz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 CheckRedirect hook that sets req.Host or req.URL.Opaque is 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:443 to https://h and http://h to https://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 a Location that puts a soft hyphen inside api. The second request went to the same address with TLS server name (SNI) api.example.test, but with Host: xn--api-hfa.example.test and 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 a Location of http://faẞ.example/mcp/ or http://fass.example/mcp/ (fullwidth f, U+FF46). The proxy received POST http://xn--fa-64s.example/mcp/, or xn--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 to http://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 to evil.test.
  • A hook that sets req.URL.Path = strings.TrimPrefix(req.URL.Path, "/api") sent the token to http://endpoint.test.evil.test/mcp/ when the server's same-origin Location was /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 reaches checkResponse, which fails the session (streamable.go#L2198-L2211). http.Redirect keeps 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 every Tools() 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.Host from the previous request.
  • dialName drops an empty xn-- label from an ASCII name, and the comment above it says ASCII names are left alone.
  • The fallback branch in dialName has 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)
}

Comment thread tool/mcptoolset/set.go Resolved
Comment thread internal/credredirect/credredirect.go Resolved
Comment thread internal/credredirect/credredirect.go Resolved
Comment thread internal/credredirect/credredirect.go Resolved
Comment thread tool/mcptoolset/set.go Resolved
Comment thread tool/mcptoolset/set.go Resolved
@wolo-lab

wolo-lab commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

All six are addressed in 8499152f.

1. The Host header and the proxy target. sameTarget now requires both names net/http derives from the host to agree: the lookup form it dials (dialName) and the punycode form of the name as written, which it puts in the Host header and a proxy's request line (hostName). Both take an ASCII name as written, as net/http does. One is not enough in either direction: a soft hyphen, a fullwidth letter, a long s or ẞ against ss share a dial address and carry a different Host, while faẞ.example and its own punycode xn--fa-64s.example share a Host and are dialed as fass.example and xn--fa-64s.example, since the lookup profile rejects the decoded label and net/http falls back to the written name. Rows for all of your spellings, plus the Kelvin sign and a non-ASCII case difference, are in TestSameTarget. Your soft-hyphen repro over TLS is refused now, and the server only ever saw Host: api.example.test. Over a fixed set of 43,264 URL pairs against the previous head, 26 host pairs change answer, every one from followed to refused, and all of them are one of those spellings.

2. The path through a forward proxy. Check now refuses a request that would address another host on the wire than its URL names (addressesOwnHost): an opaque URL, a path without a leading slash, or a Host header naming another host or port. The post-hook check in mcptoolset is just Check against the copies again, with the Host snapshot gone. Your three path hooks are in TestAuthRedirectHookRewritesTarget, including the prefix-trimming one against a /api.evil.test/mcp/ Location, and the proxy saw endpoint.test only. Each sub-check fails its own case when removed.

3. The Config.Auth sentence. Rewritten to say what happens (set.go#L247-L258): the first stream request's unfollowed 3xx means no stream unless it is labeled text/event-stream, and a labeled 3xx or any 3xx on a reconnect fails the session with the status text. The labeled case is now a test row (set_test.go#L1645): it fails at once with Found, under the retry budget, and nothing reaches the other host. I left the behavior as it is, since an error from client.Do on either of those requests gets the same retry-then-fail you measured on the earlier head, only slower.

4. The three inline notes are answered in their threads: a hook pinning req.Host to the URL's host is followed again, an ASCII name is never run through an IDNA profile, and each helper has its own table.

On the two non-blocking inline notes: the fallback comparison you pointed at is gone with dialName's rewrite, and the GET-chain refusals after a hook have cases now (redirect_test.go#L51-L52). The message that named the endpoint host now says which of the three fields pointed elsewhere.

One more thing the change surfaced: with the port rule from your first review, sameTarget keeps a chain on one host and port by itself, so the comparison against the original request refuses nothing the previous-hop comparison does not. I kept it as a second line and said so in the comment rather than claiming it stops laundering.

…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.

@wojtas000 wojtas000 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. 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 through authHTTPClient(nil).CheckRedirect on the merge base and on this head. Seven of eleven decisions differ:

    hop main this PR
    https://faß.example to https://xn--fa-hia.example refused followed
    https://xn--fa-hia.example to https://faß.example refused followed
    https://faß.example to https://faẞ.example followed refused
    https://MÜNCHEN.example to https://münchen.example followed refused
    http://h to https://h:80 refused followed
    http://h:443 to https://h refused followed
    a req.Host naming another host followed refused, new message

    None of the loosened hops sends the credential anywhere new. In each one the dial address, the port and the Host header are identical on both sides. The tightened ones close a hole, because strings.EqualFold folded ß with ẞ although the two carry different Host headers. 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 by if false, internal/credredirect and tool/mcptoolset go red while agent/remoteagent/v2 stays green: TestSameCredentialTarget moved out and nothing in remoteagent/v2 replaced it.

  2. Keep the server's Location out of the error. Details inline on set.go:202. Short version: net/http overwrites url.Error.URL with the raw Location header, so a 307 to …/cb?code=…&state=… puts that query string in what Tools() returns. On main there is no refusal and no such error, so this is new here.

  3. 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. The Config.Auth doc 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.

Comment thread tool/mcptoolset/set.go Resolved
Comment thread tool/mcptoolset/set.go Resolved
Comment thread tool/mcptoolset/set.go Resolved
Comment thread tool/mcptoolset/set.go Resolved
Comment thread internal/credredirect/credredirect.go Resolved
Comment thread internal/credredirect/credredirect.go Resolved
Comment thread tool/mcptoolset/redirect_test.go Resolved
…'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.
@wolo-lab

Copy link
Copy Markdown
Contributor Author

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 remoteagent/v2 and why none of the loosened ones sends the credential anywhere new. The pin you asked for is in remoteagent/v2's own TestCheckRedirect: the punycode pair, ß to ẞ, Unicode case, both port forms, and a Host header naming the URL's host or another one. With if false on addressesOwnHost, agent/remoteagent/v2 goes red with the other two packages now.

2. The Location in the error. The refusal is a typed error (redirectRefusedError), and redactRedirectTarget replaces the *url.Error net/http wraps it in with the refusal itself, keeping the message of every layer above, including the SDK's two-error wrap between the request and the transport error. It runs in withRetry, which every session error leaves the toolset through, on tool calls as well as on Tools(). Your repro now yields … sending "initialize": rejected by transport: mcptoolset: refusing redirect from http://localhost:<p1> to http://127.0.0.1:<p2>: Config.Auth is set and the credential would follow. The cross-host rows in TestAuthRedirectPolicy send a Location shaped like an SSO bounce and assert its query never reaches the caller (set_test.go#L1559-L1560, #L1611), and TestRedactRedirectTarget drives the chain shapes directly, including a *url.Error with no refusal under it, which is left alone.

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 go.mod makes of that.

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 via[0].Method (redirect_test.go#L60-L62). Your via[len(via)-1].Method mutant fails the first of them now. The Config.Auth doc says the bound stops at a supplied Transport (set.go#L316) and qualifies the stream behavior by protocol version and by the SDK release in go.mod (#L324). hostName's failure branch has a row, a Unicode host beside an invalid punycode label, xn--zzz-.faß.example (credredirect_test.go#L91). The orphan paragraph is now dialName's doc (credredirect.go#L106), and the Check comment names the two comparisons in the loop's order (#L40).

On the two things you could not settle: TestHostNamesMatchNetHTTP now checks dialName and hostName against net/http itself, a client whose dialer records the address it is handed and a server that records the Host it receives, over eight hosts including the soft hyphen, ẞ, Unicode case and the underscore fallback, with keep-alives off so every request dials. Swapping either profile in either helper fails it. On a2a-go and req.Host: I did not find a write to req.Host in the pinned a2a-go, so the new message is unreachable on that path today, and the row pins the shared rule rather than a behavior a2a-go can trigger.

The cap order between the two callers I left as is, for the reason you gave.

@karolpiotrowicz
karolpiotrowicz dismissed their stale review November 17, 2026 09:01

Everything this review asked for is fixed on the current head.

@karolpiotrowicz karolpiotrowicz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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's Location. 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() returns Delete "…/sso?code=…&state=…": mcptoolset: refusing redirect …. After a failed call forces a reconnect, refreshConnection writes the same text with log.Printf (client.go#L103, #L249-L250). Nothing the toolset returns or logs should carry the server's Location.
  • The Host check accepts a bracketed or unbracketed spelling of the endpoint's name (inline on credredirect.go).
  • The GET sentence in the Config.Auth doc and in refuseRedirect's comment (inline on set.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)
}

Comment thread internal/credredirect/credredirect.go Resolved
Comment thread tool/mcptoolset/set.go Resolved
Comment thread tool/mcptoolset/set.go Resolved
…, 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
@wolo-lab

Copy link
Copy Markdown
Contributor Author

All three are fixed in 9db4c6d8, and the branch is merged with current main (e11641c8) so CI runs on this head.

Close() and the reconnect log line. Both go through the same redaction as a call's error now (client.go#L103, #L250). Your DELETE repro is TestAuthRedirectLocationStaysOut: Close() returns the refusal without the Location, and a second case drops the connection under a call so the reconnect closes the dead session and writes the log line, which is captured and checked. Removing either call fails its case. The redaction also keeps every error a rebuilt layer wrapped beside the refusal, so your non-blocking note holds too: errors.As for a type wrapped next to the transport error matches as it did before (redirect_test.go#L157).

The Host check. It compares the exact string net/http writes, not a parsed host: the Host header net/http would derive from req.URL.Host against the one it would derive from req.Host, ASCII as given and punycode otherwise, port kept (credredirect.go#L72-L104). [endpoint.test], a port folded into an IPv6 literal and the default port written out are refused, the exact IPv6 spelling and the punycode of a Unicode URL are accepted (credredirect_test.go#L133-L140). Your bracket repro is a case in TestAuthRedirectHookRewritesTarget, and the proxy sees endpoint.test only.

The GET sentence. refuseRedirect's comment (set.go#L266-L273) and the Config.Auth doc (#L425-L432) now name the resume GET with Last-Event-ID and say a refused redirect there fails the call with the status text. I did not turn your resume repro into a test: it needs the server to end a call's stream after an event with an id, which is a larger fixture than the claim it would pin, and the behavior is the SDK's.

On the follow-up you mention: the redirect-cap error and remoteagent/v2's refusal carry the Location the same way on main. I will file that separately rather than widen this change.

@wojtas000 wojtas000 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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. TestCheckRedirect in agent/remoteagent/v2 now 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: TestHostNamesMatchNetHTTP now checks them against real requests, and it is what shows the hand-written table is wrong. golang.org/x/net goes from indirect to direct in go.mod at the same version.
  • Guarding against the application's own redirect hook: the Config.Auth doc 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.

Comment thread internal/credredirect/credredirect.go Resolved
Comment thread tool/mcptoolset/client.go Resolved
… 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.
@wolo-lab

Copy link
Copy Markdown
Contributor Author

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: TestHostNames/faẞ.example failed with dialName("faẞ.example") = "xn--fa-hia.example", want "fass.example". Go 1.27 ships the Unicode 17 IDNA tables, which map ẞ to ß where the Unicode 15 tables map it to ss. The table now pins only the Host header name, which involves no mapping (TestHostName), and the dial name is left to TestHostNamesMatchNetHTTP, which covers every host the table had, faẞ.example among them. Removing the ASCII fast path, the lookup profile or the fallback from dialName fails that test on both releases, so nothing the literals pinned is lost. I also compared the two releases over 29 host names and every pair of them across both schemes and four ports: the dial name of faẞ.example is the only name that differs, and no redirect decision does.

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 faẞ.example to xn--fa-64s.example is refused, and the code comments that said the same are narrowed too. The GET paragraph now names the resume GET.

The three nits are answered in their threads.

@wojtas000 wojtas000 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@wolo-lab
wolo-lab dismissed karolpiotrowicz’s stale review November 18, 2026 12:59

Review was finalized with Jan, thank you for the previous comments.

@wolo-lab
wolo-lab merged commit b9a5db9 into main Nov 18, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

tool/mcptoolset: credential forwarded across cross-host redirect — httpClient never sets CheckRedirect (contradicts auth/gcp provider contract)

3 participants