Skip to content
This repository was archived by the owner on Apr 28, 2026. It is now read-only.

Fix WebSocket Connection Hijacking and Add CORS Environment Variable Support - #904

Merged
MAVRICK-1 merged 1 commit into
kubestellar:devfrom
MAVRICK-1:fix/websocket-hijacking-cors-env
May 25, 2025
Merged

MAVRICK-1 merged 1 commit into
kubestellar:devfrom
MAVRICK-1:fix/websocket-hijacking-cors-env

Conversation

@MAVRICK-1

Copy link
Copy Markdown
Contributor

Fix WebSocket Connection Hijacking and Add CORS Environment Variable Support

📋 Summary

This PR fixes the critical WebSocket connection hijacking error and adds configurable CORS origin support through environment variables.

Fixes #903

🔧 Changes Made

1. WebSocket Handler Fix (Critical Bug Fix)

  • File: LogWorkloads handler function
  • Problem: c.JSON() calls after upgrader.Upgrade() caused hijacking errors
  • Solution: Moved all validation logic before WebSocket upgrade
  • Impact: Eliminates "connection has been hijacked" errors

2. Enhanced WebSocket-Aware Middleware

  • File: main.go - ZapMiddleware()
  • Added: WebSocket detection with isWebSocketUpgrade() helper
  • Improvement: Proper logging for WebSocket connections without interference

3. CORS Environment Variable Support

  • File: main.go - CORS middleware
  • Added: CORS_ALLOWED_ORIGIN environment variable support
  • Benefit: Configurable frontend URLs for different environments

🐛 Bug Fixes

  • Fixes #[ISSUE_NUMBER]: WebSocket connection hijacking error
  • Resolves: Status code conflicts (200 vs 400)
  • Eliminates: Console error log flooding

✨ Enhancements

  • Adds: Environment-based CORS configuration
  • Improves: WebSocket connection logging
  • Maintains: Backward compatibility with default values

🔄 Commits

feat: move validation before WebSocket upgrade in LogWorkloads handler

- Reorder parameter extraction and validation logic
- Move all c.JSON() calls before upgrader.Upgrade()
- Prevent "connection has been hijacked" errors
- Maintain proper error responses for invalid inputs

fix: enhance ZapMiddleware with WebSocket detection

- Add isWebSocketUpgrade() helper function
- Detect WebSocket upgrade requests by headers
- Skip response logging for hijacked connections
- Improve WebSocket connection lifecycle logging

feat: add CORS_ALLOWED_ORIGIN environment variable support

- Replace hardcoded localhost:5173 with configurable origin
- Add backward compatibility with default fallback
- Enable deployment flexibility across environments
- Support development and production configurations

docs: update README with CORS environment variable

- Document CORS_ALLOWED_ORIGIN usage
- Add deployment examples for Docker/Kubernetes
- Include development setup instructions

🧪 Testing

WebSocket Testing

# Test successful WebSocket connection
wscat -c ws://localhost:4000/api/volumes/drupal/log?name=drupal

# Test validation errors (should fail gracefully)
curl -X GET http://localhost:4000/api/volumes/invalid/log

# Verify no hijacking errors in logs
tail -f logs/app.log | grep "hijacked"

CORS Testing

# Test default behavior
./kubestellar-ui

# Test custom origin
CORS_ALLOWED_ORIGIN=http://localhost:3000 ./kubestellar-ui

# Test production scenario
CORS_ALLOWED_ORIGIN=https://kubestellar.example.com ./kubestellar-ui

Manual Testing Checklist

  • WebSocket connections establish without errors
  • Invalid parameters return proper HTTP error codes
  • WebSocket messages stream correctly
  • Frontend works with default CORS settings
  • Frontend works with custom CORS origin
  • No hijacking errors in server logs
  • Middleware logs WebSocket attempts properly

📊 Before vs After

Before (Broken)

Error #01: http: connection has been hijacked
[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 200 with 400
http: response.Write on hijacked connection

After (Fixed)

{"level":"info","msg":"WebSocket Upgrade Request","path":"/api/volumes/drupal/log","ip":"::1"}
{"level":"info","msg":"WebSocket Connection Established","upgrade-time":"2ms"}

🔍 Code Changes

Key Changes in LogWorkloads Handler

func LogWorkloads(c *gin.Context) {
+   // Extract and validate parameters BEFORE WebSocket upgrade
+   resourceKind := c.Param("resourceKind")
+   namespace := c.Param("namespace")
+   name := c.Query("name")
+
+   if namespace == "" {
+       c.JSON(http.StatusBadRequest, gin.H{"error": "no namespace provided"})
+       return
+   }

    // WebSocket connection upgrade
    conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
    if err != nil {
        log.Println("WebSocket Upgrade Error:", err)
-       c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    defer conn.Close()

-   if namespace == "" {
-       c.JSON(http.StatusInternalServerError, gin.H{"error": "..."})
-       return
-   }

CORS Middleware Update

// CORS Middleware
router.Use(func(c *gin.Context) {
    origin := c.Request.Header.Get("Origin")

+   corsOrigin := os.Getenv("CORS_ALLOWED_ORIGIN")
+   if corsOrigin == "" {
+       corsOrigin = "http://localhost:5173" // default fallback
+   }

-   if origin == "http://localhost:5173" {
+   if origin == corsOrigin {
        c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
    }

🚀 Deployment Guide

Development

# Use default settings
./kubestellar-ui

# Or customize for different port
CORS_ALLOWED_ORIGIN=http://localhost:3000 ./kubestellar-ui

Docker

services:
  kubestellar-ui:
    environment:
      - CORS_ALLOWED_ORIGIN=https://my-frontend.com

Kubernetes

env:
- name: CORS_ALLOWED_ORIGIN
  value: "https://kubestellar-ui.k8s.example.com"

⚠️ Breaking Changes

None - All changes are backward compatible with default fallback values.

📝 Additional Notes

WebSocket Handler Pattern

This fix establishes the pattern for all future WebSocket handlers:

  1. Extract all parameters
  2. Validate all inputs
  3. Handle all errors with HTTP responses
  4. Only then upgrade to WebSocket
  5. Use only conn.WriteMessage() after upgrade

Environment Variables

  • CORS_ALLOWED_ORIGIN - Sets allowed CORS origin (default: http://localhost:5173)

👥 Reviewers

Please focus review on:

  • WebSocket handler validation logic order
  • Middleware WebSocket detection accuracy
  • CORS environment variable implementation
  • Error handling completeness
  • Backward compatibility

🔗 Related

  • Closes #[ISSUE_NUMBER]
  • Related to WebSocket implementation improvements
  • Part of deployment flexibility enhancements

- Reorder parameter extraction and validation logic
- Move all c.JSON() calls before upgrader.Upgrade()
- Prevent 'connection has been hijacked' errors
- Maintain proper error responses for invalid inputs

Fixes: WebSocket hijacking error when validation fails
Impact: Eliminates console error flooding and status conflicts
@kubestellar-prow kubestellar-prow Bot added the size/M Denotes a PR that changes 30-99 lines, ignoring generated files. label May 25, 2025
@github-actions github-actions Bot added backend Issues or PRs related to the low-level API machinery for KubeStellar other docker labels May 25, 2025

@MAVRICK-1 MAVRICK-1 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

/approve

@kubestellar-prow

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: MAVRICK-1

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@kubestellar-prow kubestellar-prow Bot added the approved Indicates a PR has been approved by an approver from all required OWNERS files. label May 25, 2025
@kubestellar-prow

Copy link
Copy Markdown

@MAVRICK-1: The following tests failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
pull-kubestellar-ui-backend-test 3aeef30 link true /test pull-kubestellar-ui-backend-test
pull-kubestellar-ui-backend-verify 3aeef30 link true /test pull-kubestellar-ui-backend-verify
pull-kubestellar-ui-verify 3aeef30 link true /test pull-kubestellar-ui-verify
pull-kubestellar-ui-build 3aeef30 link true /test pull-kubestellar-ui-build

Full PR test history

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

@MAVRICK-1
MAVRICK-1 merged commit 7320348 into kubestellar:dev May 25, 2025
@github-project-automation github-project-automation Bot moved this from In Progress to Done in KubeStellar UI Project May 25, 2025
MAVRICK-1 added a commit that referenced this pull request May 27, 2025
* changed the labelKey to kubestellar.io/workload (#745)

* sorted list of context (#747)

Signed-off-by: Sayan Banerjee <[email protected]>

* fix the dark mode section Deploy from popular Helm charts in helm tab (#749)

* Add workload label support to namespace creation in DeployManifests (#752)

Signed-off-by: Rishi Mondal <[email protected]>

* Support Vertical Alignment for pods of all objects  and Fix Overlapping Issue in Remote Cluster View (#753)

* fix the overlaping issue in the remote cluster view

* support all objects with vertical algiment with pod

* Remove KubeStellarStatusChecker from routes configuration (#758)

Signed-off-by: Rishi Mondal <[email protected]>

* Added Bulk edit Mode (#754)

* Added Buld edit Mode

* Updated the add and import button logic in BP

* fix: Login (#760)

* Add skeleton loading states for improved user experience (#704)

* Add skeleton loading states for improved user experience

* Add Skeleton loader to all required components

* lint issue

* Remove unnecessary Skeleton

* Remove unnecessary Skeleton

* Update Header.tsx

* Add Summary Tab as Initial View for Node Clicks and Hide Logs Tab for Non-Pod Objects (#761)

* remove/hide logs tab from the objects execpt pod objects

* fix the linting isssue

* previous logs supported for viewing logs (#765)

Signed-off-by: Sayan Banerjee <[email protected]>

* Fix: KubeStellar Installation Status detection (#762)

* Fix: Status, redirect, tabs

* Fix:lint

* Refactor status message handling in CheckKubeStellarStatus function (#769)

* refactor: Improve status message handling in CheckKubeStellarStatus function

* fix: Ensure proper formatting in CheckKubeStellarStatus function

* Fix Dark/Light Mode Styling of Dropdown Components in Remote Cluster Objects, Stage Workloads also for Nodes. (#766)

* fix dark-light mode , of  objects/nodes in the remote cluster view

* fix the drop down dark-light mode in the stage workloads

* fix the bug

* Fix: PreReqs check for docker (#771)

* Create Namespace true by default (#774)

* fixed button yaml and json (#773)

Co-authored-by: Ishaan Soni <[email protected]>

* Update KubeStellar status check for multiple context types (#781)

* Fix: Update KubeStellar status check to support multiple compatible context types and improve messaging

Signed-off-by: Rishi Mondal <[email protected]>

* Refactor: Clean up whitespace in CheckKubeStellarStatus function for improved readability

Signed-off-by: Rishi Mondal <[email protected]>

---------

Signed-off-by: Rishi Mondal <[email protected]>

* Add presubmit and postsubmit jobs for frontend and backend builds in CI (#785)

Signed-off-by: Rishi Mondal <[email protected]>

* updated:utils.go (#748)

* Refactor the WECS Tree-view (#788)

* Refactor the wecs Tree-view

* fix the vertical spread in canvas

* Fix: Bug in the Manage Workloads Tree (#793)

* fix the bug in TMangae workloads Tree

* fix issue

* Skeleton loading for /src/pages/BP.tsx (#782)

* BP Loader

* Edit BP.tsx

* Fix: add the edit pencil icon (for edit labels) into the its manual section (#783)

* Update package.json

* Update ClustersTable.tsx

* Update package.json

* Update ClustersTable.tsx

* Update ClustersTable.tsx

* Update ClustersTable.tsx

* Added CODE_OF_CONDUCT.md - mirror of our Kubestellar repo (#802)

* bug: Removed all the ascii and also collapse the managed fields (#776)

* Update useBPQueries.ts

* Update package.json

* Update package-lock.json

* Update useBPQueries.ts

* Fix: Add dark themed status filter in dark theme (#790)

* Update package.json

* Update ClustersTable.tsx

* Update package.json

* Feat: Full Screen in WDS, WECS and Improvements (#799)

* [DOCS] Update Readme and Conributing .md (#798)

* fixed

* fixed

* fixed

* fixed

* Update CONTRIBUTING.md

---------

Co-authored-by: naman9271 <[email protected]>
Co-authored-by: Rahul Vishwakarma <[email protected]>

* updated the logo and added info of Kubestellar (#814)

* Toast-Enhencements (#812)

* filter object for log tab, and increase node spacing (#827)

* filter the object for log tabs

* increase the gap in the nodes/obj

* Improved-colors & 3D (#824)

* Prettier integrated successfully (#825)

* prettier integrated successfully

* prettier errors have fixed

* added gha workflow

---------

Co-authored-by: naman9271 <[email protected]>

* Implement managed cluster APIs and enhance onboarding routes (#830)

* feat: implement managed cluster APIs and enhance onboarding routes

- Added new API endpoints for managing clusters (list, retrieve details).

- Introduced ManagedClusterInfo and ManagedClusterStatus structs.

- Implemented parsing logic for unstructured Kubernetes resources.

- Enhanced onboarding routes with detachment support and logging.

- Updated cluster model with onboarding event info and status constants.

- Refactored WebSocket upgrade variable for naming consistency.

Signed-off-by: Rishi Mondal <[email protected]>

* chore: standardize YAML and JSON formatting, update dependencies, and improve example files

* chore: update pre-commit hook to exclude Docker files from Prettier formatting and standardize quotes in docker-compose.yml

---------

Signed-off-by: Rishi Mondal <[email protected]>

* Update OWNERS (#831)

* [FIX] All Lint Warnings (Currently 9) (#829)

* fixed

* prettier

* prettier

---------

Co-authored-by: naman9271 <[email protected]>

* Integrated the new its api into bidning policy cluster labels. (#833)

* Updated the new api for its in binding policy

* Fixed formatting

* fix: added condition for both kind and k3d kubeflex and updated Dockerfile (#835)

* fixed (#801)

Co-authored-by: naman9271 <[email protected]>

* fix: Enhance Pod Context Menu with Exec Pod Option (#838)

* Update WecsTopology.tsx

* update

* Update OWNERS (#844)

* Fixes Dropdown functionality in remote-cluster-page (#817)

* Update WecsTopology.tsx

* Update WecsTopology.tsx

* update topology

* fix: mitigate code injection risk by bumping js-yaml to 4.1.0 (#834)

* Update package-lock.json

* Update package.json

* package

* Integrated and Re-Structured the Remote Clusters (#848)

* Integrated and Re-Structured the Remote Clusters

* Fixed

* Fixed

* Updated the logic of no clusters in BP

* Refactor EmptyState description and improve readability in BP component

---------

Co-authored-by: Rishi Mondal <[email protected]>

* fix: add vendor folder to .prettierignore (#850)

* Updated the ITS api in BP (#854)

* Updated the ITS api in BP

* Updated the ITS api in BP

* Updated cluster context in clusters table (#856)

* backup plugin (#794)

* fixes active inactive issue for BP backend

Signed-off-by: ashish111333 <[email protected]>

* backup plugin for KS first commit

Signed-off-by: ashish111333 <[email protected]>

* fix for routes not send to gin

Signed-off-by: ashish111333 <[email protected]>

* minor update

Signed-off-by: ashish111333 <[email protected]>

* added lock to manager struct

Signed-off-by: ashish111333 <[email protected]>

* comment fix

Signed-off-by: ashish111333 <[email protected]>

* small change

Signed-off-by: ashish111333 <[email protected]>

* small updates

Signed-off-by: ashish111333 <[email protected]>

* addded etcd client

Signed-off-by: ashish111333 <[email protected]>

* comment fix

Signed-off-by: ashish111333 <[email protected]>

* expose etcd pod

Signed-off-by: ashish111333 <[email protected]>

* small update

Signed-off-by: ashish111333 <[email protected]>

* use etcdtl instead of go client

Signed-off-by: ashish111333 <[email protected]>

* small changes

Signed-off-by: ashish111333 <[email protected]>

* added makePV and createJob

Signed-off-by: ashish111333 <[email protected]>

* small fix

Signed-off-by: ashish111333 <[email protected]>

* use pvc instead of pv

Signed-off-by: ashish111333 <[email protected]>

* small changes

Signed-off-by: ashish111333 <[email protected]>

* update contributing.md

Signed-off-by: ashish111333 <[email protected]>

* updated error handling and fixed case for k3d

Signed-off-by: ashish111333 <[email protected]>

* use pg_dumpall to get all databaseses

Signed-off-by: ashish111333 <[email protected]>

---------

Signed-off-by: ashish111333 <[email protected]>

* fixed workload details panel (#867)

* fixed

* Fix code formatting issues in TreeViewComponent

* feat: complete modern UX dashboard with command palette, cluster stats, and activity log (#870)

* Updated the Closure of Create Bp dialog (#873)

* Updated the Closure of Create Bp dialog

* Updated the Closure of Create Bp dialog

* Fixed the resources and labels issues in BP (#884)

* Fixed the resources and labels issues in BP

* Fixed the resources and labels issues in BP

* UI/UX and Toast Improvements (#885)

* Added the option to add the BP name (#887)

* Added the option to add the Bp name

* Added the option to add the Bp name

* fix: remove redundant token verification after login (#879)

* fix: remove redundant token verification after login

* remove unnecessary comment

* fix the logs and exec in pod tab (#893)

* add redis cache for binding policy storage (#810)

* add redis cache for binding policy storage

* add log error in deleteAllBP

* Feat: Search , Filter Functionality and UI/UX improvement of cluster table and Quick Connect (#886)

* Cluster Table, Quick Connect

* Fix: Scroll-issue and Query dev tool

* Fix: Context Breakdown

* Fix: ContextName

* FIX: Flickering and Dark mode consitancy

* FIX: Flickering and Dark mode consitancy

* fixed bulk labeling (#894)

* fixed bulk labeling

* fixed formating

* fixed formating

* Merge branch 'dev' into fixed-bp-bulk

* Update ClustersTable.tsx

* Free scrolling on the FlowCanvas (#890)

* improve listcontext

* update

* add free scrolling

* Update common.go

* Updated the Retry logic to fetch cluster when no cluster is available  (#897)

* Updated the Retry logic to fetch cluster when no cluster is available

* Updated the Retry logic to fetch cluster when no cluster is available

* Updated the cluster table tab value

* Updated the cluster table tab value

* feat: move validation before WebSocket upgrade in LogWorkloads handler (#904)

- Reorder parameter extraction and validation logic
- Move all c.JSON() calls before upgrader.Upgrade()
- Prevent 'connection has been hijacked' errors
- Maintain proper error responses for invalid inputs

Fixes: WebSocket hijacking error when validation fails
Impact: Eliminates console error flooding and status conflicts

* Delete and Edit labels in cluster (#906)

* fixed delete labels

* fixed delete labels

* fixed labels delete BP case

* fixed labels delete BP case

* changed add lables to bulk labels

* changed add lables to bulk labels

* fixed handlers.go formatting

* refactor: enhance label management and optimize binding policy retrieval

---------

Co-authored-by: Ishaan Soni <[email protected]>
Co-authored-by: Rishi Mondal <[email protected]>

* Fix/minor UI issues (#905)

* fix: correct typo in border width

* fix: correct border width typo

* Fixed all the Bugs in Binding Policy (#908)

* Updated th redis for Binding Policy (#910)

* refactor: update Dockerfile and docker-compose to use build arguments for environment variables (#913)

Signed-off-by: Rishi Mondal <[email protected]>

* Implemented the Delete Cluster labels API to BP (#915)

* Fixed the cacheing issues of Binding Policy (#917)

---------

Signed-off-by: Sayan Banerjee <[email protected]>
Signed-off-by: Rishi Mondal <[email protected]>
Signed-off-by: ashish111333 <[email protected]>
Co-authored-by: Rahul Vishwakarma <[email protected]>
Co-authored-by: Sayan <[email protected]>
Co-authored-by: Onkar Raghunath Shelke <[email protected]>
Co-authored-by: Kunal Dugar <[email protected]>
Co-authored-by: Shivam Kumar <[email protected]>
Co-authored-by: Hiren Sharma <[email protected]>
Co-authored-by: Saumya Kumar <[email protected]>
Co-authored-by: Ishaan Soni <[email protected]>
Co-authored-by: Ishaan Soni <[email protected]>
Co-authored-by: mukeshmahato17 <[email protected]>
Co-authored-by: Hemanshu <[email protected]>
Co-authored-by: Naman Jain <[email protected]>
Co-authored-by: naman9271 <[email protected]>
Co-authored-by: Priyanshu Harshbodhi <[email protected]>
Co-authored-by: ashish <[email protected]>
@MAVRICK-1 MAVRICK-1 mentioned this pull request Jun 6, 2025
1 task done
Per0x1de-1337 pushed a commit to Per0x1de-1337/ui that referenced this pull request Jun 27, 2025
kubestellar#904)

- Reorder parameter extraction and validation logic
- Move all c.JSON() calls before upgrader.Upgrade()
- Prevent 'connection has been hijacked' errors
- Maintain proper error responses for invalid inputs

Fixes: WebSocket hijacking error when validation fails
Impact: Eliminates console error flooding and status conflicts
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

approved Indicates a PR has been approved by an approver from all required OWNERS files. backend Issues or PRs related to the low-level API machinery for KubeStellar docker other size/M Denotes a PR that changes 30-99 lines, ignoring generated files.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

The application is experiencing two related issues that affect WebSocket functionality and deployment flexibility:

1 participant