handler.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. // Common headers used for identifying the originating IP address of a client
  14. // connecting to a web server through a proxy server
  15. var (
  16. trueClientIP = http.CanonicalHeaderKey("True-Client-IP")
  17. xRealIP = http.CanonicalHeaderKey("X-Real-IP")
  18. xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
  19. )
  20. // LoggerHandler creates a logger handler
  21. type LoggerHandler struct {
  22. name string
  23. logger *logrus.Logger
  24. options options
  25. next http.Handler
  26. }
  27. // options encapsulates any overriding parameters for the logger handler
  28. type options struct {
  29. // onlyTraceHealthEndpoint determines if the kube-probe requests to the /health
  30. // endpoint should only be logged at the TRACE level in the (expected) HTTP
  31. // 200 case
  32. onlyTraceHealthEndpoint bool
  33. // logRealIP determines if the real IP address of the client should be logged
  34. // instead of the IP address of the proxy
  35. logRealIP bool
  36. }
  37. // NewLoggerHandler returns the given http.Handler with the logger integrated.
  38. func NewLoggerHandler(name string, logger *Logger, next http.Handler) http.Handler {
  39. onlyTraceHealthEndpoint, _ := strconv.ParseBool(os.Getenv("STEP_LOGGER_ONLY_TRACE_HEALTH_ENDPOINT"))
  40. logRealIP, _ := strconv.ParseBool(os.Getenv("STEP_LOGGER_LOG_REAL_IP"))
  41. return &LoggerHandler{
  42. name: name,
  43. logger: logger.GetImpl(),
  44. options: options{
  45. onlyTraceHealthEndpoint: onlyTraceHealthEndpoint,
  46. logRealIP: logRealIP,
  47. },
  48. next: next,
  49. }
  50. }
  51. // ServeHTTP implements the http.Handler and call to the handler to log with a
  52. // custom http.ResponseWriter that records the response code and the number of
  53. // bytes sent.
  54. func (l *LoggerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  55. t := time.Now()
  56. rw := NewResponseLogger(w)
  57. l.next.ServeHTTP(rw, r)
  58. d := time.Since(t)
  59. l.writeEntry(rw, r, t, d)
  60. }
  61. // writeEntry writes to the Logger writer the request information in the logger.
  62. func (l *LoggerHandler) writeEntry(w ResponseLogger, r *http.Request, t time.Time, d time.Duration) {
  63. var requestID, userID string
  64. ctx := r.Context()
  65. if v, ok := requestid.FromContext(ctx); ok {
  66. requestID = v
  67. }
  68. if v, ok := userid.FromContext(ctx); ok {
  69. userID = v
  70. }
  71. // Remote hostname
  72. addr := r.RemoteAddr
  73. if l.options.logRealIP {
  74. addr = realIP(r)
  75. }
  76. if host, _, err := net.SplitHostPort(addr); err == nil {
  77. addr = host
  78. }
  79. // From https://github.com/gorilla/handlers
  80. uri := r.RequestURI
  81. // Requests using the CONNECT method over HTTP/2.0 must use
  82. // the authority field (aka r.Host) to identify the target.
  83. // Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT
  84. if r.ProtoMajor == 2 && r.Method == "CONNECT" {
  85. uri = r.Host
  86. }
  87. if uri == "" {
  88. uri = sanitizeLogEntry(r.URL.RequestURI())
  89. }
  90. status := w.StatusCode()
  91. fields := logrus.Fields{
  92. "request-id": requestID,
  93. "remote-address": addr,
  94. "name": l.name,
  95. "user-id": userID,
  96. "time": t.Format(time.RFC3339),
  97. "duration-ns": d.Nanoseconds(),
  98. "duration": d.String(),
  99. "method": r.Method,
  100. "path": uri,
  101. "protocol": r.Proto,
  102. "status": status,
  103. "size": w.Size(),
  104. "referer": sanitizeLogEntry(r.Referer()),
  105. "user-agent": sanitizeLogEntry(r.UserAgent()),
  106. }
  107. for k, v := range w.Fields() {
  108. fields[k] = v
  109. }
  110. switch {
  111. case status < http.StatusBadRequest:
  112. if l.options.onlyTraceHealthEndpoint && uri == "/health" {
  113. l.logger.WithFields(fields).Trace()
  114. } else {
  115. l.logger.WithFields(fields).Info()
  116. }
  117. case status < http.StatusInternalServerError:
  118. l.logger.WithFields(fields).Warn()
  119. default:
  120. l.logger.WithFields(fields).Error()
  121. }
  122. }
  123. func sanitizeLogEntry(s string) string {
  124. escaped := strings.ReplaceAll(s, "\n", "")
  125. return strings.ReplaceAll(escaped, "\r", "")
  126. }
  127. // realIP returns the real IP address of the client connecting to the server by
  128. // parsing either the True-Client-IP, X-Real-IP or the X-Forwarded-For headers
  129. // (in that order). If the headers are not set or set to an invalid IP, it
  130. // returns the RemoteAddr of the request.
  131. func realIP(r *http.Request) string {
  132. var ip string
  133. if tcip := r.Header.Get(trueClientIP); tcip != "" {
  134. ip = tcip
  135. } else if xrip := r.Header.Get(xRealIP); xrip != "" {
  136. ip = xrip
  137. } else if xff := r.Header.Get(xForwardedFor); xff != "" {
  138. i := strings.Index(xff, ",")
  139. if i == -1 {
  140. i = len(xff)
  141. }
  142. ip = xff[:i]
  143. }
  144. if ip == "" || net.ParseIP(ip) == nil {
  145. return r.RemoteAddr
  146. }
  147. return ip
  148. }