Return 426 status on missing upgrade header

This commit is contained in:
Thomas Massie 2024-05-25 17:16:00 -10:00 committed by Daniel Holmes
parent 1d5465562b
commit 6426a30ef7
2 changed files with 33 additions and 1 deletions

View File

@ -497,6 +497,37 @@ func TestBadMethod(t *testing.T) {
}
}
func TestNoUpgrade(t *testing.T) {
t.Parallel()
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ws, err := cstUpgrader.Upgrade(w, r, nil)
if err == nil {
t.Errorf("handshake succeeded, expect fail")
ws.Close()
}
}))
defer s.Close()
req, err := http.NewRequest(http.MethodGet, s.URL, strings.NewReader(""))
if err != nil {
t.Fatalf("NewRequest returned error %v", err)
}
req.Header.Set("Connection", "upgrade")
req.Header.Set("Sec-Websocket-Version", "13")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("Do returned error %v", err)
}
resp.Body.Close()
if u := resp.Header.Get("Upgrade"); u != "websocket" {
t.Errorf("Uprade response header is %q, want %q", u, "websocket")
}
if resp.StatusCode != http.StatusUpgradeRequired {
t.Errorf("Status = %d, want %d", resp.StatusCode, http.StatusUpgradeRequired)
}
}
func TestDialExtraTokensInRespHeaders(t *testing.T) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
challengeKey := r.Header.Get("Sec-Websocket-Key")

View File

@ -130,7 +130,8 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade
}
if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'websocket' token not found in 'Upgrade' header")
w.Header().Set("Upgrade", "websocket")
return u.returnError(w, r, http.StatusUpgradeRequired, badHandshake+"'websocket' token not found in 'Upgrade' header")
}
if r.Method != http.MethodGet {