ds_proxy.go 9.5 KB

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