Fix websocket allowed origin (#150)

This commit is contained in:
饺子w 2019-03-15 01:16:24 +08:00 committed by Jannis Mattheis
parent 3e8abdefa7
commit 178c76f410
2 changed files with 14 additions and 5 deletions

View File

@ -4,6 +4,7 @@ import (
"net/http"
"net/url"
"regexp"
"strings"
"sync"
"time"
@ -155,22 +156,22 @@ func (a *API) Close() {
}
func isAllowedOrigin(r *http.Request, allowedOrigins []*regexp.Regexp) bool {
origin := r.Header["Origin"]
if len(origin) == 0 {
origin := r.Header.Get("origin")
if origin == "" {
return true
}
u, err := url.Parse(origin[0])
u, err := url.Parse(origin)
if err != nil {
return false
}
if u.Hostname() == r.Host {
if strings.ToLower(u.Host) == strings.ToLower(r.Host) {
return true
}
for _, allowedOrigin := range allowedOrigins {
if allowedOrigin.Match([]byte(u.Hostname())) {
if allowedOrigin.Match([]byte(strings.ToLower(u.Hostname()))) {
return true
}
}

View File

@ -408,6 +408,14 @@ func Test_sameOrigin_returnsTrue(t *testing.T) {
assert.True(t, actual)
}
func Test_sameOrigin_returnsTrue_withCustomPort(t *testing.T) {
mode.Set(mode.Prod)
req := httptest.NewRequest("GET", "http://example.com:8080/stream", nil)
req.Header.Set("Origin", "http://example.com:8080")
actual := isAllowedOrigin(req, nil)
assert.True(t, actual)
}
func Test_isAllowedOrigin_withoutAllowedOrigins_failsWhenNotSameOrigin(t *testing.T) {
mode.Set(mode.Prod)
req := httptest.NewRequest("GET", "http://example.com/stream", nil)