middleware.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. if setting.LoginCookieName == "" {
  155. return false
  156. }
  157. rawToken := ctx.GetCookie(setting.LoginCookieName)
  158. if rawToken == "" {
  159. return false
  160. }
  161. token, err := authTokenService.LookupToken(ctx.Req.Context(), rawToken)
  162. if err != nil {
  163. ctx.Logger.Error("failed to look up user based on cookie", "error", err)
  164. WriteSessionCookie(ctx, "", -1)
  165. return false
  166. }
  167. query := models.GetSignedInUserQuery{UserId: token.UserId, OrgId: orgID}
  168. if err := bus.Dispatch(&query); err != nil {
  169. ctx.Logger.Error("failed to get user with id", "userId", token.UserId, "error", err)
  170. return false
  171. }
  172. ctx.SignedInUser = query.Result
  173. ctx.IsSignedIn = true
  174. ctx.UserToken = token
  175. rotated, err := authTokenService.TryRotateToken(ctx.Req.Context(), token, ctx.RemoteAddr(), ctx.Req.UserAgent())
  176. if err != nil {
  177. ctx.Logger.Error("failed to rotate token", "error", err)
  178. return true
  179. }
  180. if rotated {
  181. WriteSessionCookie(ctx, token.UnhashedToken, setting.LoginMaxLifetimeDays)
  182. }
  183. return true
  184. }
  185. func WriteSessionCookie(ctx *models.ReqContext, value string, maxLifetimeDays int) {
  186. if setting.Env == setting.DEV {
  187. ctx.Logger.Info("new token", "unhashed token", value)
  188. }
  189. var maxAge int
  190. if maxLifetimeDays <= 0 {
  191. maxAge = -1
  192. } else {
  193. maxAgeHours := (time.Duration(setting.LoginMaxLifetimeDays) * 24 * time.Hour) + time.Hour
  194. maxAge = int(maxAgeHours.Seconds())
  195. }
  196. ctx.Resp.Header().Del("Set-Cookie")
  197. cookie := http.Cookie{
  198. Name: setting.LoginCookieName,
  199. Value: url.QueryEscape(value),
  200. HttpOnly: true,
  201. Path: setting.AppSubUrl + "/",
  202. Secure: setting.CookieSecure,
  203. MaxAge: maxAge,
  204. SameSite: setting.CookieSameSite,
  205. }
  206. http.SetCookie(ctx.Resp, &cookie)
  207. }
  208. func AddDefaultResponseHeaders() macaron.Handler {
  209. return func(ctx *macaron.Context) {
  210. ctx.Resp.Before(func(w macaron.ResponseWriter) {
  211. if !strings.HasPrefix(ctx.Req.URL.Path, "/api/datasources/proxy/") {
  212. AddNoCacheHeaders(ctx.Resp)
  213. }
  214. if !setting.AllowEmbedding {
  215. AddXFrameOptionsDenyHeader(w)
  216. }
  217. AddSecurityHeaders(w)
  218. })
  219. }
  220. }
  221. // AddSecurityHeaders adds various HTTP(S) response headers that enable various security protections behaviors in the client's browser.
  222. func AddSecurityHeaders(w macaron.ResponseWriter) {
  223. if setting.Protocol == setting.HTTPS && setting.StrictTransportSecurity {
  224. strictHeaderValues := []string{fmt.Sprintf("max-age=%v", setting.StrictTransportSecurityMaxAge)}
  225. if setting.StrictTransportSecurityPreload {
  226. strictHeaderValues = append(strictHeaderValues, "preload")
  227. }
  228. if setting.StrictTransportSecuritySubDomains {
  229. strictHeaderValues = append(strictHeaderValues, "includeSubDomains")
  230. }
  231. w.Header().Add("Strict-Transport-Security", strings.Join(strictHeaderValues, "; "))
  232. }
  233. if setting.ContentTypeProtectionHeader {
  234. w.Header().Add("X-Content-Type-Options", "nosniff")
  235. }
  236. if setting.XSSProtectionHeader {
  237. w.Header().Add("X-XSS-Protection", "1; mode=block")
  238. }
  239. }
  240. func AddNoCacheHeaders(w macaron.ResponseWriter) {
  241. w.Header().Add("Cache-Control", "no-cache")
  242. w.Header().Add("Pragma", "no-cache")
  243. w.Header().Add("Expires", "-1")
  244. }
  245. func AddXFrameOptionsDenyHeader(w macaron.ResponseWriter) {
  246. w.Header().Add("X-Frame-Options", "deny")
  247. }