dataproxy.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. package api
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "net/http/httputil"
  8. "net/url"
  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. func NewReverseProxy(ds *m.DataSource, proxyPath string, targetUrl *url.URL) *httputil.ReverseProxy {
  20. director := func(req *http.Request) {
  21. req.URL.Scheme = targetUrl.Scheme
  22. req.URL.Host = targetUrl.Host
  23. req.Host = targetUrl.Host
  24. reqQueryVals := req.URL.Query()
  25. if ds.Type == m.DS_INFLUXDB_08 {
  26. req.URL.Path = util.JoinUrlFragments(targetUrl.Path, "db/"+ds.Database+"/"+proxyPath)
  27. reqQueryVals.Add("u", ds.User)
  28. reqQueryVals.Add("p", ds.Password)
  29. req.URL.RawQuery = reqQueryVals.Encode()
  30. } else if ds.Type == m.DS_INFLUXDB {
  31. req.URL.Path = util.JoinUrlFragments(targetUrl.Path, proxyPath)
  32. req.URL.RawQuery = reqQueryVals.Encode()
  33. if !ds.BasicAuth {
  34. req.Header.Del("Authorization")
  35. req.Header.Add("Authorization", util.GetBasicAuthHeader(ds.User, ds.Password))
  36. }
  37. } else {
  38. req.URL.Path = util.JoinUrlFragments(targetUrl.Path, proxyPath)
  39. }
  40. if ds.BasicAuth {
  41. req.Header.Del("Authorization")
  42. req.Header.Add("Authorization", util.GetBasicAuthHeader(ds.BasicAuthUser, ds.BasicAuthPassword))
  43. }
  44. dsAuth := req.Header.Get("X-DS-Authorization")
  45. if len(dsAuth) > 0 {
  46. req.Header.Del("X-DS-Authorization")
  47. req.Header.Del("Authorization")
  48. req.Header.Add("Authorization", dsAuth)
  49. }
  50. // clear cookie headers
  51. req.Header.Del("Cookie")
  52. req.Header.Del("Set-Cookie")
  53. }
  54. return &httputil.ReverseProxy{Director: director, FlushInterval: time.Millisecond * 200}
  55. }
  56. func getDatasource(id int64, orgId int64) (*m.DataSource, error) {
  57. query := m.GetDataSourceByIdQuery{Id: id, OrgId: orgId}
  58. if err := bus.Dispatch(&query); err != nil {
  59. return nil, err
  60. }
  61. return query.Result, nil
  62. }
  63. func ProxyDataSourceRequest(c *middleware.Context) {
  64. c.TimeRequest(metrics.M_DataSource_ProxyReq_Timer)
  65. ds, err := getDatasource(c.ParamsInt64(":id"), c.OrgId)
  66. if err != nil {
  67. c.JsonApiErr(500, "Unable to load datasource meta data", err)
  68. return
  69. }
  70. if ds.Type == m.DS_CLOUDWATCH {
  71. cloudwatch.HandleRequest(c, ds)
  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. targetUrl, _ := url.Parse(ds.Url)
  81. if len(setting.DataProxyWhiteList) > 0 {
  82. if _, exists := setting.DataProxyWhiteList[targetUrl.Host]; !exists {
  83. c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil)
  84. return
  85. }
  86. }
  87. proxyPath := c.Params("*")
  88. if ds.Type == m.DS_ES {
  89. if c.Req.Request.Method == "DELETE" {
  90. c.JsonApiErr(403, "Deletes not allowed on proxied Elasticsearch datasource", nil)
  91. return
  92. }
  93. if c.Req.Request.Method == "PUT" {
  94. c.JsonApiErr(403, "Puts not allowed on proxied Elasticsearch datasource", nil)
  95. return
  96. }
  97. if c.Req.Request.Method == "POST" && proxyPath != "_msearch" {
  98. c.JsonApiErr(403, "Posts not allowed on proxied Elasticsearch datasource except on /_msearch", nil)
  99. return
  100. }
  101. }
  102. outputToAuditLog(ds.Type, c)
  103. proxy := NewReverseProxy(ds, proxyPath, targetUrl)
  104. proxy.Transport, err = ds.GetHttpTransport()
  105. if err != nil {
  106. c.JsonApiErr(400, "Unable to load TLS certificate", err)
  107. return
  108. }
  109. proxy.ServeHTTP(c.Resp, c.Req.Request)
  110. c.Resp.Header().Del("Set-Cookie")
  111. }
  112. func outputToAuditLog(dataSourceType string, c *middleware.Context) {
  113. auditLogger := log.New("data-proxy-audit", "userId", c.UserId, "orgId", c.OrgId, "uname", c.Login)
  114. bodyString := ""
  115. if c.Req.Request.Body != nil {
  116. reqBody := c.Req.Request.Body
  117. buffer, _ := ioutil.ReadAll(reqBody)
  118. c.Req.Request.Body = ioutil.NopCloser(bytes.NewBuffer(buffer))
  119. bodyString = string(buffer)
  120. }
  121. logFormat := "Datasource: %s, URI: %s, Method: %s, Body: %s"
  122. auditLogger.Info(fmt.Sprintf(logFormat, dataSourceType, c.Req.RequestURI, c.Req.Request.Method, bodyString))
  123. }