Debian Codegraph @

tools/remotecommand/fallback_test.go

raw symbols SCIP
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 remotecommand
18
19 import (
20 "bytes"
21 "context"
22 "crypto/rand"
23 "crypto/tls"
24 "io"
25 "net/http"
26 "net/http/httptest"
27 "net/url"
28 "sync/atomic"
29 "testing"
30 "time"
31
32 "github.com/stretchr/testify/assert"
33 "github.com/stretchr/testify/require"
34 "k8s.io/apimachinery/pkg/util/httpstream"
35 utilnettesting "k8s.io/apimachinery/pkg/util/net/testing"
36 "k8s.io/apimachinery/pkg/util/remotecommand"
37 "k8s.io/apimachinery/pkg/util/wait"
38 "k8s.io/client-go/rest"
39 )
40
41 func TestFallbackClient_WebSocketPrimarySucceeds(t *testing.T) {
42 // Create fake WebSocket server. Copy received STDIN data back onto STDOUT stream.
43 websocketServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
44 conns, err := webSocketServerStreams(req, w, streamOptionsFromRequest(req))
45 if err != nil {
46 w.WriteHeader(http.StatusForbidden)
47 return
48 }
49 defer conns.conn.Close()
50 // Loopback the STDIN stream onto the STDOUT stream.
51 _, err = io.Copy(conns.stdoutStream, conns.stdinStream)
52 if err != nil {
53 t.Errorf("unexpected error %v", err)
54 }
55 }))
56 defer websocketServer.Close()
57
58 // Now create the fallback client (executor), and point it to the "websocketServer".
59 // Must add STDIN and STDOUT query params for the client request.
60 websocketServer.URL = websocketServer.URL + "?" + "stdin=true" + "&" + "stdout=true"
61 websocketLocation, err := url.Parse(websocketServer.URL)
62 require.NoError(t, err)
63 websocketExecutor, err := NewWebSocketExecutor(&rest.Config{Host: websocketLocation.Host}, "GET", websocketServer.URL)
64 require.NoError(t, err)
65 spdyExecutor, err := NewSPDYExecutor(&rest.Config{Host: websocketLocation.Host}, "POST", websocketLocation)
66 require.NoError(t, err)
67 // Never fallback, so always use the websocketExecutor, which succeeds against websocket server.
68 exec, err := NewFallbackExecutor(websocketExecutor, spdyExecutor, func(error) bool { return false })
69 require.NoError(t, err)
70 // Generate random data, and set it up to stream on STDIN. The data will be
71 // returned on the STDOUT buffer.
72 randomSize := 1024 * 1024
73 randomData := make([]byte, randomSize)
74 if _, err := rand.Read(randomData); err != nil {
75 t.Errorf("unexpected error reading random data: %v", err)
76 }
77 var stdout bytes.Buffer
78 options := &StreamOptions{
79 Stdin: bytes.NewReader(randomData),
80 Stdout: &stdout,
81 }
82 errorChan := make(chan error)
83 go func() {
84 // Start the streaming on the WebSocket "exec" client.
85 errorChan <- exec.StreamWithContext(context.Background(), *options)
86 }()
87
88 select {
89 case <-time.After(wait.ForeverTestTimeout):
90 t.Fatalf("expect stream to be closed after connection is closed.")
91 case err := <-errorChan:
92 if err != nil {
93 t.Errorf("unexpected error")
94 }
95 }
96
97 data, err := io.ReadAll(bytes.NewReader(stdout.Bytes()))
98 if err != nil {
99 t.Errorf("error reading the stream: %v", err)
100 return
101 }
102 // Check the random data sent on STDIN was the same returned on STDOUT.
103 if !bytes.Equal(randomData, data) {
104 t.Errorf("unexpected data received: %d sent: %d", len(data), len(randomData))
105 }
106 }
107
108 func TestFallbackClient_SPDYSecondarySucceeds(t *testing.T) {
109 // Create fake SPDY server. Copy received STDIN data back onto STDOUT stream.
110 spdyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
111 var stdin, stdout bytes.Buffer
112 ctx, err := createHTTPStreams(w, req, &StreamOptions{
113 Stdin: &stdin,
114 Stdout: &stdout,
115 })
116 if err != nil {
117 w.WriteHeader(http.StatusForbidden)
118 return
119 }
120 defer ctx.conn.Close()
121 _, err = io.Copy(ctx.stdoutStream, ctx.stdinStream)
122 if err != nil {
123 t.Fatalf("error copying STDIN to STDOUT: %v", err)
124 }
125 }))
126 defer spdyServer.Close()
127
128 spdyLocation, err := url.Parse(spdyServer.URL)
129 require.NoError(t, err)
130 websocketExecutor, err := NewWebSocketExecutor(&rest.Config{Host: spdyLocation.Host}, "GET", spdyServer.URL)
131 require.NoError(t, err)
132 spdyExecutor, err := NewSPDYExecutor(&rest.Config{Host: spdyLocation.Host}, "POST", spdyLocation)
133 require.NoError(t, err)
134 // Always fallback to spdyExecutor, and spdyExecutor succeeds against fake spdy server.
135 exec, err := NewFallbackExecutor(websocketExecutor, spdyExecutor, func(error) bool { return true })
136 require.NoError(t, err)
137 // Generate random data, and set it up to stream on STDIN. The data will be
138 // returned on the STDOUT buffer.
139 randomSize := 1024 * 1024
140 randomData := make([]byte, randomSize)
141 if _, err := rand.Read(randomData); err != nil {
142 t.Errorf("unexpected error reading random data: %v", err)
143 }
144 var stdout bytes.Buffer
145 options := &StreamOptions{
146 Stdin: bytes.NewReader(randomData),
147 Stdout: &stdout,
148 }
149 errorChan := make(chan error)
150 go func() {
151 errorChan <- exec.StreamWithContext(context.Background(), *options)
152 }()
153
154 select {
155 case <-time.After(wait.ForeverTestTimeout):
156 t.Fatalf("expect stream to be closed after connection is closed.")
157 case err := <-errorChan:
158 if err != nil {
159 t.Errorf("unexpected error")
160 }
161 }
162
163 data, err := io.ReadAll(bytes.NewReader(stdout.Bytes()))
164 if err != nil {
165 t.Errorf("error reading the stream: %v", err)
166 return
167 }
168 // Check the random data sent on STDIN was the same returned on STDOUT.
169 if !bytes.Equal(randomData, data) {
170 t.Errorf("unexpected data received: %d sent: %d", len(data), len(randomData))
171 }
172 }
173
174 func TestFallbackClient_PrimaryAndSecondaryFail(t *testing.T) {
175 // Create fake WebSocket server. Copy received STDIN data back onto STDOUT stream.
176 websocketServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
177 conns, err := webSocketServerStreams(req, w, streamOptionsFromRequest(req))
178 if err != nil {
179 w.WriteHeader(http.StatusForbidden)
180 return
181 }
182 defer conns.conn.Close()
183 // Loopback the STDIN stream onto the STDOUT stream.
184 _, err = io.Copy(conns.stdoutStream, conns.stdinStream)
185 if err != nil {
186 t.Errorf("unexpected error %v", err)
187 }
188 }))
189 defer websocketServer.Close()
190
191 // Now create the fallback client (executor), and point it to the "websocketServer".
192 // Must add STDIN and STDOUT query params for the client request.
193 websocketServer.URL = websocketServer.URL + "?" + "stdin=true" + "&" + "stdout=true"
194 websocketLocation, err := url.Parse(websocketServer.URL)
195 require.NoError(t, err)
196 websocketExecutor, err := NewWebSocketExecutor(&rest.Config{Host: websocketLocation.Host}, "GET", websocketServer.URL)
197 require.NoError(t, err)
198 spdyExecutor, err := NewSPDYExecutor(&rest.Config{Host: websocketLocation.Host}, "POST", websocketLocation)
199 require.NoError(t, err)
200 // Always fallback to spdyExecutor, but spdyExecutor fails against websocket server.
201 exec, err := NewFallbackExecutor(websocketExecutor, spdyExecutor, func(error) bool { return true })
202 require.NoError(t, err)
203 // Update the websocket executor to request remote command v4, which is unsupported.
204 fallbackExec, ok := exec.(*FallbackExecutor)
205 assert.True(t, ok, "error casting executor as FallbackExecutor")
206 websocketExec, ok := fallbackExec.primary.(*wsStreamExecutor)
207 assert.True(t, ok, "error casting executor as websocket executor")
208 // Set the attempted subprotocol version to V4; websocket server only accepts V5.
209 websocketExec.protocols = []string{remotecommand.StreamProtocolV4Name}
210
211 // Generate random data, and set it up to stream on STDIN. The data will be
212 // returned on the STDOUT buffer.
213 randomSize := 1024 * 1024
214 randomData := make([]byte, randomSize)
215 if _, err := rand.Read(randomData); err != nil {
216 t.Errorf("unexpected error reading random data: %v", err)
217 }
218 var stdout bytes.Buffer
219 options := &StreamOptions{
220 Stdin: bytes.NewReader(randomData),
221 Stdout: &stdout,
222 }
223 errorChan := make(chan error)
224 go func() {
225 errorChan <- exec.StreamWithContext(context.Background(), *options)
226 }()
227
228 select {
229 case <-time.After(wait.ForeverTestTimeout):
230 t.Fatalf("expect stream to be closed after connection is closed.")
231 case err := <-errorChan:
232 // Ensure secondary executor returned an error.
233 require.Error(t, err)
234 }
235 }
236
237 // localhostCert was generated from crypto/tls/generate_cert.go with the following command:
238 //
239 // go run generate_cert.go --rsa-bits 2048 --host 127.0.0.1,::1,example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h
240 var localhostCert = []byte(`-----BEGIN CERTIFICATE-----
241 MIIDGTCCAgGgAwIBAgIRALL5AZcefF4kkYV1SEG6YrMwDQYJKoZIhvcNAQELBQAw
242 EjEQMA4GA1UEChMHQWNtZSBDbzAgFw03MDAxMDEwMDAwMDBaGA8yMDg0MDEyOTE2
243 MDAwMFowEjEQMA4GA1UEChMHQWNtZSBDbzCCASIwDQYJKoZIhvcNAQEBBQADggEP
244 ADCCAQoCggEBALQ/FHcyVwdFHxARbbD2KBtDUT7Eni+8ioNdjtGcmtXqBv45EC1C
245 JOqqGJTroFGJ6Q9kQIZ9FqH5IJR2fOOJD9kOTueG4Vt1JY1rj1Kbpjefu8XleZ5L
246 SBwIWVnN/lEsEbuKmj7N2gLt5AH3zMZiBI1mg1u9Z5ZZHYbCiTpBrwsq6cTlvR9g
247 dyo1YkM5hRESCzsrL0aUByoo0qRMD8ZsgANJwgsiO0/M6idbxDwv1BnGwGmRYvOE
248 Hxpy3v0Jg7GJYrvnpnifJTs4nw91N5X9pXxR7FFzi/6HTYDWRljvTb0w6XciKYAz
249 bWZ0+cJr5F7wB7ovlbm7HrQIR7z7EIIu2d8CAwEAAaNoMGYwDgYDVR0PAQH/BAQD
250 AgKkMBMGA1UdJQQMMAoGCCsGAQUFBwMBMA8GA1UdEwEB/wQFMAMBAf8wLgYDVR0R
251 BCcwJYILZXhhbXBsZS5jb22HBH8AAAGHEAAAAAAAAAAAAAAAAAAAAAEwDQYJKoZI
252 hvcNAQELBQADggEBAFPPWopNEJtIA2VFAQcqN6uJK+JVFOnjGRoCrM6Xgzdm0wxY
253 XCGjsxY5dl+V7KzdGqu858rCaq5osEBqypBpYAnS9C38VyCDA1vPS1PsN8SYv48z
254 DyBwj+7R2qar0ADBhnhWxvYO9M72lN/wuCqFKYMeFSnJdQLv3AsrrHe9lYqOa36s
255 8wxSwVTFTYXBzljPEnSaaJMPqFD8JXaZK1ryJPkO5OsCNQNGtatNiWAf3DcmwHAT
256 MGYMzP0u4nw47aRz9shB8w+taPKHx2BVwE1m/yp3nHVioOjXqA1fwRQVGclCJSH1
257 D2iq3hWVHRENgjTjANBPICLo9AZ4JfN6PH19mnU=
258 -----END CERTIFICATE-----`)
259
260 // localhostKey is the private key for localhostCert.
261 var localhostKey = []byte(`-----BEGIN RSA PRIVATE KEY-----
262 MIIEogIBAAKCAQEAtD8UdzJXB0UfEBFtsPYoG0NRPsSeL7yKg12O0Zya1eoG/jkQ
263 LUIk6qoYlOugUYnpD2RAhn0WofkglHZ844kP2Q5O54bhW3UljWuPUpumN5+7xeV5
264 nktIHAhZWc3+USwRu4qaPs3aAu3kAffMxmIEjWaDW71nllkdhsKJOkGvCyrpxOW9
265 H2B3KjViQzmFERILOysvRpQHKijSpEwPxmyAA0nCCyI7T8zqJ1vEPC/UGcbAaZFi
266 84QfGnLe/QmDsYliu+emeJ8lOzifD3U3lf2lfFHsUXOL/odNgNZGWO9NvTDpdyIp
267 gDNtZnT5wmvkXvAHui+VubsetAhHvPsQgi7Z3wIDAQABAoIBAGmw93IxjYCQ0ncc
268 kSKMJNZfsdtJdaxuNRZ0nNNirhQzR2h403iGaZlEpmdkhzxozsWcto1l+gh+SdFk
269 bTUK4MUZM8FlgO2dEqkLYh5BcMT7ICMZvSfJ4v21E5eqR68XVUqQKoQbNvQyxFk3
270 EddeEGdNrkb0GDK8DKlBlzAW5ep4gjG85wSTjR+J+muUv3R0BgLBFSuQnIDM/IMB
271 LWqsja/QbtB7yppe7jL5u8UCFdZG8BBKT9fcvFIu5PRLO3MO0uOI7LTc8+W1Xm23
272 uv+j3SY0+v+6POjK0UlJFFi/wkSPTFIfrQO1qFBkTDQHhQ6q/7GnILYYOiGbIRg2
273 NNuP52ECgYEAzXEoy50wSYh8xfFaBuxbm3ruuG2W49jgop7ZfoFrPWwOQKAZS441
274 VIwV4+e5IcA6KkuYbtGSdTYqK1SMkgnUyD/VevwAqH5TJoEIGu0pDuKGwVuwqioZ
275 frCIAV5GllKyUJ55VZNbRr2vY2fCsWbaCSCHETn6C16DNuTCe5C0JBECgYEA4JqY
276 5GpNbMG8fOt4H7hU0Fbm2yd6SHJcQ3/9iimef7xG6ajxsYrIhg1ft+3IPHMjVI0+
277 9brwHDnWg4bOOx/VO4VJBt6Dm/F33bndnZRkuIjfSNpLM51P+EnRdaFVHOJHwKqx
278 uF69kihifCAG7YATgCveeXImzBUSyZUz9UrETu8CgYARNBimdFNG1RcdvEg9rC0/
279 p9u1tfecvNySwZqU7WF9kz7eSonTueTdX521qAHowaAdSpdJMGODTTXaywm6cPhQ
280 jIfj9JZZhbqQzt1O4+08Qdvm9TamCUB5S28YLjza+bHU7nBaqixKkDfPqzCyilpX
281 yVGGL8SwjwmN3zop/sQXAQKBgC0JMsESQ6YcDsRpnrOVjYQc+LtW5iEitTdfsaID
282 iGGKihmOI7B66IxgoCHMTws39wycKdSyADVYr5e97xpR3rrJlgQHmBIrz+Iow7Q2
283 LiAGaec8xjl6QK/DdXmFuQBKqyKJ14rljFODP4QuE9WJid94bGqjpf3j99ltznZP
284 4J8HAoGAJb4eb4lu4UGwifDzqfAPzLGCoi0fE1/hSx34lfuLcc1G+LEu9YDKoOVJ
285 9suOh0b5K/bfEy9KrVMBBriduvdaERSD8S3pkIQaitIz0B029AbE4FLFf9lKQpP2
286 KR8NJEkK99Vh/tew6jAMll70xFrE7aF8VLXJVE7w4sQzuvHxl9Q=
287 -----END RSA PRIVATE KEY-----
288 `)
289
290 // See (https://github.com/kubernetes/kubernetes/issues/126134).
291 func TestFallbackClient_WebSocketHTTPSProxyNoFallback(t *testing.T) {
292 cert, err := tls.X509KeyPair(localhostCert, localhostKey)
293 if err != nil {
294 t.Errorf("https (valid hostname): proxy_test: %v", err)
295 }
296
297 var proxyCalled atomic.Int64
298 proxyHandler := utilnettesting.NewHTTPProxyHandler(t, func(req *http.Request) bool {
299 proxyCalled.Add(1)
300 return true
301 })
302 defer proxyHandler.Wait()
303
304 proxyServer := httptest.NewUnstartedServer(proxyHandler)
305 proxyServer.TLS = &tls.Config{Certificates: []tls.Certificate{cert}}
306 proxyServer.StartTLS()
307 defer proxyServer.Close() //nolint:errcheck
308
309 proxyLocation, err := url.Parse(proxyServer.URL)
310 require.NoError(t, err)
311
312 // Create fake WebSocket server. Copy received STDIN data back onto STDOUT stream.
313 websocketServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
314 conns, err := webSocketServerStreams(req, w, streamOptionsFromRequest(req))
315 if err != nil {
316 w.WriteHeader(http.StatusForbidden)
317 return
318 }
319 defer conns.conn.Close() //nolint:errcheck
320 // Loopback the STDIN stream onto the STDOUT stream.
321 _, err = io.Copy(conns.stdoutStream, conns.stdinStream)
322 if err != nil {
323 t.Fatalf("websocket copy error: %v", err)
324 }
325 }))
326 defer websocketServer.Close() //nolint:errcheck
327
328 // Now create the WebSocket client (executor), and point it to the TLS proxy server.
329 // The proxy server should open a websocket connection to the fake websocket server.
330 websocketServer.URL = websocketServer.URL + "?" + "stdin=true" + "&" + "stdout=true"
331 websocketLocation, err := url.Parse(websocketServer.URL)
332 require.NoError(t, err)
333 clientConfig := &rest.Config{
334 Host: websocketLocation.Host,
335 TLSClientConfig: rest.TLSClientConfig{CAData: localhostCert},
336 Proxy: func(req *http.Request) (*url.URL, error) {
337 return proxyLocation, nil
338 },
339 }
340 websocketExecutor, err := NewWebSocketExecutor(clientConfig, "GET", websocketServer.URL)
341 require.NoError(t, err)
342 emptyURL, _ := url.Parse("")
343 spdyExecutor, err := NewSPDYExecutor(clientConfig, "POST", emptyURL)
344 require.NoError(t, err)
345 // No fallback to spdyExecutor with websocket.
346 sawHTTPSProxyError := false
347 exec, err := NewFallbackExecutor(websocketExecutor, spdyExecutor, func(err error) bool {
348 if httpstream.IsUpgradeFailure(err) {
349 t.Errorf("saw upgrade failure: %v", err)
350 return true
351 }
352 if httpstream.IsHTTPSProxyError(err) {
353 sawHTTPSProxyError = true
354 t.Logf("saw https proxy error: %v", err)
355 return true
356 }
357 return false
358 })
359 require.NoError(t, err)
360
361 // Generate random data, and set it up to stream on STDIN. The data will be
362 // returned on the STDOUT buffer.
363 randomSize := 1024 * 1024
364 randomData := make([]byte, randomSize)
365 if _, err := rand.Read(randomData); err != nil {
366 t.Errorf("unexpected error reading random data: %v", err)
367 }
368 var stdout bytes.Buffer
369 options := &StreamOptions{
370 Stdin: bytes.NewReader(randomData),
371 Stdout: &stdout,
372 }
373 errorChan := make(chan error)
374 go func() {
375 errorChan <- exec.StreamWithContext(context.Background(), *options)
376 }()
377
378 select {
379 case <-time.After(wait.ForeverTestTimeout):
380 t.Fatalf("expect stream to be closed after connection is closed.")
381 case err := <-errorChan:
382 if err != nil {
383 t.Errorf("unexpected error")
384 }
385 }
386
387 data, err := io.ReadAll(bytes.NewReader(stdout.Bytes()))
388 if err != nil {
389 t.Errorf("error reading the stream: %v", err)
390 return
391 }
392 // Check the random data sent on STDIN was the same returned on STDOUT.
393 if !bytes.Equal(randomData, data) {
394 t.Errorf("unexpected data received: %d sent: %d", len(data), len(randomData))
395 }
396
397 // Ensure the https proxy error was *not* observed
398 if sawHTTPSProxyError {
399 t.Errorf("expected to *not* see https proxy error")
400 }
401 // Ensure the proxy was called once
402 if e, a := int64(1), proxyCalled.Load(); e != a {
403 t.Errorf("expected %d proxy call, got %d", e, a)
404 }
405 }