config: add metrics_basic_auth option (#1917)

* config: add metrics_basic_auth option

* remove println

* use constant time compare
This commit is contained in:
Caleb Doxsey 2021-02-22 13:37:18 -07:00 committed by GitHub
parent 03d8ffaee2
commit 8b42eb5ebd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 309 additions and 170 deletions

View file

@ -2,6 +2,7 @@ package httputil
import (
"bytes"
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
@ -64,3 +65,25 @@ func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
e.ErrorResponse(w, r)
}
}
// RequireBasicAuth creates a new handler that requires basic auth from the client before
// calling the underlying handler.
func RequireBasicAuth(handler http.Handler, username, password string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
u, p, ok := r.BasicAuth()
if !ok {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
if subtle.ConstantTimeCompare([]byte(u), []byte(username)) != 1 ||
subtle.ConstantTimeCompare([]byte(p), []byte(password)) != 1 {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
handler.ServeHTTP(w, r)
})
}