ds_proxy.go 9.3 KB

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