ds_proxy.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. package pluginproxy
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "net"
  10. "net/http"
  11. "net/http/httputil"
  12. "net/url"
  13. "strconv"
  14. "strings"
  15. "text/template"
  16. "time"
  17. "github.com/opentracing/opentracing-go"
  18. "golang.org/x/oauth2/jwt"
  19. "github.com/grafana/grafana/pkg/log"
  20. m "github.com/grafana/grafana/pkg/models"
  21. "github.com/grafana/grafana/pkg/plugins"
  22. "github.com/grafana/grafana/pkg/setting"
  23. "github.com/grafana/grafana/pkg/util"
  24. )
  25. var (
  26. logger = log.New("data-proxy-log")
  27. tokenCache = map[string]*jwtToken{}
  28. client = newHTTPClient()
  29. )
  30. type jwtToken struct {
  31. ExpiresOn time.Time `json:"-"`
  32. ExpiresOnString string `json:"expires_on"`
  33. AccessToken string `json:"access_token"`
  34. }
  35. type DataSourceProxy struct {
  36. ds *m.DataSource
  37. ctx *m.ReqContext
  38. targetUrl *url.URL
  39. proxyPath string
  40. route *plugins.AppPluginRoute
  41. plugin *plugins.DataSourcePlugin
  42. }
  43. type httpClient interface {
  44. Do(req *http.Request) (*http.Response, error)
  45. }
  46. func NewDataSourceProxy(ds *m.DataSource, plugin *plugins.DataSourcePlugin, ctx *m.ReqContext, proxyPath string) *DataSourceProxy {
  47. targetURL, _ := url.Parse(ds.Url)
  48. return &DataSourceProxy{
  49. ds: ds,
  50. plugin: plugin,
  51. ctx: ctx,
  52. proxyPath: proxyPath,
  53. targetUrl: targetURL,
  54. }
  55. }
  56. func newHTTPClient() httpClient {
  57. return &http.Client{
  58. Timeout: time.Second * 30,
  59. Transport: &http.Transport{Proxy: http.ProxyFromEnvironment},
  60. }
  61. }
  62. func (proxy *DataSourceProxy) HandleRequest() {
  63. if err := proxy.validateRequest(); err != nil {
  64. proxy.ctx.JsonApiErr(403, err.Error(), nil)
  65. return
  66. }
  67. reverseProxy := &httputil.ReverseProxy{
  68. Director: proxy.getDirector(),
  69. FlushInterval: time.Millisecond * 200,
  70. }
  71. var err error
  72. reverseProxy.Transport, err = proxy.ds.GetHttpTransport()
  73. if err != nil {
  74. proxy.ctx.JsonApiErr(400, "Unable to load TLS certificate", err)
  75. return
  76. }
  77. proxy.logRequest()
  78. span, ctx := opentracing.StartSpanFromContext(proxy.ctx.Req.Context(), "datasource reverse proxy")
  79. proxy.ctx.Req.Request = proxy.ctx.Req.WithContext(ctx)
  80. defer span.Finish()
  81. span.SetTag("datasource_id", proxy.ds.Id)
  82. span.SetTag("datasource_type", proxy.ds.Type)
  83. span.SetTag("user_id", proxy.ctx.SignedInUser.UserId)
  84. span.SetTag("org_id", proxy.ctx.SignedInUser.OrgId)
  85. proxy.addTraceFromHeaderValue(span, "X-Panel-Id", "panel_id")
  86. proxy.addTraceFromHeaderValue(span, "X-Dashboard-Id", "dashboard_id")
  87. opentracing.GlobalTracer().Inject(
  88. span.Context(),
  89. opentracing.HTTPHeaders,
  90. opentracing.HTTPHeadersCarrier(proxy.ctx.Req.Request.Header))
  91. reverseProxy.ServeHTTP(proxy.ctx.Resp, proxy.ctx.Req.Request)
  92. proxy.ctx.Resp.Header().Del("Set-Cookie")
  93. }
  94. func (proxy *DataSourceProxy) addTraceFromHeaderValue(span opentracing.Span, headerName string, tagName string) {
  95. panelId := proxy.ctx.Req.Header.Get(headerName)
  96. dashId, err := strconv.Atoi(panelId)
  97. if err == nil {
  98. span.SetTag(tagName, dashId)
  99. }
  100. }
  101. func (proxy *DataSourceProxy) useCustomHeaders(req *http.Request) {
  102. decryptSdj := proxy.ds.SecureJsonData.Decrypt()
  103. index := 1
  104. for {
  105. headerNameSuffix := fmt.Sprintf("httpHeaderName%d", index)
  106. headerValueSuffix := fmt.Sprintf("httpHeaderValue%d", index)
  107. if key := proxy.ds.JsonData.Get(headerNameSuffix).MustString(); key != "" {
  108. if val, ok := decryptSdj[headerValueSuffix]; ok {
  109. // remove if exists
  110. if req.Header.Get(key) != "" {
  111. req.Header.Del(key)
  112. }
  113. req.Header.Add(key, val)
  114. logger.Debug("Using custom header ", "CustomHeaders", key)
  115. }
  116. } else {
  117. break
  118. }
  119. index += 1
  120. }
  121. }
  122. func (proxy *DataSourceProxy) getDirector() func(req *http.Request) {
  123. return func(req *http.Request) {
  124. req.URL.Scheme = proxy.targetUrl.Scheme
  125. req.URL.Host = proxy.targetUrl.Host
  126. req.Host = proxy.targetUrl.Host
  127. reqQueryVals := req.URL.Query()
  128. if proxy.ds.Type == m.DS_INFLUXDB_08 {
  129. req.URL.Path = util.JoinUrlFragments(proxy.targetUrl.Path, "db/"+proxy.ds.Database+"/"+proxy.proxyPath)
  130. reqQueryVals.Add("u", proxy.ds.User)
  131. reqQueryVals.Add("p", proxy.ds.Password)
  132. req.URL.RawQuery = reqQueryVals.Encode()
  133. } else if proxy.ds.Type == m.DS_INFLUXDB {
  134. req.URL.Path = util.JoinUrlFragments(proxy.targetUrl.Path, proxy.proxyPath)
  135. req.URL.RawQuery = reqQueryVals.Encode()
  136. if !proxy.ds.BasicAuth {
  137. req.Header.Del("Authorization")
  138. req.Header.Add("Authorization", util.GetBasicAuthHeader(proxy.ds.User, proxy.ds.Password))
  139. }
  140. } else {
  141. req.URL.Path = util.JoinUrlFragments(proxy.targetUrl.Path, proxy.proxyPath)
  142. }
  143. if proxy.ds.BasicAuth {
  144. req.Header.Del("Authorization")
  145. req.Header.Add("Authorization", util.GetBasicAuthHeader(proxy.ds.BasicAuthUser, proxy.ds.BasicAuthPassword))
  146. }
  147. // Lookup and use custom headers
  148. if proxy.ds.SecureJsonData != nil {
  149. proxy.useCustomHeaders(req)
  150. }
  151. dsAuth := req.Header.Get("X-DS-Authorization")
  152. if len(dsAuth) > 0 {
  153. req.Header.Del("X-DS-Authorization")
  154. req.Header.Del("Authorization")
  155. req.Header.Add("Authorization", dsAuth)
  156. }
  157. // clear cookie header, except for whitelisted cookies
  158. var keptCookies []*http.Cookie
  159. if proxy.ds.JsonData != nil {
  160. if keepCookies := proxy.ds.JsonData.Get("keepCookies"); keepCookies != nil {
  161. keepCookieNames := keepCookies.MustStringArray()
  162. for _, c := range req.Cookies() {
  163. for _, v := range keepCookieNames {
  164. if c.Name == v {
  165. keptCookies = append(keptCookies, c)
  166. }
  167. }
  168. }
  169. }
  170. }
  171. req.Header.Del("Cookie")
  172. for _, c := range keptCookies {
  173. req.AddCookie(c)
  174. }
  175. // clear X-Forwarded Host/Port/Proto headers
  176. req.Header.Del("X-Forwarded-Host")
  177. req.Header.Del("X-Forwarded-Port")
  178. req.Header.Del("X-Forwarded-Proto")
  179. req.Header.Set("User-Agent", fmt.Sprintf("Grafana/%s", setting.BuildVersion))
  180. // set X-Forwarded-For header
  181. if req.RemoteAddr != "" {
  182. remoteAddr, _, err := net.SplitHostPort(req.RemoteAddr)
  183. if err != nil {
  184. remoteAddr = req.RemoteAddr
  185. }
  186. if req.Header.Get("X-Forwarded-For") != "" {
  187. req.Header.Set("X-Forwarded-For", req.Header.Get("X-Forwarded-For")+", "+remoteAddr)
  188. } else {
  189. req.Header.Set("X-Forwarded-For", remoteAddr)
  190. }
  191. }
  192. if proxy.route != nil {
  193. proxy.applyRoute(req)
  194. }
  195. }
  196. }
  197. func (proxy *DataSourceProxy) validateRequest() error {
  198. if !checkWhiteList(proxy.ctx, proxy.targetUrl.Host) {
  199. return errors.New("Target url is not a valid target")
  200. }
  201. if proxy.ds.Type == m.DS_PROMETHEUS {
  202. if proxy.ctx.Req.Request.Method == "DELETE" {
  203. return errors.New("Deletes not allowed on proxied Prometheus datasource")
  204. }
  205. if proxy.ctx.Req.Request.Method == "PUT" {
  206. return errors.New("Puts not allowed on proxied Prometheus datasource")
  207. }
  208. if proxy.ctx.Req.Request.Method == "POST" && !(proxy.proxyPath == "api/v1/query" || proxy.proxyPath == "api/v1/query_range") {
  209. return errors.New("Posts not allowed on proxied Prometheus datasource except on /query and /query_range")
  210. }
  211. }
  212. if proxy.ds.Type == m.DS_ES {
  213. if proxy.ctx.Req.Request.Method == "DELETE" {
  214. return errors.New("Deletes not allowed on proxied Elasticsearch datasource")
  215. }
  216. if proxy.ctx.Req.Request.Method == "PUT" {
  217. return errors.New("Puts not allowed on proxied Elasticsearch datasource")
  218. }
  219. if proxy.ctx.Req.Request.Method == "POST" && proxy.proxyPath != "_msearch" {
  220. return errors.New("Posts not allowed on proxied Elasticsearch datasource except on /_msearch")
  221. }
  222. }
  223. // found route if there are any
  224. if len(proxy.plugin.Routes) > 0 {
  225. for _, route := range proxy.plugin.Routes {
  226. // method match
  227. if route.Method != "" && route.Method != "*" && route.Method != proxy.ctx.Req.Method {
  228. continue
  229. }
  230. if route.ReqRole.IsValid() {
  231. if !proxy.ctx.HasUserRole(route.ReqRole) {
  232. return errors.New("Plugin proxy route access denied")
  233. }
  234. }
  235. if strings.HasPrefix(proxy.proxyPath, route.Path) {
  236. proxy.route = route
  237. break
  238. }
  239. }
  240. }
  241. return nil
  242. }
  243. func (proxy *DataSourceProxy) logRequest() {
  244. if !setting.DataProxyLogging {
  245. return
  246. }
  247. var body string
  248. if proxy.ctx.Req.Request.Body != nil {
  249. buffer, err := ioutil.ReadAll(proxy.ctx.Req.Request.Body)
  250. if err == nil {
  251. proxy.ctx.Req.Request.Body = ioutil.NopCloser(bytes.NewBuffer(buffer))
  252. body = string(buffer)
  253. }
  254. }
  255. logger.Info("Proxying incoming request",
  256. "userid", proxy.ctx.UserId,
  257. "orgid", proxy.ctx.OrgId,
  258. "username", proxy.ctx.Login,
  259. "datasource", proxy.ds.Type,
  260. "uri", proxy.ctx.Req.RequestURI,
  261. "method", proxy.ctx.Req.Request.Method,
  262. "body", body)
  263. }
  264. func checkWhiteList(c *m.ReqContext, host string) bool {
  265. if host != "" && len(setting.DataProxyWhiteList) > 0 {
  266. if _, exists := setting.DataProxyWhiteList[host]; !exists {
  267. c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil)
  268. return false
  269. }
  270. }
  271. return true
  272. }
  273. func (proxy *DataSourceProxy) applyRoute(req *http.Request) {
  274. proxy.proxyPath = strings.TrimPrefix(proxy.proxyPath, proxy.route.Path)
  275. data := templateData{
  276. JsonData: proxy.ds.JsonData.Interface().(map[string]interface{}),
  277. SecureJsonData: proxy.ds.SecureJsonData.Decrypt(),
  278. }
  279. interpolatedURL, err := interpolateString(proxy.route.Url, data)
  280. if err != nil {
  281. logger.Error("Error interpolating proxy url", "error", err)
  282. return
  283. }
  284. routeURL, err := url.Parse(interpolatedURL)
  285. if err != nil {
  286. logger.Error("Error parsing plugin route url", "error", err)
  287. return
  288. }
  289. req.URL.Scheme = routeURL.Scheme
  290. req.URL.Host = routeURL.Host
  291. req.Host = routeURL.Host
  292. req.URL.Path = util.JoinUrlFragments(routeURL.Path, proxy.proxyPath)
  293. if err := addHeaders(&req.Header, proxy.route, data); err != nil {
  294. logger.Error("Failed to render plugin headers", "error", err)
  295. }
  296. if proxy.route.TokenAuth != nil {
  297. if token, err := proxy.getAccessToken(data); err != nil {
  298. logger.Error("Failed to get access token", "error", err)
  299. } else {
  300. req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
  301. }
  302. }
  303. if proxy.route.JwtTokenAuth != nil {
  304. logger.Info("getJwtAccessToken", "JwtAccessToken", proxy.route.JwtTokenAuth)
  305. if token, err := proxy.getJwtAccessToken(data); err != nil {
  306. logger.Error("Failed to get access token", "error", err)
  307. } else {
  308. req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token))
  309. }
  310. }
  311. logger.Info("Requesting", "url", req.URL.String())
  312. }
  313. func (proxy *DataSourceProxy) getAccessToken(data templateData) (string, error) {
  314. if cachedToken, found := tokenCache[proxy.getAccessTokenCacheKey()]; found {
  315. if cachedToken.ExpiresOn.After(time.Now().Add(time.Second * 10)) {
  316. logger.Info("Using token from cache")
  317. return cachedToken.AccessToken, nil
  318. }
  319. }
  320. urlInterpolated, err := interpolateString(proxy.route.TokenAuth.Url, data)
  321. if err != nil {
  322. return "", err
  323. }
  324. params := make(url.Values)
  325. for key, value := range proxy.route.TokenAuth.Params {
  326. interpolatedParam, err := interpolateString(value, data)
  327. if err != nil {
  328. return "", err
  329. }
  330. params.Add(key, interpolatedParam)
  331. }
  332. getTokenReq, _ := http.NewRequest("POST", urlInterpolated, bytes.NewBufferString(params.Encode()))
  333. getTokenReq.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  334. getTokenReq.Header.Add("Content-Length", strconv.Itoa(len(params.Encode())))
  335. resp, err := client.Do(getTokenReq)
  336. if err != nil {
  337. return "", err
  338. }
  339. defer resp.Body.Close()
  340. var token jwtToken
  341. if err := json.NewDecoder(resp.Body).Decode(&token); err != nil {
  342. return "", err
  343. }
  344. expiresOnEpoch, _ := strconv.ParseInt(token.ExpiresOnString, 10, 64)
  345. token.ExpiresOn = time.Unix(expiresOnEpoch, 0)
  346. tokenCache[proxy.getAccessTokenCacheKey()] = &token
  347. logger.Info("Got new access token", "ExpiresOn", token.ExpiresOn)
  348. return token.AccessToken, nil
  349. }
  350. func (proxy *DataSourceProxy) getJwtAccessToken(data templateData) (string, error) {
  351. conf := new(jwt.Config)
  352. if val, ok := proxy.route.JwtTokenAuth.Params["client_email"]; ok {
  353. interpolatedVal, err := interpolateString(val, data)
  354. if err != nil {
  355. return "", err
  356. }
  357. conf.Email = interpolatedVal
  358. }
  359. if val, ok := proxy.route.JwtTokenAuth.Params["private_key"]; ok {
  360. interpolatedVal, err := interpolateString(val, data)
  361. if err != nil {
  362. return "", err
  363. }
  364. conf.PrivateKey = []byte(interpolatedVal)
  365. }
  366. conf.Scopes = []string{"https://www.googleapis.com/auth/monitoring.read"}
  367. conf.TokenURL = "https://oauth2.googleapis.com/token"
  368. ctx := context.Background()
  369. tokenSrc := conf.TokenSource(ctx)
  370. token, err := tokenSrc.Token()
  371. if err == nil {
  372. return "", err
  373. }
  374. return token.AccessToken, nil
  375. }
  376. func (proxy *DataSourceProxy) getAccessTokenCacheKey() string {
  377. return fmt.Sprintf("%v_%v_%v", proxy.ds.Id, proxy.route.Path, proxy.route.Method)
  378. }
  379. func interpolateString(text string, data templateData) (string, error) {
  380. t, err := template.New("content").Parse(text)
  381. if err != nil {
  382. return "", fmt.Errorf("could not parse template %s", text)
  383. }
  384. var contentBuf bytes.Buffer
  385. err = t.Execute(&contentBuf, data)
  386. if err != nil {
  387. return "", fmt.Errorf("failed to execute template %s", text)
  388. }
  389. return contentBuf.String(), nil
  390. }
  391. func addHeaders(reqHeaders *http.Header, route *plugins.AppPluginRoute, data templateData) error {
  392. for _, header := range route.Headers {
  393. interpolated, err := interpolateString(header.Content, data)
  394. if err != nil {
  395. return err
  396. }
  397. reqHeaders.Add(header.Name, interpolated)
  398. }
  399. return nil
  400. }