middleware.go 8.2 KB

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