diff --git a/context.go b/context.go index 582d00f2..c57a2b7d 100644 --- a/context.go +++ b/context.go @@ -1062,9 +1062,15 @@ func (c *Context) ContentType() string { // IsWebsocket returns true if the request headers indicate that a websocket // handshake is being initiated by the client. func (c *Context) IsWebsocket() bool { - if strings.Contains(strings.ToLower(c.requestHeader("Connection")), "upgrade") && - strings.EqualFold(c.requestHeader("Upgrade"), "websocket") { - return true + if !strings.EqualFold(c.requestHeader("Upgrade"), "websocket") { + return false + } + for _, connection := range c.Request.Header.Values("Connection") { + for token := range strings.SplitSeq(connection, ",") { + if strings.EqualFold(strings.Trim(token, " \t"), "upgrade") { + return true + } + } } return false } diff --git a/context_test.go b/context_test.go index b82e04d5..bca51f00 100644 --- a/context_test.go +++ b/context_test.go @@ -3143,6 +3143,42 @@ func TestWebsocketsRequired(t *testing.T) { assert.False(t, c.IsWebsocket()) } +func TestIsWebsocketConnectionHeaders(t *testing.T) { + for _, tt := range []struct { + name string + connection []string + upgrade string + want bool + }{ + {"single token", []string{"Upgrade"}, "websocket", true}, + {"mixed case", []string{"uPgRaDe"}, "WebSocket", true}, + {"token list", []string{"keep-alive, Upgrade"}, "websocket", true}, + {"optional whitespace", []string{"keep-alive, \tUpgrade\t "}, "websocket", true}, + {"repeated fields", []string{"keep-alive", "Upgrade"}, "websocket", true}, + {"empty first field", []string{"", "Upgrade"}, "websocket", true}, + {"comma-only field", []string{",,"}, "websocket", false}, + {"empty list entries", []string{",,Upgrade,,"}, "websocket", true}, + {"token prefix", []string{"notupgrade"}, "websocket", false}, + {"token suffix", []string{"upgrades"}, "websocket", false}, + {"non-HTTP whitespace", []string{"\u00a0upgrade"}, "websocket", false}, + {"no upgrade token", []string{"keep-alive"}, "websocket", false}, + {"missing connection", nil, "websocket", false}, + {"missing upgrade", []string{"Upgrade"}, "", false}, + {"different protocol", []string{"Upgrade"}, "h2c", false}, + } { + t.Run(tt.name, func(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodGet, "/chat", nil) + for _, connection := range tt.connection { + c.Request.Header.Add("Connection", connection) + } + c.Request.Header.Set("Upgrade", tt.upgrade) + + assert.Equal(t, tt.want, c.IsWebsocket()) + }) + } +} + func TestContextScheme(t *testing.T) { // TLS connection takes highest priority. c, _ := CreateTestContext(httptest.NewRecorder())