Skip to content

Commit

Permalink
Merge pull request #14 from justincjohnson/justincjohnson/validate-st…
Browse files Browse the repository at this point in the history
…atus

fix: validate status codes
  • Loading branch information
lidel authored Sep 22, 2022
2 parents 4946b03 + 7216fa7 commit 0fce9c8
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
20 changes: 18 additions & 2 deletions redirects.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,25 @@ func ParseString(s string) ([]Rule, error) {
func parseStatus(s string) (code int, err error) {
if strings.HasSuffix(s, "!") {
// See https://docs.netlify.com/routing/redirects/rewrites-proxies/#shadowing
return -1, fmt.Errorf("forced redirects (or \"shadowing\") are not supported by IPFS gateways")
return 0, fmt.Errorf("forced redirects (or \"shadowing\") are not supported by IPFS gateways")
}

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

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

return code, nil
}

func isValidStatusCode(status int) bool {
switch status {
case 200, 301, 302, 303, 307, 308, 404, 410, 451:
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 0fce9c8

Please sign in to comment.