mirror of
https://github.com/TecharoHQ/anubis.git
synced 2026-04-23 16:46:40 +00:00
681c2cc2ed
* feat(internal): add basic auth HTTP middleware Signed-off-by: Xe Iaso <me@xeiaso.net> * feat(config): add HTTP basic auth for metrics Signed-off-by: Xe Iaso <me@xeiaso.net> * feat(metrics): wire up basic auth Signed-off-by: Xe Iaso <me@xeiaso.net> * doc: document HTTP basic auth for metrics server Signed-off-by: Xe Iaso <me@xeiaso.net> * chore: spelling Signed-off-by: Xe Iaso <me@xeiaso.net> * docs(admin/policies): give people a python command Signed-off-by: Xe Iaso <me@xeiaso.net> --------- Signed-off-by: Xe Iaso <me@xeiaso.net>
52 lines
1.4 KiB
Go
52 lines
1.4 KiB
Go
package internal
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
)
|
|
|
|
// BasicAuth wraps next in HTTP Basic authentication using the provided
|
|
// credentials. If either username or password is empty, next is returned
|
|
// unchanged and a debug log line is emitted.
|
|
//
|
|
// Credentials are compared in constant time to avoid leaking information
|
|
// through timing side channels.
|
|
func BasicAuth(realm, username, password string, next http.Handler) http.Handler {
|
|
if username == "" || password == "" {
|
|
slog.Debug("skipping middleware, basic auth credentials are empty")
|
|
return next
|
|
}
|
|
|
|
expectedUser := sha256.Sum256([]byte(username))
|
|
expectedPass := sha256.Sum256([]byte(password))
|
|
challenge := fmt.Sprintf("Basic realm=%q, charset=\"UTF-8\"", realm)
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
user, pass, ok := r.BasicAuth()
|
|
if !ok {
|
|
unauthorized(w, challenge)
|
|
return
|
|
}
|
|
|
|
gotUser := sha256.Sum256([]byte(user))
|
|
gotPass := sha256.Sum256([]byte(pass))
|
|
|
|
userMatch := subtle.ConstantTimeCompare(gotUser[:], expectedUser[:])
|
|
passMatch := subtle.ConstantTimeCompare(gotPass[:], expectedPass[:])
|
|
|
|
if userMatch&passMatch != 1 {
|
|
unauthorized(w, challenge)
|
|
return
|
|
}
|
|
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func unauthorized(w http.ResponseWriter, challenge string) {
|
|
w.Header().Set("WWW-Authenticate", challenge)
|
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
|
} |