瀏覽代碼

client: set hard limit on redirect checks

Brian Waldon 11 年之前
父節點
當前提交
b41d6bc416
共有 2 個文件被更改,包括 18 次插入3 次删除
  1. 6 3
      client/client.go
  2. 12 0
      client/client_test.go

+ 6 - 3
client/client.go

@@ -28,8 +28,9 @@ import (
 )
 
 var (
-	ErrNoEndpoints      = errors.New("client: no endpoints available")
-	ErrTooManyRedirects = errors.New("client: too many redirects")
+	ErrNoEndpoints           = errors.New("client: no endpoints available")
+	ErrTooManyRedirects      = errors.New("client: too many redirects")
+	errTooManyRedirectChecks = errors.New("client: too many redirect checks")
 )
 
 var DefaultRequestTimeout = 5 * time.Second
@@ -297,7 +298,7 @@ type redirectFollowingHTTPClient struct {
 }
 
 func (r *redirectFollowingHTTPClient) Do(ctx context.Context, act httpAction) (*http.Response, []byte, error) {
-	for i := 0; ; i++ {
+	for i := 0; i < 100; i++ {
 		if i > 0 {
 			if err := r.checkRedirect(i); err != nil {
 				return nil, nil, err
@@ -324,6 +325,8 @@ func (r *redirectFollowingHTTPClient) Do(ctx context.Context, act httpAction) (*
 		}
 		return resp, body, nil
 	}
+
+	return nil, nil, errTooManyRedirectChecks
 }
 
 type redirectedHTTPAction struct {

+ 12 - 0
client/client_test.go

@@ -522,6 +522,18 @@ func TestRedirectFollowingHTTPClient(t *testing.T) {
 			},
 			wantErr: errors.New("Location header not valid URL: :"),
 		},
+
+		// fail if redirects checked way too many times
+		{
+			checkRedirect: func(int) error { return nil },
+			client: &staticHTTPClient{
+				resp: http.Response{
+					StatusCode: http.StatusTemporaryRedirect,
+					Header:     http.Header{"Location": []string{"http://example.com"}},
+				},
+			},
+			wantErr: errTooManyRedirectChecks,
+		},
 	}
 
 	for i, tt := range tests {