4
0

handler.go 4.6 KB

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