File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 44 "context"
55 "io"
66 "net/http"
7+ "net/url"
78 "sync"
89 "time"
910
@@ -14,7 +15,18 @@ import (
1415)
1516
1617var 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
2032type wsStream struct {
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments