dataproxy.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. package api
  2. import (
  3. "crypto/tls"
  4. "net"
  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/bus"
  11. "github.com/grafana/grafana/pkg/metrics"
  12. "github.com/grafana/grafana/pkg/middleware"
  13. m "github.com/grafana/grafana/pkg/models"
  14. "github.com/grafana/grafana/pkg/setting"
  15. "github.com/grafana/grafana/pkg/util"
  16. )
  17. func DataProxyTransport(ds *m.DataSource) (*http.Transport, error) {
  18. transport := &http.Transport{
  19. TLSClientConfig: &tls.Config{
  20. InsecureSkipVerify: true,
  21. },
  22. Proxy: http.ProxyFromEnvironment,
  23. Dial: (&net.Dialer{
  24. Timeout: 30 * time.Second,
  25. KeepAlive: 30 * time.Second,
  26. }).Dial,
  27. TLSHandshakeTimeout: 10 * time.Second,
  28. }
  29. var tlsAuth bool
  30. var err error
  31. if ds.JsonData != nil {
  32. tlsAuth, err = ds.JsonData.Get("tlsAuth").Bool()
  33. }
  34. if err == nil && tlsAuth {
  35. transport.TLSClientConfig.InsecureSkipVerify = false
  36. decrypted := ds.SecureJsonData.Decrypt()
  37. cert, err := tls.X509KeyPair([]byte(decrypted["tlsClientCert"]), []byte(decrypted["tlsClientKey"]))
  38. if err != nil {
  39. return nil, err
  40. }
  41. transport.TLSClientConfig.Certificates = []tls.Certificate{cert}
  42. }
  43. return transport, nil
  44. }
  45. func NewReverseProxy(ds *m.DataSource, proxyPath string, targetUrl *url.URL) *httputil.ReverseProxy {
  46. director := func(req *http.Request) {
  47. req.URL.Scheme = targetUrl.Scheme
  48. req.URL.Host = targetUrl.Host
  49. req.Host = targetUrl.Host
  50. reqQueryVals := req.URL.Query()
  51. if ds.Type == m.DS_INFLUXDB_08 {
  52. req.URL.Path = util.JoinUrlFragments(targetUrl.Path, "db/"+ds.Database+"/"+proxyPath)
  53. reqQueryVals.Add("u", ds.User)
  54. reqQueryVals.Add("p", ds.Password)
  55. req.URL.RawQuery = reqQueryVals.Encode()
  56. } else if ds.Type == m.DS_INFLUXDB {
  57. req.URL.Path = util.JoinUrlFragments(targetUrl.Path, proxyPath)
  58. req.URL.RawQuery = reqQueryVals.Encode()
  59. if !ds.BasicAuth {
  60. req.Header.Del("Authorization")
  61. req.Header.Add("Authorization", util.GetBasicAuthHeader(ds.User, ds.Password))
  62. }
  63. } else {
  64. req.URL.Path = util.JoinUrlFragments(targetUrl.Path, proxyPath)
  65. }
  66. if ds.BasicAuth {
  67. req.Header.Del("Authorization")
  68. req.Header.Add("Authorization", util.GetBasicAuthHeader(ds.BasicAuthUser, ds.BasicAuthPassword))
  69. }
  70. dsAuth := req.Header.Get("X-DS-Authorization")
  71. if len(dsAuth) > 0 {
  72. req.Header.Del("X-DS-Authorization")
  73. req.Header.Del("Authorization")
  74. req.Header.Add("Authorization", dsAuth)
  75. }
  76. // clear cookie headers
  77. req.Header.Del("Cookie")
  78. req.Header.Del("Set-Cookie")
  79. }
  80. return &httputil.ReverseProxy{Director: director, FlushInterval: time.Millisecond * 200}
  81. }
  82. func getDatasource(id int64, orgId int64) (*m.DataSource, error) {
  83. query := m.GetDataSourceByIdQuery{Id: id, OrgId: orgId}
  84. if err := bus.Dispatch(&query); err != nil {
  85. return nil, err
  86. }
  87. return query.Result, nil
  88. }
  89. func ProxyDataSourceRequest(c *middleware.Context) {
  90. c.TimeRequest(metrics.M_DataSource_ProxyReq_Timer)
  91. ds, err := getDatasource(c.ParamsInt64(":id"), c.OrgId)
  92. if err != nil {
  93. c.JsonApiErr(500, "Unable to load datasource meta data", err)
  94. return
  95. }
  96. if ds.Type == m.DS_CLOUDWATCH {
  97. cloudwatch.HandleRequest(c, ds)
  98. return
  99. }
  100. if ds.Type == m.DS_INFLUXDB {
  101. if c.Query("db") != ds.Database {
  102. c.JsonApiErr(403, "Datasource is not configured to allow this database", nil)
  103. return
  104. }
  105. }
  106. targetUrl, _ := url.Parse(ds.Url)
  107. if len(setting.DataProxyWhiteList) > 0 {
  108. if _, exists := setting.DataProxyWhiteList[targetUrl.Host]; !exists {
  109. c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil)
  110. return
  111. }
  112. }
  113. proxyPath := c.Params("*")
  114. if ds.Type == m.DS_ES {
  115. if c.Req.Request.Method == "DELETE" {
  116. c.JsonApiErr(403, "Deletes not allowed on proxied Elasticsearch datasource", nil)
  117. return
  118. }
  119. if c.Req.Request.Method == "PUT" {
  120. c.JsonApiErr(403, "Puts not allowed on proxied Elasticsearch datasource", nil)
  121. return
  122. }
  123. if c.Req.Request.Method == "POST" && proxyPath != "_msearch" {
  124. c.JsonApiErr(403, "Posts not allowed on proxied Elasticsearch datasource except on /_msearch", nil)
  125. return
  126. }
  127. }
  128. proxy := NewReverseProxy(ds, proxyPath, targetUrl)
  129. proxy.Transport, err = DataProxyTransport(ds)
  130. if err != nil {
  131. c.JsonApiErr(400, "Unable to load TLS certificate", err)
  132. return
  133. }
  134. proxy.ServeHTTP(c.Resp, c.Req.Request)
  135. c.Resp.Header().Del("Set-Cookie")
  136. }