Extract allowedByWhiteList for unit testability, and add tests

This commit is contained in:
Leonardo Mosquera 2023-12-20 16:50:57 -03:00
parent 12d537b902
commit 0df66c9afa
No known key found for this signature in database
GPG Key ID: A5174CB390D9E8B1
2 changed files with 36 additions and 4 deletions

16
main.go
View File

@ -128,14 +128,22 @@ func checkAuthorizationHeader(handler http.Handler, r *http.Request, w http.Resp
return false
}
func checkWhitelist(handler http.Handler, r *http.Request, w http.ResponseWriter) bool {
if config.Whitelist == "" && config.WhitelistPrefix == "" {
func allowedByWhiteList(c *Config, p string) bool {
if c.Whitelist == "" && c.WhitelistPrefix == "" {
return false
}
prefixAllowed := len(config.WhitelistPrefix) > 0 && strings.HasPrefix(r.URL.Path, config.WhitelistPrefix)
prefixAllowed := len(c.WhitelistPrefix) > 0 && strings.HasPrefix(p, c.WhitelistPrefix)
if r.URL.Path == config.Whitelist || prefixAllowed {
if p == c.Whitelist || prefixAllowed {
return true
}
return false
}
func checkWhitelist(handler http.Handler, r *http.Request, w http.ResponseWriter) bool {
if allowedByWhiteList(config, r.URL.Path) {
handler.ServeHTTP(w, r)
return true
}

View File

@ -202,3 +202,27 @@ func TestValidPayload(t *testing.T) {
assert.Equal(t, username, "user")
assert.Equal(t, group, "group")
}
func TestNotWhitelistedPath(t *testing.T) {
c := NewTestConfig()
c.Whitelist = ""
res := allowedByWhiteList(&c, "/some_path")
assert.Equal(t, false, res)
}
func TestWhitelistedPath(t *testing.T) {
c := NewTestConfig()
c.Whitelist = "/some_path"
res := allowedByWhiteList(&c, "/some_path")
assert.Equal(t, true, res)
}
func TestWhitelistedPrefixPath(t *testing.T) {
c := NewTestConfig()
c.WhitelistPrefix = "/prefix/"
res := allowedByWhiteList(&c, "/prefix/some_path")
assert.Equal(t, true, res)
}