router.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright (C) 2019-2023 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package telemetry
  15. import (
  16. "net/http"
  17. "github.com/go-chi/chi/v5"
  18. "github.com/go-chi/chi/v5/middleware"
  19. "github.com/go-chi/render"
  20. "github.com/drakkan/sftpgo/v2/internal/common"
  21. "github.com/drakkan/sftpgo/v2/internal/logger"
  22. "github.com/drakkan/sftpgo/v2/internal/metric"
  23. )
  24. func initializeRouter(enableProfiler bool) {
  25. router = chi.NewRouter()
  26. router.Use(middleware.GetHead)
  27. router.Use(logger.NewStructuredLogger(logger.GetLogger()))
  28. router.Use(middleware.Recoverer)
  29. router.Group(func(r chi.Router) {
  30. r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
  31. render.PlainText(w, r, "ok")
  32. })
  33. })
  34. router.Group(func(router chi.Router) {
  35. router.Use(checkAuth)
  36. metric.AddMetricsEndpoint(metricsPath, router)
  37. if enableProfiler {
  38. logger.InfoToConsole("enabling the built-in profiler")
  39. logger.Info(logSender, "", "enabling the built-in profiler")
  40. router.Mount(pprofBasePath, middleware.Profiler())
  41. }
  42. })
  43. }
  44. func checkAuth(next http.Handler) http.Handler {
  45. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  46. if !validateCredentials(r) {
  47. w.Header().Set(common.HTTPAuthenticationHeader, "Basic realm=\"SFTPGo telemetry\"")
  48. http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  49. return
  50. }
  51. next.ServeHTTP(w, r)
  52. })
  53. }
  54. func validateCredentials(r *http.Request) bool {
  55. if !httpAuth.IsEnabled() {
  56. return true
  57. }
  58. username, password, ok := r.BasicAuth()
  59. if !ok {
  60. return false
  61. }
  62. return httpAuth.ValidateCredentials(username, password)
  63. }