ds_proxy.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. package pluginproxy
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "net"
  9. "net/http"
  10. "net/http/httputil"
  11. "net/url"
  12. "strconv"
  13. "strings"
  14. "text/template"
  15. "time"
  16. "github.com/opentracing/opentracing-go"
  17. "github.com/grafana/grafana/pkg/log"
  18. m "github.com/grafana/grafana/pkg/models"
  19. "github.com/grafana/grafana/pkg/plugins"
  20. "github.com/grafana/grafana/pkg/setting"
  21. "github.com/grafana/grafana/pkg/util"
  22. )
  23. var (
  24. logger log.Logger = log.New("data-proxy-log")
  25. client *http.Client = &http.Client{
  26. Timeout: time.Second * 30,
  27. Transport: &http.Transport{Proxy: http.ProxyFromEnvironment},
  28. }
  29. tokenCache = map[int64]*jwtToken{}
  30. )
  31. type jwtToken struct {
  32. ExpiresOn time.Time `json:"-"`
  33. ExpiresOnString string `json:"expires_on"`
  34. AccessToken string `json:"access_token"`
  35. }
  36. type DataSourceProxy struct {
  37. ds *m.DataSource
  38. ctx *m.ReqContext
  39. targetUrl *url.URL
  40. proxyPath string
  41. route *plugins.AppPluginRoute
  42. plugin *plugins.DataSourcePlugin
  43. }
  44. func NewDataSourceProxy(ds *m.DataSource, plugin *plugins.DataSourcePlugin, ctx *m.ReqContext, proxyPath string) *DataSourceProxy {
  45. targetUrl, _ := url.Parse(ds.Url)
  46. return &DataSourceProxy{
  47. ds: ds,
  48. plugin: plugin,
  49. ctx: ctx,
  50. proxyPath: proxyPath,
  51. targetUrl: targetUrl,
  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. opentracing.GlobalTracer().Inject(
  78. span.Context(),
  79. opentracing.HTTPHeaders,
  80. opentracing.HTTPHeadersCarrier(proxy.ctx.Req.Request.Header))
  81. reverseProxy.ServeHTTP(proxy.ctx.Resp, proxy.ctx.Req.Request)
  82. proxy.ctx.Resp.Header().Del("Set-Cookie")
  83. }
  84. func (proxy *DataSourceProxy) getDirector() func(req *http.Request) {
  85. return func(req *http.Request) {
  86. req.URL.Scheme = proxy.targetUrl.Scheme
  87. req.URL.Host = proxy.targetUrl.Host
  88. req.Host = proxy.targetUrl.Host
  89. reqQueryVals := req.URL.Query()
  90. if proxy.ds.Type == m.DS_INFLUXDB_08 {
  91. req.URL.Path = util.JoinUrlFragments(proxy.targetUrl.Path, "db/"+proxy.ds.Database+"/"+proxy.proxyPath)
  92. reqQueryVals.Add("u", proxy.ds.User)
  93. reqQueryVals.Add("p", proxy.ds.Password)
  94. req.URL.RawQuery = reqQueryVals.Encode()
  95. } else if proxy.ds.Type == m.DS_INFLUXDB {
  96. req.URL.Path = util.JoinUrlFragments(proxy.targetUrl.Path, proxy.proxyPath)
  97. req.URL.RawQuery = reqQueryVals.Encode()
  98. if !proxy.ds.BasicAuth {
  99. req.Header.Del("Authorization")
  100. req.Header.Add("Authorization", util.GetBasicAuthHeader(proxy.ds.User, proxy.ds.Password))
  101. }
  102. } else {
  103. req.URL.Path = util.JoinUrlFragments(proxy.targetUrl.Path, proxy.proxyPath)
  104. }
  105. if proxy.ds.BasicAuth {
  106. req.Header.Del("Authorization")
  107. req.Header.Add("Authorization", util.GetBasicAuthHeader(proxy.ds.BasicAuthUser, proxy.ds.BasicAuthPassword))
  108. }
  109. dsAuth := req.Header.Get("X-DS-Authorization")
  110. if len(dsAuth) > 0 {
  111. req.Header.Del("X-DS-Authorization")
  112. req.Header.Del("Authorization")
  113. req.Header.Add("Authorization", dsAuth)
  114. }
  115. // clear cookie header, except for whitelisted cookies
  116. var keptCookies []*http.Cookie
  117. if proxy.ds.JsonData != nil {
  118. if keepCookies := proxy.ds.JsonData.Get("keepCookies"); keepCookies != nil {
  119. keepCookieNames := keepCookies.MustStringArray()
  120. for _, c := range req.Cookies() {
  121. for _, v := range keepCookieNames {
  122. if c.Name == v {
  123. keptCookies = append(keptCookies, c)
  124. }
  125. }
  126. }
  127. }
  128. }
  129. req.Header.Del("Cookie")
  130. for _, c := range keptCookies {
  131. req.AddCookie(c)
  132. }
  133. // clear X-Forwarded Host/Port/Proto headers
  134. req.Header.Del("X-Forwarded-Host")
  135. req.Header.Del("X-Forwarded-Port")
  136. req.Header.Del("X-Forwarded-Proto")
  137. // set X-Forwarded-For header
  138. if req.RemoteAddr != "" {
  139. remoteAddr, _, err := net.SplitHostPort(req.RemoteAddr)
  140. if err != nil {
  141. remoteAddr = req.RemoteAddr
  142. }
  143. if req.Header.Get("X-Forwarded-For") != "" {
  144. req.Header.Set("X-Forwarded-For", req.Header.Get("X-Forwarded-For")+", "+remoteAddr)
  145. } else {
  146. req.Header.Set("X-Forwarded-For", remoteAddr)
  147. }
  148. }
  149. if proxy.route != nil {
  150. proxy.applyRoute(req)
  151. }
  152. }
  153. }
  154. func (proxy *DataSourceProxy) validateRequest() error {
  155. if proxy.ds.Type == m.DS_INFLUXDB {
  156. if proxy.ctx.Query("db") != proxy.ds.Database {
  157. return errors.New("Datasource is not configured to allow this database")
  158. }
  159. }
  160. if !checkWhiteList(proxy.ctx, proxy.targetUrl.Host) {
  161. return errors.New("Target url is not a valid target")
  162. }
  163. if proxy.ds.Type == m.DS_PROMETHEUS {
  164. if proxy.ctx.Req.Request.Method == "DELETE" {
  165. return errors.New("Deletes not allowed on proxied Prometheus datasource")
  166. }
  167. if proxy.ctx.Req.Request.Method == "PUT" {
  168. return errors.New("Puts not allowed on proxied Prometheus datasource")
  169. }
  170. if proxy.ctx.Req.Request.Method == "POST" && !(proxy.proxyPath == "api/v1/query" || proxy.proxyPath == "api/v1/query_range") {
  171. return errors.New("Posts not allowed on proxied Prometheus datasource except on /query and /query_range")
  172. }
  173. }
  174. if proxy.ds.Type == m.DS_ES {
  175. if proxy.ctx.Req.Request.Method == "DELETE" {
  176. return errors.New("Deletes not allowed on proxied Elasticsearch datasource")
  177. }
  178. if proxy.ctx.Req.Request.Method == "PUT" {
  179. return errors.New("Puts not allowed on proxied Elasticsearch datasource")
  180. }
  181. if proxy.ctx.Req.Request.Method == "POST" && proxy.proxyPath != "_msearch" {
  182. return errors.New("Posts not allowed on proxied Elasticsearch datasource except on /_msearch")
  183. }
  184. }
  185. // found route if there are any
  186. if len(proxy.plugin.Routes) > 0 {
  187. for _, route := range proxy.plugin.Routes {
  188. // method match
  189. if route.Method != "" && route.Method != "*" && route.Method != proxy.ctx.Req.Method {
  190. continue
  191. }
  192. if route.ReqRole.IsValid() {
  193. if !proxy.ctx.HasUserRole(route.ReqRole) {
  194. return errors.New("Plugin proxy route access denied")
  195. }
  196. }
  197. if strings.HasPrefix(proxy.proxyPath, route.Path) {
  198. proxy.route = route
  199. break
  200. }
  201. }
  202. }
  203. return nil
  204. }
  205. func (proxy *DataSourceProxy) logRequest() {
  206. if !setting.DataProxyLogging {
  207. return
  208. }
  209. var body string
  210. if proxy.ctx.Req.Request.Body != nil {
  211. buffer, err := ioutil.ReadAll(proxy.ctx.Req.Request.Body)
  212. if err == nil {
  213. proxy.ctx.Req.Request.Body = ioutil.NopCloser(bytes.NewBuffer(buffer))
  214. body = string(buffer)
  215. }
  216. }
  217. logger.Info("Proxying incoming request",
  218. "userid", proxy.ctx.UserId,
  219. "orgid", proxy.ctx.OrgId,
  220. "username", proxy.ctx.Login,
  221. "datasource", proxy.ds.Type,
  222. "uri", proxy.ctx.Req.RequestURI,
  223. "method", proxy.ctx.Req.Request.Method,
  224. "body", body)
  225. }
  226. func checkWhiteList(c *m.ReqContext, host string) bool {
  227. if host != "" && len(setting.DataProxyWhiteList) > 0 {
  228. if _, exists := setting.DataProxyWhiteList[host]; !exists {
  229. c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil)
  230. return false
  231. }
  232. }
  233. return true
  234. }
  235. func (proxy *DataSourceProxy) applyRoute(req *http.Request) {
  236. proxy.proxyPath = strings.TrimPrefix(proxy.proxyPath, proxy.route.Path)
  237. data := templateData{
  238. JsonData: proxy.ds.JsonData.Interface().(map[string]interface{}),
  239. SecureJsonData: proxy.ds.SecureJsonData.Decrypt(),
  240. }
  241. routeUrl, err := url.Parse(proxy.route.Url)
  242. if err != nil {
  243. logger.Error("Error parsing plugin route url")
  244. return
  245. }
  246. req.URL.Scheme = routeUrl.Scheme
  247. req.URL.Host = routeUrl.Host
  248. req.Host = routeUrl.Host
  249. req.URL.Path = util.JoinUrlFragments(routeUrl.Path, proxy.proxyPath)
  250. if err := addHeaders(&req.Header, proxy.route, data); err != nil {
  251. logger.Error("Failed to render plugin headers", "error", err)
  252. }
  253. if proxy.route.TokenAuth != nil {
  254. if token, err := proxy.getAccessToken(data); err != nil {
  255. logger.Error("Failed to get access token", "error", err)
  256. } else {
  257. req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
  258. }
  259. }
  260. logger.Info("Requesting", "url", req.URL.String())
  261. }
  262. func (proxy *DataSourceProxy) getAccessToken(data templateData) (string, error) {
  263. if cachedToken, found := tokenCache[proxy.ds.Id]; found {
  264. if cachedToken.ExpiresOn.After(time.Now().Add(time.Second * 10)) {
  265. logger.Info("Using token from cache")
  266. return cachedToken.AccessToken, nil
  267. }
  268. }
  269. urlInterpolated, err := interpolateString(proxy.route.TokenAuth.Url, data)
  270. if err != nil {
  271. return "", err
  272. }
  273. params := make(url.Values)
  274. for key, value := range proxy.route.TokenAuth.Params {
  275. if interpolatedParam, err := interpolateString(value, data); err != nil {
  276. return "", err
  277. } else {
  278. params.Add(key, interpolatedParam)
  279. }
  280. }
  281. getTokenReq, _ := http.NewRequest("POST", urlInterpolated, bytes.NewBufferString(params.Encode()))
  282. getTokenReq.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  283. getTokenReq.Header.Add("Content-Length", strconv.Itoa(len(params.Encode())))
  284. resp, err := client.Do(getTokenReq)
  285. if err != nil {
  286. return "", err
  287. }
  288. defer resp.Body.Close()
  289. var token jwtToken
  290. if err := json.NewDecoder(resp.Body).Decode(&token); err != nil {
  291. return "", err
  292. }
  293. expiresOnEpoch, _ := strconv.ParseInt(token.ExpiresOnString, 10, 64)
  294. token.ExpiresOn = time.Unix(expiresOnEpoch, 0)
  295. tokenCache[proxy.ds.Id] = &token
  296. logger.Info("Got new access token", "ExpiresOn", token.ExpiresOn)
  297. return token.AccessToken, nil
  298. }
  299. func interpolateString(text string, data templateData) (string, error) {
  300. t, err := template.New("content").Parse(text)
  301. if err != nil {
  302. return "", errors.New(fmt.Sprintf("Could not parse template %s.", text))
  303. }
  304. var contentBuf bytes.Buffer
  305. err = t.Execute(&contentBuf, data)
  306. if err != nil {
  307. return "", errors.New(fmt.Sprintf("Failed to execute template %s.", text))
  308. }
  309. return contentBuf.String(), nil
  310. }
  311. func addHeaders(reqHeaders *http.Header, route *plugins.AppPluginRoute, data templateData) error {
  312. for _, header := range route.Headers {
  313. interpolated, err := interpolateString(header.Content, data)
  314. if err != nil {
  315. return err
  316. }
  317. reqHeaders.Add(header.Name, interpolated)
  318. }
  319. return nil
  320. }