shosti
shosti

Reputation: 7422

Is it possible to check for WebSocket 403 responses?

Is it possible to programmatically check if a WebSocket connection failed with a 403 response? For instance, with the following server code:

package main

import (
    "errors"
    "io"
    "log"
    "net/http"

    "golang.org/x/net/websocket"
)

func main() {
    handler := websocket.Handler(func(ws *websocket.Conn) {
        io.Copy(ws, ws)
    })
    handshake := func(conf *websocket.Config, req *http.Request) error {
        if req.URL.Path == "/sekret" {
            return nil
        }
        return errors.New("Oops!")
    }
    server := &websocket.Server{
        Handshake: handshake,
        Handler:   handler,
    }
    log.Fatal(http.ListenAndServe(":8080", server))
}

And the following sample JS connection that triggers a 403 response:

var ws = new WebSocket("ws://localhost:8080/something"); 
ws.onerror = console.log;

The error response is an Event with type "error". On the other hand, the following JS code triggers a net::ERR_CONNECTION_REFUSED (at least on Chrome):

var ws = new WebSocket("ws://localhost:8081/something"); 
ws.onerror = console.log;

The error event object looks almost exactly the same. Is there some way to distinguish error types in WebSocket connections from the client side? (I'm specifically looking for 403 responses, so I can alert the user to take special action.)

Upvotes: 3

Views: 1609

Answers (1)

shosti
shosti

Reputation: 7422

Apparently it's deliberate:

My understanding is that for security reasons, WebSocket error statuses are fairly restricted to limit the ability of malicious JS to probe an internal network.

Upvotes: 2

Related Questions