middleware: equalize lengths of input (#1934)

Signed-off-by: Bobby DeSimone <bobbydesimone@gmail.com>
This commit is contained in:
bobby 2021-02-23 08:31:17 -08:00 committed by GitHub
parent e56fb38cb5
commit 9c7958b66f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 75 additions and 24 deletions

View file

@ -1,6 +1,8 @@
package middleware
import (
"crypto/sha256"
"crypto/subtle"
"net/http"
"strings"
"time"
@ -75,3 +77,31 @@ func TimeoutHandlerFunc(timeout time.Duration, timeoutError string) func(next ht
})
}
}
// RequireBasicAuth creates a new handler that requires basic auth from the client before
// calling the underlying handler.
func RequireBasicAuth(username, password string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u, p, ok := r.BasicAuth()
if !ok {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
givenUser := sha256.Sum256([]byte(u))
givenPass := sha256.Sum256([]byte(p))
requiredUser := sha256.Sum256([]byte(username))
requiredPass := sha256.Sum256([]byte(password))
if subtle.ConstantTimeCompare(givenUser[:], requiredUser[:]) != 1 ||
subtle.ConstantTimeCompare(givenPass[:], requiredPass[:]) != 1 {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
}