ds_proxy.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. client = newHTTPClient()
  27. )
  28. type jwtToken struct {
  29. ExpiresOn time.Time `json:"-"`
  30. ExpiresOnString string `json:"expires_on"`
  31. AccessToken string `json:"access_token"`
  32. }
  33. type DataSourceProxy struct {
  34. ds *m.DataSource
  35. ctx *m.ReqContext
  36. targetUrl *url.URL
  37. proxyPath string
  38. route *plugins.AppPluginRoute
  39. plugin *plugins.DataSourcePlugin
  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. }
  53. }
  54. func newHTTPClient() httpClient {
  55. return &http.Client{
  56. Timeout: time.Second * 30,
  57. Transport: &http.Transport{Proxy: http.ProxyFromEnvironment},
  58. }
  59. }
  60. func (proxy *DataSourceProxy) HandleRequest() {
  61. if err := proxy.validateRequest(); err != nil {
  62. proxy.ctx.JsonApiErr(403, err.Error(), nil)
  63. return
  64. }
  65. reverseProxy := &httputil.ReverseProxy{
  66. Director: proxy.getDirector(),
  67. FlushInterval: time.Millisecond * 200,
  68. }
  69. var err error
  70. reverseProxy.Transport, err = proxy.ds.GetHttpTransport()
  71. if err != nil {
  72. proxy.ctx.JsonApiErr(400, "Unable to load TLS certificate", err)
  73. return
  74. }
  75. proxy.logRequest()
  76. span, ctx := opentracing.StartSpanFromContext(proxy.ctx.Req.Context(), "datasource reverse proxy")
  77. proxy.ctx.Req.Request = proxy.ctx.Req.WithContext(ctx)
  78. defer span.Finish()
  79. span.SetTag("datasource_id", proxy.ds.Id)
  80. span.SetTag("datasource_type", proxy.ds.Type)
  81. span.SetTag("user_id", proxy.ctx.SignedInUser.UserId)
  82. span.SetTag("org_id", proxy.ctx.SignedInUser.OrgId)
  83. proxy.addTraceFromHeaderValue(span, "X-Panel-Id", "panel_id")
  84. proxy.addTraceFromHeaderValue(span, "X-Dashboard-Id", "dashboard_id")
  85. opentracing.GlobalTracer().Inject(
  86. span.Context(),
  87. opentracing.HTTPHeaders,
  88. opentracing.HTTPHeadersCarrier(proxy.ctx.Req.Request.Header))
  89. reverseProxy.ServeHTTP(proxy.ctx.Resp, proxy.ctx.Req.Request)
  90. proxy.ctx.Resp.Header().Del("Set-Cookie")
  91. }
  92. func (proxy *DataSourceProxy) addTraceFromHeaderValue(span opentracing.Span, headerName string, tagName string) {
  93. panelId := proxy.ctx.Req.Header.Get(headerName)
  94. dashId, err := strconv.Atoi(panelId)
  95. if err == nil {
  96. span.SetTag(tagName, dashId)
  97. }
  98. }
  99. func (proxy *DataSourceProxy) useCustomHeaders(req *http.Request) {
  100. decryptSdj := proxy.ds.SecureJsonData.Decrypt()
  101. index := 1
  102. for {
  103. headerNameSuffix := fmt.Sprintf("httpHeaderName%d", index)
  104. headerValueSuffix := fmt.Sprintf("httpHeaderValue%d", index)
  105. if key := proxy.ds.JsonData.Get(headerNameSuffix).MustString(); key != "" {
  106. if val, ok := decryptSdj[headerValueSuffix]; ok {
  107. // remove if exists
  108. if req.Header.Get(key) != "" {
  109. req.Header.Del(key)
  110. }
  111. req.Header.Add(key, val)
  112. logger.Debug("Using custom header ", "CustomHeaders", key)
  113. }
  114. } else {
  115. break
  116. }
  117. index += 1
  118. }
  119. }
  120. func (proxy *DataSourceProxy) getDirector() func(req *http.Request) {
  121. return func(req *http.Request) {
  122. req.URL.Scheme = proxy.targetUrl.Scheme
  123. req.URL.Host = proxy.targetUrl.Host
  124. req.Host = proxy.targetUrl.Host
  125. reqQueryVals := req.URL.Query()
  126. if proxy.ds.Type == m.DS_INFLUXDB_08 {
  127. req.URL.Path = util.JoinUrlFragments(proxy.targetUrl.Path, "db/"+proxy.ds.Database+"/"+proxy.proxyPath)
  128. reqQueryVals.Add("u", proxy.ds.User)
  129. reqQueryVals.Add("p", proxy.ds.Password)
  130. req.URL.RawQuery = reqQueryVals.Encode()
  131. } else if proxy.ds.Type == m.DS_INFLUXDB {
  132. req.URL.Path = util.JoinUrlFragments(proxy.targetUrl.Path, proxy.proxyPath)
  133. req.URL.RawQuery = reqQueryVals.Encode()
  134. if !proxy.ds.BasicAuth {
  135. req.Header.Del("Authorization")
  136. req.Header.Add("Authorization", util.GetBasicAuthHeader(proxy.ds.User, proxy.ds.Password))
  137. }
  138. } else {
  139. req.URL.Path = util.JoinUrlFragments(proxy.targetUrl.Path, proxy.proxyPath)
  140. }
  141. if proxy.ds.BasicAuth {
  142. req.Header.Del("Authorization")
  143. req.Header.Add("Authorization", util.GetBasicAuthHeader(proxy.ds.BasicAuthUser, proxy.ds.BasicAuthPassword))
  144. }
  145. // Lookup and use custom headers
  146. if proxy.ds.SecureJsonData != nil {
  147. proxy.useCustomHeaders(req)
  148. }
  149. dsAuth := req.Header.Get("X-DS-Authorization")
  150. if len(dsAuth) > 0 {
  151. req.Header.Del("X-DS-Authorization")
  152. req.Header.Del("Authorization")
  153. req.Header.Add("Authorization", dsAuth)
  154. }
  155. // clear cookie header, except for whitelisted cookies
  156. var keptCookies []*http.Cookie
  157. if proxy.ds.JsonData != nil {
  158. if keepCookies := proxy.ds.JsonData.Get("keepCookies"); keepCookies != nil {
  159. keepCookieNames := keepCookies.MustStringArray()
  160. for _, c := range req.Cookies() {
  161. for _, v := range keepCookieNames {
  162. if c.Name == v {
  163. keptCookies = append(keptCookies, c)
  164. }
  165. }
  166. }
  167. }
  168. }
  169. req.Header.Del("Cookie")
  170. for _, c := range keptCookies {
  171. req.AddCookie(c)
  172. }
  173. // clear X-Forwarded Host/Port/Proto headers
  174. req.Header.Del("X-Forwarded-Host")
  175. req.Header.Del("X-Forwarded-Port")
  176. req.Header.Del("X-Forwarded-Proto")
  177. req.Header.Set("User-Agent", fmt.Sprintf("Grafana/%s", setting.BuildVersion))
  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. proxy.applyRoute(req)
  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. }
  271. func (proxy *DataSourceProxy) applyRoute(req *http.Request) {
  272. proxy.proxyPath = strings.TrimPrefix(proxy.proxyPath, proxy.route.Path)
  273. data := templateData{
  274. JsonData: proxy.ds.JsonData.Interface().(map[string]interface{}),
  275. SecureJsonData: proxy.ds.SecureJsonData.Decrypt(),
  276. }
  277. interpolatedURL, err := interpolateString(proxy.route.Url, data)
  278. if err != nil {
  279. logger.Error("Error interpolating proxy url", "error", err)
  280. return
  281. }
  282. routeURL, err := url.Parse(interpolatedURL)
  283. if err != nil {
  284. logger.Error("Error parsing plugin route url", "error", err)
  285. return
  286. }
  287. req.URL.Scheme = routeURL.Scheme
  288. req.URL.Host = routeURL.Host
  289. req.Host = routeURL.Host
  290. req.URL.Path = util.JoinUrlFragments(routeURL.Path, proxy.proxyPath)
  291. if err := addHeaders(&req.Header, proxy.route, data); err != nil {
  292. logger.Error("Failed to render plugin headers", "error", err)
  293. }
  294. if proxy.route.TokenAuth != nil {
  295. if token, err := proxy.getAccessToken(data); err != nil {
  296. logger.Error("Failed to get access token", "error", err)
  297. } else {
  298. req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
  299. }
  300. }
  301. logger.Info("Requesting", "url", req.URL.String())
  302. }
  303. func (proxy *DataSourceProxy) getAccessToken(data templateData) (string, error) {
  304. if cachedToken, found := tokenCache[proxy.getAccessTokenCacheKey()]; found {
  305. if cachedToken.ExpiresOn.After(time.Now().Add(time.Second * 10)) {
  306. logger.Info("Using token from cache")
  307. return cachedToken.AccessToken, nil
  308. }
  309. }
  310. urlInterpolated, err := interpolateString(proxy.route.TokenAuth.Url, data)
  311. if err != nil {
  312. return "", err
  313. }
  314. params := make(url.Values)
  315. for key, value := range proxy.route.TokenAuth.Params {
  316. interpolatedParam, err := interpolateString(value, data)
  317. if err != nil {
  318. return "", err
  319. }
  320. params.Add(key, interpolatedParam)
  321. }
  322. getTokenReq, _ := http.NewRequest("POST", urlInterpolated, bytes.NewBufferString(params.Encode()))
  323. getTokenReq.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  324. getTokenReq.Header.Add("Content-Length", strconv.Itoa(len(params.Encode())))
  325. resp, err := client.Do(getTokenReq)
  326. if err != nil {
  327. return "", err
  328. }
  329. defer resp.Body.Close()
  330. var token jwtToken
  331. if err := json.NewDecoder(resp.Body).Decode(&token); err != nil {
  332. return "", err
  333. }
  334. expiresOnEpoch, _ := strconv.ParseInt(token.ExpiresOnString, 10, 64)
  335. token.ExpiresOn = time.Unix(expiresOnEpoch, 0)
  336. tokenCache[proxy.getAccessTokenCacheKey()] = &token
  337. logger.Info("Got new access token", "ExpiresOn", token.ExpiresOn)
  338. return token.AccessToken, nil
  339. }
  340. func (proxy *DataSourceProxy) getAccessTokenCacheKey() string {
  341. return fmt.Sprintf("%v_%v_%v", proxy.ds.Id, proxy.route.Path, proxy.route.Method)
  342. }
  343. func interpolateString(text string, data templateData) (string, error) {
  344. t, err := template.New("content").Parse(text)
  345. if err != nil {
  346. return "", fmt.Errorf("could not parse template %s", text)
  347. }
  348. var contentBuf bytes.Buffer
  349. err = t.Execute(&contentBuf, data)
  350. if err != nil {
  351. return "", fmt.Errorf("failed to execute template %s", text)
  352. }
  353. return contentBuf.String(), nil
  354. }
  355. func addHeaders(reqHeaders *http.Header, route *plugins.AppPluginRoute, data templateData) error {
  356. for _, header := range route.Headers {
  357. interpolated, err := interpolateString(header.Content, data)
  358. if err != nil {
  359. return err
  360. }
  361. reqHeaders.Add(header.Name, interpolated)
  362. }
  363. return nil
  364. }