middleware.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. package middleware
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/url"
  6. "strconv"
  7. "strings"
  8. "time"
  9. macaron "gopkg.in/macaron.v1"
  10. "github.com/grafana/grafana/pkg/bus"
  11. "github.com/grafana/grafana/pkg/components/apikeygen"
  12. "github.com/grafana/grafana/pkg/infra/log"
  13. "github.com/grafana/grafana/pkg/infra/remotecache"
  14. "github.com/grafana/grafana/pkg/models"
  15. "github.com/grafana/grafana/pkg/setting"
  16. "github.com/grafana/grafana/pkg/util"
  17. )
  18. var getTime = time.Now
  19. var (
  20. ReqGrafanaAdmin = Auth(&AuthOptions{ReqSignedIn: true, ReqGrafanaAdmin: true})
  21. ReqSignedIn = Auth(&AuthOptions{ReqSignedIn: true})
  22. ReqEditorRole = RoleAuth(models.ROLE_EDITOR, models.ROLE_ADMIN)
  23. ReqOrgAdmin = RoleAuth(models.ROLE_ADMIN)
  24. )
  25. func GetContextHandler(
  26. ats models.UserTokenService,
  27. remoteCache *remotecache.RemoteCache,
  28. ) macaron.Handler {
  29. return func(c *macaron.Context) {
  30. ctx := &models.ReqContext{
  31. Context: c,
  32. SignedInUser: &models.SignedInUser{},
  33. IsSignedIn: false,
  34. AllowAnonymous: false,
  35. SkipCache: false,
  36. Logger: log.New("context"),
  37. }
  38. orgId := int64(0)
  39. orgIdHeader := ctx.Req.Header.Get("X-Grafana-Org-Id")
  40. if orgIdHeader != "" {
  41. orgId, _ = strconv.ParseInt(orgIdHeader, 10, 64)
  42. }
  43. // the order in which these are tested are important
  44. // look for api key in Authorization header first
  45. // then init session and look for userId in session
  46. // then look for api key in session (special case for render calls via api)
  47. // then test if anonymous access is enabled
  48. switch {
  49. case initContextWithRenderAuth(ctx):
  50. case initContextWithApiKey(ctx):
  51. case initContextWithBasicAuth(ctx, orgId):
  52. case initContextWithAuthProxy(remoteCache, ctx, orgId):
  53. case initContextWithToken(ats, ctx, orgId):
  54. case initContextWithAnonymousUser(ctx):
  55. }
  56. ctx.Logger = log.New("context", "userId", ctx.UserId, "orgId", ctx.OrgId, "uname", ctx.Login)
  57. ctx.Data["ctx"] = ctx
  58. c.Map(ctx)
  59. // update last seen every 5min
  60. if ctx.ShouldUpdateLastSeenAt() {
  61. ctx.Logger.Debug("Updating last user_seen_at", "user_id", ctx.UserId)
  62. if err := bus.Dispatch(&models.UpdateUserLastSeenAtCommand{UserId: ctx.UserId}); err != nil {
  63. ctx.Logger.Error("Failed to update last_seen_at", "error", err)
  64. }
  65. }
  66. }
  67. }
  68. func initContextWithAnonymousUser(ctx *models.ReqContext) bool {
  69. if !setting.AnonymousEnabled {
  70. return false
  71. }
  72. orgQuery := models.GetOrgByNameQuery{Name: setting.AnonymousOrgName}
  73. if err := bus.Dispatch(&orgQuery); err != nil {
  74. log.Error(3, "Anonymous access organization error: '%s': %s", setting.AnonymousOrgName, err)
  75. return false
  76. }
  77. ctx.IsSignedIn = false
  78. ctx.AllowAnonymous = true
  79. ctx.SignedInUser = &models.SignedInUser{IsAnonymous: true}
  80. ctx.OrgRole = models.RoleType(setting.AnonymousOrgRole)
  81. ctx.OrgId = orgQuery.Result.Id
  82. ctx.OrgName = orgQuery.Result.Name
  83. return true
  84. }
  85. func initContextWithApiKey(ctx *models.ReqContext) bool {
  86. var keyString string
  87. if keyString = getApiKey(ctx); keyString == "" {
  88. return false
  89. }
  90. // base64 decode key
  91. decoded, err := apikeygen.Decode(keyString)
  92. if err != nil {
  93. ctx.JsonApiErr(401, "Invalid API key", err)
  94. return true
  95. }
  96. // fetch key
  97. keyQuery := models.GetApiKeyByNameQuery{KeyName: decoded.Name, OrgId: decoded.OrgId}
  98. if err := bus.Dispatch(&keyQuery); err != nil {
  99. ctx.JsonApiErr(401, "Invalid API key", err)
  100. return true
  101. }
  102. apikey := keyQuery.Result
  103. // validate api key
  104. if !apikeygen.IsValid(decoded, apikey.Key) {
  105. ctx.JsonApiErr(401, "Invalid API key", err)
  106. return true
  107. }
  108. // check for expiration
  109. if apikey.Expires != nil && *apikey.Expires <= getTime().Unix() {
  110. ctx.JsonApiErr(401, "Expired API key", err)
  111. return true
  112. }
  113. ctx.IsSignedIn = true
  114. ctx.SignedInUser = &models.SignedInUser{}
  115. ctx.OrgRole = apikey.Role
  116. ctx.ApiKeyId = apikey.Id
  117. ctx.OrgId = apikey.OrgId
  118. return true
  119. }
  120. func initContextWithBasicAuth(ctx *models.ReqContext, orgId int64) bool {
  121. if !setting.BasicAuthEnabled {
  122. return false
  123. }
  124. header := ctx.Req.Header.Get("Authorization")
  125. if header == "" {
  126. return false
  127. }
  128. username, password, err := util.DecodeBasicAuthHeader(header)
  129. if err != nil {
  130. ctx.JsonApiErr(401, "Invalid Basic Auth Header", err)
  131. return true
  132. }
  133. loginQuery := models.GetUserByLoginQuery{LoginOrEmail: username}
  134. if err := bus.Dispatch(&loginQuery); err != nil {
  135. ctx.JsonApiErr(401, "Basic auth failed", err)
  136. return true
  137. }
  138. user := loginQuery.Result
  139. loginUserQuery := models.LoginUserQuery{Username: username, Password: password, User: user}
  140. if err := bus.Dispatch(&loginUserQuery); err != nil {
  141. ctx.JsonApiErr(401, "Invalid username or password", err)
  142. return true
  143. }
  144. query := models.GetSignedInUserQuery{UserId: user.Id, OrgId: orgId}
  145. if err := bus.Dispatch(&query); err != nil {
  146. ctx.JsonApiErr(401, "Authentication error", err)
  147. return true
  148. }
  149. ctx.SignedInUser = query.Result
  150. ctx.IsSignedIn = true
  151. return true
  152. }
  153. func initContextWithToken(authTokenService models.UserTokenService, ctx *models.ReqContext, orgID int64) bool {
  154. rawToken := ctx.GetCookie(setting.LoginCookieName)
  155. if rawToken == "" {
  156. return false
  157. }
  158. token, err := authTokenService.LookupToken(ctx.Req.Context(), rawToken)
  159. if err != nil {
  160. ctx.Logger.Error("failed to look up user based on cookie", "error", err)
  161. WriteSessionCookie(ctx, "", -1)
  162. return false
  163. }
  164. query := models.GetSignedInUserQuery{UserId: token.UserId, OrgId: orgID}
  165. if err := bus.Dispatch(&query); err != nil {
  166. ctx.Logger.Error("failed to get user with id", "userId", token.UserId, "error", err)
  167. return false
  168. }
  169. ctx.SignedInUser = query.Result
  170. ctx.IsSignedIn = true
  171. ctx.UserToken = token
  172. rotated, err := authTokenService.TryRotateToken(ctx.Req.Context(), token, ctx.RemoteAddr(), ctx.Req.UserAgent())
  173. if err != nil {
  174. ctx.Logger.Error("failed to rotate token", "error", err)
  175. return true
  176. }
  177. if rotated {
  178. WriteSessionCookie(ctx, token.UnhashedToken, setting.LoginMaxLifetimeDays)
  179. }
  180. return true
  181. }
  182. func WriteSessionCookie(ctx *models.ReqContext, value string, maxLifetimeDays int) {
  183. if setting.Env == setting.DEV {
  184. ctx.Logger.Info("new token", "unhashed token", value)
  185. }
  186. var maxAge int
  187. if maxLifetimeDays <= 0 {
  188. maxAge = -1
  189. } else {
  190. maxAgeHours := (time.Duration(setting.LoginMaxLifetimeDays) * 24 * time.Hour) + time.Hour
  191. maxAge = int(maxAgeHours.Seconds())
  192. }
  193. ctx.Resp.Header().Del("Set-Cookie")
  194. cookie := http.Cookie{
  195. Name: setting.LoginCookieName,
  196. Value: url.QueryEscape(value),
  197. HttpOnly: true,
  198. Path: setting.AppSubUrl + "/",
  199. Secure: setting.CookieSecure,
  200. MaxAge: maxAge,
  201. SameSite: setting.CookieSameSite,
  202. }
  203. http.SetCookie(ctx.Resp, &cookie)
  204. }
  205. func AddDefaultResponseHeaders() macaron.Handler {
  206. return func(ctx *macaron.Context) {
  207. ctx.Resp.Before(func(w macaron.ResponseWriter) {
  208. if !strings.HasPrefix(ctx.Req.URL.Path, "/api/datasources/proxy/") {
  209. AddNoCacheHeaders(ctx.Resp)
  210. }
  211. if !setting.AllowEmbedding {
  212. AddXFrameOptionsDenyHeader(w)
  213. }
  214. AddSecurityHeaders(w)
  215. })
  216. }
  217. }
  218. // AddSecurityHeaders adds various HTTP(S) response headers that enable various security protections behaviors in the client's browser.
  219. func AddSecurityHeaders(w macaron.ResponseWriter) {
  220. if setting.Protocol == setting.HTTPS && setting.StrictTransportSecurity {
  221. strictHeaderValues := []string{fmt.Sprintf("max-age=%v", setting.StrictTransportSecurityMaxAge)}
  222. if setting.StrictTransportSecurityPreload {
  223. strictHeaderValues = append(strictHeaderValues, "preload")
  224. }
  225. if setting.StrictTransportSecuritySubDomains {
  226. strictHeaderValues = append(strictHeaderValues, "includeSubDomains")
  227. }
  228. w.Header().Add("Strict-Transport-Security", strings.Join(strictHeaderValues, "; "))
  229. }
  230. if setting.ContentTypeProtectionHeader {
  231. w.Header().Add("X-Content-Type-Options", "nosniff")
  232. }
  233. if setting.XSSProtectionHeader {
  234. w.Header().Add("X-XSS-Protection", "1; mode=block")
  235. }
  236. }
  237. func AddNoCacheHeaders(w macaron.ResponseWriter) {
  238. w.Header().Add("Cache-Control", "no-cache")
  239. w.Header().Add("Pragma", "no-cache")
  240. w.Header().Add("Expires", "-1")
  241. }
  242. func AddXFrameOptionsDenyHeader(w macaron.ResponseWriter) {
  243. w.Header().Add("X-Frame-Options", "deny")
  244. }