Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions cli/linter/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -1828,6 +1828,10 @@
"type": ["boolean", "null"],
"additionalProperties": false
},
"allow_unsafe_websocket_origin": {
"type": ["boolean", "null"],
"additionalProperties": false
},
"error_overrides": {
"$ref": "#/definitions/ErrorOverrides"
}
Expand Down
6 changes: 6 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -1519,6 +1519,12 @@ type Config struct {
// A token with no iss claim is matched by key ID (kid) alone.
// It exists for compatibility with legacy records that predate issuer becoming mandatory. Not recommended for production use: without the issuer check, an identity provider that shares signing keys across tenants cannot be distinguished by tenant.
AllowUnsafeIDPMissingIssuer bool `json:"allow_unsafe_idp_missing_issuer"`

// AllowUnsafeWebSocketOrigin turns off the Origin check on WebSocket handshakes for GraphQL and Streams APIs, so a handshake from any origin is accepted (default: false).
// It exists for compatibility with browser clients on other origins that connected before the check was added.
// Not recommended: any website can then open a WebSocket to these APIs through a visitor's browser and read the responses.
// To allow a browser client, add its origin to the API's CORS allowed origins instead.
AllowUnsafeWebSocketOrigin bool `json:"allow_unsafe_websocket_origin"`
}

// LabsConfig include config for streaming
Expand Down
7 changes: 7 additions & 0 deletions ee/middleware/streams/model.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package streams

import (
"net/http"
"sync/atomic"
"time"

Expand Down Expand Up @@ -33,6 +34,12 @@ type APISpec struct {
OAS oas.OAS

StripListenPath model.StripListenPathFunc

// WebSocketOriginAllowed reports whether a WebSocket handshake may
// proceed. Bento's http_server output accepts every origin unless its own
// cors setting is on, so the Gateway checks the origin first. When nil,
// handshakes are refused.
WebSocketOriginAllowed func(*http.Request) bool
}

// NewAPISpec creates a new APISpec object based on the required inputs.
Expand Down
17 changes: 17 additions & 0 deletions ee/middleware/streams/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"net/http"

"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
)

Expand All @@ -25,6 +26,11 @@ func (h *HandleFuncAdapter) HandleFunc(path string, f func(http.ResponseWriter,

h.StreamManager.routeLock.Lock()
h.Muxer.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
if websocket.IsWebSocketUpgrade(r) && !h.webSocketOriginAllowed(r) {
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}

recorder := h.StreamManager.analyticsFactory.CreateRecorder(r)
analyticsResponseWriter := h.StreamManager.analyticsFactory.CreateResponseWriter(w, r, h.StreamID, recorder)

Expand All @@ -36,6 +42,17 @@ func (h *HandleFuncAdapter) HandleFunc(path string, f func(http.ResponseWriter,
h.Logger.Debugf("Registered handler for path: %s", path)
}

// webSocketOriginAllowed runs the Gateway's origin check before Bento handles
// a WebSocket handshake. Bento's own cors check, when set, still runs after it,
// so an origin must pass both.
func (h *HandleFuncAdapter) webSocketOriginAllowed(r *http.Request) bool {
spec := h.StreamMiddleware.Spec
if spec == nil || spec.WebSocketOriginAllowed == nil {
return false
}
return spec.WebSocketOriginAllowed(r)
}

// Helper function to extract paths from an http_server configuration
func extractPaths(httpConfig map[string]interface{}) []string {
var paths []string
Expand Down
6 changes: 6 additions & 0 deletions gateway/model_apispec.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,12 @@ type APISpec struct {
mcpTrustedOrigins map[string]struct{}
mcpTrustedProxyPrefixes []netip.Prefix
mcpOriginConfigErr error

// WebSocket origin checking is immutable for a loaded spec. Build the
// checker once, off the request path.
webSocketOriginOnce sync.Once
webSocketOrigin *httputil.WebSocketOriginChecker
webSocketOriginErr error
}

// MCPAdapterRuntime groups runtime-only state for a synthetic REST-as-MCP
Expand Down
1 change: 1 addition & 0 deletions gateway/mw_streaming_ee.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
func getStreamingMiddleware(baseMid *BaseMiddleware) TykMiddleware {
spec := baseMid.Spec
streamSpec := streams.NewAPISpec(spec.APIID, spec.Name, spec.IsOAS, spec.OAS, spec.StripListenPath)
streamSpec.WebSocketOriginAllowed = spec.webSocketOriginAllowed

streamAnalyticsFactory := NewStreamAnalyticsFactory(baseMid.logger.Dup(), baseMid.Gw, spec)
streamMw := streams.NewMiddleware(baseMid.Gw, baseMid, streamSpec, streamAnalyticsFactory)
Expand Down
37 changes: 24 additions & 13 deletions gateway/reverse_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -439,13 +439,10 @@
TykAPISpec: spec,
FlushInterval: time.Duration(spec.GlobalConfig.HttpServerOptions.FlushInterval) * time.Millisecond,
logger: logger,
wsUpgrader: websocket.Upgrader{
// CheckOrigin is not needed for the upgrader as tyk already provides
// its own middlewares for that.
CheckOrigin: func(r *http.Request) bool {
return true
},
},
// CheckOrigin is set for each handshake in handleGraphQL, because it
// must check the inbound request, not the request rewritten for the
// upstream.
wsUpgrader: websocket.Upgrader{},
sp: sync.Pool{
New: func() interface{} {
buffer := make([]byte, 32*1024)
Expand Down Expand Up @@ -1264,7 +1261,7 @@

func (p *ReverseProxy) handleOutboundRequest(
roundTripper http.RoundTripper,
outreq *http.Request,
inreq, outreq *http.Request,
w http.ResponseWriter,
) (res *http.Response, hijacked bool, latency time.Duration, err error) {

Expand All @@ -1274,7 +1271,7 @@
}()

if p.TykAPISpec.GraphQL.Enabled {
res, hijacked, err = p.handleGraphQL(roundTripper, outreq, w)
res, hijacked, err = p.handleGraphQL(roundTripper, inreq, outreq, w)
return
}

Expand All @@ -1286,7 +1283,9 @@
return r.Method == http.MethodOptions
}

func (p *ReverseProxy) handleGraphQL(roundTripper http.RoundTripper, outreq *http.Request, w http.ResponseWriter) (res *http.Response, hijacked bool, err error) {
// handleGraphQL serves a GraphQL request. inreq is the request as the Gateway
// received it, and outreq is the same request rewritten for the upstream.
func (p *ReverseProxy) handleGraphQL(roundTripper http.RoundTripper, inreq, outreq *http.Request, w http.ResponseWriter) (res *http.Response, hijacked bool, err error) {
isWebSocketUpgrade := ctxGetGraphQLIsWebSocketUpgrade(outreq)
needsEngine := needsGraphQLExecutionEngine(p.TykAPISpec)

Expand All @@ -1306,11 +1305,23 @@
// Use the canonical format of the MIME header key.
requestHeadersRewrite[textproto.CanonicalMIMEHeaderKey(key)] = value
}
wsUpgrader := &p.wsUpgrader
if isWebSocketUpgrade {
// Browsers don't apply CORS to WebSocket handshakes, so Tyk's CORS
// middleware doesn't protect them. Check the inbound request's Origin:
// the outbound request carries the upstream's Host.
upgrader := p.wsUpgrader
upgrader.CheckOrigin = func(*http.Request) bool {
return p.TykAPISpec.webSocketOriginAllowed(inreq)
}
wsUpgrader = &upgrader
}

res, hijacked, err = p.TykAPISpec.GraphEngine.HandleReverseProxy(graphengine.ReverseProxyParams{
RoundTripper: roundTripper,

Check warning on line 1321 in gateway/reverse_proxy.go

View check run for this annotation

probelabs / Visor: performance

performance Issue

A new `websocket.Upgrader` struct is created by-copy and a new closure for `CheckOrigin` is allocated for every GraphQL WebSocket handshake request. This introduces a small, per-handshake allocation overhead.
Raw output
To avoid these per-request allocations, consider alternative approaches. One option is to pass the inbound request (`inreq`) via the context of the outbound request (`outreq`). A single, pre-defined `CheckOrigin` function on the `ReverseProxy` could then be used for all handshakes, retrieving `inreq` from the request context. This would eliminate the struct copy and closure allocation on the connection setup path.
ResponseWriter: w,
OutRequest: outreq,
WebSocketUpgrader: &p.wsUpgrader,
WebSocketUpgrader: wsUpgrader,
NeedsEngine: needsEngine,
IsCORSPreflight: isCORSPreflight(outreq),
IsWebSocketUpgrade: isWebSocketUpgrade,
Expand Down Expand Up @@ -1547,14 +1558,14 @@
}
p.logger.Debug("ON REQUEST: Circuit Breaker is in CLOSED or HALF-OPEN state")

res, isHijacked, upstreamLatency, err = p.handleOutboundRequest(decoratedRoundTripper, outreq, rw)
res, isHijacked, upstreamLatency, err = p.handleOutboundRequest(decoratedRoundTripper, req, outreq, rw)
if err != nil || res.StatusCode/100 == 5 {
breakerConf.CB.Fail()
} else {
breakerConf.CB.Success()
}
} else {
res, isHijacked, upstreamLatency, err = p.handleOutboundRequest(decoratedRoundTripper, outreq, rw)
res, isHijacked, upstreamLatency, err = p.handleOutboundRequest(decoratedRoundTripper, req, outreq, rw)
}

if err != nil {
Expand Down
5 changes: 5 additions & 0 deletions gateway/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -1200,7 +1200,7 @@
}

// Create the response processor chain
func (gw *Gateway) createResponseMiddlewareChain(

Check failure on line 1203 in gateway/server.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 23 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=TykTechnologies_tyk&issues=AaITTDNiek19WPACVIdh&open=AaITTDNiek19WPACVIdh&pullRequest=8986
spec *APISpec,
middlewares []apidef.MiddlewareDefinition,
log *logrus.Entry,
Expand Down Expand Up @@ -2100,6 +2100,11 @@
"Risk: API definitions can read arbitrary files from the gateway filesystem.")
}

if conf.AllowUnsafeWebSocketOrigin {
mainLog.Warn("allow_unsafe_websocket_origin is enabled: WebSocket handshakes for GraphQL and Streams APIs are accepted from any origin. " +
"Risk: any website can open a WebSocket to these APIs through a visitor's browser and read the responses.")
}

if conf.HealthCheckEndpointName == "" {
conf.HealthCheckEndpointName = "hello"
}
Expand Down
49 changes: 49 additions & 0 deletions gateway/websocket_origin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package gateway

import (
"net/http"

"github.com/sirupsen/logrus"

internalhttputil "github.com/TykTechnologies/tyk/internal/httputil"
)

// webSocketOriginAllowed reports whether a WebSocket handshake to the API may
// proceed, and logs each refusal. Browsers don't apply CORS to WebSocket
// handshakes, so the Origin header is the only protection against another
// website reading the API through a visitor's browser.
func (spec *APISpec) webSocketOriginAllowed(r *http.Request) bool {
// A checker error means the API's origin settings can't be parsed, so
// refuse every handshake rather than guess. Startup already rejects invalid
// trusted_proxy_cidrs, so this isn't expected in practice.
checker, err := spec.webSocketOriginChecker()
if err == nil && checker.Allowed(r) {
return true
}

entry := log.WithFields(logrus.Fields{
"prefix": "websocket",
"api_id": spec.APIID,
"origin": r.Header.Get("Origin"),
})
if err != nil {
entry = entry.WithError(err)
}
entry.Warn("WebSocket handshake refused: origin is not the Gateway's own origin and not in the API's CORS allowed origins")
return false
}

// webSocketOriginChecker builds the API's checker once. A loaded spec's CORS
// and Gateway settings don't change, so the result is reused for every
// handshake.
func (spec *APISpec) webSocketOriginChecker() (*internalhttputil.WebSocketOriginChecker, error) {
spec.webSocketOriginOnce.Do(func() {
spec.webSocketOrigin, spec.webSocketOriginErr = internalhttputil.NewWebSocketOriginChecker(internalhttputil.WebSocketOriginOptions{
AllowAnyOrigin: spec.GlobalConfig.AllowUnsafeWebSocketOrigin,
CORSEnabled: spec.CORS.Enable,
AllowedOrigins: spec.CORS.AllowedOrigins,
TrustedProxyCIDRs: spec.GlobalConfig.HttpServerOptions.TrustedProxyCIDRs,
})
})
return spec.webSocketOrigin, spec.webSocketOriginErr
}
Loading
Loading