ds_proxy.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. package pluginproxy
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "net/http"
  9. "net/http/httputil"
  10. "net/url"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/opentracing/opentracing-go"
  15. "github.com/grafana/grafana/pkg/log"
  16. m "github.com/grafana/grafana/pkg/models"
  17. "github.com/grafana/grafana/pkg/plugins"
  18. "github.com/grafana/grafana/pkg/setting"
  19. "github.com/grafana/grafana/pkg/util"
  20. )
  21. var (
  22. logger = log.New("data-proxy-log")
  23. client = newHTTPClient()
  24. )
  25. type DataSourceProxy struct {
  26. ds *m.DataSource
  27. ctx *m.ReqContext
  28. targetUrl *url.URL
  29. proxyPath string
  30. route *plugins.AppPluginRoute
  31. plugin *plugins.DataSourcePlugin
  32. cfg *setting.Cfg
  33. }
  34. type httpClient interface {
  35. Do(req *http.Request) (*http.Response, error)
  36. }
  37. func NewDataSourceProxy(ds *m.DataSource, plugin *plugins.DataSourcePlugin, ctx *m.ReqContext, proxyPath string, cfg *setting.Cfg) *DataSourceProxy {
  38. targetURL, _ := url.Parse(ds.Url)
  39. return &DataSourceProxy{
  40. ds: ds,
  41. plugin: plugin,
  42. ctx: ctx,
  43. proxyPath: proxyPath,
  44. targetUrl: targetURL,
  45. cfg: cfg,
  46. }
  47. }
  48. func newHTTPClient() httpClient {
  49. return &http.Client{
  50. Timeout: 30 * time.Second,
  51. Transport: &http.Transport{Proxy: http.ProxyFromEnvironment},
  52. }
  53. }
  54. func (proxy *DataSourceProxy) HandleRequest() {
  55. if err := proxy.validateRequest(); err != nil {
  56. proxy.ctx.JsonApiErr(403, err.Error(), nil)
  57. return
  58. }
  59. reverseProxy := &httputil.ReverseProxy{
  60. Director: proxy.getDirector(),
  61. FlushInterval: time.Millisecond * 200,
  62. }
  63. var err error
  64. reverseProxy.Transport, err = proxy.ds.GetHttpTransport()
  65. if err != nil {
  66. proxy.ctx.JsonApiErr(400, "Unable to load TLS certificate", err)
  67. return
  68. }
  69. proxy.logRequest()
  70. span, ctx := opentracing.StartSpanFromContext(proxy.ctx.Req.Context(), "datasource reverse proxy")
  71. proxy.ctx.Req.Request = proxy.ctx.Req.WithContext(ctx)
  72. defer span.Finish()
  73. span.SetTag("datasource_id", proxy.ds.Id)
  74. span.SetTag("datasource_type", proxy.ds.Type)
  75. span.SetTag("user_id", proxy.ctx.SignedInUser.UserId)
  76. span.SetTag("org_id", proxy.ctx.SignedInUser.OrgId)
  77. proxy.addTraceFromHeaderValue(span, "X-Panel-Id", "panel_id")
  78. proxy.addTraceFromHeaderValue(span, "X-Dashboard-Id", "dashboard_id")
  79. opentracing.GlobalTracer().Inject(
  80. span.Context(),
  81. opentracing.HTTPHeaders,
  82. opentracing.HTTPHeadersCarrier(proxy.ctx.Req.Request.Header))
  83. reverseProxy.ServeHTTP(proxy.ctx.Resp, proxy.ctx.Req.Request)
  84. proxy.ctx.Resp.Header().Del("Set-Cookie")
  85. }
  86. func (proxy *DataSourceProxy) addTraceFromHeaderValue(span opentracing.Span, headerName string, tagName string) {
  87. panelId := proxy.ctx.Req.Header.Get(headerName)
  88. dashId, err := strconv.Atoi(panelId)
  89. if err == nil {
  90. span.SetTag(tagName, dashId)
  91. }
  92. }
  93. func (proxy *DataSourceProxy) useCustomHeaders(req *http.Request) {
  94. decryptSdj := proxy.ds.SecureJsonData.Decrypt()
  95. index := 1
  96. for {
  97. headerNameSuffix := fmt.Sprintf("httpHeaderName%d", index)
  98. headerValueSuffix := fmt.Sprintf("httpHeaderValue%d", index)
  99. if key := proxy.ds.JsonData.Get(headerNameSuffix).MustString(); key != "" {
  100. if val, ok := decryptSdj[headerValueSuffix]; ok {
  101. // remove if exists
  102. if req.Header.Get(key) != "" {
  103. req.Header.Del(key)
  104. }
  105. req.Header.Add(key, val)
  106. logger.Debug("Using custom header ", "CustomHeaders", key)
  107. }
  108. } else {
  109. break
  110. }
  111. index += 1
  112. }
  113. }
  114. func (proxy *DataSourceProxy) getDirector() func(req *http.Request) {
  115. return func(req *http.Request) {
  116. req.URL.Scheme = proxy.targetUrl.Scheme
  117. req.URL.Host = proxy.targetUrl.Host
  118. req.Host = proxy.targetUrl.Host
  119. reqQueryVals := req.URL.Query()
  120. if proxy.ds.Type == m.DS_INFLUXDB_08 {
  121. req.URL.Path = util.JoinURLFragments(proxy.targetUrl.Path, "db/"+proxy.ds.Database+"/"+proxy.proxyPath)
  122. reqQueryVals.Add("u", proxy.ds.User)
  123. reqQueryVals.Add("p", proxy.ds.Password)
  124. req.URL.RawQuery = reqQueryVals.Encode()
  125. } else if proxy.ds.Type == m.DS_INFLUXDB {
  126. req.URL.Path = util.JoinURLFragments(proxy.targetUrl.Path, proxy.proxyPath)
  127. req.URL.RawQuery = reqQueryVals.Encode()
  128. if !proxy.ds.BasicAuth {
  129. req.Header.Del("Authorization")
  130. req.Header.Add("Authorization", util.GetBasicAuthHeader(proxy.ds.User, proxy.ds.Password))
  131. }
  132. } else {
  133. req.URL.Path = util.JoinURLFragments(proxy.targetUrl.Path, proxy.proxyPath)
  134. }
  135. if proxy.ds.BasicAuth {
  136. req.Header.Del("Authorization")
  137. req.Header.Add("Authorization", util.GetBasicAuthHeader(proxy.ds.BasicAuthUser, proxy.ds.BasicAuthPassword))
  138. }
  139. // Lookup and use custom headers
  140. if proxy.ds.SecureJsonData != nil {
  141. proxy.useCustomHeaders(req)
  142. }
  143. dsAuth := req.Header.Get("X-DS-Authorization")
  144. if len(dsAuth) > 0 {
  145. req.Header.Del("X-DS-Authorization")
  146. req.Header.Del("Authorization")
  147. req.Header.Add("Authorization", dsAuth)
  148. }
  149. if proxy.cfg.SendUserHeader {
  150. req.Header.Add("X-Grafana-User", proxy.ctx.SignedInUser.Login)
  151. }
  152. // clear cookie header, except for whitelisted cookies
  153. var keptCookies []*http.Cookie
  154. if proxy.ds.JsonData != nil {
  155. if keepCookies := proxy.ds.JsonData.Get("keepCookies"); keepCookies != nil {
  156. keepCookieNames := keepCookies.MustStringArray()
  157. for _, c := range req.Cookies() {
  158. for _, v := range keepCookieNames {
  159. if c.Name == v {
  160. keptCookies = append(keptCookies, c)
  161. }
  162. }
  163. }
  164. }
  165. }
  166. req.Header.Del("Cookie")
  167. for _, c := range keptCookies {
  168. req.AddCookie(c)
  169. }
  170. // clear X-Forwarded Host/Port/Proto headers
  171. req.Header.Del("X-Forwarded-Host")
  172. req.Header.Del("X-Forwarded-Port")
  173. req.Header.Del("X-Forwarded-Proto")
  174. req.Header.Set("User-Agent", fmt.Sprintf("Grafana/%s", setting.BuildVersion))
  175. // Clear Origin and Referer to avoir CORS issues
  176. req.Header.Del("Origin")
  177. req.Header.Del("Referer")
  178. // set X-Forwarded-For header
  179. if req.RemoteAddr != "" {
  180. remoteAddr, _, err := net.SplitHostPort(req.RemoteAddr)
  181. if err != nil {
  182. remoteAddr = req.RemoteAddr
  183. }
  184. if req.Header.Get("X-Forwarded-For") != "" {
  185. req.Header.Set("X-Forwarded-For", req.Header.Get("X-Forwarded-For")+", "+remoteAddr)
  186. } else {
  187. req.Header.Set("X-Forwarded-For", remoteAddr)
  188. }
  189. }
  190. if proxy.route != nil {
  191. ApplyRoute(proxy.ctx.Req.Context(), req, proxy.proxyPath, proxy.route, proxy.ds)
  192. }
  193. }
  194. }
  195. func (proxy *DataSourceProxy) validateRequest() error {
  196. if !checkWhiteList(proxy.ctx, proxy.targetUrl.Host) {
  197. return errors.New("Target url is not a valid target")
  198. }
  199. if proxy.ds.Type == m.DS_PROMETHEUS {
  200. if proxy.ctx.Req.Request.Method == "DELETE" {
  201. return errors.New("Deletes not allowed on proxied Prometheus datasource")
  202. }
  203. if proxy.ctx.Req.Request.Method == "PUT" {
  204. return errors.New("Puts not allowed on proxied Prometheus datasource")
  205. }
  206. if proxy.ctx.Req.Request.Method == "POST" && !(proxy.proxyPath == "api/v1/query" || proxy.proxyPath == "api/v1/query_range") {
  207. return errors.New("Posts not allowed on proxied Prometheus datasource except on /query and /query_range")
  208. }
  209. }
  210. if proxy.ds.Type == m.DS_ES {
  211. if proxy.ctx.Req.Request.Method == "DELETE" {
  212. return errors.New("Deletes not allowed on proxied Elasticsearch datasource")
  213. }
  214. if proxy.ctx.Req.Request.Method == "PUT" {
  215. return errors.New("Puts not allowed on proxied Elasticsearch datasource")
  216. }
  217. if proxy.ctx.Req.Request.Method == "POST" && proxy.proxyPath != "_msearch" {
  218. return errors.New("Posts not allowed on proxied Elasticsearch datasource except on /_msearch")
  219. }
  220. }
  221. // found route if there are any
  222. if len(proxy.plugin.Routes) > 0 {
  223. for _, route := range proxy.plugin.Routes {
  224. // method match
  225. if route.Method != "" && route.Method != "*" && route.Method != proxy.ctx.Req.Method {
  226. continue
  227. }
  228. if route.ReqRole.IsValid() {
  229. if !proxy.ctx.HasUserRole(route.ReqRole) {
  230. return errors.New("Plugin proxy route access denied")
  231. }
  232. }
  233. if strings.HasPrefix(proxy.proxyPath, route.Path) {
  234. proxy.route = route
  235. break
  236. }
  237. }
  238. }
  239. return nil
  240. }
  241. func (proxy *DataSourceProxy) logRequest() {
  242. if !setting.DataProxyLogging {
  243. return
  244. }
  245. var body string
  246. if proxy.ctx.Req.Request.Body != nil {
  247. buffer, err := ioutil.ReadAll(proxy.ctx.Req.Request.Body)
  248. if err == nil {
  249. proxy.ctx.Req.Request.Body = ioutil.NopCloser(bytes.NewBuffer(buffer))
  250. body = string(buffer)
  251. }
  252. }
  253. logger.Info("Proxying incoming request",
  254. "userid", proxy.ctx.UserId,
  255. "orgid", proxy.ctx.OrgId,
  256. "username", proxy.ctx.Login,
  257. "datasource", proxy.ds.Type,
  258. "uri", proxy.ctx.Req.RequestURI,
  259. "method", proxy.ctx.Req.Request.Method,
  260. "body", body)
  261. }
  262. func checkWhiteList(c *m.ReqContext, host string) bool {
  263. if host != "" && len(setting.DataProxyWhiteList) > 0 {
  264. if _, exists := setting.DataProxyWhiteList[host]; !exists {
  265. c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil)
  266. return false
  267. }
  268. }
  269. return true
  270. }