ds_proxy.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. 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. 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. // clear cookie header, except for whitelisted cookies
  150. var keptCookies []*http.Cookie
  151. if proxy.ds.JsonData != nil {
  152. if keepCookies := proxy.ds.JsonData.Get("keepCookies"); keepCookies != nil {
  153. keepCookieNames := keepCookies.MustStringArray()
  154. for _, c := range req.Cookies() {
  155. for _, v := range keepCookieNames {
  156. if c.Name == v {
  157. keptCookies = append(keptCookies, c)
  158. }
  159. }
  160. }
  161. }
  162. }
  163. req.Header.Del("Cookie")
  164. for _, c := range keptCookies {
  165. req.AddCookie(c)
  166. }
  167. // clear X-Forwarded Host/Port/Proto headers
  168. req.Header.Del("X-Forwarded-Host")
  169. req.Header.Del("X-Forwarded-Port")
  170. req.Header.Del("X-Forwarded-Proto")
  171. // set X-Forwarded-For header
  172. if req.RemoteAddr != "" {
  173. remoteAddr, _, err := net.SplitHostPort(req.RemoteAddr)
  174. if err != nil {
  175. remoteAddr = req.RemoteAddr
  176. }
  177. if req.Header.Get("X-Forwarded-For") != "" {
  178. req.Header.Set("X-Forwarded-For", req.Header.Get("X-Forwarded-For")+", "+remoteAddr)
  179. } else {
  180. req.Header.Set("X-Forwarded-For", remoteAddr)
  181. }
  182. }
  183. if proxy.route != nil {
  184. proxy.applyRoute(req)
  185. }
  186. }
  187. }
  188. func (proxy *DataSourceProxy) validateRequest() error {
  189. if !checkWhiteList(proxy.ctx, proxy.targetUrl.Host) {
  190. return errors.New("Target url is not a valid target")
  191. }
  192. if proxy.ds.Type == m.DS_PROMETHEUS {
  193. if proxy.ctx.Req.Request.Method == "DELETE" {
  194. return errors.New("Deletes not allowed on proxied Prometheus datasource")
  195. }
  196. if proxy.ctx.Req.Request.Method == "PUT" {
  197. return errors.New("Puts not allowed on proxied Prometheus datasource")
  198. }
  199. if proxy.ctx.Req.Request.Method == "POST" && !(proxy.proxyPath == "api/v1/query" || proxy.proxyPath == "api/v1/query_range") {
  200. return errors.New("Posts not allowed on proxied Prometheus datasource except on /query and /query_range")
  201. }
  202. }
  203. if proxy.ds.Type == m.DS_ES {
  204. if proxy.ctx.Req.Request.Method == "DELETE" {
  205. return errors.New("Deletes not allowed on proxied Elasticsearch datasource")
  206. }
  207. if proxy.ctx.Req.Request.Method == "PUT" {
  208. return errors.New("Puts not allowed on proxied Elasticsearch datasource")
  209. }
  210. if proxy.ctx.Req.Request.Method == "POST" && proxy.proxyPath != "_msearch" {
  211. return errors.New("Posts not allowed on proxied Elasticsearch datasource except on /_msearch")
  212. }
  213. }
  214. // found route if there are any
  215. if len(proxy.plugin.Routes) > 0 {
  216. for _, route := range proxy.plugin.Routes {
  217. // method match
  218. if route.Method != "" && route.Method != "*" && route.Method != proxy.ctx.Req.Method {
  219. continue
  220. }
  221. if route.ReqRole.IsValid() {
  222. if !proxy.ctx.HasUserRole(route.ReqRole) {
  223. return errors.New("Plugin proxy route access denied")
  224. }
  225. }
  226. if strings.HasPrefix(proxy.proxyPath, route.Path) {
  227. proxy.route = route
  228. break
  229. }
  230. }
  231. }
  232. return nil
  233. }
  234. func (proxy *DataSourceProxy) logRequest() {
  235. if !setting.DataProxyLogging {
  236. return
  237. }
  238. var body string
  239. if proxy.ctx.Req.Request.Body != nil {
  240. buffer, err := ioutil.ReadAll(proxy.ctx.Req.Request.Body)
  241. if err == nil {
  242. proxy.ctx.Req.Request.Body = ioutil.NopCloser(bytes.NewBuffer(buffer))
  243. body = string(buffer)
  244. }
  245. }
  246. logger.Info("Proxying incoming request",
  247. "userid", proxy.ctx.UserId,
  248. "orgid", proxy.ctx.OrgId,
  249. "username", proxy.ctx.Login,
  250. "datasource", proxy.ds.Type,
  251. "uri", proxy.ctx.Req.RequestURI,
  252. "method", proxy.ctx.Req.Request.Method,
  253. "body", body)
  254. }
  255. func checkWhiteList(c *m.ReqContext, host string) bool {
  256. if host != "" && len(setting.DataProxyWhiteList) > 0 {
  257. if _, exists := setting.DataProxyWhiteList[host]; !exists {
  258. c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil)
  259. return false
  260. }
  261. }
  262. return true
  263. }
  264. func (proxy *DataSourceProxy) applyRoute(req *http.Request) {
  265. proxy.proxyPath = strings.TrimPrefix(proxy.proxyPath, proxy.route.Path)
  266. data := templateData{
  267. JsonData: proxy.ds.JsonData.Interface().(map[string]interface{}),
  268. SecureJsonData: proxy.ds.SecureJsonData.Decrypt(),
  269. }
  270. routeURL, err := url.Parse(proxy.route.Url)
  271. if err != nil {
  272. logger.Error("Error parsing plugin route url")
  273. return
  274. }
  275. req.URL.Scheme = routeURL.Scheme
  276. req.URL.Host = routeURL.Host
  277. req.Host = routeURL.Host
  278. req.URL.Path = util.JoinUrlFragments(routeURL.Path, proxy.proxyPath)
  279. if err := addHeaders(&req.Header, proxy.route, data); err != nil {
  280. logger.Error("Failed to render plugin headers", "error", err)
  281. }
  282. if proxy.route.TokenAuth != nil {
  283. if token, err := proxy.getAccessToken(data); err != nil {
  284. logger.Error("Failed to get access token", "error", err)
  285. } else {
  286. req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
  287. }
  288. }
  289. logger.Info("Requesting", "url", req.URL.String())
  290. }
  291. func (proxy *DataSourceProxy) getAccessToken(data templateData) (string, error) {
  292. if cachedToken, found := tokenCache[proxy.ds.Id]; found {
  293. if cachedToken.ExpiresOn.After(time.Now().Add(time.Second * 10)) {
  294. logger.Info("Using token from cache")
  295. return cachedToken.AccessToken, nil
  296. }
  297. }
  298. urlInterpolated, err := interpolateString(proxy.route.TokenAuth.Url, data)
  299. if err != nil {
  300. return "", err
  301. }
  302. params := make(url.Values)
  303. for key, value := range proxy.route.TokenAuth.Params {
  304. interpolatedParam, err := interpolateString(value, data)
  305. if err != nil {
  306. return "", err
  307. }
  308. params.Add(key, interpolatedParam)
  309. }
  310. getTokenReq, _ := http.NewRequest("POST", urlInterpolated, bytes.NewBufferString(params.Encode()))
  311. getTokenReq.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  312. getTokenReq.Header.Add("Content-Length", strconv.Itoa(len(params.Encode())))
  313. resp, err := client.Do(getTokenReq)
  314. if err != nil {
  315. return "", err
  316. }
  317. defer resp.Body.Close()
  318. var token jwtToken
  319. if err := json.NewDecoder(resp.Body).Decode(&token); err != nil {
  320. return "", err
  321. }
  322. expiresOnEpoch, _ := strconv.ParseInt(token.ExpiresOnString, 10, 64)
  323. token.ExpiresOn = time.Unix(expiresOnEpoch, 0)
  324. tokenCache[proxy.ds.Id] = &token
  325. logger.Info("Got new access token", "ExpiresOn", token.ExpiresOn)
  326. return token.AccessToken, nil
  327. }
  328. func interpolateString(text string, data templateData) (string, error) {
  329. t, err := template.New("content").Parse(text)
  330. if err != nil {
  331. return "", fmt.Errorf("could not parse template %s", text)
  332. }
  333. var contentBuf bytes.Buffer
  334. err = t.Execute(&contentBuf, data)
  335. if err != nil {
  336. return "", fmt.Errorf("failed to execute template %s", text)
  337. }
  338. return contentBuf.String(), nil
  339. }
  340. func addHeaders(reqHeaders *http.Header, route *plugins.AppPluginRoute, data templateData) error {
  341. for _, header := range route.Headers {
  342. interpolated, err := interpolateString(header.Content, data)
  343. if err != nil {
  344. return err
  345. }
  346. reqHeaders.Add(header.Name, interpolated)
  347. }
  348. return nil
  349. }