Debian Codegraph @

tools/portforward/tunneling_connection_test.go

raw
1 /*
2 Copyright 2024 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 portforward
18
19 import (
20 "io"
21 "net"
22 "net/http"
23 "net/http/httptest"
24 "net/url"
25 "strings"
26 "testing"
27 "time"
28
29 gwebsocket "github.com/gorilla/websocket"
30 "github.com/stretchr/testify/assert"
31 "github.com/stretchr/testify/require"
32
33 "k8s.io/apimachinery/pkg/util/httpstream"
34 "k8s.io/apimachinery/pkg/util/httpstream/spdy"
35 constants "k8s.io/apimachinery/pkg/util/portforward"
36 "k8s.io/apimachinery/pkg/util/wait"
37 "k8s.io/client-go/rest"
38 "k8s.io/client-go/transport/websocket"
39 )
40
41 func TestTunnelingConnection_ReadWriteClose(t *testing.T) {
42 // Stream channel that will receive streams created on upstream SPDY server.
43 streamChan := make(chan httpstream.Stream)
44 defer close(streamChan)
45 stopServerChan := make(chan struct{})
46 defer close(stopServerChan)
47 // Create tunneling connection server endpoint with fake upstream SPDY server.
48 tunnelingServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
49 var upgrader = gwebsocket.Upgrader{
50 CheckOrigin: func(r *http.Request) bool { return true },
51 Subprotocols: []string{constants.WebsocketsSPDYTunnelingPortForwardV1},
52 }
53 conn, err := upgrader.Upgrade(w, req, nil)
54 if err != nil {
55 t.Errorf("unexpected error %v", err)
56 return
57 }
58 defer conn.Close() //nolint:errcheck
59 if conn.Subprotocol() != constants.WebsocketsSPDYTunnelingPortForwardV1 {
60 t.Errorf("Not acceptable agreement Subprotocol: %v", conn.Subprotocol())
61 return
62 }
63 tunnelingConn := NewTunnelingConnection("server", conn)
64 spdyConn, err := spdy.NewServerConnection(tunnelingConn, justQueueStream(streamChan))
65 if err != nil {
66 t.Errorf("unexpected error %v", err)
67 return
68 }
69 defer spdyConn.Close() //nolint:errcheck
70 <-stopServerChan
71 }))
72 defer tunnelingServer.Close()
73 // Dial the client tunneling connection to the tunneling server.
74 url, err := url.Parse(tunnelingServer.URL)
75 require.NoError(t, err)
76 dialer, err := NewSPDYOverWebsocketDialer(url, &rest.Config{Host: url.Host})
77 require.NoError(t, err)
78 spdyClient, protocol, err := dialer.Dial(constants.PortForwardV1Name)
79 require.NoError(t, err)
80 assert.Equal(t, constants.PortForwardV1Name, protocol)
81 defer spdyClient.Close() //nolint:errcheck
82 // Create a SPDY client stream, which will queue a SPDY server stream
83 // on the stream creation channel. Send data on the client stream
84 // reading off the SPDY server stream, and validating it was tunneled.
85 expected := "This is a test tunneling SPDY data through websockets."
86 var actual []byte
87 go func() {
88 clientStream, err := spdyClient.CreateStream(http.Header{})
89 if err != nil {
90 t.Errorf("unexpected error %v", err)
91 return
92 }
93 _, err = io.Copy(clientStream, strings.NewReader(expected))
94 if err != nil {
95 t.Errorf("unexpected error %v", err)
96 return
97 }
98 clientStream.Close() //nolint:errcheck
99 }()
100 select {
101 case serverStream := <-streamChan:
102 actual, err = io.ReadAll(serverStream)
103 require.NoError(t, err)
104 defer serverStream.Close() //nolint:errcheck
105 case <-time.After(wait.ForeverTestTimeout):
106 t.Fatalf("timeout waiting for spdy stream to arrive on channel.")
107 }
108 assert.Equal(t, expected, string(actual), "error validating tunneled string")
109 }
110
111 func TestTunnelingConnection_LocalRemoteAddress(t *testing.T) {
112 stopServerChan := make(chan struct{})
113 defer close(stopServerChan)
114 tunnelingServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
115 var upgrader = gwebsocket.Upgrader{
116 CheckOrigin: func(r *http.Request) bool { return true },
117 Subprotocols: []string{constants.WebsocketsSPDYTunnelingPortForwardV1},
118 }
119 conn, err := upgrader.Upgrade(w, req, nil)
120 if err != nil {
121 t.Errorf("unexpected error %v", err)
122 return
123 }
124 defer conn.Close() //nolint:errcheck
125 if conn.Subprotocol() != constants.WebsocketsSPDYTunnelingPortForwardV1 {
126 t.Errorf("Not acceptable agreement Subprotocol: %v", conn.Subprotocol())
127 }
128 <-stopServerChan
129 }))
130 defer tunnelingServer.Close()
131 // Create the client side tunneling connection.
132 url, err := url.Parse(tunnelingServer.URL)
133 require.NoError(t, err)
134 tConn, err := dialForTunnelingConnection(url)
135 require.NoError(t, err, "error creating client tunneling connection")
136 defer tConn.Close() //nolint:errcheck
137 // Validate "LocalAddr()" and "RemoteAddr()"
138 localAddr := tConn.LocalAddr()
139 remoteAddr := tConn.RemoteAddr()
140 assert.Equal(t, "tcp", localAddr.Network(), "tunneling connection must be TCP")
141 assert.Equal(t, "tcp", remoteAddr.Network(), "tunneling connection must be TCP")
142 _, err = net.ResolveTCPAddr("tcp", localAddr.String())
143 assert.NoError(t, err, "tunneling connection local addr should parse")
144 _, err = net.ResolveTCPAddr("tcp", remoteAddr.String())
145 assert.NoError(t, err, "tunneling connection remote addr should parse")
146 }
147
148 func TestTunnelingConnection_ReadWriteDeadlines(t *testing.T) {
149 stopServerChan := make(chan struct{})
150 defer close(stopServerChan)
151 tunnelingServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
152 var upgrader = gwebsocket.Upgrader{
153 CheckOrigin: func(r *http.Request) bool { return true },
154 Subprotocols: []string{constants.WebsocketsSPDYTunnelingPortForwardV1},
155 }
156 conn, err := upgrader.Upgrade(w, req, nil)
157 if err != nil {
158 t.Errorf("unexpected error %v", err)
159 return
160 }
161 defer conn.Close() //nolint:errcheck
162 if conn.Subprotocol() != constants.WebsocketsSPDYTunnelingPortForwardV1 {
163 t.Errorf("Not acceptable agreement Subprotocol: %v", conn.Subprotocol())
164 return
165 }
166 <-stopServerChan
167 }))
168 defer tunnelingServer.Close()
169 // Create the client side tunneling connection.
170 url, err := url.Parse(tunnelingServer.URL)
171 require.NoError(t, err)
172 tConn, err := dialForTunnelingConnection(url)
173 require.NoError(t, err, "error creating client tunneling connection")
174 defer tConn.Close() //nolint:errcheck
175 // Validate the read and write deadlines.
176 err = tConn.SetReadDeadline(time.Time{})
177 assert.NoError(t, err, "setting zero deadline should always succeed; turns off deadline")
178 err = tConn.SetWriteDeadline(time.Time{})
179 assert.NoError(t, err, "setting zero deadline should always succeed; turns off deadline")
180 err = tConn.SetDeadline(time.Time{})
181 assert.NoError(t, err, "setting zero deadline should always succeed; turns off deadline")
182 err = tConn.SetReadDeadline(time.Now().AddDate(10, 0, 0))
183 assert.NoError(t, err, "setting deadline 10 year from now succeeds")
184 err = tConn.SetWriteDeadline(time.Now().AddDate(10, 0, 0))
185 assert.NoError(t, err, "setting deadline 10 year from now succeeds")
186 err = tConn.SetDeadline(time.Now().AddDate(10, 0, 0))
187 assert.NoError(t, err, "setting deadline 10 year from now succeeds")
188 }
189
190 // dialForTunnelingConnection upgrades a request at the passed "url", creating
191 // a websocket connection. Returns the TunnelingConnection injected with the
192 // websocket connection or an error if one occurs.
193 func dialForTunnelingConnection(url *url.URL) (*TunnelingConnection, error) {
194 req, err := http.NewRequest("GET", url.String(), nil)
195 if err != nil {
196 return nil, err
197 }
198 // Tunneling must initiate a websocket upgrade connection, using tunneling portforward protocol.
199 tunnelingProtocols := []string{constants.WebsocketsSPDYTunnelingPortForwardV1}
200 transport, holder, err := websocket.RoundTripperFor(&rest.Config{Host: url.Host})
201 if err != nil {
202 return nil, err
203 }
204 conn, err := websocket.Negotiate(transport, holder, req, tunnelingProtocols...)
205 if err != nil {
206 return nil, err
207 }
208 return NewTunnelingConnection("client", conn), nil
209 }
210
211 func justQueueStream(streams chan httpstream.Stream) func(httpstream.Stream, <-chan struct{}) error {
212 return func(stream httpstream.Stream, replySent <-chan struct{}) error {
213 streams <- stream
214 return nil
215 }
216 }