router.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (C) 2019-2022 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(middleware.Recoverer)
  28. router.Group(func(r chi.Router) {
  29. r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
  30. render.PlainText(w, r, "ok")
  31. })
  32. })
  33. router.Group(func(router chi.Router) {
  34. router.Use(checkAuth)
  35. metric.AddMetricsEndpoint(metricsPath, router)
  36. if enableProfiler {
  37. logger.InfoToConsole("enabling the built-in profiler")
  38. logger.Info(logSender, "", "enabling the built-in profiler")
  39. router.Mount(pprofBasePath, middleware.Profiler())
  40. }
  41. })
  42. }
  43. func checkAuth(next http.Handler) http.Handler {
  44. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  45. if !validateCredentials(r) {
  46. w.Header().Set(common.HTTPAuthenticationHeader, "Basic realm=\"SFTPGo telemetry\"")
  47. http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  48. return
  49. }
  50. next.ServeHTTP(w, r)
  51. })
  52. }
  53. func validateCredentials(r *http.Request) bool {
  54. if !httpAuth.IsEnabled() {
  55. return true
  56. }
  57. username, password, ok := r.BasicAuth()
  58. if !ok {
  59. return false
  60. }
  61. return httpAuth.ValidateCredentials(username, password)
  62. }