metrics.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package server // import "miniflux.app/v2/internal/http/server"
  4. import (
  5. "log/slog"
  6. "net/http"
  7. "miniflux.app/v2/internal/config"
  8. "miniflux.app/v2/internal/crypto"
  9. "miniflux.app/v2/internal/http/request"
  10. "github.com/prometheus/client_golang/prometheus/promhttp"
  11. )
  12. func metricsHandler() http.Handler {
  13. handler := promhttp.Handler()
  14. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  15. if !isAllowedToAccessMetricsEndpoint(r) {
  16. slog.Warn("Authentication failed while accessing the metrics endpoint",
  17. slog.String("client_ip", request.ClientIP(r)),
  18. slog.String("client_user_agent", r.UserAgent()),
  19. slog.String("client_remote_addr", r.RemoteAddr),
  20. )
  21. http.NotFound(w, r)
  22. return
  23. }
  24. handler.ServeHTTP(w, r)
  25. })
  26. }
  27. func isAllowedToAccessMetricsEndpoint(r *http.Request) bool {
  28. clientIP := request.ClientIP(r)
  29. if config.Opts.MetricsUsername() != "" && config.Opts.MetricsPassword() != "" {
  30. username, password, authOK := r.BasicAuth()
  31. if !authOK {
  32. slog.Warn("Metrics endpoint accessed without authentication header",
  33. slog.Bool("authentication_failed", true),
  34. slog.String("client_ip", clientIP),
  35. slog.String("client_user_agent", r.UserAgent()),
  36. slog.String("client_remote_addr", r.RemoteAddr),
  37. )
  38. return false
  39. }
  40. if username == "" || password == "" {
  41. slog.Warn("Metrics endpoint accessed with empty username or password",
  42. slog.Bool("authentication_failed", true),
  43. slog.String("client_ip", clientIP),
  44. slog.String("client_user_agent", r.UserAgent()),
  45. slog.String("client_remote_addr", r.RemoteAddr),
  46. )
  47. return false
  48. }
  49. // Both checks have to be run to avoid leaking informations
  50. // about the username and the password.
  51. usernameCorrect := crypto.ConstantTimeCmp(username, config.Opts.MetricsUsername())
  52. passwordCorrect := crypto.ConstantTimeCmp(password, config.Opts.MetricsPassword())
  53. if !usernameCorrect || !passwordCorrect {
  54. slog.Warn("Metrics endpoint accessed with invalid username or password",
  55. slog.Bool("authentication_failed", true),
  56. slog.String("client_ip", clientIP),
  57. slog.String("client_user_agent", r.UserAgent()),
  58. slog.String("client_remote_addr", r.RemoteAddr),
  59. )
  60. return false
  61. }
  62. }
  63. remoteIP := request.FindRemoteIP(r)
  64. return request.IsTrustedIP(remoteIP, config.Opts.MetricsAllowedNetworks())
  65. }