traefik/pkg/middlewares/ipwhitelist/ip_whitelist_test.go

101 lines
2.1 KiB
Go
Raw Normal View History

2018-11-14 09:18:03 +00:00
package ipwhitelist
2018-04-03 16:36:03 +00:00
import (
2018-11-14 09:18:03 +00:00
"context"
2018-04-03 16:36:03 +00:00
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/traefik/traefik/v2/pkg/config/dynamic"
2018-04-03 16:36:03 +00:00
)
func TestNewIPWhiteLister(t *testing.T) {
testCases := []struct {
desc string
whiteList dynamic.IPWhiteList
2018-11-14 09:18:03 +00:00
expectedError bool
2018-04-03 16:36:03 +00:00
}{
{
2018-11-14 09:18:03 +00:00
desc: "invalid IP",
whiteList: dynamic.IPWhiteList{
2018-11-14 09:18:03 +00:00
SourceRange: []string{"foo"},
},
expectedError: true,
2018-04-03 16:36:03 +00:00
},
{
2018-11-14 09:18:03 +00:00
desc: "valid IP",
whiteList: dynamic.IPWhiteList{
2018-11-14 09:18:03 +00:00
SourceRange: []string{"10.10.10.10"},
},
2018-04-03 16:36:03 +00:00
},
}
for _, test := range testCases {
test := test
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
2018-11-14 09:18:03 +00:00
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
whiteLister, err := New(context.Background(), next, test.whiteList, "traefikTest")
2018-04-03 16:36:03 +00:00
2018-11-14 09:18:03 +00:00
if test.expectedError {
assert.Error(t, err)
2018-04-03 16:36:03 +00:00
} else {
require.NoError(t, err)
assert.NotNil(t, whiteLister)
}
})
}
}
func TestIPWhiteLister_ServeHTTP(t *testing.T) {
testCases := []struct {
desc string
whiteList dynamic.IPWhiteList
remoteAddr string
expected int
2018-04-03 16:36:03 +00:00
}{
{
2018-11-14 09:18:03 +00:00
desc: "authorized with remote address",
whiteList: dynamic.IPWhiteList{
2018-11-14 09:18:03 +00:00
SourceRange: []string{"20.20.20.20"},
},
remoteAddr: "20.20.20.20:1234",
expected: 200,
2018-04-03 16:36:03 +00:00
},
{
2018-11-14 09:18:03 +00:00
desc: "non authorized with remote address",
whiteList: dynamic.IPWhiteList{
2018-11-14 09:18:03 +00:00
SourceRange: []string{"20.20.20.20"},
},
remoteAddr: "20.20.20.21:1234",
expected: 403,
2018-04-03 16:36:03 +00:00
},
}
for _, test := range testCases {
test := test
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
2018-11-14 09:18:03 +00:00
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
whiteLister, err := New(context.Background(), next, test.whiteList, "traefikTest")
2018-04-03 16:36:03 +00:00
require.NoError(t, err)
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "http://10.10.10.10", nil)
if len(test.remoteAddr) > 0 {
req.RemoteAddr = test.remoteAddr
}
2018-11-14 09:18:03 +00:00
whiteLister.ServeHTTP(recorder, req)
2018-04-03 16:36:03 +00:00
assert.Equal(t, test.expected, recorder.Code)
})
}
}