diff --git a/lib/netext/httpext/request.go b/lib/netext/httpext/request.go index b9c5242b5e38..89c2024521c8 100644 --- a/lib/netext/httpext/request.go +++ b/lib/netext/httpext/request.go @@ -23,6 +23,7 @@ package httpext import ( "bytes" "context" + "fmt" "io" "io/ioutil" "net" @@ -314,6 +315,11 @@ func MakeRequest(ctx context.Context, preq *ParsedHTTPRequest) (*Response, error mreq := preq.Req.WithContext(ctx) res, resErr := client.Do(mreq) + if res != nil && res.StatusCode == http.StatusSwitchingProtocols { + _ = res.Body.Close() + return nil, fmt.Errorf("unsupported response status: %s", res.Status) + } + resp.Body, resErr = readResponseBody(state, preq.ResponseType, res, resErr) finishedReq := tracerTransport.processLastSavedRequest(wrapDecompressionError(resErr)) if finishedReq != nil { diff --git a/lib/netext/httpext/request_test.go b/lib/netext/httpext/request_test.go index 91ba642d0f3f..ba00dca82309 100644 --- a/lib/netext/httpext/request_test.go +++ b/lib/netext/httpext/request_test.go @@ -6,10 +6,14 @@ import ( "io" "io/ioutil" "net/http" + "net/http/httptest" "net/url" "testing" + "github.com/loadimpact/k6/lib" + "github.com/loadimpact/k6/stats" "github.com/pkg/errors" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -82,6 +86,29 @@ func TestMakeRequestError(t *testing.T) { require.Error(t, err) require.Equal(t, err.Error(), "unknown compressionType CompressionType(13)") }) + + t.Run("invalid upgrade response", func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Add("Connection", "Upgrade") + w.Header().Add("Upgrade", "h2c") + w.WriteHeader(http.StatusSwitchingProtocols) + })) + defer srv.Close() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + state := &lib.State{ + Options: lib.Options{RunTags: &stats.SampleTags{}}, + Transport: srv.Client().Transport, + } + ctx = lib.WithState(ctx, state) + req, _ := http.NewRequest("GET", srv.URL, nil) + var preq = &ParsedHTTPRequest{Req: req, URL: &URL{u: req.URL}, Body: new(bytes.Buffer)} + + res, err := MakeRequest(ctx, preq) + + assert.Nil(t, res) + assert.EqualError(t, err, "unsupported response status: 101 Switching Protocols") + }) } func TestURL(t *testing.T) {