Skip to content

Commit

Permalink
Validate status codes
Browse files Browse the repository at this point in the history
  • Loading branch information
Justin Johnson committed Sep 15, 2022
1 parent 4946b03 commit 0d96739
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
18 changes: 18 additions & 0 deletions redirects.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,5 +158,23 @@ func parseStatus(s string) (code int, err error) {
}

code, err = strconv.Atoi(s)
if err != nil {
return code, err
}

if !isValidStatusCode(code) {
return code, fmt.Errorf("status code %d is not supported", code)
}

return code, err
}

func isValidStatusCode(status int) bool {
validStatuses := []int{200, 301, 302, 303, 307, 308, 404, 410, 451}
for _, validStatus := range validStatuses {
if validStatus == status {
return true
}
}
return false
}
14 changes: 12 additions & 2 deletions redirects_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,22 @@ func TestRule_IsRewrite(t *testing.T) {
})
}

func TestParse(t *testing.T) {
func Test_Parse(t *testing.T) {
t.Run("with illegal force", func(t *testing.T) {
_, err := Parse(strings.NewReader(`
/home / 301!
`))

assert.Error(t, err, "forced redirects should return an error")
assert.Error(t, err)
assert.Contains(t, err.Error(), "forced redirects")
})

t.Run("with illegal code", func(t *testing.T) {
_, err := Parse(strings.NewReader(`
/home / 42
`))

assert.Error(t, err)
assert.Contains(t, err.Error(), "status code 42 is not supported")
})
}

0 comments on commit 0d96739

Please sign in to comment.