2020-12-18 08:01:19 +00:00
|
|
|
package telemetry
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2021-03-01 18:28:11 +00:00
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"github.com/go-chi/chi/v5/middleware"
|
2020-12-18 08:01:19 +00:00
|
|
|
"github.com/go-chi/render"
|
|
|
|
|
2020-12-18 15:04:42 +00:00
|
|
|
"github.com/drakkan/sftpgo/common"
|
2020-12-18 08:01:19 +00:00
|
|
|
"github.com/drakkan/sftpgo/logger"
|
|
|
|
"github.com/drakkan/sftpgo/metrics"
|
|
|
|
)
|
|
|
|
|
|
|
|
func initializeRouter(enableProfiler bool) {
|
|
|
|
router = chi.NewRouter()
|
|
|
|
|
2020-12-20 09:22:16 +00:00
|
|
|
router.Use(middleware.GetHead)
|
2020-12-18 08:01:19 +00:00
|
|
|
router.Use(middleware.Recoverer)
|
|
|
|
|
|
|
|
router.Group(func(r chi.Router) {
|
|
|
|
r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
render.PlainText(w, r, "ok")
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
2020-12-18 15:04:42 +00:00
|
|
|
router.Group(func(router chi.Router) {
|
|
|
|
router.Use(checkAuth)
|
|
|
|
metrics.AddMetricsEndpoint(metricsPath, router)
|
2020-12-18 08:01:19 +00:00
|
|
|
|
2020-12-18 15:04:42 +00:00
|
|
|
if enableProfiler {
|
|
|
|
logger.InfoToConsole("enabling the built-in profiler")
|
|
|
|
logger.Info(logSender, "", "enabling the built-in profiler")
|
|
|
|
router.Mount(pprofBasePath, middleware.Profiler())
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func checkAuth(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if !validateCredentials(r) {
|
|
|
|
w.Header().Set(common.HTTPAuthenticationHeader, "Basic realm=\"SFTPGo telemetry\"")
|
|
|
|
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func validateCredentials(r *http.Request) bool {
|
|
|
|
if !httpAuth.IsEnabled() {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
username, password, ok := r.BasicAuth()
|
|
|
|
if !ok {
|
|
|
|
return false
|
2020-12-18 08:01:19 +00:00
|
|
|
}
|
2020-12-18 15:04:42 +00:00
|
|
|
return httpAuth.ValidateCredentials(username, password)
|
2020-12-18 08:01:19 +00:00
|
|
|
}
|