ds_proxy.go 11 KB

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