dataproxy.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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/api/sqldb"
  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. }
  58. return &httputil.ReverseProxy{Director: director, FlushInterval: time.Millisecond * 200}
  59. }
  60. func getDatasource(id int64, orgId int64) (*m.DataSource, error) {
  61. query := m.GetDataSourceByIdQuery{Id: id, OrgId: orgId}
  62. if err := bus.Dispatch(&query); err != nil {
  63. return nil, err
  64. }
  65. return query.Result, nil
  66. }
  67. func ProxyDataSourceRequest(c *middleware.Context) {
  68. c.TimeRequest(metrics.M_DataSource_ProxyReq_Timer)
  69. ds, err := getDatasource(c.ParamsInt64(":id"), c.OrgId)
  70. if err != nil {
  71. c.JsonApiErr(500, "Unable to load datasource meta data", err)
  72. return
  73. }
  74. if ds.Type == m.DS_INFLUXDB {
  75. if c.Query("db") != ds.Database {
  76. c.JsonApiErr(403, "Datasource is not configured to allow this database", nil)
  77. return
  78. }
  79. }
  80. if ds.Type == m.DS_CLOUDWATCH {
  81. cloudwatch.HandleRequest(c, ds)
  82. return
  83. }
  84. if ds.Type == m.DS_SQLDB {
  85. targetUrl, _ := url.Parse(ds.Url)
  86. if !checkWhiteList(c, targetUrl.Host) {
  87. return
  88. }
  89. sqldb.HandleRequest(c, ds)
  90. return
  91. }
  92. targetUrl, _ := url.Parse(ds.Url)
  93. if !checkWhiteList(c, targetUrl.Host) {
  94. return
  95. }
  96. proxyPath := c.Params("*")
  97. if ds.Type == m.DS_PROMETHEUS {
  98. if c.Req.Request.Method != http.MethodGet || !strings.HasPrefix(proxyPath, "api/") {
  99. c.JsonApiErr(403, "GET is only allowed on proxied Prometheus datasource", nil)
  100. return
  101. }
  102. }
  103. if ds.Type == m.DS_ES {
  104. if c.Req.Request.Method == "DELETE" {
  105. c.JsonApiErr(403, "Deletes not allowed on proxied Elasticsearch datasource", nil)
  106. return
  107. }
  108. if c.Req.Request.Method == "PUT" {
  109. c.JsonApiErr(403, "Puts not allowed on proxied Elasticsearch datasource", nil)
  110. return
  111. }
  112. if c.Req.Request.Method == "POST" && proxyPath != "_msearch" {
  113. c.JsonApiErr(403, "Posts not allowed on proxied Elasticsearch datasource except on /_msearch", nil)
  114. return
  115. }
  116. }
  117. proxy := NewReverseProxy(ds, proxyPath, targetUrl)
  118. proxy.Transport, err = ds.GetHttpTransport()
  119. if err != nil {
  120. c.JsonApiErr(400, "Unable to load TLS certificate", err)
  121. return
  122. }
  123. logProxyRequest(ds.Type, c)
  124. proxy.ServeHTTP(c.Resp, c.Req.Request)
  125. c.Resp.Header().Del("Set-Cookie")
  126. }
  127. func logProxyRequest(dataSourceType string, c *middleware.Context) {
  128. if !setting.DataProxyLogging {
  129. return
  130. }
  131. var body string
  132. if c.Req.Request.Body != nil {
  133. buffer, err := ioutil.ReadAll(c.Req.Request.Body)
  134. if err == nil {
  135. c.Req.Request.Body = ioutil.NopCloser(bytes.NewBuffer(buffer))
  136. body = string(buffer)
  137. }
  138. }
  139. dataproxyLogger.Info("Proxying incoming request",
  140. "userid", c.UserId,
  141. "orgid", c.OrgId,
  142. "username", c.Login,
  143. "datasource", dataSourceType,
  144. "uri", c.Req.RequestURI,
  145. "method", c.Req.Request.Method,
  146. "body", body)
  147. }
  148. func checkWhiteList(c *middleware.Context, host string) bool {
  149. if host != "" && len(setting.DataProxyWhiteList) > 0 {
  150. if _, exists := setting.DataProxyWhiteList[host]; !exists {
  151. c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil)
  152. return false
  153. }
  154. }
  155. return true
  156. }