]> Cypherpunks repositories - gostls13.git/commitdiff
net/http: use relative path in Location redirect
authorRoland Shoemaker <roland@golang.org>
Tue, 27 Apr 2021 03:10:56 +0000 (20:10 -0700)
committerRoland Shoemaker <roland@golang.org>
Mon, 3 May 2021 17:34:10 +0000 (17:34 +0000)
If the cleaned path did not match the requested path, ServeMux.Handler
would return a Location header which reflected the hostname in the
request, possibly leading to an incorrect redirect. Instead the
Location header should be relative, like the other cases in
ServeMux.Handler.

Change-Id: I2c220d925e708061bc128f0bdc96cca7a32764d3
Reviewed-on: https://go-review.googlesource.com/c/go/+/313950
Trust: Roland Shoemaker <roland@golang.org>
Trust: Katie Hockman <katie@golang.org>
Run-TryBot: Roland Shoemaker <roland@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Katie Hockman <katie@golang.org>
src/net/http/serve_test.go
src/net/http/server.go

index f8687416fe96c019a80e7e2ae58740f2dd7508db..a9714682c7ebb56bc05222798214923aef47d760 100644 (file)
@@ -6507,3 +6507,20 @@ func TestDisableKeepAliveUpgrade(t *testing.T) {
                t.Fatalf("unexpected value read from body:\ngot: %q\nwant: %q", b, "hello")
        }
 }
+
+func TestMuxRedirectRelative(t *testing.T) {
+       setParallel(t)
+       req, err := ReadRequest(bufio.NewReader(strings.NewReader("GET http://example.com HTTP/1.1\r\nHost: test\r\n\r\n")))
+       if err != nil {
+               t.Errorf("%s", err)
+       }
+       mux := NewServeMux()
+       resp := httptest.NewRecorder()
+       mux.ServeHTTP(resp, req)
+       if got, want := resp.Header().Get("Location"), "/"; got != want {
+               t.Errorf("Location header expected %q; got %q", want, got)
+       }
+       if got, want := resp.Code, StatusMovedPermanently; got != want {
+               t.Errorf("Expected response code %d; got %d", want, got)
+       }
+}
index e52a78e652c4cf5b84ee2cf093f4ad61a82e26db..4e73508973a1fe0993b6c4e4f91e955d0b84cbbb 100644 (file)
@@ -2404,9 +2404,8 @@ func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
 
        if path != r.URL.Path {
                _, pattern = mux.handler(host, path)
-               url := *r.URL
-               url.Path = path
-               return RedirectHandler(url.String(), StatusMovedPermanently), pattern
+               u := &url.URL{Path: path, RawQuery: r.URL.RawQuery}
+               return RedirectHandler(u.String(), StatusMovedPermanently), pattern
        }
 
        return mux.handler(host, r.URL.Path)