dataproxy.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. package api
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "net/http"
  6. "net/http/httputil"
  7. "net/url"
  8. "time"
  9. "github.com/grafana/grafana/pkg/api/cloudwatch"
  10. "github.com/grafana/grafana/pkg/api/sqldb"
  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. if ds.Type == m.DS_SQLDB {
  84. targetUrl, _ := url.Parse(ds.Url)
  85. if !checkWhiteList(c, targetUrl.Host) {
  86. return
  87. }
  88. sqldb.HandleRequest(c, ds)
  89. return
  90. }
  91. targetUrl, _ := url.Parse(ds.Url)
  92. if !checkWhiteList(c, targetUrl.Host) {
  93. return
  94. }
  95. proxyPath := c.Params("*")
  96. if ds.Type == m.DS_ES {
  97. if c.Req.Request.Method == "DELETE" {
  98. c.JsonApiErr(403, "Deletes not allowed on proxied Elasticsearch datasource", nil)
  99. return
  100. }
  101. if c.Req.Request.Method == "PUT" {
  102. c.JsonApiErr(403, "Puts not allowed on proxied Elasticsearch datasource", nil)
  103. return
  104. }
  105. if c.Req.Request.Method == "POST" && proxyPath != "_msearch" {
  106. c.JsonApiErr(403, "Posts not allowed on proxied Elasticsearch datasource except on /_msearch", nil)
  107. return
  108. }
  109. }
  110. proxy := NewReverseProxy(ds, proxyPath, targetUrl)
  111. proxy.Transport, err = ds.GetHttpTransport()
  112. if err != nil {
  113. c.JsonApiErr(400, "Unable to load TLS certificate", err)
  114. return
  115. }
  116. logProxyRequest(ds.Type, c)
  117. proxy.ServeHTTP(c.Resp, c.Req.Request)
  118. c.Resp.Header().Del("Set-Cookie")
  119. }
  120. func logProxyRequest(dataSourceType string, c *middleware.Context) {
  121. if !setting.DataProxyLogging {
  122. return
  123. }
  124. var body string
  125. if c.Req.Request.Body != nil {
  126. buffer, err := ioutil.ReadAll(c.Req.Request.Body)
  127. if err == nil {
  128. c.Req.Request.Body = ioutil.NopCloser(bytes.NewBuffer(buffer))
  129. body = string(buffer)
  130. }
  131. }
  132. dataproxyLogger.Info("Proxying incoming request",
  133. "userid", c.UserId,
  134. "orgid", c.OrgId,
  135. "username", c.Login,
  136. "datasource", dataSourceType,
  137. "uri", c.Req.RequestURI,
  138. "method", c.Req.Request.Method,
  139. "body", body)
  140. }
  141. func checkWhiteList(c *middleware.Context, host string) bool {
  142. if host != "" && len(setting.DataProxyWhiteList) > 0 {
  143. if _, exists := setting.DataProxyWhiteList[host]; !exists {
  144. c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil)
  145. return false
  146. }
  147. }
  148. return true
  149. }