ds_proxy.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. package pluginproxy
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "net"
  8. "net/http"
  9. "net/http/httputil"
  10. "net/url"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/opentracing/opentracing-go"
  15. "golang.org/x/oauth2"
  16. "github.com/grafana/grafana/pkg/bus"
  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/social"
  22. "github.com/grafana/grafana/pkg/util"
  23. )
  24. var (
  25. logger = log.New("data-proxy-log")
  26. client = newHTTPClient()
  27. )
  28. type DataSourceProxy struct {
  29. ds *m.DataSource
  30. ctx *m.ReqContext
  31. targetUrl *url.URL
  32. proxyPath string
  33. route *plugins.AppPluginRoute
  34. plugin *plugins.DataSourcePlugin
  35. }
  36. type httpClient interface {
  37. Do(req *http.Request) (*http.Response, error)
  38. }
  39. func NewDataSourceProxy(ds *m.DataSource, plugin *plugins.DataSourcePlugin, ctx *m.ReqContext, proxyPath string) *DataSourceProxy {
  40. targetURL, _ := url.Parse(ds.Url)
  41. return &DataSourceProxy{
  42. ds: ds,
  43. plugin: plugin,
  44. ctx: ctx,
  45. proxyPath: proxyPath,
  46. targetUrl: targetURL,
  47. }
  48. }
  49. func newHTTPClient() httpClient {
  50. return &http.Client{
  51. Timeout: time.Duration(setting.DataProxyTimeout) * time.Second,
  52. Transport: &http.Transport{Proxy: http.ProxyFromEnvironment},
  53. }
  54. }
  55. func (proxy *DataSourceProxy) HandleRequest() {
  56. if err := proxy.validateRequest(); err != nil {
  57. proxy.ctx.JsonApiErr(403, err.Error(), nil)
  58. return
  59. }
  60. reverseProxy := &httputil.ReverseProxy{
  61. Director: proxy.getDirector(),
  62. FlushInterval: time.Millisecond * 200,
  63. }
  64. var err error
  65. reverseProxy.Transport, err = proxy.ds.GetHttpTransport()
  66. if err != nil {
  67. proxy.ctx.JsonApiErr(400, "Unable to load TLS certificate", err)
  68. return
  69. }
  70. proxy.logRequest()
  71. span, ctx := opentracing.StartSpanFromContext(proxy.ctx.Req.Context(), "datasource reverse proxy")
  72. proxy.ctx.Req.Request = proxy.ctx.Req.WithContext(ctx)
  73. defer span.Finish()
  74. span.SetTag("datasource_id", proxy.ds.Id)
  75. span.SetTag("datasource_type", proxy.ds.Type)
  76. span.SetTag("user_id", proxy.ctx.SignedInUser.UserId)
  77. span.SetTag("org_id", proxy.ctx.SignedInUser.OrgId)
  78. proxy.addTraceFromHeaderValue(span, "X-Panel-Id", "panel_id")
  79. proxy.addTraceFromHeaderValue(span, "X-Dashboard-Id", "dashboard_id")
  80. opentracing.GlobalTracer().Inject(
  81. span.Context(),
  82. opentracing.HTTPHeaders,
  83. opentracing.HTTPHeadersCarrier(proxy.ctx.Req.Request.Header))
  84. reverseProxy.ServeHTTP(proxy.ctx.Resp, proxy.ctx.Req.Request)
  85. proxy.ctx.Resp.Header().Del("Set-Cookie")
  86. }
  87. func (proxy *DataSourceProxy) addTraceFromHeaderValue(span opentracing.Span, headerName string, tagName string) {
  88. panelId := proxy.ctx.Req.Header.Get(headerName)
  89. dashId, err := strconv.Atoi(panelId)
  90. if err == nil {
  91. span.SetTag(tagName, dashId)
  92. }
  93. }
  94. func (proxy *DataSourceProxy) useCustomHeaders(req *http.Request) {
  95. decryptSdj := proxy.ds.SecureJsonData.Decrypt()
  96. index := 1
  97. for {
  98. headerNameSuffix := fmt.Sprintf("httpHeaderName%d", index)
  99. headerValueSuffix := fmt.Sprintf("httpHeaderValue%d", index)
  100. if key := proxy.ds.JsonData.Get(headerNameSuffix).MustString(); key != "" {
  101. if val, ok := decryptSdj[headerValueSuffix]; ok {
  102. // remove if exists
  103. if req.Header.Get(key) != "" {
  104. req.Header.Del(key)
  105. }
  106. req.Header.Add(key, val)
  107. logger.Debug("Using custom header ", "CustomHeaders", key)
  108. }
  109. } else {
  110. break
  111. }
  112. index += 1
  113. }
  114. }
  115. func (proxy *DataSourceProxy) getDirector() func(req *http.Request) {
  116. return func(req *http.Request) {
  117. req.URL.Scheme = proxy.targetUrl.Scheme
  118. req.URL.Host = proxy.targetUrl.Host
  119. req.Host = proxy.targetUrl.Host
  120. reqQueryVals := req.URL.Query()
  121. if proxy.ds.Type == m.DS_INFLUXDB_08 {
  122. req.URL.Path = util.JoinURLFragments(proxy.targetUrl.Path, "db/"+proxy.ds.Database+"/"+proxy.proxyPath)
  123. reqQueryVals.Add("u", proxy.ds.User)
  124. reqQueryVals.Add("p", proxy.ds.Password)
  125. req.URL.RawQuery = reqQueryVals.Encode()
  126. } else if proxy.ds.Type == m.DS_INFLUXDB {
  127. req.URL.Path = util.JoinURLFragments(proxy.targetUrl.Path, proxy.proxyPath)
  128. req.URL.RawQuery = reqQueryVals.Encode()
  129. if !proxy.ds.BasicAuth {
  130. req.Header.Del("Authorization")
  131. req.Header.Add("Authorization", util.GetBasicAuthHeader(proxy.ds.User, proxy.ds.Password))
  132. }
  133. } else {
  134. req.URL.Path = util.JoinURLFragments(proxy.targetUrl.Path, proxy.proxyPath)
  135. }
  136. if proxy.ds.BasicAuth {
  137. req.Header.Del("Authorization")
  138. req.Header.Add("Authorization", util.GetBasicAuthHeader(proxy.ds.BasicAuthUser, proxy.ds.BasicAuthPassword))
  139. }
  140. // Lookup and use custom headers
  141. if proxy.ds.SecureJsonData != nil {
  142. proxy.useCustomHeaders(req)
  143. }
  144. dsAuth := req.Header.Get("X-DS-Authorization")
  145. if len(dsAuth) > 0 {
  146. req.Header.Del("X-DS-Authorization")
  147. req.Header.Del("Authorization")
  148. req.Header.Add("Authorization", dsAuth)
  149. }
  150. // clear cookie header, except for whitelisted cookies
  151. var keptCookies []*http.Cookie
  152. if proxy.ds.JsonData != nil {
  153. if keepCookies := proxy.ds.JsonData.Get("keepCookies"); keepCookies != nil {
  154. keepCookieNames := keepCookies.MustStringArray()
  155. for _, c := range req.Cookies() {
  156. for _, v := range keepCookieNames {
  157. if c.Name == v {
  158. keptCookies = append(keptCookies, c)
  159. }
  160. }
  161. }
  162. }
  163. }
  164. req.Header.Del("Cookie")
  165. for _, c := range keptCookies {
  166. req.AddCookie(c)
  167. }
  168. // clear X-Forwarded Host/Port/Proto headers
  169. req.Header.Del("X-Forwarded-Host")
  170. req.Header.Del("X-Forwarded-Port")
  171. req.Header.Del("X-Forwarded-Proto")
  172. req.Header.Set("User-Agent", fmt.Sprintf("Grafana/%s", setting.BuildVersion))
  173. // Clear Origin and Referer to avoir CORS issues
  174. req.Header.Del("Origin")
  175. req.Header.Del("Referer")
  176. // set X-Forwarded-For header
  177. if req.RemoteAddr != "" {
  178. remoteAddr, _, err := net.SplitHostPort(req.RemoteAddr)
  179. if err != nil {
  180. remoteAddr = req.RemoteAddr
  181. }
  182. if req.Header.Get("X-Forwarded-For") != "" {
  183. req.Header.Set("X-Forwarded-For", req.Header.Get("X-Forwarded-For")+", "+remoteAddr)
  184. } else {
  185. req.Header.Set("X-Forwarded-For", remoteAddr)
  186. }
  187. }
  188. if proxy.route != nil {
  189. ApplyRoute(proxy.ctx.Req.Context(), req, proxy.proxyPath, proxy.route, proxy.ds)
  190. }
  191. if proxy.ds.JsonData != nil && proxy.ds.JsonData.Get("oauthPassThru").MustBool() {
  192. provider := proxy.ds.JsonData.Get("oauthPassThruProvider").MustString()
  193. connect, ok := social.SocialMap[strings.TrimPrefix(provider, "oauth_")] // The socialMap keys don't have "oauth_" prefix, but everywhere else in the system does
  194. if !ok {
  195. logger.Error("Failed to find oauth provider with given name", "provider", provider)
  196. }
  197. cmd := &m.GetAuthInfoQuery{UserId: proxy.ctx.UserId, AuthModule: provider}
  198. if err := bus.Dispatch(cmd); err != nil {
  199. logger.Error("Error feching oauth information for user", "error", err)
  200. }
  201. // TokenSource handles refreshing the token if it has expired
  202. token, err := connect.TokenSource(proxy.ctx.Req.Context(), &oauth2.Token{
  203. AccessToken: cmd.Result.OAuthAccessToken,
  204. Expiry: cmd.Result.OAuthExpiry,
  205. RefreshToken: cmd.Result.OAuthRefreshToken,
  206. TokenType: cmd.Result.OAuthTokenType,
  207. }).Token()
  208. if err != nil {
  209. logger.Error("Failed to retrieve access token from oauth provider", "provider", cmd.Result.AuthModule)
  210. }
  211. // If the tokens are not the same, update the entry in the DB
  212. if token.AccessToken != cmd.Result.OAuthAccessToken {
  213. cmd2 := &m.UpdateAuthInfoCommand{
  214. UserId: cmd.Result.Id,
  215. AuthModule: cmd.Result.AuthModule,
  216. AuthId: cmd.Result.AuthId,
  217. OAuthToken: token,
  218. }
  219. if err := bus.Dispatch(cmd2); err != nil {
  220. logger.Error("Failed to update access token during token refresh", "error", err)
  221. }
  222. }
  223. req.Header.Del("Authorization")
  224. req.Header.Add("Authorization", fmt.Sprintf("%s %s", token.Type(), token.AccessToken))
  225. }
  226. }
  227. }
  228. func (proxy *DataSourceProxy) validateRequest() error {
  229. if !checkWhiteList(proxy.ctx, proxy.targetUrl.Host) {
  230. return errors.New("Target url is not a valid target")
  231. }
  232. if proxy.ds.Type == m.DS_PROMETHEUS {
  233. if proxy.ctx.Req.Request.Method == "DELETE" {
  234. return errors.New("Deletes not allowed on proxied Prometheus datasource")
  235. }
  236. if proxy.ctx.Req.Request.Method == "PUT" {
  237. return errors.New("Puts not allowed on proxied Prometheus datasource")
  238. }
  239. if proxy.ctx.Req.Request.Method == "POST" && !(proxy.proxyPath == "api/v1/query" || proxy.proxyPath == "api/v1/query_range") {
  240. return errors.New("Posts not allowed on proxied Prometheus datasource except on /query and /query_range")
  241. }
  242. }
  243. if proxy.ds.Type == m.DS_ES {
  244. if proxy.ctx.Req.Request.Method == "DELETE" {
  245. return errors.New("Deletes not allowed on proxied Elasticsearch datasource")
  246. }
  247. if proxy.ctx.Req.Request.Method == "PUT" {
  248. return errors.New("Puts not allowed on proxied Elasticsearch datasource")
  249. }
  250. if proxy.ctx.Req.Request.Method == "POST" && proxy.proxyPath != "_msearch" {
  251. return errors.New("Posts not allowed on proxied Elasticsearch datasource except on /_msearch")
  252. }
  253. }
  254. // found route if there are any
  255. if len(proxy.plugin.Routes) > 0 {
  256. for _, route := range proxy.plugin.Routes {
  257. // method match
  258. if route.Method != "" && route.Method != "*" && route.Method != proxy.ctx.Req.Method {
  259. continue
  260. }
  261. if route.ReqRole.IsValid() {
  262. if !proxy.ctx.HasUserRole(route.ReqRole) {
  263. return errors.New("Plugin proxy route access denied")
  264. }
  265. }
  266. if strings.HasPrefix(proxy.proxyPath, route.Path) {
  267. proxy.route = route
  268. break
  269. }
  270. }
  271. }
  272. return nil
  273. }
  274. func (proxy *DataSourceProxy) logRequest() {
  275. if !setting.DataProxyLogging {
  276. return
  277. }
  278. var body string
  279. if proxy.ctx.Req.Request.Body != nil {
  280. buffer, err := ioutil.ReadAll(proxy.ctx.Req.Request.Body)
  281. if err == nil {
  282. proxy.ctx.Req.Request.Body = ioutil.NopCloser(bytes.NewBuffer(buffer))
  283. body = string(buffer)
  284. }
  285. }
  286. logger.Info("Proxying incoming request",
  287. "userid", proxy.ctx.UserId,
  288. "orgid", proxy.ctx.OrgId,
  289. "username", proxy.ctx.Login,
  290. "datasource", proxy.ds.Type,
  291. "uri", proxy.ctx.Req.RequestURI,
  292. "method", proxy.ctx.Req.Request.Method,
  293. "body", body)
  294. }
  295. func checkWhiteList(c *m.ReqContext, host string) bool {
  296. if host != "" && len(setting.DataProxyWhiteList) > 0 {
  297. if _, exists := setting.DataProxyWhiteList[host]; !exists {
  298. c.JsonApiErr(403, "Data proxy hostname and ip are not included in whitelist", nil)
  299. return false
  300. }
  301. }
  302. return true
  303. }