Skip to content

Commit

Permalink
websocket: don't set a WSS multiaddr for accepted unencrypted conns
Browse files Browse the repository at this point in the history
  • Loading branch information
marten-seemann committed Mar 17, 2023
1 parent ed96a64 commit 2c5f801
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
6 changes: 5 additions & 1 deletion p2p/transport/websocket/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ import (
type listener struct {
nl net.Listener
server http.Server
// The Go standard library sets the http.Server.TLSConfig no matter if this is a WS or WSS,
// so we can't rely on checking if server.TLSConfig is set.
isWss bool

laddr ma.Multiaddr

Expand Down Expand Up @@ -80,6 +83,7 @@ func newListener(a ma.Multiaddr, tlsConf *tls.Config) (*listener, error) {
}
ln.server = http.Server{Handler: ln}
if parsed.isWSS {
ln.isWss = true
ln.server.TLSConfig = tlsConf
}
return ln, nil
Expand All @@ -96,7 +100,7 @@ func (l *listener) serve() {

func (l *listener) ServeHTTP(w http.ResponseWriter, r *http.Request) {
scheme := "ws"
if l.server.TLSConfig != nil {
if l.isWss {
scheme = "wss"
}

Expand Down
14 changes: 14 additions & 0 deletions p2p/transport/websocket/websocket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,16 @@ func TestWebsocketTransport(t *testing.T) {
ttransport.SubtestTransport(t, ta, tb, "/ip4/127.0.0.1/tcp/0/ws", "peerA")
}

func isWSS(addr ma.Multiaddr) bool {
if _, err := addr.ValueForProtocol(ma.P_WSS); err == nil {
return true
}
if _, err := addr.ValueForProtocol(ma.P_WS); err == nil {
return false
}
panic("not a WebSocket address")
}

func connectAndExchangeData(t *testing.T, laddr ma.Multiaddr, secure bool) {
var opts []Option
var tlsConf *tls.Config
Expand Down Expand Up @@ -339,6 +349,8 @@ func connectAndExchangeData(t *testing.T, laddr ma.Multiaddr, secure bool) {
require.NoError(t, err)
c, err := tpt.Dial(context.Background(), l.Multiaddr(), server)
require.NoError(t, err)
require.Equal(t, secure, isWSS(c.LocalMultiaddr()))
require.Equal(t, secure, isWSS(c.RemoteMultiaddr()))
str, err := c.OpenStream(context.Background())
require.NoError(t, err)
defer str.Close()
Expand All @@ -349,6 +361,8 @@ func connectAndExchangeData(t *testing.T, laddr ma.Multiaddr, secure bool) {
c, err := l.Accept()
require.NoError(t, err)
defer c.Close()
require.Equal(t, secure, isWSS(c.LocalMultiaddr()))
require.Equal(t, secure, isWSS(c.RemoteMultiaddr()))
str, err := c.AcceptStream()
require.NoError(t, err)
defer str.Close()
Expand Down

0 comments on commit 2c5f801

Please sign in to comment.