middleware.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. package middleware
  2. import (
  3. "net/http"
  4. "net/url"
  5. "strconv"
  6. "github.com/grafana/grafana/pkg/bus"
  7. "github.com/grafana/grafana/pkg/components/apikeygen"
  8. "github.com/grafana/grafana/pkg/log"
  9. m "github.com/grafana/grafana/pkg/models"
  10. "github.com/grafana/grafana/pkg/services/auth/authtoken"
  11. "github.com/grafana/grafana/pkg/services/session"
  12. "github.com/grafana/grafana/pkg/setting"
  13. "github.com/grafana/grafana/pkg/util"
  14. macaron "gopkg.in/macaron.v1"
  15. )
  16. var (
  17. ReqGrafanaAdmin = Auth(&AuthOptions{ReqSignedIn: true, ReqGrafanaAdmin: true})
  18. ReqSignedIn = Auth(&AuthOptions{ReqSignedIn: true})
  19. ReqEditorRole = RoleAuth(m.ROLE_EDITOR, m.ROLE_ADMIN)
  20. ReqOrgAdmin = RoleAuth(m.ROLE_ADMIN)
  21. )
  22. func GetContextHandler(ats authtoken.UserAuthTokenService) macaron.Handler {
  23. return func(c *macaron.Context) {
  24. ctx := &m.ReqContext{
  25. Context: c,
  26. SignedInUser: &m.SignedInUser{},
  27. Session: session.GetSession(), // should only be used by auth_proxy
  28. IsSignedIn: false,
  29. AllowAnonymous: false,
  30. SkipCache: false,
  31. Logger: log.New("context"),
  32. }
  33. orgId := int64(0)
  34. orgIdHeader := ctx.Req.Header.Get("X-Grafana-Org-Id")
  35. if orgIdHeader != "" {
  36. orgId, _ = strconv.ParseInt(orgIdHeader, 10, 64)
  37. }
  38. // the order in which these are tested are important
  39. // look for api key in Authorization header first
  40. // then init session and look for userId in session
  41. // then look for api key in session (special case for render calls via api)
  42. // then test if anonymous access is enabled
  43. switch {
  44. case initContextWithRenderAuth(ctx):
  45. case initContextWithApiKey(ctx):
  46. case initContextWithBasicAuth(ctx, orgId):
  47. case initContextWithAuthProxy(ctx, orgId):
  48. case initContextWithToken(ats, ctx, orgId):
  49. case initContextWithAnonymousUser(ctx):
  50. }
  51. ctx.Logger = log.New("context", "userId", ctx.UserId, "orgId", ctx.OrgId, "uname", ctx.Login)
  52. ctx.Data["ctx"] = ctx
  53. c.Map(ctx)
  54. // update last seen every 5min
  55. if ctx.ShouldUpdateLastSeenAt() {
  56. ctx.Logger.Debug("Updating last user_seen_at", "user_id", ctx.UserId)
  57. if err := bus.Dispatch(&m.UpdateUserLastSeenAtCommand{UserId: ctx.UserId}); err != nil {
  58. ctx.Logger.Error("Failed to update last_seen_at", "error", err)
  59. }
  60. }
  61. }
  62. }
  63. func initContextWithAnonymousUser(ctx *m.ReqContext) bool {
  64. if !setting.AnonymousEnabled {
  65. return false
  66. }
  67. orgQuery := m.GetOrgByNameQuery{Name: setting.AnonymousOrgName}
  68. if err := bus.Dispatch(&orgQuery); err != nil {
  69. log.Error(3, "Anonymous access organization error: '%s': %s", setting.AnonymousOrgName, err)
  70. return false
  71. }
  72. ctx.IsSignedIn = false
  73. ctx.AllowAnonymous = true
  74. ctx.SignedInUser = &m.SignedInUser{IsAnonymous: true}
  75. ctx.OrgRole = m.RoleType(setting.AnonymousOrgRole)
  76. ctx.OrgId = orgQuery.Result.Id
  77. ctx.OrgName = orgQuery.Result.Name
  78. return true
  79. }
  80. func initContextWithApiKey(ctx *m.ReqContext) bool {
  81. var keyString string
  82. if keyString = getApiKey(ctx); keyString == "" {
  83. return false
  84. }
  85. // base64 decode key
  86. decoded, err := apikeygen.Decode(keyString)
  87. if err != nil {
  88. ctx.JsonApiErr(401, "Invalid API key", err)
  89. return true
  90. }
  91. // fetch key
  92. keyQuery := m.GetApiKeyByNameQuery{KeyName: decoded.Name, OrgId: decoded.OrgId}
  93. if err := bus.Dispatch(&keyQuery); err != nil {
  94. ctx.JsonApiErr(401, "Invalid API key", err)
  95. return true
  96. }
  97. apikey := keyQuery.Result
  98. // validate api key
  99. if !apikeygen.IsValid(decoded, apikey.Key) {
  100. ctx.JsonApiErr(401, "Invalid API key", err)
  101. return true
  102. }
  103. ctx.IsSignedIn = true
  104. ctx.SignedInUser = &m.SignedInUser{}
  105. ctx.OrgRole = apikey.Role
  106. ctx.ApiKeyId = apikey.Id
  107. ctx.OrgId = apikey.OrgId
  108. return true
  109. }
  110. func initContextWithBasicAuth(ctx *m.ReqContext, orgId int64) bool {
  111. if !setting.BasicAuthEnabled {
  112. return false
  113. }
  114. header := ctx.Req.Header.Get("Authorization")
  115. if header == "" {
  116. return false
  117. }
  118. username, password, err := util.DecodeBasicAuthHeader(header)
  119. if err != nil {
  120. ctx.JsonApiErr(401, "Invalid Basic Auth Header", err)
  121. return true
  122. }
  123. loginQuery := m.GetUserByLoginQuery{LoginOrEmail: username}
  124. if err := bus.Dispatch(&loginQuery); err != nil {
  125. ctx.JsonApiErr(401, "Basic auth failed", err)
  126. return true
  127. }
  128. user := loginQuery.Result
  129. loginUserQuery := m.LoginUserQuery{Username: username, Password: password, User: user}
  130. if err := bus.Dispatch(&loginUserQuery); err != nil {
  131. ctx.JsonApiErr(401, "Invalid username or password", err)
  132. return true
  133. }
  134. query := m.GetSignedInUserQuery{UserId: user.Id, OrgId: orgId}
  135. if err := bus.Dispatch(&query); err != nil {
  136. ctx.JsonApiErr(401, "Authentication error", err)
  137. return true
  138. }
  139. ctx.SignedInUser = query.Result
  140. ctx.IsSignedIn = true
  141. return true
  142. }
  143. const cookieName = "grafana_session"
  144. const OneYearInSeconds = 31557600 //used as default maxage for session cookies. We validate/rotate them more often.
  145. func initContextWithToken(authTokenService authtoken.UserAuthTokenService, ctx *m.ReqContext, orgID int64) bool {
  146. rawToken := ctx.GetCookie(cookieName)
  147. if rawToken == "" {
  148. return false
  149. }
  150. token, err := authTokenService.LookupToken(rawToken)
  151. if err != nil {
  152. ctx.Logger.Error("failed to look up user based on cookie", "error", err)
  153. return false
  154. }
  155. query := m.GetSignedInUserQuery{UserId: token.GetUserId(), OrgId: orgID}
  156. if err := bus.Dispatch(&query); err != nil {
  157. ctx.Logger.Error("failed to get user with id", "userId", token.GetUserId(), "error", err)
  158. return false
  159. }
  160. ctx.SignedInUser = query.Result
  161. ctx.IsSignedIn = true
  162. ctx.UserToken = token
  163. rotated, err := authTokenService.TryRotateToken(token, ctx.RemoteAddr(), ctx.Req.UserAgent())
  164. if err != nil {
  165. ctx.Logger.Error("failed to rotate token", "error", err)
  166. return true
  167. }
  168. if rotated {
  169. WriteSessionCookie(ctx, token.GetToken(), OneYearInSeconds)
  170. }
  171. return true
  172. }
  173. func WriteSessionCookie(ctx *m.ReqContext, value string, maxAge int) {
  174. if setting.Env == setting.DEV {
  175. ctx.Logger.Info("new token", "unhashed token", value)
  176. }
  177. ctx.Resp.Header().Del("Set-Cookie")
  178. cookie := http.Cookie{
  179. Name: cookieName,
  180. Value: url.QueryEscape(value),
  181. HttpOnly: true,
  182. Path: setting.AppSubUrl + "/",
  183. Secure: false, // TODO: use setting SecurityHTTPSCookies
  184. MaxAge: maxAge,
  185. SameSite: http.SameSiteLaxMode, // TODO: use setting LoginCookieSameSite
  186. }
  187. http.SetCookie(ctx.Resp, &cookie)
  188. }
  189. func AddDefaultResponseHeaders() macaron.Handler {
  190. return func(ctx *m.ReqContext) {
  191. if ctx.IsApiRequest() && ctx.Req.Method == "GET" {
  192. ctx.Resp.Header().Add("Cache-Control", "no-cache")
  193. ctx.Resp.Header().Add("Pragma", "no-cache")
  194. ctx.Resp.Header().Add("Expires", "-1")
  195. }
  196. }
  197. }