-
Notifications
You must be signed in to change notification settings - Fork 12
/
socket_edge_case_test.go
323 lines (279 loc) · 8.92 KB
/
socket_edge_case_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package enigma
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/http/httptrace"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"golang.org/x/net/websocket"
)
var serverAddr string
var once sync.Once
var originAndJwtHeaders = http.Header{"origin": []string{"http://localhost"}, "authorization": []string{"jwt content"}}
type Handler func(*websocket.Conn)
func checkOrigin(config *websocket.Config, req *http.Request) (err error) {
config.Origin, err = websocket.Origin(config, req)
if err == nil && config.Origin == nil {
return fmt.Errorf("null origin")
}
return err
}
// ServeHTTP implements the http.Handler interface for a WebSocket
func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.Header.Get("authorization") == "" {
w.WriteHeader(401)
return
}
s := websocket.Server{Handler: func(c *websocket.Conn) {
h(c)
}, Handshake: checkOrigin}
s.ServeHTTP(w, req)
}
func fakeEngineServer(waitTime time.Duration, error *qixError) Handler {
return func(ws *websocket.Conn) {
defer ws.Close()
preMessages := []string{
// Testing notifications
`{"jsonrpc":"2.0","method":"OnConnected","params":{"qSessionState":"SESSION_CREATED"}}`,
// Testing pending messages
`{"jsonrpc":"2.0","id": 42}`,
}
// Send websocket messages that should be ignored
for _, msg := range preMessages {
err := websocket.Message.Send(ws, msg)
if err != nil {
return
}
}
for {
var req socketOutput
err := websocket.JSON.Receive(ws, &req)
if err != nil {
return
}
var res interface{}
if error != nil {
res = socketInput{
JSONRPC: req.JSONRPC,
rpcInvocationResponse: rpcInvocationResponse{
ID: req.ID,
Error: error,
},
}
} else {
result := json.RawMessage(`{ qHandle: 1, qType: "doc", qGenericID: "/apps/something" }`)
res = socketInput{
JSONRPC: req.JSONRPC,
rpcInvocationResponse: rpcInvocationResponse{
ID: req.ID,
Result: &result,
},
}
}
time.Sleep(waitTime)
err = websocket.JSON.Send(ws, res)
if err != nil {
return
}
}
}
}
func buildSuccessServer() Handler {
return fakeEngineServer(0, nil)
}
func buildTimeoutServer() Handler {
return fakeEngineServer(500*time.Millisecond, nil)
}
func buildMissingResultServer() Handler {
return func(ws *websocket.Conn) {
defer ws.Close()
for {
var req socketOutput
err := websocket.JSON.Receive(ws, &req)
if err != nil {
return
}
err = websocket.Message.Send(ws, `{"jsonrpc":"2.0","id":1,"result":null}`)
if err != nil {
return
}
}
}
}
type HandshakeTimeoutHandler struct{}
func (ct HandshakeTimeoutHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
time.Sleep(1000 * time.Millisecond)
buildSuccessServer().ServeHTTP(w, req)
}
func buildErrorServer() Handler {
return fakeEngineServer(0, &qixError{
ErrorCode: 500,
ErrorMessage: "parameter",
ErrorParameter: "error",
})
}
func startServer() {
http.Handle("/success", buildSuccessServer())
http.Handle("/error", buildErrorServer())
http.Handle("/missing-result", buildMissingResultServer())
http.Handle("/timeout", buildTimeoutServer())
http.Handle("/handshake-timeout", HandshakeTimeoutHandler{})
http.Handle("/configureError", buildErrorServer())
http.Handle("/doReloadError", buildErrorServer())
http.Handle("/activeDocError", buildErrorServer())
server := httptest.NewServer(nil)
serverAddr = server.Listener.Addr().String()
}
func TestDial(t *testing.T) {
once.Do(startServer)
jwtHeader := http.Header{"authorization": []string{"jwt content"}}
originHeader := http.Header{"origin": []string{"http://localhost"}}
var dialTests = []struct {
test string
url string
httpHeader http.Header
handshakeTimeout time.Duration
expectedError string
}{
{"success", "ws://" + serverAddr + "/success", originAndJwtHeaders, 0, ""},
{"failure bad url", "//" + serverAddr + "/success", originHeader, 0, "malformed ws or wss URL"},
{"failure bad origin", "ws://" + serverAddr + "/success", jwtHeader, 0, "403 from ws server"},
{"failure no jwt", "ws://" + serverAddr + "/success", originHeader, 0, "401 from ws server"},
{"failure with handshake timeout", "ws://" + serverAddr + "/handshake-timeout", originAndJwtHeaders, 5 * time.Millisecond, "context deadline exceeded"},
}
for _, tt := range dialTests {
ctx := context.Background()
if tt.handshakeTimeout != 0 {
var cancel func()
ctx, cancel = context.WithTimeout(ctx, tt.handshakeTimeout)
defer cancel()
}
conn, err := Dialer{}.Dial(ctx, tt.url, tt.httpHeader)
if tt.expectedError != "" {
assert.Error(t, err, tt.test)
assert.Contains(t, err.Error(), tt.expectedError, tt.test)
continue
} else {
assert.NoError(t, err, tt.test)
}
conn.DisconnectFromServer()
}
}
func TestOpenDocOnClosedConnectionError(t *testing.T) {
once.Do(startServer)
conn, err := Dialer{}.Dial(context.Background(), "ws://"+serverAddr+"/error", originAndJwtHeaders)
assert.NoError(t, err)
conn.DisconnectFromServer()
doc, err := conn.OpenDoc(context.Background(), "appID", "", "", "", false)
assert.Nil(t, doc)
assert.Error(t, err)
assert.Contains(t, err.Error(), "use of closed network connection")
assert.EqualValues(t, 0, conn.pendingCallCount())
}
func TestConnectionClosedDuringOpenDoc(t *testing.T) {
once.Do(startServer)
conn, err := Dialer{}.Dial(context.Background(), "ws://"+serverAddr+"/timeout", originAndJwtHeaders)
assert.NoError(t, err)
go func() {
time.Sleep(1000 * time.Millisecond)
conn.DisconnectFromServer()
}()
doc, err := conn.OpenDoc(context.Background(), "appID", "", "", "", false)
fmt.Print(err)
assert.Nil(t, doc)
assert.Error(t, err)
assert.Contains(t, err.Error(), "websocket: close 1000 (normal)")
assert.EqualValues(t, 0, conn.pendingCallCount())
}
func TestOpenDocSendTimeout(t *testing.T) {
once.Do(startServer)
conn, err := Dialer{}.Dial(context.Background(), "ws://"+serverAddr+"/timeout", originAndJwtHeaders)
assert.NoError(t, err)
defer conn.DisconnectFromServer()
ctx, cancel := context.WithCancel(context.Background())
// Cancelling before calling
cancel()
doc, err := conn.OpenDoc(ctx, "appID", "", "", "", false)
assert.Nil(t, doc)
assert.EqualError(t, err, "context canceled")
assert.EqualValues(t, 0, conn.pendingCallCount())
}
func TestOpenDocTimeout(t *testing.T) {
once.Do(startServer)
conn, err := Dialer{}.Dial(context.Background(), "ws://"+serverAddr+"/timeout", originAndJwtHeaders)
assert.EqualValues(t, 0, conn.pendingCallCount())
assert.NoError(t, err)
defer conn.DisconnectFromServer()
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
defer cancel()
doc, err := conn.OpenDoc(ctx, "appID", "", "", "", false)
assert.Nil(t, doc)
assert.EqualError(t, err, "context deadline exceeded")
}
func TestHTTPTrace(t *testing.T) {
url := "ws://" + serverAddr + "/success"
header := originAndJwtHeaders
// See if the builtin http.ClientTrace can be provided in a
// context to provide granular information about how the
// HTTP request (the upgrade) was performed.
funcsCalled := map[string]int{}
ctx := httptrace.WithClientTrace(context.Background(), testTrace(funcsCalled))
_, err := Dialer{}.Dial(ctx, url, header)
if err != nil {
t.Fatal("Connection error: ", err)
}
// Validate which trace-functions were called.
expectCalled := []string{"GetConn", "ConnectStart", "ConnectDone", "GotConn",
"WroteHeaderField", "WroteHeaders", "WroteRequest", "GotFirstResponseByte"}
for _, funcName := range expectCalled {
if c := funcsCalled[funcName]; c == 0 {
t.Errorf("Expected %s to be called at least once", funcName)
}
}
}
// testTrace takes a map. For each function the map-entry with the same function name
// is incremented by one.
// Note, this is a subset of the functions that can be used, for the complete set of
// functions see: https://pkg.go.dev/net/http/httptrace#ClientTrace
func testTrace(m map[string]int) *httptrace.ClientTrace {
return &httptrace.ClientTrace{
GetConn: func(hostPort string) {
fmt.Println("Get Connection:", hostPort)
m["GetConn"]++
},
GotConn: func(info httptrace.GotConnInfo) {
fmt.Printf("Got Connection: %#v\n", info)
m["GotConn"]++
},
GotFirstResponseByte: func() {
fmt.Println("First byte!")
m["GotFirstResponseByte"]++
},
ConnectStart: func(network, addr string) {
fmt.Printf("Connect start: %s %s\n", network, addr)
m["ConnectStart"]++
},
ConnectDone: func(network, addr string, err error) {
fmt.Printf("Connect done: %s %s - err: %v\n", network, addr, err)
m["ConnectDone"]++
},
WroteHeaderField: func(key string, value []string) {
fmt.Printf("> %s: %s\n", key, strings.Join(value, ""))
m["WroteHeaderField"]++
},
WroteHeaders: func() {
fmt.Println("Wrote Headers")
m["WroteHeaders"]++
},
WroteRequest: func(info httptrace.WroteRequestInfo) {
fmt.Println("Wrote Request - err:", info.Err)
m["WroteRequest"]++
},
}
}