dataproxy.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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_CLOUDWATCH {
  74. cloudwatch.HandleRequest(c, ds)
  75. return
  76. }
  77. if ds.Type == m.DS_INFLUXDB {
  78. if c.Query("db") != ds.Database {
  79. c.JsonApiErr(403, "Datasource is not configured to allow this database", nil)
  80. return
  81. }
  82. }
  83. targetUrl, _ := url.Parse(ds.Url)
  84. if len(setting.DataProxyWhiteList) > 0 {
  85. if _, exists := setting.DataProxyWhiteList[targetUrl.Host]; !exists {
  86. c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil)
  87. return
  88. }
  89. }
  90. proxyPath := c.Params("*")
  91. if ds.Type == m.DS_PROMETHEUS {
  92. if !(c.Req.Request.Method == "GET" && strings.Index(proxyPath, "api/") == 0) {
  93. c.JsonApiErr(403, "GET is only allowed on proxied Prometheus datasource", nil)
  94. return
  95. }
  96. }
  97. if ds.Type == m.DS_ES {
  98. if c.Req.Request.Method == "DELETE" {
  99. c.JsonApiErr(403, "Deletes not allowed on proxied Elasticsearch datasource", nil)
  100. return
  101. }
  102. if c.Req.Request.Method == "PUT" {
  103. c.JsonApiErr(403, "Puts not allowed on proxied Elasticsearch datasource", nil)
  104. return
  105. }
  106. if c.Req.Request.Method == "POST" && proxyPath != "_msearch" {
  107. c.JsonApiErr(403, "Posts not allowed on proxied Elasticsearch datasource except on /_msearch", nil)
  108. return
  109. }
  110. }
  111. proxy := NewReverseProxy(ds, proxyPath, targetUrl)
  112. proxy.Transport, err = ds.GetHttpTransport()
  113. if err != nil {
  114. c.JsonApiErr(400, "Unable to load TLS certificate", err)
  115. return
  116. }
  117. logProxyRequest(ds.Type, c)
  118. proxy.ServeHTTP(c.Resp, c.Req.Request)
  119. c.Resp.Header().Del("Set-Cookie")
  120. }
  121. func logProxyRequest(dataSourceType string, c *middleware.Context) {
  122. if !setting.DataProxyLogging {
  123. return
  124. }
  125. var body string
  126. if c.Req.Request.Body != nil {
  127. buffer, err := ioutil.ReadAll(c.Req.Request.Body)
  128. if err == nil {
  129. c.Req.Request.Body = ioutil.NopCloser(bytes.NewBuffer(buffer))
  130. body = string(buffer)
  131. }
  132. }
  133. dataproxyLogger.Info("Proxying incoming request",
  134. "userid", c.UserId,
  135. "orgid", c.OrgId,
  136. "username", c.Login,
  137. "datasource", dataSourceType,
  138. "uri", c.Req.RequestURI,
  139. "method", c.Req.Request.Method,
  140. "body", body)
  141. }