ds_proxy.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. package pluginproxy
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "html/template"
  7. "io/ioutil"
  8. "net"
  9. "net/http"
  10. "net/http/httputil"
  11. "net/url"
  12. "strings"
  13. "time"
  14. "github.com/grafana/grafana/pkg/api/cloudwatch"
  15. "github.com/grafana/grafana/pkg/log"
  16. "github.com/grafana/grafana/pkg/middleware"
  17. m "github.com/grafana/grafana/pkg/models"
  18. "github.com/grafana/grafana/pkg/plugins"
  19. "github.com/grafana/grafana/pkg/setting"
  20. "github.com/grafana/grafana/pkg/util"
  21. )
  22. var (
  23. logger log.Logger = log.New("data-proxy-log")
  24. )
  25. type DataSourceProxy struct {
  26. ds *m.DataSource
  27. ctx *middleware.Context
  28. targetUrl *url.URL
  29. proxyPath string
  30. route *plugins.AppPluginRoute
  31. }
  32. func NewDataSourceProxy(ds *m.DataSource, ctx *middleware.Context, proxyPath string) *DataSourceProxy {
  33. return &DataSourceProxy{
  34. ds: ds,
  35. ctx: ctx,
  36. proxyPath: proxyPath,
  37. }
  38. }
  39. func (proxy *DataSourceProxy) HandleRequest() {
  40. if proxy.ds.Type == m.DS_CLOUDWATCH {
  41. cloudwatch.HandleRequest(proxy.ctx, proxy.ds)
  42. return
  43. }
  44. if err := proxy.validateRequest(); err != nil {
  45. proxy.ctx.JsonApiErr(403, err.Error(), nil)
  46. return
  47. }
  48. reverseProxy := &httputil.ReverseProxy{
  49. Director: proxy.getDirector(),
  50. FlushInterval: time.Millisecond * 200,
  51. }
  52. var err error
  53. reverseProxy.Transport, err = proxy.ds.GetHttpTransport()
  54. if err != nil {
  55. proxy.ctx.JsonApiErr(400, "Unable to load TLS certificate", err)
  56. return
  57. }
  58. proxy.logRequest()
  59. reverseProxy.ServeHTTP(proxy.ctx.Resp, proxy.ctx.Req.Request)
  60. proxy.ctx.Resp.Header().Del("Set-Cookie")
  61. }
  62. func (proxy *DataSourceProxy) getDirector() func(req *http.Request) {
  63. return func(req *http.Request) {
  64. req.URL.Scheme = proxy.targetUrl.Scheme
  65. req.URL.Host = proxy.targetUrl.Host
  66. req.Host = proxy.targetUrl.Host
  67. reqQueryVals := req.URL.Query()
  68. if proxy.ds.Type == m.DS_INFLUXDB_08 {
  69. req.URL.Path = util.JoinUrlFragments(proxy.targetUrl.Path, "db/"+proxy.ds.Database+"/"+proxy.proxyPath)
  70. reqQueryVals.Add("u", proxy.ds.User)
  71. reqQueryVals.Add("p", proxy.ds.Password)
  72. req.URL.RawQuery = reqQueryVals.Encode()
  73. } else if proxy.ds.Type == m.DS_INFLUXDB {
  74. req.URL.Path = util.JoinUrlFragments(proxy.targetUrl.Path, proxy.proxyPath)
  75. req.URL.RawQuery = reqQueryVals.Encode()
  76. if !proxy.ds.BasicAuth {
  77. req.Header.Del("Authorization")
  78. req.Header.Add("Authorization", util.GetBasicAuthHeader(proxy.ds.User, proxy.ds.Password))
  79. }
  80. } else {
  81. req.URL.Path = util.JoinUrlFragments(proxy.targetUrl.Path, proxy.proxyPath)
  82. }
  83. if proxy.ds.BasicAuth {
  84. req.Header.Del("Authorization")
  85. req.Header.Add("Authorization", util.GetBasicAuthHeader(proxy.ds.BasicAuthUser, proxy.ds.BasicAuthPassword))
  86. }
  87. dsAuth := req.Header.Get("X-DS-Authorization")
  88. if len(dsAuth) > 0 {
  89. req.Header.Del("X-DS-Authorization")
  90. req.Header.Del("Authorization")
  91. req.Header.Add("Authorization", dsAuth)
  92. }
  93. // clear cookie headers
  94. req.Header.Del("Cookie")
  95. req.Header.Del("Set-Cookie")
  96. // clear X-Forwarded Host/Port/Proto headers
  97. req.Header.Del("X-Forwarded-Host")
  98. req.Header.Del("X-Forwarded-Port")
  99. req.Header.Del("X-Forwarded-Proto")
  100. // set X-Forwarded-For header
  101. if req.RemoteAddr != "" {
  102. remoteAddr, _, err := net.SplitHostPort(req.RemoteAddr)
  103. if err != nil {
  104. remoteAddr = req.RemoteAddr
  105. }
  106. if req.Header.Get("X-Forwarded-For") != "" {
  107. req.Header.Set("X-Forwarded-For", req.Header.Get("X-Forwarded-For")+", "+remoteAddr)
  108. } else {
  109. req.Header.Set("X-Forwarded-For", remoteAddr)
  110. }
  111. }
  112. if proxy.route != nil {
  113. proxy.applyRoute(req)
  114. }
  115. }
  116. }
  117. func (proxy *DataSourceProxy) validateRequest() error {
  118. if proxy.ds.Type == m.DS_INFLUXDB {
  119. if proxy.ctx.Query("db") != proxy.ds.Database {
  120. return errors.New("Datasource is not configured to allow this database")
  121. }
  122. }
  123. targetUrl, _ := url.Parse(proxy.ds.Url)
  124. if !checkWhiteList(proxy.ctx, targetUrl.Host) {
  125. return errors.New("Target url is not a valid target")
  126. }
  127. if proxy.ds.Type == m.DS_PROMETHEUS {
  128. if proxy.ctx.Req.Request.Method != http.MethodGet || !strings.HasPrefix(proxy.proxyPath, "api/") {
  129. return errors.New("GET is only allowed on proxied Prometheus datasource")
  130. }
  131. }
  132. if proxy.ds.Type == m.DS_ES {
  133. if proxy.ctx.Req.Request.Method == "DELETE" {
  134. return errors.New("Deletes not allowed on proxied Elasticsearch datasource")
  135. }
  136. if proxy.ctx.Req.Request.Method == "PUT" {
  137. return errors.New("Puts not allowed on proxied Elasticsearch datasource")
  138. }
  139. if proxy.ctx.Req.Request.Method == "POST" && proxy.proxyPath != "_msearch" {
  140. return errors.New("Posts not allowed on proxied Elasticsearch datasource except on /_msearch")
  141. }
  142. }
  143. // found route if there are any
  144. if plugin, ok := plugins.DataSources[proxy.ds.Type]; ok {
  145. if len(plugin.Routes) > 0 {
  146. for _, route := range plugin.Routes {
  147. // method match
  148. if route.Method != "*" && route.Method != proxy.ctx.Req.Method {
  149. continue
  150. }
  151. if strings.HasPrefix(proxy.proxyPath, route.Path) {
  152. logger.Info("Apply Route Rule", "rule", route.Path)
  153. proxy.proxyPath = strings.TrimPrefix(proxy.proxyPath, route.Path)
  154. proxy.route = route
  155. break
  156. }
  157. }
  158. }
  159. }
  160. proxy.targetUrl = targetUrl
  161. return nil
  162. }
  163. func (proxy *DataSourceProxy) logRequest() {
  164. if !setting.DataProxyLogging {
  165. return
  166. }
  167. var body string
  168. if proxy.ctx.Req.Request.Body != nil {
  169. buffer, err := ioutil.ReadAll(proxy.ctx.Req.Request.Body)
  170. if err == nil {
  171. proxy.ctx.Req.Request.Body = ioutil.NopCloser(bytes.NewBuffer(buffer))
  172. body = string(buffer)
  173. }
  174. }
  175. logger.Info("Proxying incoming request",
  176. "userid", proxy.ctx.UserId,
  177. "orgid", proxy.ctx.OrgId,
  178. "username", proxy.ctx.Login,
  179. "datasource", proxy.ds.Type,
  180. "uri", proxy.ctx.Req.RequestURI,
  181. "method", proxy.ctx.Req.Request.Method,
  182. "body", body)
  183. }
  184. func checkWhiteList(c *middleware.Context, host string) bool {
  185. if host != "" && len(setting.DataProxyWhiteList) > 0 {
  186. if _, exists := setting.DataProxyWhiteList[host]; !exists {
  187. c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil)
  188. return false
  189. }
  190. }
  191. return true
  192. }
  193. func (proxy *DataSourceProxy) applyRoute(req *http.Request) {
  194. logger.Info("ApplyDataSourceRouteRules", "route", proxy.route.Path, "proxyPath", proxy.proxyPath)
  195. data := templateData{
  196. JsonData: proxy.ds.JsonData.Interface().(map[string]interface{}),
  197. SecureJsonData: proxy.ds.SecureJsonData.Decrypt(),
  198. }
  199. logger.Info("Apply Route Rule", "rule", proxy.route.Path)
  200. routeUrl, err := url.Parse(proxy.route.Url)
  201. if err != nil {
  202. logger.Error("Error parsing plugin route url")
  203. return
  204. }
  205. req.URL.Scheme = routeUrl.Scheme
  206. req.URL.Host = routeUrl.Host
  207. req.Host = routeUrl.Host
  208. req.URL.Path = util.JoinUrlFragments(routeUrl.Path, proxy.proxyPath)
  209. if err := addHeaders(&req.Header, proxy.route, data); err != nil {
  210. logger.Error("Failed to render plugin headers", "error", err)
  211. }
  212. }
  213. func addHeaders(reqHeaders *http.Header, route *plugins.AppPluginRoute, data templateData) error {
  214. for _, header := range route.Headers {
  215. var contentBuf bytes.Buffer
  216. t, err := template.New("content").Parse(header.Content)
  217. if err != nil {
  218. return errors.New(fmt.Sprintf("could not parse header content template for header %s.", header.Name))
  219. }
  220. err = t.Execute(&contentBuf, data)
  221. if err != nil {
  222. return errors.New(fmt.Sprintf("failed to execute header content template for header %s.", header.Name))
  223. }
  224. value := contentBuf.String()
  225. logger.Info("Adding headers", "name", header.Name, "value", value)
  226. reqHeaders.Add(header.Name, value)
  227. }
  228. return nil
  229. }