Skip to content

[TT-19132] Check the Origin of GraphQL and Streams WebSocket handshakes - #8986

Merged
kofoworola merged 6 commits into
masterfrom
TT-19132-websocket-origin-check
Nov 26, 2026
Merged

kofoworola merged 6 commits into
masterfrom
TT-19132-websocket-origin-check

Conversation

@kofoworola

@kofoworola kofoworola commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Description

The Gateway now checks the Origin header of WebSocket handshakes for GraphQL APIs and Streams ws_path endpoints. Browsers don't apply CORS to WebSocket handshakes, so the API's CORS settings didn't protect these endpoints before.

A handshake is accepted when one of these is true:

  • It has no Origin header. Server-to-server and CLI clients keep working.
  • The origin is the Gateway's own origin. This uses Host, or the forwarded headers when the request comes from a proxy in http_server_options.trusted_proxy_cidrs.
  • The API has CORS on and its allowed_origins allows the origin. Wildcards count, and an empty list allows every origin, as for HTTP CORS.

Any other origin gets 403 Forbidden, and the Gateway logs the refusal with the API ID and the origin.

For a Streams output with Bento's own cors configured, an origin must pass both the Gateway's check and Bento's.

A new Gateway option, allow_unsafe_websocket_origin (TYK_GW_ALLOWUNSAFEWEBSOCKETORIGIN), is false by default. When it's true, the check is off and handshakes are accepted from any origin, as before. The Gateway logs a warning at startup when it's on.

Commits, one per task:

  1. internal/httputil/websocket_origin.go: a shared check. It reuses CanonicalOrigin, ExternalOriginWithTrustedProxies and the rs/cors origin matching that Tyk's CORS middleware already uses.
  2. config/config.go, gateway/server.go, cli/linter/schema.json: the new option and its startup warning.
  3. gateway/reverse_proxy.go, gateway/websocket_origin.go: the GraphQL upgrader checks the inbound request. The request the graph engine receives already carries the upstream's Host, so it can't be used for the "own origin" comparison.
  4. ee/middleware/streams/util.go: HandleFuncAdapter runs the check before Bento handles a WebSocket handshake. Bento isn't forked.

Related Issue

TT-19132

Motivation and Context

Both WebSocket upgraders accepted every origin. The acceptance criteria and the decisions behind this behaviour are on the ticket.

Behaviour change. A browser client on another origin that connects today without CORS configured is refused after this change. That includes GraphQL subscriptions in the Dashboard's API playground: queries and mutations there go through the Dashboard backend and aren't affected, but subscriptions open a WebSocket from the browser on the Dashboard's origin. To allow such a client, add its origin to the API's CORS allowed origins. allow_unsafe_websocket_origin restores the old behaviour for the whole Gateway, and isn't recommended.

How This Has Been Tested

Criterion Test
1. Streams: an origin the API doesn't allow is refused with 403 TestStreamsWebSocket_OriginCheck
2. GraphQL: an origin the API doesn't allow is refused with 403 TestGraphQLWebSocket_OriginCheck
3. Own origin and CORS-allowed origins connect, and Streams delivers messages Both tests above, plus TestWebSocketOriginChecker
4. No Origin connects Both integration tests
5. With Bento cors on, both checks must pass TestStreamsWebSocket_OriginCheck
6. allow_unsafe_websocket_origin is off by default; when on, any origin connects TestAfterConfSetup_WarnsWhenWebSocketOriginCheckIsOff and both integration tests
7. Startup warning when the option is on TestAfterConfSetup_WarnsWhenWebSocketOriginCheckIsOff
8. Each refusal is logged with the API ID and origin Both integration tests
9. Documentation Not in this PR

TestWebSocketOriginChecker covers no origin, own origin (plain and TLS), scheme mismatch, case, null, malformed and repeated Origin headers, a non-ASCII origin, exact CORS origins, CORS turned off, *, an empty list, subdomain patterns and a lookalike domain, a trusted proxy, and forwarded headers from an untrusted client.

Before the fix, the GraphQL and Streams refusal cases returned 101. The Streams "Bento allows, Gateway doesn't" case also connected.

Run locally on Go 1.26.5 against master at e66db61f4:

  • go test ./internal/httputil/
  • go test ./gateway/ -run 'TestGraphQLWebSocket_OriginCheck|TestAfterConfSetup_WarnsWhenWebSocketOriginCheckIsOff'
  • go test -tags dev ./gateway/ -run TestStreamsWebSocket_OriginCheck
  • go test -tags dev ./ee/...
  • The Streams, GraphQL, CORS and reverse-proxy Gateway tests.

Not covered yet: manual QA in a browser and in the Dashboard playground; GraphQL UDG, supergraph and tyk:// looped APIs (the tests use proxy-only v2, which goes through the same code path); and CORS set through OAS on a Dashboard-created Streams API.

Screenshots (if appropriate)

None: there's no UI change.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Refactoring or add test (improvements in base code or adds test coverage to functionality)

Checklist

  • I ensured that the documentation is up to date
  • I explained why this PR updates go.mod in detail with reasoning why it's required
  • I would like a code coverage CI quality gate exception and have explained why

go.mod isn't changed. The documentation (criterion 9) will follow separately.

Ticket Details

TT-19132
Status In Code Review
Summary [Security] Gateway: Streams and GraphQL WebSocket endpoints accept connections from any Origin

Generated at: 2026-11-26 14:28:29

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

📚 Documentation preview

This PR changes generated documentation (component: gateway).

cc @TykTechnologies/pms — advisory review requested; this does not block merging.

Rendered docs diff
diff -ruN out-base/gateway-config.mdx out-head/gateway-config.mdx
--- out-base/gateway-config.mdx	2026-11-26 14:29:23.953015403 +0000
+++ out-head/gateway-config.mdx	2026-11-26 14:29:25.875712017 +0000
@@ -3157,3 +3157,12 @@
 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.
 
+### allow_unsafe_websocket_origin
+ENV: <b>TYK_GW_ALLOWUNSAFEWEBSOCKETORIGIN</b><br />
+Type: `bool`<br />
+
+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.
+

@probelabs

probelabs Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

This PR introduces a security enhancement by adding an Origin header check for WebSocket handshakes in GraphQL and Streams APIs. This mitigates the risk of Cross-Site WebSocket Hijacking, as browsers do not enforce CORS on WebSocket requests.

A handshake is accepted when:

  • It has no Origin header (allowing server-to-server communication).
  • The origin matches the Gateway's own origin.
  • The origin is permitted by the API's existing CORS allowed_origins configuration.

Handshakes from non-compliant origins are rejected with a 403 Forbidden status, and the event is logged. A new global configuration flag, allow_unsafe_websocket_origin, is introduced for backward compatibility to disable this check. When enabled, it logs a warning at startup.

Files Changed Analysis

The changes are well-structured across 13 files, with 680 additions and 13 deletions. The core validation logic is encapsulated in a new file, internal/httputil/websocket_origin.go, and integrated into the gateway via gateway/websocket_origin.go. A significant portion of the changes consists of new tests (..._test.go files), indicating thorough validation. Configuration changes in config/config.go and cli/linter/schema.json introduce the new global flag. The core application points are modified in gateway/reverse_proxy.go for GraphQL and ee/middleware/streams/util.go for Streams to invoke the new check.

Architecture & Impact Assessment

  • What this PR accomplishes:

    • It closes a security vulnerability by validating the Origin of WebSocket handshakes for GraphQL and Streams endpoints.
    • It provides a centralized and reusable origin-checking mechanism that leverages existing CORS configurations.
    • It introduces the allow_unsafe_websocket_origin configuration flag for backward compatibility.
  • Key technical changes introduced:

    • A new WebSocketOriginChecker is implemented in internal/httputil/websocket_origin.go.
    • The GraphQL reverse proxy (gateway/reverse_proxy.go) and the Streams middleware (ee/middleware/streams/util.go) are updated to use this new checker during the WebSocket upgrade process.
  • Affected system components:

    • GraphQL Subscriptions: Any client using WebSocket-based subscriptions will be subject to this new origin check.
    • Streams: Clients connecting to ws_path endpoints will also be validated.
    • Gateway Configuration: A new global option allow_unsafe_websocket_origin is added.
    • This is a breaking change for browser-based clients connecting from an origin not listed in the API's CORS policy.
  • Visualization:

    sequenceDiagram
        participant Client as Browser Client
        participant Gateway
        participant Upstream as GraphQL/Streams
    
        Client->>Gateway: WebSocket Upgrade Request (Origin: https://app.example.com)
        alt GraphQL or Streams API
            Gateway->>Gateway: APISpec.webSocketOriginAllowed(request)
            Note over Gateway: 1. Check if Origin matches self<br/>2. Check if Origin in API's CORS list
            alt Origin is NOT allowed
                Gateway-->>Client: 403 Forbidden
            else Origin is allowed
                Gateway->>Upstream: Forward request
                Upstream-->>Client: 101 Switching Protocols
            end
        end
    
    Loading

Scope Discovery & Context Expansion

This change introduces a potential breaking change for existing browser-based clients that rely on WebSocket connections for GraphQL subscriptions or Streams from a different origin than the Gateway. For instance, API playgrounds (including the Tyk Dashboard's) or single-page applications will now require their origin to be explicitly added to the API's CORS allowed_origins list to maintain functionality. The impact is confined to WebSocket endpoints, leaving standard HTTP requests unaffected. The implementation correctly reuses the existing CORS configuration, which is a good design choice that avoids introducing a separate configuration for WebSockets.

Metadata
  • Review Effort: 3 / 5
  • Primary Label: bug

Powered by Visor from Probelabs

Last updated: 2026-11-26T14:30:27.055Z | Triggered by: pr_updated | Commit: 4ec312e

💡 TIP: You can chat with Visor using /visor ask <your question>

@probelabs

probelabs Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

✅ Security Check Passed

No security issues found – changes LGTM.

✅ Architecture Check Passed

No architecture issues found – changes LGTM.

✅ Security Check Passed

No security issues found – changes LGTM.

\n\n

✅ Architecture Check Passed

No architecture issues found – changes LGTM.

\n\n \n\n

✅ Quality Check Passed

No quality issues found – changes LGTM.


Powered by Visor from Probelabs

Last updated: 2026-11-26T14:30:21.117Z | Triggered by: pr_updated | Commit: 4ec312e

💡 TIP: You can chat with Visor using /visor ask <your question>

@kofoworola
kofoworola marked this pull request as ready for review November 25, 2026 14:11
@kofoworola

Copy link
Copy Markdown
Contributor Author

CI: the remaining failures are not caused by this pull request

drift / drift-check (1 job) fails at head 5b421ec. The job log is here. The check reports:

##[error]Files in this PR differ from what gromit generates for tyk/master. These files are managed by gromit; make this change in gromit's templates instead (https://github.com/TykTechnologies/gromit).

The difference is in action pins in gromit-managed workflow files, for example:

-        uses: aws-actions/amazon-ecr-login@f2e9fc6c2b355c1890b65e6f6f0e2ac3e6e22f78 # v2
+        uses: aws-actions/amazon-ecr-login@7290e214a610b32bc0eef81748948b6d466a8783 # v2.2.0

Why this pull request isn't the cause:

  • This pull request changes no .github or other gromit-managed files: git diff --name-only origin/master...HEAD lists only Go sources, tests and cli/linter/schema.json.
  • master's generated files lag gromit's current templates. Another master-based pull request failed the same check on the same amazon-ecr-login pins at 13:20 UTC: run 45622489854.
  • The gromit sync for master, [TT-18378 master] gromit: sync templates #8977 ("[TT-19416 master] gromit: sync templates"), is open and waiting for review. After it merges, merging master into this branch should clear the check.

What I didn't check: I compared only against recent runs of the Drift Check workflow, not every open pull request. I also didn't compare #8977's generated files line by line with this diff.

The two aggregate checks that show red ("Unit Tests & Linting" and "Aggregated CI Status") are from the run made while this pull request was a draft. In that run the test job was skipped (if: ${{ !github.event.pull_request.draft }}), and the aggregate counts a skipped job as failed. A new run started when the pull request was marked ready.

@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

API Changes

--- prev.txt	2026-11-26 14:29:44.972367192 +0000
+++ current.txt	2026-11-26 14:29:39.114304692 +0000
@@ -8304,6 +8304,12 @@
 	// 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"`
 }
     Config is the configuration object used by Tyk to set up various parameters.
 
@@ -10590,6 +10596,12 @@
 	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
 }
     APISpec is a subset of gateway.APISpec for the values the middleware
     consumes.

@kofoworola
kofoworola enabled auto-merge (squash) November 26, 2026 12:14
Adds WebSocketOriginChecker to internal/httputil. It accepts a handshake with
no Origin, the Gateway's own origin (using the existing trusted-proxy rules),
or an origin the API's CORS settings allow, including wildcards. Nothing uses
it yet, so Gateway behaviour is unchanged.

Code: internal/httputil/websocket_origin.go

Criteria (shared check only; endpoints are wired in later commits):
- 3 own origin and CORS allowed origins accepted: TestWebSocketOriginChecker
- 4 no Origin accepted: TestWebSocketOriginChecker
- trusted proxy, wildcard and subdomain pattern cases: TestWebSocketOriginChecker
Adds allow_unsafe_websocket_origin (TYK_GW_ALLOWUNSAFEWEBSOCKETORIGIN), false
by default, and logs a startup warning when it is on. Nothing reads it yet, so
Gateway behaviour is unchanged apart from the warning.

Code: config/config.go, gateway/server.go (afterConfSetup), cli/linter/schema.json

Criteria:
- 6 (default only) option is false by default: TestAfterConfSetup_WarnsWhenWebSocketOriginCheckIsOff
- 7 startup warning when on: TestAfterConfSetup_WarnsWhenWebSocketOriginCheckIsOff
The GraphQL upgrader accepted every origin, and Tyk's CORS middleware does not
protect WebSocket handshakes. It now refuses, with 403, a handshake whose
Origin is neither the Gateway's own origin nor allowed by the API's CORS
settings, and logs the refusal with the API ID and origin. Handshakes with no
Origin, and every handshake when allow_unsafe_websocket_origin is on, are
accepted as before. The check uses the inbound request, because the request
the engine receives already carries the upstream's Host.

Code: gateway/websocket_origin.go, gateway/reverse_proxy.go (handleGraphQL),
gateway/model_apispec.go

Criteria:
- 2 other origin refused with 403: TestGraphQLWebSocket_OriginCheck
- 3 own origin and CORS allowed origin connect (GraphQL): TestGraphQLWebSocket_OriginCheck
- 4 no Origin connects (GraphQL): TestGraphQLWebSocket_OriginCheck
- 6 option on accepts any origin (GraphQL): TestGraphQLWebSocket_OriginCheck
- 8 refusal logged with API ID and origin (GraphQL): TestGraphQLWebSocket_OriginCheck
Bento's http_server output accepts every origin unless its own cors setting is
on. HandleFuncAdapter now runs the Gateway's origin check before Bento handles
a WebSocket handshake, and refuses with 403 an origin that is neither the
Gateway's own nor allowed by the API's CORS settings. When Bento's cors is on,
it still runs afterwards, so an origin must pass both. Non-WebSocket Streams
requests are unchanged.

Code: ee/middleware/streams/util.go (HandleFuncAdapter.HandleFunc),
ee/middleware/streams/model.go, gateway/mw_streaming_ee.go

Criteria:
- 1 other origin refused with 403, no message: TestStreamsWebSocket_OriginCheck
- 3 own origin connects and receives messages, CORS allowed origin connects: TestStreamsWebSocket_OriginCheck
- 4 no Origin connects (Streams): TestStreamsWebSocket_OriginCheck
- 5 Bento cors: both checks must pass: TestStreamsWebSocket_OriginCheck
- 6 option on accepts any origin (Streams): TestStreamsWebSocket_OriginCheck
- 8 refusal logged with API ID and origin (Streams): TestStreamsWebSocket_OriginCheck
Moves the graphql-go-tools import into its own group, as the repository's gci
formatter requires. Test-only change; behaviour is unchanged.

This push also starts the plugin-compiler image build, which was skipped while
the pull request was a draft and is not re-triggered by marking it ready, so
the release tests could not find the image for the merge commit.

Code: gateway/websocket_origin_test.go
Declares inreq and outreq together, as SonarCloud rule go:S8209 asks for
consecutive parameters of the same type. Behaviour is unchanged.

Code: gateway/reverse_proxy.go (handleOutboundRequest)
@kofoworola
kofoworola force-pushed the TT-19132-websocket-origin-check branch from f00e07d to 4ec312e Compare November 26, 2026 14:28
@sentinelone-cnapp-eu1

Copy link
Copy Markdown

SentinelOne CNS Hardcoded Secret Detector
✅ Congratulations, your code is safe

SentinelOne CNS is a cloud-agnostic, agentless CSPM & CWPP solution that continuously detects and prevents vulnerabilities that have the highest probability of being exploited in Azure, AWS, Google Cloud, and Kubernetes.

@github-actions

Copy link
Copy Markdown
Contributor

🎯 Recommended Merge Targets

Based on JIRA ticket TT-19132: [Security] Gateway: Streams and GraphQL WebSocket endpoints accept connections from any Origin

Fix Version: Tyk 5.13.9

Required:

  • release-5.13 - Minor version branch for 5.13.x patches - required for creating Tyk 5.13.9
  • master - Main development branch - ensures fix is in all future releases

Fix Version: Tyk 5.17.0

⚠️ Warning: Expected release branches not found in repository

Required:

  • master - No matching release branches found. Fix will be included in future releases.

Fix Version: Tyk 5.8.21

Required:

  • release-5.8 - Minor version branch for 5.8.x patches - required for creating Tyk 5.8.21
  • master - Main development branch - ensures fix is in all future releases

📋 Workflow

  1. Merge this PR to master first

  2. Cherry-pick to release branches by commenting on the merged PR:

    • /release to release-5.13
    • /release to release-5.8
  3. Automated backport - The bot will automatically create backport PRs to the specified release branches

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Passed Quality Gate passed

Issues
1 New issue
1 Accepted issue

Measures
0 Security Hotspots
97.4% Coverage on New Code
0.0% Duplication on New Code

See analysis details on SonarQube Cloud

@rafalgolarz rafalgolarz left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good: WebSocket Origin check for GraphQL and Streams handshakes, Jira TT-19132 acceptance criteria covered by tests, Go and API tests green. [head 4ec312e]

@kofoworola
kofoworola merged commit af4e4d3 into master Nov 26, 2026
64 of 65 checks passed
@kofoworola
kofoworola deleted the TT-19132-websocket-origin-check branch November 26, 2026 15:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants