ds_proxy.go 11 KB

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