Skip to content

Commit 6b5073d

Browse files
cbronzerbitx
authored andcommitted
Adds check for websocket source
1 parent af83b7e commit 6b5073d

2 files changed

Lines changed: 46 additions & 1 deletion

File tree

pkg/devspace/server/logs.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"context"
55
"io"
66
"net/http"
7+
"net/url"
78
"sync"
89
"time"
910

@@ -14,7 +15,18 @@ import (
1415
)
1516

1617
var upgrader = websocket.Upgrader{
17-
CheckOrigin: func(r *http.Request) bool { return true },
18+
CheckOrigin: func(r *http.Request) bool {
19+
origin := r.Header.Get("Origin")
20+
if origin == "" {
21+
return true // non-browser clients (CLI tools, curl) send no Origin header
22+
}
23+
u, err := url.Parse(origin)
24+
if err != nil {
25+
return false
26+
}
27+
h := u.Hostname()
28+
return h == "localhost" || h == "127.0.0.1"
29+
},
1830
}
1931

2032
type wsStream struct {

pkg/devspace/server/logs_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package server
2+
3+
import (
4+
"net/http"
5+
"testing"
6+
7+
"gotest.tools/assert"
8+
)
9+
10+
func TestCheckOrigin(t *testing.T) {
11+
cases := map[string]struct {
12+
origin string
13+
want bool
14+
}{
15+
"no origin header (CLI/curl)": {origin: "", want: true},
16+
"localhost origin": {origin: "http://localhost:8080", want: true},
17+
"127.0.0.1 origin": {origin: "http://127.0.0.1:3000", want: true},
18+
"localhost no port": {origin: "http://localhost", want: true},
19+
"external origin": {origin: "http://bad.example.com", want: false},
20+
"invalid origin": {origin: "://bad-url", want: false},
21+
}
22+
23+
for name, tc := range cases {
24+
t.Run(name, func(t *testing.T) {
25+
r := &http.Request{Header: http.Header{}}
26+
if tc.origin != "" {
27+
r.Header.Set("Origin", tc.origin)
28+
}
29+
got := upgrader.CheckOrigin(r)
30+
assert.Equal(t, tc.want, got, name)
31+
})
32+
}
33+
}

0 commit comments

Comments
 (0)