feat(metrics): add metrics server (#1930)

* feat(metrics): add metrics server

* chore: update license headers

* feat(metrics): add optional basic auth

* feat(metrics): add go and process collectors

---------

Co-authored-by: ze0s <43699394+zze0s@users.noreply.github.com>
Co-authored-by: ze0s <ze0s@riseup.net>
This commit is contained in:
Antoine 2025-01-25 17:58:18 +01:00 committed by GitHub
parent 0d5902c8f6
commit 3f8bc0140c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 1191 additions and 83 deletions

View file

@ -5,6 +5,7 @@ package http
import (
"context"
"fmt"
"net/http"
"runtime/debug"
"strings"
@ -12,6 +13,7 @@ import (
"github.com/go-chi/chi/v5/middleware"
"github.com/rs/zerolog"
"golang.org/x/crypto/bcrypt"
)
func (s Server) IsAuthenticated(next http.Handler) http.Handler {
@ -133,3 +135,45 @@ func LoggerMiddleware(logger *zerolog.Logger) func(next http.Handler) http.Handl
return http.HandlerFunc(fn)
}
}
// BasicAuth implements a simple middleware handler for adding basic http auth to a route.
func BasicAuth(realm string, users string) func(next http.Handler) http.Handler {
creds := map[string]string{}
userCreds := strings.Split(users, ",")
for _, cred := range userCreds {
credParts := strings.Split(cred, ":")
if len(credParts) != 2 {
//s.log.Warn().Msgf("Invalid metrics basic auth credentials: %s", cred)
continue
}
creds[credParts[0]] = credParts[1]
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if !ok {
basicAuthFailed(w, realm)
return
}
// Validate username and password using htpasswd data
if hashedPassword, exists := creds[username]; exists {
// Use bcrypt to validate the password
if err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)); err == nil {
next.ServeHTTP(w, r)
return
}
}
basicAuthFailed(w, realm)
})
}
}
func basicAuthFailed(w http.ResponseWriter, realm string) {
w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm))
w.WriteHeader(http.StatusUnauthorized)
}