| 1 |
/* |
| 2 |
Copyright 2023 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package websocket |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"errors" |
| 22 |
"io" |
| 23 |
"net/http" |
| 24 |
"net/http/httptest" |
| 25 |
"net/url" |
| 26 |
"testing" |
| 27 |
"time" |
| 28 |
|
| 29 |
"github.com/stretchr/testify/assert" |
| 30 |
"github.com/stretchr/testify/require" |
| 31 |
|
| 32 |
apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 33 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 34 |
"k8s.io/apimachinery/pkg/runtime" |
| 35 |
"k8s.io/apimachinery/pkg/util/httpstream" |
| 36 |
"k8s.io/apimachinery/pkg/util/httpstream/wsstream" |
| 37 |
"k8s.io/apimachinery/pkg/util/remotecommand" |
| 38 |
restclient "k8s.io/client-go/rest" |
| 39 |
) |
| 40 |
|
| 41 |
func TestWebSocketRoundTripper_RoundTripperSucceeds(t *testing.T) { |
| 42 |
// Create fake WebSocket server. |
| 43 |
websocketServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 44 |
conns, err := webSocketServerStreams(req, w) |
| 45 |
if err != nil { |
| 46 |
t.Fatalf("error on webSocketServerStreams: %v", err) |
| 47 |
} |
| 48 |
defer conns.conn.Close() |
| 49 |
})) |
| 50 |
defer websocketServer.Close() |
| 51 |
|
| 52 |
// Create the wrapped roundtripper and websocket upgrade roundtripper and call "RoundTrip()". |
| 53 |
websocketLocation, err := url.Parse(websocketServer.URL) |
| 54 |
require.NoError(t, err) |
| 55 |
req, err := http.NewRequestWithContext(context.Background(), "GET", websocketServer.URL, nil) |
| 56 |
require.NoError(t, err) |
| 57 |
rt, wsRt, err := RoundTripperFor(&restclient.Config{Host: websocketLocation.Host}) |
| 58 |
require.NoError(t, err) |
| 59 |
requestedProtocol := remotecommand.StreamProtocolV5Name |
| 60 |
req.Header[wsstream.WebSocketProtocolHeader] = []string{requestedProtocol} |
| 61 |
_, err = rt.RoundTrip(req) |
| 62 |
require.NoError(t, err) |
| 63 |
// WebSocket Connection is stored in websocket RoundTripper. |
| 64 |
// Compare the expected negotiated subprotocol with the actual subprotocol. |
| 65 |
actualProtocol := wsRt.Connection().Subprotocol() |
| 66 |
assert.Equal(t, requestedProtocol, actualProtocol) |
| 67 |
|
| 68 |
} |
| 69 |
|
| 70 |
func TestWebSocketRoundTripper_RoundTripperFails(t *testing.T) { |
| 71 |
testCases := map[string]struct { |
| 72 |
statusCode int |
| 73 |
body string |
| 74 |
status *metav1.Status |
| 75 |
expectedError string |
| 76 |
}{ |
| 77 |
"Empty response status still returns basic websocket error": { |
| 78 |
statusCode: -1, |
| 79 |
body: "", |
| 80 |
expectedError: "websocket: bad handshake", |
| 81 |
}, |
| 82 |
"Empty response body still returns status": { |
| 83 |
statusCode: http.StatusForbidden, |
| 84 |
body: "", |
| 85 |
expectedError: "(403 Forbidden)", |
| 86 |
}, |
| 87 |
"Error response body returned as string when can not be cast as metav1.Status": { |
| 88 |
statusCode: http.StatusForbidden, |
| 89 |
body: "RBAC violated", |
| 90 |
expectedError: "(403 Forbidden): RBAC violated", |
| 91 |
}, |
| 92 |
"Error returned as metav1.Status within response body": { |
| 93 |
statusCode: http.StatusBadRequest, |
| 94 |
body: "", |
| 95 |
status: &metav1.Status{ |
| 96 |
TypeMeta: metav1.TypeMeta{ |
| 97 |
APIVersion: "meta.k8s.io/v1", |
| 98 |
Kind: "Status", |
| 99 |
}, |
| 100 |
Status: "Failure", |
| 101 |
Reason: "Unable to negotiate sub-protocol", |
| 102 |
Code: http.StatusBadRequest, |
| 103 |
}, |
| 104 |
}, |
| 105 |
} |
| 106 |
encoder := statusCodecs.LegacyCodec(metav1.SchemeGroupVersion) |
| 107 |
for testName, testCase := range testCases { |
| 108 |
t.Run(testName, func(t *testing.T) { |
| 109 |
// Create fake WebSocket server. |
| 110 |
websocketServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 111 |
if testCase.statusCode > 0 { |
| 112 |
w.WriteHeader(testCase.statusCode) |
| 113 |
} |
| 114 |
if testCase.status != nil { |
| 115 |
statusBytes, err := runtime.Encode(encoder, testCase.status) |
| 116 |
if err != nil { |
| 117 |
t.Errorf("unexpected error %v", err) |
| 118 |
return |
| 119 |
} |
| 120 |
_, err = w.Write(statusBytes) |
| 121 |
if err != nil { |
| 122 |
t.Errorf("unexpected error %v", err) |
| 123 |
return |
| 124 |
} |
| 125 |
} else if len(testCase.body) > 0 { |
| 126 |
_, err := w.Write([]byte(testCase.body)) |
| 127 |
if err != nil { |
| 128 |
t.Errorf("unexpected error %v", err) |
| 129 |
return |
| 130 |
} |
| 131 |
} |
| 132 |
})) |
| 133 |
defer websocketServer.Close() |
| 134 |
|
| 135 |
// Create the wrapped roundtripper and websocket upgrade roundtripper and call "RoundTrip()". |
| 136 |
websocketLocation, err := url.Parse(websocketServer.URL) |
| 137 |
require.NoError(t, err) |
| 138 |
req, err := http.NewRequestWithContext(context.Background(), "GET", websocketServer.URL, nil) |
| 139 |
require.NoError(t, err) |
| 140 |
rt, _, err := RoundTripperFor(&restclient.Config{Host: websocketLocation.Host}) |
| 141 |
require.NoError(t, err) |
| 142 |
_, err = rt.RoundTrip(req) |
| 143 |
require.Error(t, err) |
| 144 |
assert.True(t, httpstream.IsUpgradeFailure(err)) |
| 145 |
if testCase.status != nil { |
| 146 |
upgradeErr := &httpstream.UpgradeFailureError{} |
| 147 |
validErr := errors.As(err, &upgradeErr) |
| 148 |
assert.True(t, validErr, "could not cast error as httpstream.UpgradeFailureError") |
| 149 |
statusErr := upgradeErr.Cause |
| 150 |
apiErr := &apierrors.StatusError{} |
| 151 |
validErr = errors.As(statusErr, &apiErr) |
| 152 |
assert.True(t, validErr, "could not cast error as apierrors.StatusError") |
| 153 |
assert.Equal(t, *testCase.status, apiErr.ErrStatus) |
| 154 |
} else { |
| 155 |
assert.Contains(t, err.Error(), testCase.expectedError, |
| 156 |
"expected (%s), got (%s)", testCase.expectedError, err.Error()) |
| 157 |
} |
| 158 |
}) |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
func TestWebSocketRoundTripper_NegotiateCreatesConnection(t *testing.T) { |
| 163 |
// Create fake WebSocket server. |
| 164 |
websocketServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 165 |
conns, err := webSocketServerStreams(req, w) |
| 166 |
if err != nil { |
| 167 |
t.Fatalf("error on webSocketServerStreams: %v", err) |
| 168 |
} |
| 169 |
defer conns.conn.Close() |
| 170 |
})) |
| 171 |
defer websocketServer.Close() |
| 172 |
|
| 173 |
// Create the websocket roundtripper and call "Negotiate" to create websocket connection. |
| 174 |
websocketLocation, err := url.Parse(websocketServer.URL) |
| 175 |
require.NoError(t, err) |
| 176 |
req, err := http.NewRequestWithContext(context.Background(), "GET", websocketServer.URL, nil) |
| 177 |
require.NoError(t, err) |
| 178 |
rt, wsRt, err := RoundTripperFor(&restclient.Config{Host: websocketLocation.Host}) |
| 179 |
require.NoError(t, err) |
| 180 |
requestedProtocol := remotecommand.StreamProtocolV5Name |
| 181 |
conn, err := Negotiate(rt, wsRt, req, requestedProtocol) |
| 182 |
require.NoError(t, err) |
| 183 |
// Compare the expected negotiated subprotocol with the actual subprotocol. |
| 184 |
actualProtocol := conn.Subprotocol() |
| 185 |
assert.Equal(t, requestedProtocol, actualProtocol) |
| 186 |
} |
| 187 |
|
| 188 |
// websocketStreams contains the WebSocket connection and streams from a server. |
| 189 |
type websocketStreams struct { |
| 190 |
conn io.Closer |
| 191 |
} |
| 192 |
|
| 193 |
func webSocketServerStreams(req *http.Request, w http.ResponseWriter) (*websocketStreams, error) { |
| 194 |
conn := wsstream.NewConn(map[string]wsstream.ChannelProtocolConfig{ |
| 195 |
remotecommand.StreamProtocolV5Name: { |
| 196 |
Binary: true, |
| 197 |
Channels: []wsstream.ChannelType{}, |
| 198 |
}, |
| 199 |
}) |
| 200 |
conn.SetIdleTimeout(4 * time.Hour) |
| 201 |
// Opening the connection responds to WebSocket client, negotiating |
| 202 |
// the WebSocket upgrade connection and the subprotocol. |
| 203 |
_, _, err := conn.Open(w, req) |
| 204 |
if err != nil { |
| 205 |
return nil, err |
| 206 |
} |
| 207 |
return &websocketStreams{conn: conn}, nil |
| 208 |
} |