ds_proxy.go 7.5 KB

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