dataproxy.go 4.5 KB

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