handler.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. package logging
  2. import (
  3. "net"
  4. "net/http"
  5. "os"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/sirupsen/logrus"
  10. "github.com/smallstep/certificates/internal/userid"
  11. "github.com/smallstep/certificates/middleware/requestid"
  12. )
  13. // LoggerHandler creates a logger handler
  14. type LoggerHandler struct {
  15. name string
  16. logger *logrus.Logger
  17. options options
  18. next http.Handler
  19. }
  20. // options encapsulates any overriding parameters for the logger handler
  21. type options struct {
  22. // onlyTraceHealthEndpoint determines if the kube-probe requests to the /health
  23. // endpoint should only be logged at the TRACE level in the (expected) HTTP
  24. // 200 case
  25. onlyTraceHealthEndpoint bool
  26. }
  27. // NewLoggerHandler returns the given http.Handler with the logger integrated.
  28. func NewLoggerHandler(name string, logger *Logger, next http.Handler) http.Handler {
  29. onlyTraceHealthEndpoint, _ := strconv.ParseBool(os.Getenv("STEP_LOGGER_ONLY_TRACE_HEALTH_ENDPOINT"))
  30. return &LoggerHandler{
  31. name: name,
  32. logger: logger.GetImpl(),
  33. options: options{
  34. onlyTraceHealthEndpoint: onlyTraceHealthEndpoint,
  35. },
  36. next: next,
  37. }
  38. }
  39. // ServeHTTP implements the http.Handler and call to the handler to log with a
  40. // custom http.ResponseWriter that records the response code and the number of
  41. // bytes sent.
  42. func (l *LoggerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  43. t := time.Now()
  44. rw := NewResponseLogger(w)
  45. l.next.ServeHTTP(rw, r)
  46. d := time.Since(t)
  47. l.writeEntry(rw, r, t, d)
  48. }
  49. // writeEntry writes to the Logger writer the request information in the logger.
  50. func (l *LoggerHandler) writeEntry(w ResponseLogger, r *http.Request, t time.Time, d time.Duration) {
  51. var requestID, userID string
  52. ctx := r.Context()
  53. if v, ok := requestid.FromContext(ctx); ok {
  54. requestID = v
  55. }
  56. if v, ok := userid.FromContext(ctx); ok {
  57. userID = v
  58. }
  59. // Remote hostname
  60. addr, _, err := net.SplitHostPort(r.RemoteAddr)
  61. if err != nil {
  62. addr = r.RemoteAddr
  63. }
  64. // From https://github.com/gorilla/handlers
  65. uri := r.RequestURI
  66. // Requests using the CONNECT method over HTTP/2.0 must use
  67. // the authority field (aka r.Host) to identify the target.
  68. // Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT
  69. if r.ProtoMajor == 2 && r.Method == "CONNECT" {
  70. uri = r.Host
  71. }
  72. if uri == "" {
  73. uri = sanitizeLogEntry(r.URL.RequestURI())
  74. }
  75. status := w.StatusCode()
  76. fields := logrus.Fields{
  77. "request-id": requestID,
  78. "remote-address": addr,
  79. "name": l.name,
  80. "user-id": userID,
  81. "time": t.Format(time.RFC3339),
  82. "duration-ns": d.Nanoseconds(),
  83. "duration": d.String(),
  84. "method": r.Method,
  85. "path": uri,
  86. "protocol": r.Proto,
  87. "status": status,
  88. "size": w.Size(),
  89. "referer": sanitizeLogEntry(r.Referer()),
  90. "user-agent": sanitizeLogEntry(r.UserAgent()),
  91. }
  92. for k, v := range w.Fields() {
  93. fields[k] = v
  94. }
  95. switch {
  96. case status < http.StatusBadRequest:
  97. if l.options.onlyTraceHealthEndpoint && uri == "/health" {
  98. l.logger.WithFields(fields).Trace()
  99. } else {
  100. l.logger.WithFields(fields).Info()
  101. }
  102. case status < http.StatusInternalServerError:
  103. l.logger.WithFields(fields).Warn()
  104. default:
  105. l.logger.WithFields(fields).Error()
  106. }
  107. }
  108. func sanitizeLogEntry(s string) string {
  109. escaped := strings.ReplaceAll(s, "\n", "")
  110. return strings.ReplaceAll(escaped, "\r", "")
  111. }