-
Notifications
You must be signed in to change notification settings - Fork 219
Expand file tree
/
Copy pathwebsocket.go
More file actions
1403 lines (1226 loc) · 43.9 KB
/
websocket.go
File metadata and controls
1403 lines (1226 loc) · 43.9 KB
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package core
import (
"bytes"
"compress/flate"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"regexp"
"slices"
"sync"
"syscall"
"time"
"github.com/buger/jsonparser"
"github.com/go-chi/chi/v5/middleware"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsflate"
"github.com/gobwas/ws/wsutil"
"github.com/gorilla/websocket"
"github.com/tidwall/gjson"
"github.com/wundergraph/astjson"
"go.uber.org/atomic"
"go.uber.org/zap"
"github.com/wundergraph/graphql-go-tools/v2/pkg/engine/plan"
"github.com/wundergraph/graphql-go-tools/v2/pkg/engine/resolve"
"github.com/wundergraph/graphql-go-tools/v2/pkg/netpoll"
"github.com/wundergraph/cosmo/router/internal/expr"
"github.com/wundergraph/cosmo/router/internal/persistedoperation"
"github.com/wundergraph/cosmo/router/internal/wsproto"
"github.com/wundergraph/cosmo/router/pkg/authentication"
"github.com/wundergraph/cosmo/router/pkg/config"
"github.com/wundergraph/cosmo/router/pkg/logging"
"github.com/wundergraph/cosmo/router/pkg/statistics"
rtrace "github.com/wundergraph/cosmo/router/pkg/trace"
)
var (
errClientTerminatedConnection = errors.New("client terminated connection")
)
type WebsocketMiddlewareOptions struct {
OperationProcessor *OperationProcessor
OperationBlocker *OperationBlocker
Planner *OperationPlanner
GraphQLHandler *GraphQLHandler
PreHandler *PreHandler
Metrics RouterMetrics
AccessController *AccessController
Logger *zap.Logger
Stats statistics.EngineStatistics
ReadTimeout time.Duration
WriteTimeout time.Duration
EnableNetPoll bool
NetPollTimeout time.Duration
NetPollConnBufferSize int
WebSocketConfiguration *config.WebSocketConfiguration
ClientHeader config.ClientHeader
DisableVariablesRemapping bool
ApolloCompatibilityFlags config.ApolloCompatibilityFlags
}
// NewWebsocketMiddleware creates an HTTP middleware that upgrades eligible requests to WebSocket
// connections and dispatches them to an internal WebsocketHandler configured by opts.
//
// The returned middleware delegates non-WebSocket requests to the next handler. Options in
// WebsocketMiddlewareOptions control timeouts, compression and protocol features, access control,
// header/query param forwarding allow-lists, net-poll integration, and the components used to
// process GraphQL operations over WebSocket.
func NewWebsocketMiddleware(ctx context.Context, opts WebsocketMiddlewareOptions) func(http.Handler) http.Handler {
handler := &WebsocketHandler{
ctx: ctx,
operationProcessor: opts.OperationProcessor,
operationBlocker: opts.OperationBlocker,
planner: opts.Planner,
graphqlHandler: opts.GraphQLHandler,
preHandler: opts.PreHandler,
metrics: opts.Metrics,
accessController: opts.AccessController,
logger: opts.Logger,
stats: opts.Stats,
readTimeout: opts.ReadTimeout,
writeTimeout: opts.WriteTimeout,
config: opts.WebSocketConfiguration,
clientHeader: opts.ClientHeader,
disableVariablesRemapping: opts.DisableVariablesRemapping,
apolloCompatibilityFlags: opts.ApolloCompatibilityFlags,
}
if opts.WebSocketConfiguration != nil && opts.WebSocketConfiguration.Compression.Enabled {
handler.compressionEnabled = true
handler.compressionLevel = opts.WebSocketConfiguration.Compression.Level
if handler.compressionLevel < 1 || handler.compressionLevel > 9 {
handler.compressionLevel = flate.DefaultCompression
}
}
if opts.WebSocketConfiguration != nil && opts.WebSocketConfiguration.AbsintheProtocol.Enabled {
handler.absintheHandlerEnabled = true
handler.absintheHandlerPath = opts.WebSocketConfiguration.AbsintheProtocol.HandlerPath
}
if opts.WebSocketConfiguration.ForwardUpgradeHeaders.Enabled {
handler.forwardUpgradeHeadersConfig.enabled = true
for _, str := range opts.WebSocketConfiguration.ForwardUpgradeHeaders.AllowList {
if detectNonRegex.MatchString(str) {
canonicalHeaderKey := http.CanonicalHeaderKey(str)
handler.forwardUpgradeHeadersConfig.staticAllowList = append(handler.forwardUpgradeHeadersConfig.staticAllowList, canonicalHeaderKey)
} else {
re, err := regexp.Compile(str)
if err != nil {
opts.Logger.Warn("Invalid regex in forward upgrade headers allow list", zap.String("regex", str), zap.Error(err))
continue
}
handler.forwardUpgradeHeadersConfig.regexAllowList = append(handler.forwardUpgradeHeadersConfig.regexAllowList, re)
}
}
handler.forwardUpgradeHeadersConfig.withStaticAllowList = len(handler.forwardUpgradeHeadersConfig.staticAllowList) > 0
handler.forwardUpgradeHeadersConfig.withRegexAllowList = len(handler.forwardUpgradeHeadersConfig.regexAllowList) > 0
}
if opts.WebSocketConfiguration.ForwardUpgradeQueryParams.Enabled {
handler.forwardQueryParamsConfig.enabled = true
for _, str := range opts.WebSocketConfiguration.ForwardUpgradeQueryParams.AllowList {
if detectNonRegex.MatchString(str) {
handler.forwardQueryParamsConfig.staticAllowList = append(handler.forwardQueryParamsConfig.staticAllowList, str)
} else {
re, err := regexp.Compile(str)
if err != nil {
opts.Logger.Warn("Invalid regex in forward upgrade query params allow list", zap.String("regex", str), zap.Error(err))
continue
}
handler.forwardQueryParamsConfig.regexAllowList = append(handler.forwardQueryParamsConfig.regexAllowList, re)
}
}
handler.forwardQueryParamsConfig.withStaticAllowList = len(handler.forwardQueryParamsConfig.staticAllowList) > 0
handler.forwardQueryParamsConfig.withRegexAllowList = len(handler.forwardQueryParamsConfig.regexAllowList) > 0
}
if opts.EnableNetPoll {
poller, err := netpoll.NewPoller(opts.NetPollConnBufferSize, opts.NetPollTimeout)
if err == nil {
opts.Logger.Debug("Net poller is available")
handler.netPoll = poller
handler.connections = make(map[int]*WebSocketConnectionHandler)
go handler.runPoller()
}
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !websocket.IsWebSocketUpgrade(r) {
next.ServeHTTP(w, r)
return
}
handler.handleUpgradeRequest(w, r)
})
}
}
// wsConnectionWrapper is a wrapper around websocket.Conn that allows
// writing from multiple goroutines
type wsConnectionWrapper struct {
conn net.Conn
mu sync.Mutex
readTimeout time.Duration
writeTimeout time.Duration
// Compression fields
compressionEnabled bool
compressionLevel int
}
// deflate compression level when enabled (typically 1–9 or flate.DefaultCompression).
func newWSConnectionWrapper(conn net.Conn, readTimeout, writeTimeout time.Duration, compressionEnabled bool, compressionLevel int) *wsConnectionWrapper {
return &wsConnectionWrapper{
conn: conn,
readTimeout: readTimeout,
writeTimeout: writeTimeout,
compressionEnabled: compressionEnabled,
compressionLevel: compressionLevel,
}
}
func (c *wsConnectionWrapper) ReadJSON(v any) error {
if c.readTimeout > 0 {
err := c.conn.SetReadDeadline(time.Now().Add(c.readTimeout))
if err != nil {
return err
}
}
var text []byte
var err error
if c.compressionEnabled {
// Read frames directly and handle compression
controlHandler := wsutil.ControlFrameHandler(c.conn, ws.StateServerSide)
for {
frame, err := ws.ReadFrame(c.conn)
if err != nil {
return err
}
// Unmask client frames
if frame.Header.Masked {
ws.Cipher(frame.Payload, frame.Header.Mask, 0)
}
if frame.Header.OpCode.IsControl() {
if err := controlHandler(frame.Header, bytes.NewReader(frame.Payload)); err != nil {
return err
}
continue
}
if frame.Header.OpCode == ws.OpText || frame.Header.OpCode == ws.OpBinary {
// Check if frame is compressed (RSV1 bit set)
isCompressed, err := wsflate.IsCompressed(frame.Header)
if err != nil {
return err
}
if isCompressed {
frame, err = wsflate.DecompressFrame(frame)
if err != nil {
return err
}
}
text = frame.Payload
break
}
}
} else {
text, err = wsutil.ReadClientText(c.conn)
if err != nil {
return err
}
}
return json.Unmarshal(text, v)
}
func (c *wsConnectionWrapper) WriteText(text string) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.writeTimeout > 0 {
err := c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
if err != nil {
return err
}
}
if c.compressionEnabled {
return c.writeCompressed([]byte(text))
}
return wsutil.WriteServerText(c.conn, []byte(text))
}
func (c *wsConnectionWrapper) WriteJSON(v any) error {
c.mu.Lock()
defer c.mu.Unlock()
data, err := json.Marshal(v)
if err != nil {
return err
}
if c.writeTimeout > 0 {
err := c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
if err != nil {
return err
}
}
if c.compressionEnabled {
return c.writeCompressed(data)
}
return wsutil.WriteServerText(c.conn, data)
}
// writeCompressed writes data with compression. Must be called with the mutex held.
func (c *wsConnectionWrapper) writeCompressed(data []byte) error {
var buf bytes.Buffer
writer := wsflate.NewWriter(&buf, func(w io.Writer) wsflate.Compressor {
fw, _ := flate.NewWriter(w, c.compressionLevel)
return fw
})
if _, err := writer.Write(data); err != nil {
return err
}
if err := writer.Flush(); err != nil {
return err
}
frame := ws.NewFrame(ws.OpText, true, buf.Bytes())
frame.Header.Rsv = ws.Rsv(true, false, false) // Set RSV1 bit for compression
return ws.WriteFrame(c.conn, frame)
}
func (c *wsConnectionWrapper) WriteCloseFrame(code ws.StatusCode, reason string) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.writeTimeout > 0 {
err := c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
if err != nil {
return err
}
}
return ws.WriteFrame(c.conn, ws.NewCloseFrame(ws.NewCloseFrameBody(code, reason)))
}
func (c *wsConnectionWrapper) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
return c.conn.Close()
}
type WebsocketHandler struct {
ctx context.Context
config *config.WebSocketConfiguration
operationProcessor *OperationProcessor
operationBlocker *OperationBlocker
planner *OperationPlanner
graphqlHandler *GraphQLHandler
preHandler *PreHandler
metrics RouterMetrics
accessController *AccessController
logger *zap.Logger
netPoll netpoll.Poller
connections map[int]*WebSocketConnectionHandler
connectionsMu sync.RWMutex
stats statistics.EngineStatistics
readTimeout time.Duration
writeTimeout time.Duration
absintheHandlerEnabled bool
absintheHandlerPath string
forwardUpgradeHeadersConfig forwardConfig
forwardQueryParamsConfig forwardConfig
clientHeader config.ClientHeader
disableVariablesRemapping bool
apolloCompatibilityFlags config.ApolloCompatibilityFlags
compressionEnabled bool
compressionLevel int
}
func (h *WebsocketHandler) handleUpgradeRequest(w http.ResponseWriter, r *http.Request) {
var (
subProtocol string
)
requestID := middleware.GetReqID(r.Context())
requestContext := getRequestContext(r.Context())
requestLogger := h.logger.With(logging.WithRequestID(requestID), logging.WithTraceID(rtrace.GetTraceID(r.Context())))
if batchedOperationId, ok := r.Context().Value(BatchedOperationId{}).(string); ok {
requestLogger = requestLogger.With(logging.WithBatchedRequestOperationID(batchedOperationId))
}
clientInfo := NewClientInfoFromRequest(r, h.clientHeader)
if h.accessController != nil && !h.config.Authentication.FromInitialPayload.Enabled {
// Check access control before upgrading the connection
validatedReq, err := h.accessController.Access(w, r)
if err != nil {
statusCode := http.StatusForbidden
if errors.Is(err, ErrUnauthorized) {
statusCode = http.StatusUnauthorized
}
http.Error(w, http.StatusText(statusCode), statusCode)
return
}
r = validatedReq
requestContext.expressionContext.Request.Auth = expr.LoadAuth(r.Context())
}
upgrader := ws.HTTPUpgrader{
Timeout: time.Second * 5,
Protocol: func(s string) bool {
if wsproto.IsSupportedSubprotocol(s) {
subProtocol = s
return true
}
return false
},
}
// Configure permessage-deflate compression if enabled
var compressionNegotiated bool
var ext wsflate.Extension
if h.compressionEnabled {
ext = wsflate.Extension{
Parameters: wsflate.Parameters{
ServerNoContextTakeover: true,
ClientNoContextTakeover: true,
},
}
upgrader.Negotiate = ext.Negotiate
}
c, _, _, err := upgrader.Upgrade(r, w)
// Check if compression was negotiated
if h.compressionEnabled && err == nil {
if _, accepted := ext.Accepted(); accepted {
compressionNegotiated = true
}
}
if err != nil {
requestLogger.Warn("Websocket upgrade", zap.Error(err))
_ = c.Close()
return
}
// legacy absinthe clients don't set the Sec-WebSocket-Protocol header (Subprotocol)
// so we need to check the path to determine if it's an absinthe client and set the subprotocol manually
if subProtocol == "" && h.absintheHandlerEnabled && r.URL.Path == h.absintheHandlerPath {
subProtocol = wsproto.AbsintheWSSubProtocol
}
// After successful upgrade, we can't write to the response writer anymore
// because it's hijacked by the websocket connection
conn := newWSConnectionWrapper(c, h.readTimeout, h.writeTimeout, compressionNegotiated, h.compressionLevel)
protocol, err := wsproto.NewProtocol(subProtocol, conn)
if err != nil {
requestLogger.Error("Create websocket protocol", zap.Error(err))
_ = c.Close()
return
}
// We can parse the request options before creating the handler
// this avoids touching the client request across goroutines
executionOptions, traceOptions, err := h.preHandler.parseRequestOptions(r, clientInfo, requestLogger)
if err != nil {
requestLogger.Error("Parse request options", zap.Error(err))
_ = c.Close()
return
}
planOptions := PlanOptions{
ClientInfo: clientInfo,
TraceOptions: traceOptions,
ExecutionOptions: executionOptions,
TrackSchemaUsageInfo: h.preHandler.trackSchemaUsageInfo,
}
handler := NewWebsocketConnectionHandler(h.ctx, WebSocketConnectionHandlerOptions{
ClientInfoFromInitialPayload: h.config.ClientInfoFromInitialPayload,
ForwardInitialPayload: h.config.ForwardInitialPayload,
OperationProcessor: h.operationProcessor,
OperationBlocker: h.operationBlocker,
Planner: h.planner,
GraphQLHandler: h.graphqlHandler,
PreHandler: h.preHandler,
Metrics: h.metrics,
PlanOptions: planOptions,
ResponseWriter: w,
Request: r,
Connection: conn,
Protocol: protocol,
Logger: requestLogger,
Stats: h.stats,
ConnectionID: resolve.ConnectionIDs.Inc(),
ClientInfo: clientInfo,
InitRequestID: requestID,
ForwardUpgradeHeaders: h.forwardUpgradeHeadersConfig,
ForwardQueryParams: h.forwardQueryParamsConfig,
DisableVariablesRemapping: h.disableVariablesRemapping,
ApolloCompatibilityFlags: h.apolloCompatibilityFlags,
})
err = handler.Initialize()
if err != nil {
// Don't produce errors logs here because it can only be client side errors
// e.g. slow client, aborted connection, invalid JSON, etc.
// We log it as debug because it's not a server side error
requestLogger.Debug("Initializing websocket connection", zap.Error(err))
handler.Close(false)
return
}
// Authenticate the connection using the initial payload
fromInitialPayloadConfig := h.config.Authentication.FromInitialPayload
if fromInitialPayloadConfig.Enabled {
// Setting the initialPayload in the context to be used by the websocketInitialPayloadAuthenticator
r = r.WithContext(authentication.WithWebsocketInitialPayloadContextKey(r.Context(), handler.initialPayload))
// Later check access control after initial payload is read and set into the context
if h.accessController != nil {
handler.request, err = h.accessController.Access(w, r)
if err != nil {
statusCode := http.StatusForbidden
if errors.Is(err, ErrUnauthorized) {
statusCode = http.StatusUnauthorized
}
http.Error(handler.w, http.StatusText(statusCode), statusCode)
_ = handler.writeErrorMessage(requestID, err)
handler.Close(false)
return
}
}
// Export the token from the initial payload to the request header
if fromInitialPayloadConfig.ExportToken.Enabled {
var initialPayloadMap map[string]any
err := json.Unmarshal(handler.initialPayload, &initialPayloadMap)
if err != nil {
requestLogger.Error("Error parsing initial payload: %v", zap.Error(err))
_ = handler.writeErrorMessage(requestID, err)
handler.Close(false)
return
}
jwtToken, ok := initialPayloadMap[fromInitialPayloadConfig.Key].(string)
if !ok {
err := fmt.Errorf("invalid JWT token in initial payload: JWT token is not a string")
requestLogger.Error(err.Error())
_ = handler.writeErrorMessage(requestID, err)
handler.Close(false)
return
}
handler.request.Header.Set(fromInitialPayloadConfig.ExportToken.HeaderKey, jwtToken)
}
requestContext.expressionContext.Request.Auth = expr.LoadAuth(handler.request.Context())
}
// Only when epoll/kqueue is available. On Windows, epoll is not available
if h.netPoll != nil {
err = h.addConnection(c, handler)
if err != nil {
requestLogger.Error("Adding connection to net poller", zap.Error(err))
handler.Close(true)
}
return
}
// Handle messages sync when net poller implementation is not available
go h.handleConnectionSync(handler)
}
func (h *WebsocketHandler) handleConnectionSync(handler *WebSocketConnectionHandler) {
h.stats.ConnectionsInc()
defer h.stats.ConnectionsDec()
serverDone := h.ctx.Done()
defer handler.Close(true)
for {
select {
case <-serverDone:
return
default:
msg, err := handler.protocol.ReadMessage()
if err != nil {
if isReadTimeout(err) {
continue
}
h.logger.Debug("Client closed connection")
return
}
err = h.HandleMessage(handler, msg)
if err != nil {
h.logger.Debug("Handling websocket message", zap.Error(err))
if errors.Is(err, errClientTerminatedConnection) {
return
}
}
}
}
}
func (h *WebsocketHandler) addConnection(conn net.Conn, handler *WebSocketConnectionHandler) error {
h.stats.ConnectionsInc()
h.connectionsMu.Lock()
defer h.connectionsMu.Unlock()
fd := socketFd(conn)
if fd == 0 {
return fmt.Errorf("unable to get socket fd for conn: %d", handler.connectionID)
}
h.connections[fd] = handler
return h.netPoll.Add(conn)
}
func (h *WebsocketHandler) removeConnection(conn net.Conn, handler *WebSocketConnectionHandler, fd int) {
h.stats.ConnectionsDec()
h.connectionsMu.Lock()
delete(h.connections, fd)
h.connectionsMu.Unlock()
err := h.netPoll.Remove(conn)
if err != nil {
h.logger.Warn("Removing connection from net poller", zap.Error(err))
}
handler.Close(true)
}
func socketFd(conn net.Conn) int {
if con, ok := conn.(syscall.Conn); ok {
raw, err := con.SyscallConn()
if err != nil {
return 0
}
sfd := 0
_ = raw.Control(func(fd uintptr) {
sfd = int(fd)
})
return sfd
}
if con, ok := conn.(netpoll.ConnImpl); ok {
return con.GetFD()
}
return 0
}
func isReadTimeout(err error) bool {
if err == nil {
return false
}
var netErr net.Error
if errors.As(err, &netErr) {
return netErr.Timeout()
}
return false
}
func (h *WebsocketHandler) runPoller() {
done := h.ctx.Done()
defer func() {
h.connectionsMu.Lock()
_ = h.netPoll.Close(true)
h.connectionsMu.Unlock()
}()
for {
select {
case <-done:
return
default:
connections, err := h.netPoll.Wait(128)
if err != nil {
h.logger.Warn("Net Poller wait", zap.Error(err))
continue
}
for i := range len(connections) {
if connections[i] == nil {
continue
}
conn := connections[i].(netpoll.ConnImpl)
// check if the connection is still valid
fd := socketFd(conn)
h.connectionsMu.RLock()
handler, exists := h.connections[fd]
h.connectionsMu.RUnlock()
if !exists {
h.logger.Debug("Connection not found", zap.Int("fd", fd))
continue
}
if fd == 0 {
h.logger.Debug("Invalid socket fd", zap.Int("fd", fd))
h.removeConnection(conn, handler, fd)
continue
}
msg, err := handler.protocol.ReadMessage()
if err != nil {
h.logger.Debug("Client closed connection", zap.Error(err))
h.removeConnection(conn, handler, fd)
continue
}
err = h.HandleMessage(handler, msg)
if err != nil {
h.logger.Debug("Handling websocket message", zap.Error(err))
if errors.Is(err, errClientTerminatedConnection) {
h.removeConnection(conn, handler, fd)
continue
}
}
}
}
}
}
type websocketResponseWriter struct {
id string
protocol wsproto.Proto
header http.Header
buf bytes.Buffer
writtenBytes int
logger *zap.Logger
stats statistics.EngineStatistics
propagateErrors bool
}
var _ http.ResponseWriter = (*websocketResponseWriter)(nil)
var _ resolve.SubscriptionResponseWriter = (*websocketResponseWriter)(nil)
func newWebsocketResponseWriter(id string, protocol wsproto.Proto, propagateErrors bool, logger *zap.Logger, stats statistics.EngineStatistics) *websocketResponseWriter {
return &websocketResponseWriter{
id: id,
protocol: protocol,
header: make(http.Header),
logger: logger.With(zap.String("subscription_id", id)),
stats: stats,
propagateErrors: propagateErrors,
}
}
func (rw *websocketResponseWriter) Header() http.Header {
return rw.header
}
func (rw *websocketResponseWriter) WriteHeader(statusCode int) {
rw.logger.Debug("Response status code", zap.Int("status_code", statusCode))
}
func (rw *websocketResponseWriter) Complete() {
err := rw.protocol.Complete(rw.id)
if err != nil {
rw.logger.Debug("Sending complete message", zap.Error(err))
}
}
// Heartbeat is a no-op function for WebSocket subscriptions.
func (rw *websocketResponseWriter) Heartbeat() error {
return nil
}
func (rw *websocketResponseWriter) Close(kind resolve.SubscriptionCloseKind) {
err := rw.protocol.Close(kind.WSCode, kind.Reason)
if err != nil {
rw.logger.Debug("Sending error message", zap.Error(err))
}
}
func (rw *websocketResponseWriter) Write(data []byte) (int, error) {
rw.writtenBytes += len(data)
return rw.buf.Write(data)
}
func (rw *websocketResponseWriter) Flush() error {
if rw.buf.Len() > 0 {
rw.logger.Debug("flushing", zap.Int("bytes", rw.buf.Len()))
payload := rw.buf.Bytes()
var extensions []byte
var err error
if len(rw.header) > 0 {
extensions, err = json.Marshal(map[string]any{
"response_headers": rw.header,
})
if err != nil {
rw.logger.Warn("Serializing response headers", zap.Error(err))
return err
}
}
// Check if the result is an error
errorsResult := gjson.GetBytes(payload, "errors")
if errorsResult.Type == gjson.JSON {
if rw.propagateErrors {
err = rw.protocol.WriteGraphQLErrors(rw.id, json.RawMessage(errorsResult.Raw), extensions)
} else {
err = rw.protocol.WriteGraphQLErrors(rw.id, json.RawMessage(`[{"message":"Unable to subscribe"}]`), extensions)
}
} else {
err = rw.protocol.WriteGraphQLData(rw.id, payload, extensions)
}
rw.buf.Reset()
if err != nil {
return err
}
}
return nil
}
func (rw *websocketResponseWriter) SubscriptionResponseWriter() resolve.SubscriptionResponseWriter {
return rw
}
type graphqlError struct {
Message string `json:"message"`
Extensions *Extensions `json:"extensions,omitempty"`
}
type WebSocketConnectionHandlerOptions struct {
ClientInfoFromInitialPayload config.WebSocketClientInfoFromInitialPayloadConfiguration
ForwardInitialPayload bool
OperationProcessor *OperationProcessor
OperationBlocker *OperationBlocker
Planner *OperationPlanner
GraphQLHandler *GraphQLHandler
PreHandler *PreHandler
Metrics RouterMetrics
ResponseWriter http.ResponseWriter
Request *http.Request
Connection *wsConnectionWrapper
Protocol wsproto.Proto
Logger *zap.Logger
Stats statistics.EngineStatistics
PlanOptions PlanOptions
ConnectionID int64
ClientInfo *ClientInfo
InitRequestID string
ForwardUpgradeHeaders forwardConfig
ForwardQueryParams forwardConfig
DisableVariablesRemapping bool
ApolloCompatibilityFlags config.ApolloCompatibilityFlags
}
type WebSocketConnectionHandler struct {
ctx context.Context
operationProcessor *OperationProcessor
operationBlocker *OperationBlocker
planner *OperationPlanner
graphqlHandler *GraphQLHandler
plannerOptions PlanOptions
preHandler *PreHandler
metrics RouterMetrics
w http.ResponseWriter
// request is the original client request. It is not safe for concurrent use.
// You have to clone it before using it in a goroutine.
request *http.Request
conn *wsConnectionWrapper
protocol wsproto.Proto
clientInfo *ClientInfo
logger *zap.Logger
initialPayload json.RawMessage
upgradeRequestHeaders json.RawMessage
upgradeRequestQueryParams json.RawMessage
initRequestID string
connectionID int64
subscriptionIDs atomic.Int64
subscriptions sync.Map
stats statistics.EngineStatistics
forwardInitialPayload bool
forwardUpgradeHeaders *forwardConfig
forwardQueryParams *forwardConfig
disableVariablesRemapping bool
apolloCompatibilityFlags config.ApolloCompatibilityFlags
clientInfoFromInitialPayload config.WebSocketClientInfoFromInitialPayloadConfiguration
}
type forwardConfig struct {
enabled bool
withStaticAllowList bool
staticAllowList []string
withRegexAllowList bool
regexAllowList []*regexp.Regexp
}
var (
detectNonRegex = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
)
func NewWebsocketConnectionHandler(ctx context.Context, opts WebSocketConnectionHandlerOptions) *WebSocketConnectionHandler {
return &WebSocketConnectionHandler{
ctx: ctx,
operationProcessor: opts.OperationProcessor,
operationBlocker: opts.OperationBlocker,
planner: opts.Planner,
graphqlHandler: opts.GraphQLHandler,
preHandler: opts.PreHandler,
metrics: opts.Metrics,
w: opts.ResponseWriter,
request: opts.Request,
conn: opts.Connection,
protocol: opts.Protocol,
logger: opts.Logger,
connectionID: opts.ConnectionID,
stats: opts.Stats,
clientInfo: opts.ClientInfo,
initRequestID: opts.InitRequestID,
forwardUpgradeHeaders: &opts.ForwardUpgradeHeaders,
forwardQueryParams: &opts.ForwardQueryParams,
forwardInitialPayload: opts.ForwardInitialPayload,
plannerOptions: opts.PlanOptions,
disableVariablesRemapping: opts.DisableVariablesRemapping,
apolloCompatibilityFlags: opts.ApolloCompatibilityFlags,
clientInfoFromInitialPayload: opts.ClientInfoFromInitialPayload,
}
}
func (h *WebSocketConnectionHandler) requestError(err error) error {
if errors.As(err, &wsutil.ClosedError{}) {
h.logger.Debug("Client closed connection")
return err
}
h.logger.Warn("Handling websocket connection", zap.Error(err))
return h.conn.WriteText(err.Error())
}
func (h *WebSocketConnectionHandler) writeErrorMessage(operationID string, err error) error {
gqlErrors := []graphqlError{
{Message: err.Error()},
}
payload, err := json.Marshal(gqlErrors)
if err != nil {
return fmt.Errorf("encoding GraphQL errors: %w", err)
}
return h.protocol.WriteGraphQLErrors(operationID, payload, nil)
}
func (h *WebSocketConnectionHandler) parseAndPlan(registration *SubscriptionRegistration) (*ParsedOperation, *operationContext, error) {
operationKit, err := h.operationProcessor.NewKit()
if err != nil {
return nil, nil, err
}
defer operationKit.Free()
opContext := &operationContext{
clientInfo: h.plannerOptions.ClientInfo,
}
if err := operationKit.UnmarshalOperationFromBody(registration.msg.Payload); err != nil {
return nil, nil, err
}
opContext.extensions = operationKit.parsedOperation.Request.Extensions
var (
skipParse bool
isApq bool
)
if h.shouldComputeOperationSha256(operationKit) {
err = operationKit.ComputeOperationSha256()
if err != nil {
return nil, nil, err
}
// Ensure if operation has both hash and query, that the hash matches the query
if operationKit.parsedOperation.GraphQLRequestExtensions.PersistedQuery.HasHash() && operationKit.parsedOperation.Request.Query != "" {
if operationKit.parsedOperation.Sha256Hash != operationKit.parsedOperation.GraphQLRequestExtensions.PersistedQuery.Sha256Hash {
return nil, nil, errors.New("persistedQuery sha256 hash does not match query body")
}
}
if h.operationBlocker.safelistEnabled || h.operationBlocker.logUnknownOperationsEnabled {
// Set the request hash to the parsed hash, to see if it matches a persisted operation
operationKit.parsedOperation.GraphQLRequestExtensions.PersistedQuery = &GraphQLRequestExtensionsPersistedQuery{
Sha256Hash: operationKit.parsedOperation.Sha256Hash,
}
}
}
if operationKit.parsedOperation.IsPersistedOperation || h.operationBlocker.safelistEnabled || h.operationBlocker.logUnknownOperationsEnabled {
skipParse, isApq, err = operationKit.FetchPersistedOperation(h.ctx, h.clientInfo)
if err != nil {
var poNotFoundErr *persistedoperation.PersistentOperationNotFoundError
if h.operationBlocker.logUnknownOperationsEnabled && errors.As(err, &poNotFoundErr) {
h.logger.Warn("Unknown persisted operation found", zap.String("query", operationKit.parsedOperation.Request.Query), zap.String("sha256Hash", poNotFoundErr.Sha256Hash))
if h.operationBlocker.safelistEnabled {
return nil, nil, err
}
} else {
return nil, nil, err
}
}
}
// If the persistent operation is already in the cache, we skip the parse step
// because the operation was already parsed. This is a performance optimization, and we
// can do it because we know that the persisted operation is immutable (identified by the hash)
if !skipParse {
startParsing := time.Now()
if err := operationKit.Parse(); err != nil {
opContext.parsingTime = time.Since(startParsing)