Skip to content

Commit e5919c0

Browse files
committed
chore: allow only status codes valid for redirections
Signed-off-by: Thorsten Hans <[email protected]>
1 parent 0686645 commit e5919c0

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

redirect.go

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"fmt"
45
"net/http"
56
"strconv"
67

@@ -39,7 +40,7 @@ func NewSpinRedirect() SpinRedirect {
3940

4041
func (s SpinRedirect) handleFunc(w http.ResponseWriter, r *http.Request) {
4142
dest := s.getDestination()
42-
code := s.getStatusCode()
43+
code := s.getStatusCode(r.Method)
4344

4445
w.Header().Set("Location", dest)
4546
w.WriteHeader(code)
@@ -54,11 +55,37 @@ func (s SpinRedirect) getDestination() string {
5455
// getStatusCode returns the HTTP status code
5556
// If no status code is found, or if the provided value is invalid,
5657
// DefaultStatusCode is returned.
57-
func (s SpinRedirect) getStatusCode() int {
58+
func (s SpinRedirect) getStatusCode(method string) int {
5859
str := s.cfg.Get(statusCodeKey)
5960
code, err := strconv.Atoi(str)
6061
if err != nil {
6162
return DefaultStatusCode
6263
}
64+
if !isValidRedirectStatusCode(code, method) {
65+
fmt.Printf("Invalid status code provided: %d. Will use %d instead.\n", code, DefaultStatusCode)
66+
return DefaultStatusCode
67+
}
68+
6369
return code
6470
}
71+
72+
// isValidRedirectStatusCode returns true if the provided status code is valid for redirection
73+
func isValidRedirectStatusCode(code int, method string) bool {
74+
if code == http.StatusSeeOther &&
75+
(method == http.MethodPut || method == http.MethodPost) {
76+
return true
77+
}
78+
validCodes := []int{
79+
http.StatusMovedPermanently,
80+
http.StatusFound,
81+
http.StatusTemporaryRedirect,
82+
http.StatusPermanentRedirect,
83+
}
84+
85+
for _, c := range validCodes {
86+
if c == code {
87+
return true
88+
}
89+
}
90+
return false
91+
}

0 commit comments

Comments
 (0)