dataproxy.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. package api
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "net"
  6. "net/http"
  7. "net/http/httputil"
  8. "net/url"
  9. "strings"
  10. "time"
  11. "github.com/grafana/grafana/pkg/api/cloudwatch"
  12. "github.com/grafana/grafana/pkg/bus"
  13. "github.com/grafana/grafana/pkg/log"
  14. "github.com/grafana/grafana/pkg/metrics"
  15. "github.com/grafana/grafana/pkg/middleware"
  16. m "github.com/grafana/grafana/pkg/models"
  17. "github.com/grafana/grafana/pkg/setting"
  18. "github.com/grafana/grafana/pkg/util"
  19. )
  20. var (
  21. dataproxyLogger log.Logger = log.New("data-proxy-log")
  22. )
  23. func NewReverseProxy(ds *m.DataSource, proxyPath string, targetUrl *url.URL) *httputil.ReverseProxy {
  24. director := func(req *http.Request) {
  25. req.URL.Scheme = targetUrl.Scheme
  26. req.URL.Host = targetUrl.Host
  27. req.Host = targetUrl.Host
  28. reqQueryVals := req.URL.Query()
  29. if ds.Type == m.DS_INFLUXDB_08 {
  30. req.URL.Path = util.JoinUrlFragments(targetUrl.Path, "db/"+ds.Database+"/"+proxyPath)
  31. reqQueryVals.Add("u", ds.User)
  32. reqQueryVals.Add("p", ds.Password)
  33. req.URL.RawQuery = reqQueryVals.Encode()
  34. } else if ds.Type == m.DS_INFLUXDB {
  35. req.URL.Path = util.JoinUrlFragments(targetUrl.Path, proxyPath)
  36. req.URL.RawQuery = reqQueryVals.Encode()
  37. if !ds.BasicAuth {
  38. req.Header.Del("Authorization")
  39. req.Header.Add("Authorization", util.GetBasicAuthHeader(ds.User, ds.Password))
  40. }
  41. } else {
  42. req.URL.Path = util.JoinUrlFragments(targetUrl.Path, proxyPath)
  43. }
  44. if ds.BasicAuth {
  45. req.Header.Del("Authorization")
  46. req.Header.Add("Authorization", util.GetBasicAuthHeader(ds.BasicAuthUser, ds.BasicAuthPassword))
  47. }
  48. dsAuth := req.Header.Get("X-DS-Authorization")
  49. if len(dsAuth) > 0 {
  50. req.Header.Del("X-DS-Authorization")
  51. req.Header.Del("Authorization")
  52. req.Header.Add("Authorization", dsAuth)
  53. }
  54. // clear cookie headers
  55. req.Header.Del("Cookie")
  56. req.Header.Del("Set-Cookie")
  57. // clear X-Forwarded Host/Port/Proto headers
  58. req.Header.Del("X-Forwarded-Host")
  59. req.Header.Del("X-Forwarded-Port")
  60. req.Header.Del("X-Forwarded-Proto")
  61. // set X-Forwarded-For header
  62. if req.RemoteAddr != "" {
  63. remoteAddr, _, err := net.SplitHostPort(req.RemoteAddr)
  64. if err != nil {
  65. remoteAddr = req.RemoteAddr
  66. }
  67. if req.Header.Get("X-Forwarded-For") != "" {
  68. req.Header.Set("X-Forwarded-For", req.Header.Get("X-Forwarded-For")+", "+remoteAddr)
  69. } else {
  70. req.Header.Set("X-Forwarded-For", remoteAddr)
  71. }
  72. }
  73. // reqBytes, _ := httputil.DumpRequestOut(req, true);
  74. // log.Trace("Proxying datasource request: %s", string(reqBytes))
  75. }
  76. return &httputil.ReverseProxy{Director: director, FlushInterval: time.Millisecond * 200}
  77. }
  78. func getDatasource(id int64, orgId int64) (*m.DataSource, error) {
  79. query := m.GetDataSourceByIdQuery{Id: id, OrgId: orgId}
  80. if err := bus.Dispatch(&query); err != nil {
  81. return nil, err
  82. }
  83. return query.Result, nil
  84. }
  85. func ProxyDataSourceRequest(c *middleware.Context) {
  86. c.TimeRequest(metrics.M_DataSource_ProxyReq_Timer)
  87. ds, err := getDatasource(c.ParamsInt64(":id"), c.OrgId)
  88. if err != nil {
  89. c.JsonApiErr(500, "Unable to load datasource meta data", err)
  90. return
  91. }
  92. if ds.Type == m.DS_INFLUXDB {
  93. if c.Query("db") != ds.Database {
  94. c.JsonApiErr(403, "Datasource is not configured to allow this database", nil)
  95. return
  96. }
  97. }
  98. if ds.Type == m.DS_CLOUDWATCH {
  99. cloudwatch.HandleRequest(c, ds)
  100. return
  101. }
  102. targetUrl, _ := url.Parse(ds.Url)
  103. if !checkWhiteList(c, targetUrl.Host) {
  104. return
  105. }
  106. proxyPath := c.Params("*")
  107. if ds.Type == m.DS_PROMETHEUS {
  108. if c.Req.Request.Method != http.MethodGet || !strings.HasPrefix(proxyPath, "api/") {
  109. c.JsonApiErr(403, "GET is only allowed on proxied Prometheus datasource", nil)
  110. return
  111. }
  112. }
  113. if ds.Type == m.DS_ES {
  114. if c.Req.Request.Method == "DELETE" {
  115. c.JsonApiErr(403, "Deletes not allowed on proxied Elasticsearch datasource", nil)
  116. return
  117. }
  118. if c.Req.Request.Method == "PUT" {
  119. c.JsonApiErr(403, "Puts not allowed on proxied Elasticsearch datasource", nil)
  120. return
  121. }
  122. if c.Req.Request.Method == "POST" && proxyPath != "_msearch" {
  123. c.JsonApiErr(403, "Posts not allowed on proxied Elasticsearch datasource except on /_msearch", nil)
  124. return
  125. }
  126. }
  127. proxy := NewReverseProxy(ds, proxyPath, targetUrl)
  128. proxy.Transport, err = ds.GetHttpTransport()
  129. if err != nil {
  130. c.JsonApiErr(400, "Unable to load TLS certificate", err)
  131. return
  132. }
  133. logProxyRequest(ds.Type, c)
  134. proxy.ServeHTTP(c.Resp, c.Req.Request)
  135. c.Resp.Header().Del("Set-Cookie")
  136. }
  137. func logProxyRequest(dataSourceType string, c *middleware.Context) {
  138. if !setting.DataProxyLogging {
  139. return
  140. }
  141. var body string
  142. if c.Req.Request.Body != nil {
  143. buffer, err := ioutil.ReadAll(c.Req.Request.Body)
  144. if err == nil {
  145. c.Req.Request.Body = ioutil.NopCloser(bytes.NewBuffer(buffer))
  146. body = string(buffer)
  147. }
  148. }
  149. dataproxyLogger.Info("Proxying incoming request",
  150. "userid", c.UserId,
  151. "orgid", c.OrgId,
  152. "username", c.Login,
  153. "datasource", dataSourceType,
  154. "uri", c.Req.RequestURI,
  155. "method", c.Req.Request.Method,
  156. "body", body)
  157. }
  158. func checkWhiteList(c *middleware.Context, host string) bool {
  159. if host != "" && len(setting.DataProxyWhiteList) > 0 {
  160. if _, exists := setting.DataProxyWhiteList[host]; !exists {
  161. c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil)
  162. return false
  163. }
  164. }
  165. return true
  166. }