Skip to content

Commit 077d532

Browse files
authored
Allow localhost origins (#67)
* Allow localhost origins * Bump v1.6.1
1 parent ba3c9be commit 077d532

File tree

3 files changed

+40
-7
lines changed

3 files changed

+40
-7
lines changed

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
SHELL = /bin/sh
22

3-
VERSION=1.6.0
3+
VERSION=1.6.1
44
BUILD=`git rev-parse HEAD`
55

66
LDFLAGS=-ldflags "-w -s \

fakeserver/server.go

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"log"
77
"net"
88
"net/http"
9+
"net/url"
910
"os"
1011
"strings"
1112
"sync"
@@ -50,13 +51,19 @@ func createCors() *cors.Cors {
5051
return true
5152
}
5253
}
53-
if origin == "localhost" {
54-
return true
55-
}
56-
ip := net.ParseIP(origin)
57-
if ip != nil && ip.IsLoopback() {
58-
return true
54+
55+
if parsed, err := url.Parse(origin); err == nil {
56+
hostname := parsed.Hostname()
57+
58+
if hostname == "localhost" {
59+
return true
60+
}
61+
62+
if ip := net.ParseIP(hostname); ip != nil && ip.IsLoopback() {
63+
return true
64+
}
5965
}
66+
6067
return false
6168
},
6269
})

fakeserver/server_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,32 @@ func TestCors(t *testing.T) {
246246
require.Equal(t, "http://www.allowed.com", w.HeaderMap.Get("Access-Control-Allow-Origin"))
247247
})
248248

249+
t.Run("it passes cors from localhost", func(t *testing.T) {
250+
w := httptest.NewRecorder()
251+
h := createHandler()
252+
253+
request := httptest.NewRequest("GET", "/api/v2/split_registry", nil)
254+
request.Header.Add("Origin", "http://localhost:3000")
255+
256+
h.ServeHTTP(w, request)
257+
258+
require.Equal(t, http.StatusOK, w.Code)
259+
require.Equal(t, "http://localhost:3000", w.HeaderMap.Get("Access-Control-Allow-Origin"))
260+
})
261+
262+
t.Run("it passes cors from loopback ip", func(t *testing.T) {
263+
w := httptest.NewRecorder()
264+
h := createHandler()
265+
266+
request := httptest.NewRequest("GET", "/api/v2/split_registry", nil)
267+
request.Header.Add("Origin", "http://127.0.0.1:3000")
268+
269+
h.ServeHTTP(w, request)
270+
271+
require.Equal(t, http.StatusOK, w.Code)
272+
require.Equal(t, "http://127.0.0.1:3000", w.HeaderMap.Get("Access-Control-Allow-Origin"))
273+
})
274+
249275
os.Unsetenv("TESTTRACK_ALLOWED_ORIGINS")
250276
}
251277

0 commit comments

Comments
 (0)