2014-10-05 09:50:04 -05:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2020-02-17 10:31:44 -06:00
|
|
|
"context"
|
2019-06-12 06:15:50 -05:00
|
|
|
"fmt"
|
2019-02-04 16:44:28 -06:00
|
|
|
"net/url"
|
2014-10-07 16:56:37 -05:00
|
|
|
"strconv"
|
2019-05-06 02:22:59 -05:00
|
|
|
"strings"
|
2019-02-05 14:14:23 -06:00
|
|
|
"time"
|
2014-10-05 09:50:04 -05:00
|
|
|
|
2019-05-17 06:57:26 -05:00
|
|
|
macaron "gopkg.in/macaron.v1"
|
|
|
|
|
2015-02-05 03:37:13 -06:00
|
|
|
"github.com/grafana/grafana/pkg/bus"
|
2015-02-26 10:23:28 -06:00
|
|
|
"github.com/grafana/grafana/pkg/components/apikeygen"
|
2019-05-13 01:45:54 -05:00
|
|
|
"github.com/grafana/grafana/pkg/infra/log"
|
2019-04-08 06:31:46 -05:00
|
|
|
"github.com/grafana/grafana/pkg/infra/remotecache"
|
2019-06-26 01:47:03 -05:00
|
|
|
"github.com/grafana/grafana/pkg/models"
|
2020-02-19 12:47:39 -06:00
|
|
|
"github.com/grafana/grafana/pkg/services/rendering"
|
2015-02-05 03:37:13 -06:00
|
|
|
"github.com/grafana/grafana/pkg/setting"
|
2015-06-30 02:37:52 -05:00
|
|
|
"github.com/grafana/grafana/pkg/util"
|
2014-10-05 09:50:04 -05:00
|
|
|
)
|
|
|
|
|
2019-06-26 01:47:03 -05:00
|
|
|
var getTime = time.Now
|
|
|
|
|
2019-08-02 04:16:31 -05:00
|
|
|
const (
|
|
|
|
errStringInvalidUsernamePassword = "Invalid username or password"
|
|
|
|
errStringInvalidAPIKey = "Invalid API key"
|
|
|
|
)
|
|
|
|
|
2018-10-11 05:36:04 -05:00
|
|
|
var (
|
2019-08-02 04:16:31 -05:00
|
|
|
ReqGrafanaAdmin = Auth(&AuthOptions{
|
|
|
|
ReqSignedIn: true,
|
|
|
|
ReqGrafanaAdmin: true,
|
|
|
|
})
|
|
|
|
ReqSignedIn = Auth(&AuthOptions{ReqSignedIn: true})
|
|
|
|
ReqEditorRole = RoleAuth(models.ROLE_EDITOR, models.ROLE_ADMIN)
|
|
|
|
ReqOrgAdmin = RoleAuth(models.ROLE_ADMIN)
|
2018-10-11 05:36:04 -05:00
|
|
|
)
|
|
|
|
|
2019-06-13 09:47:52 -05:00
|
|
|
func GetContextHandler(
|
2019-06-26 01:47:03 -05:00
|
|
|
ats models.UserTokenService,
|
2019-06-13 09:47:52 -05:00
|
|
|
remoteCache *remotecache.RemoteCache,
|
2020-02-19 12:47:39 -06:00
|
|
|
renderService rendering.Service,
|
2019-06-13 09:47:52 -05:00
|
|
|
) macaron.Handler {
|
2015-04-07 12:21:14 -05:00
|
|
|
return func(c *macaron.Context) {
|
2019-06-26 01:47:03 -05:00
|
|
|
ctx := &models.ReqContext{
|
2015-03-11 11:34:11 -05:00
|
|
|
Context: c,
|
2019-06-26 01:47:03 -05:00
|
|
|
SignedInUser: &models.SignedInUser{},
|
2015-03-11 11:34:11 -05:00
|
|
|
IsSignedIn: false,
|
|
|
|
AllowAnonymous: false,
|
2018-10-26 03:40:33 -05:00
|
|
|
SkipCache: false,
|
2016-06-06 16:06:44 -05:00
|
|
|
Logger: log.New("context"),
|
2014-10-05 09:50:04 -05:00
|
|
|
}
|
|
|
|
|
2017-04-14 08:47:39 -05:00
|
|
|
orgId := int64(0)
|
|
|
|
orgIdHeader := ctx.Req.Header.Get("X-Grafana-Org-Id")
|
|
|
|
if orgIdHeader != "" {
|
|
|
|
orgId, _ = strconv.ParseInt(orgIdHeader, 10, 64)
|
|
|
|
}
|
|
|
|
|
2015-04-08 01:59:12 -05:00
|
|
|
// the order in which these are tested are important
|
|
|
|
// look for api key in Authorization header first
|
|
|
|
// then init session and look for userId in session
|
|
|
|
// then look for api key in session (special case for render calls via api)
|
|
|
|
// then test if anonymous access is enabled
|
2018-10-15 14:13:03 -05:00
|
|
|
switch {
|
2020-02-19 12:47:39 -06:00
|
|
|
case initContextWithRenderAuth(ctx, renderService):
|
2018-10-15 14:13:03 -05:00
|
|
|
case initContextWithApiKey(ctx):
|
|
|
|
case initContextWithBasicAuth(ctx, orgId):
|
2019-04-08 06:31:46 -05:00
|
|
|
case initContextWithAuthProxy(remoteCache, ctx, orgId):
|
2019-02-04 16:44:28 -06:00
|
|
|
case initContextWithToken(ats, ctx, orgId):
|
2018-10-15 14:13:03 -05:00
|
|
|
case initContextWithAnonymousUser(ctx):
|
2015-01-15 05:16:54 -06:00
|
|
|
}
|
|
|
|
|
2016-06-07 05:20:46 -05:00
|
|
|
ctx.Logger = log.New("context", "userId", ctx.UserId, "orgId", ctx.OrgId, "uname", ctx.Login)
|
2016-06-07 02:29:47 -05:00
|
|
|
ctx.Data["ctx"] = ctx
|
2016-06-06 16:06:44 -05:00
|
|
|
|
2014-10-05 09:50:04 -05:00
|
|
|
c.Map(ctx)
|
2017-08-09 03:36:41 -05:00
|
|
|
|
|
|
|
// update last seen every 5min
|
|
|
|
if ctx.ShouldUpdateLastSeenAt() {
|
|
|
|
ctx.Logger.Debug("Updating last user_seen_at", "user_id", ctx.UserId)
|
2019-06-26 01:47:03 -05:00
|
|
|
if err := bus.Dispatch(&models.UpdateUserLastSeenAtCommand{UserId: ctx.UserId}); err != nil {
|
2017-08-09 03:36:41 -05:00
|
|
|
ctx.Logger.Error("Failed to update last_seen_at", "error", err)
|
|
|
|
}
|
|
|
|
}
|
2014-10-05 09:50:04 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-26 01:47:03 -05:00
|
|
|
func initContextWithAnonymousUser(ctx *models.ReqContext) bool {
|
2015-04-07 12:21:14 -05:00
|
|
|
if !setting.AnonymousEnabled {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2019-06-26 01:47:03 -05:00
|
|
|
orgQuery := models.GetOrgByNameQuery{Name: setting.AnonymousOrgName}
|
2015-04-07 12:21:14 -05:00
|
|
|
if err := bus.Dispatch(&orgQuery); err != nil {
|
|
|
|
log.Error(3, "Anonymous access organization error: '%s': %s", setting.AnonymousOrgName, err)
|
|
|
|
return false
|
|
|
|
}
|
2017-04-14 08:47:39 -05:00
|
|
|
|
|
|
|
ctx.IsSignedIn = false
|
|
|
|
ctx.AllowAnonymous = true
|
2019-06-26 01:47:03 -05:00
|
|
|
ctx.SignedInUser = &models.SignedInUser{IsAnonymous: true}
|
|
|
|
ctx.OrgRole = models.RoleType(setting.AnonymousOrgRole)
|
2017-04-14 08:47:39 -05:00
|
|
|
ctx.OrgId = orgQuery.Result.Id
|
|
|
|
ctx.OrgName = orgQuery.Result.Name
|
|
|
|
return true
|
2015-04-07 12:21:14 -05:00
|
|
|
}
|
|
|
|
|
2019-06-26 01:47:03 -05:00
|
|
|
func initContextWithApiKey(ctx *models.ReqContext) bool {
|
2015-04-07 12:21:14 -05:00
|
|
|
var keyString string
|
|
|
|
if keyString = getApiKey(ctx); keyString == "" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// base64 decode key
|
|
|
|
decoded, err := apikeygen.Decode(keyString)
|
|
|
|
if err != nil {
|
2019-08-02 04:16:31 -05:00
|
|
|
ctx.JsonApiErr(401, errStringInvalidAPIKey, err)
|
2015-04-07 12:21:14 -05:00
|
|
|
return true
|
|
|
|
}
|
2017-04-14 08:47:39 -05:00
|
|
|
|
2015-04-07 12:21:14 -05:00
|
|
|
// fetch key
|
2019-06-26 01:47:03 -05:00
|
|
|
keyQuery := models.GetApiKeyByNameQuery{KeyName: decoded.Name, OrgId: decoded.OrgId}
|
2015-04-07 12:21:14 -05:00
|
|
|
if err := bus.Dispatch(&keyQuery); err != nil {
|
2019-08-02 04:16:31 -05:00
|
|
|
ctx.JsonApiErr(401, errStringInvalidAPIKey, err)
|
2015-04-07 12:21:14 -05:00
|
|
|
return true
|
2017-04-14 08:47:39 -05:00
|
|
|
}
|
2015-04-07 12:21:14 -05:00
|
|
|
|
2017-04-14 08:47:39 -05:00
|
|
|
apikey := keyQuery.Result
|
2015-04-07 12:21:14 -05:00
|
|
|
|
2017-04-14 08:47:39 -05:00
|
|
|
// validate api key
|
2019-10-23 03:40:12 -05:00
|
|
|
isValid, err := apikeygen.IsValid(decoded, apikey.Key)
|
|
|
|
if err != nil {
|
|
|
|
ctx.JsonApiErr(500, "Validating API key failed", err)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if !isValid {
|
2019-08-02 04:16:31 -05:00
|
|
|
ctx.JsonApiErr(401, errStringInvalidAPIKey, err)
|
2015-04-08 01:59:12 -05:00
|
|
|
return true
|
|
|
|
}
|
2017-04-14 08:47:39 -05:00
|
|
|
|
2019-06-26 01:47:03 -05:00
|
|
|
// check for expiration
|
|
|
|
if apikey.Expires != nil && *apikey.Expires <= getTime().Unix() {
|
|
|
|
ctx.JsonApiErr(401, "Expired API key", err)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2017-04-14 08:47:39 -05:00
|
|
|
ctx.IsSignedIn = true
|
2019-06-26 01:47:03 -05:00
|
|
|
ctx.SignedInUser = &models.SignedInUser{}
|
2017-04-14 08:47:39 -05:00
|
|
|
ctx.OrgRole = apikey.Role
|
|
|
|
ctx.ApiKeyId = apikey.Id
|
|
|
|
ctx.OrgId = apikey.OrgId
|
|
|
|
return true
|
2015-04-08 01:59:12 -05:00
|
|
|
}
|
|
|
|
|
2019-06-26 01:47:03 -05:00
|
|
|
func initContextWithBasicAuth(ctx *models.ReqContext, orgId int64) bool {
|
2015-06-30 02:37:52 -05:00
|
|
|
if !setting.BasicAuthEnabled {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
header := ctx.Req.Header.Get("Authorization")
|
|
|
|
if header == "" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
username, password, err := util.DecodeBasicAuthHeader(header)
|
|
|
|
if err != nil {
|
|
|
|
ctx.JsonApiErr(401, "Invalid Basic Auth Header", err)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2019-08-03 14:50:05 -05:00
|
|
|
authQuery := models.LoginUserQuery{
|
2019-08-02 04:16:31 -05:00
|
|
|
Username: username,
|
|
|
|
Password: password,
|
|
|
|
}
|
2019-08-03 14:50:05 -05:00
|
|
|
if err := bus.Dispatch(&authQuery); err != nil {
|
2019-08-02 04:16:31 -05:00
|
|
|
ctx.Logger.Debug(
|
|
|
|
"Failed to authorize the user",
|
|
|
|
"username", username,
|
|
|
|
)
|
|
|
|
|
|
|
|
ctx.JsonApiErr(401, errStringInvalidUsernamePassword, err)
|
2015-06-30 02:37:52 -05:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2019-08-03 14:50:05 -05:00
|
|
|
user := authQuery.User
|
|
|
|
|
2019-06-26 01:47:03 -05:00
|
|
|
query := models.GetSignedInUserQuery{UserId: user.Id, OrgId: orgId}
|
2015-06-30 02:37:52 -05:00
|
|
|
if err := bus.Dispatch(&query); err != nil {
|
2019-08-02 04:16:31 -05:00
|
|
|
ctx.Logger.Error(
|
|
|
|
"Failed at user signed in",
|
|
|
|
"id", user.Id,
|
|
|
|
"org", orgId,
|
|
|
|
)
|
|
|
|
ctx.JsonApiErr(401, errStringInvalidUsernamePassword, err)
|
2015-06-30 02:37:52 -05:00
|
|
|
return true
|
|
|
|
}
|
2017-04-14 08:47:39 -05:00
|
|
|
|
|
|
|
ctx.SignedInUser = query.Result
|
|
|
|
ctx.IsSignedIn = true
|
|
|
|
return true
|
2015-06-30 02:37:52 -05:00
|
|
|
}
|
|
|
|
|
2019-06-26 01:47:03 -05:00
|
|
|
func initContextWithToken(authTokenService models.UserTokenService, ctx *models.ReqContext, orgID int64) bool {
|
2019-07-09 04:15:52 -05:00
|
|
|
if setting.LoginCookieName == "" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2019-02-05 14:14:23 -06:00
|
|
|
rawToken := ctx.GetCookie(setting.LoginCookieName)
|
2019-02-04 16:44:28 -06:00
|
|
|
if rawToken == "" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2019-04-30 07:42:01 -05:00
|
|
|
token, err := authTokenService.LookupToken(ctx.Req.Context(), rawToken)
|
2019-02-04 16:44:28 -06:00
|
|
|
if err != nil {
|
2019-08-02 04:16:31 -05:00
|
|
|
ctx.Logger.Error("Failed to look up user based on cookie", "error", err)
|
2019-02-06 01:45:01 -06:00
|
|
|
WriteSessionCookie(ctx, "", -1)
|
2019-02-04 16:44:28 -06:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2019-06-26 01:47:03 -05:00
|
|
|
query := models.GetSignedInUserQuery{UserId: token.UserId, OrgId: orgID}
|
2019-02-04 16:44:28 -06:00
|
|
|
if err := bus.Dispatch(&query); err != nil {
|
2019-08-02 04:16:31 -05:00
|
|
|
ctx.Logger.Error("Failed to get user with id", "userId", token.UserId, "error", err)
|
2019-02-04 16:44:28 -06:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx.SignedInUser = query.Result
|
|
|
|
ctx.IsSignedIn = true
|
|
|
|
ctx.UserToken = token
|
|
|
|
|
2020-01-15 06:03:12 -06:00
|
|
|
// Rotate the token just before we write response headers to ensure there is no delay between
|
|
|
|
// the new token being generated and the client receiving it.
|
2020-02-17 10:31:44 -06:00
|
|
|
ctx.Resp.Before(rotateEndOfRequestFunc(ctx, authTokenService, token))
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
func rotateEndOfRequestFunc(ctx *models.ReqContext, authTokenService models.UserTokenService, token *models.UserToken) macaron.BeforeFunc {
|
|
|
|
return func(w macaron.ResponseWriter) {
|
2020-02-18 15:53:40 -06:00
|
|
|
// if response has already been written, skip.
|
|
|
|
if w.Written() {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-02-17 10:31:44 -06:00
|
|
|
// if the request is cancelled by the client we should not try
|
|
|
|
// to rotate the token since the client would not accept any result.
|
|
|
|
if ctx.Context.Req.Context().Err() == context.Canceled {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-01-15 06:03:12 -06:00
|
|
|
rotated, err := authTokenService.TryRotateToken(ctx.Req.Context(), token, ctx.RemoteAddr(), ctx.Req.UserAgent())
|
|
|
|
if err != nil {
|
|
|
|
ctx.Logger.Error("Failed to rotate token", "error", err)
|
|
|
|
return
|
|
|
|
}
|
2019-02-04 16:44:28 -06:00
|
|
|
|
2020-01-15 06:03:12 -06:00
|
|
|
if rotated {
|
|
|
|
WriteSessionCookie(ctx, token.UnhashedToken, setting.LoginMaxLifetimeDays)
|
|
|
|
}
|
2020-02-17 10:31:44 -06:00
|
|
|
}
|
2019-02-04 16:44:28 -06:00
|
|
|
}
|
|
|
|
|
2019-06-26 01:47:03 -05:00
|
|
|
func WriteSessionCookie(ctx *models.ReqContext, value string, maxLifetimeDays int) {
|
2019-02-04 16:44:28 -06:00
|
|
|
if setting.Env == setting.DEV {
|
2019-08-02 04:16:31 -05:00
|
|
|
ctx.Logger.Info("New token", "unhashed token", value)
|
2019-02-04 16:44:28 -06:00
|
|
|
}
|
|
|
|
|
2019-02-05 14:14:23 -06:00
|
|
|
var maxAge int
|
|
|
|
if maxLifetimeDays <= 0 {
|
|
|
|
maxAge = -1
|
|
|
|
} else {
|
|
|
|
maxAgeHours := (time.Duration(setting.LoginMaxLifetimeDays) * 24 * time.Hour) + time.Hour
|
|
|
|
maxAge = int(maxAgeHours.Seconds())
|
|
|
|
}
|
|
|
|
|
2020-01-10 07:55:30 -06:00
|
|
|
WriteCookie(ctx.Resp, setting.LoginCookieName, url.QueryEscape(value), maxAge, newCookieOptions)
|
2019-02-04 16:44:28 -06:00
|
|
|
}
|
|
|
|
|
2017-07-04 09:33:37 -05:00
|
|
|
func AddDefaultResponseHeaders() macaron.Handler {
|
2019-05-06 02:22:59 -05:00
|
|
|
return func(ctx *macaron.Context) {
|
|
|
|
ctx.Resp.Before(func(w macaron.ResponseWriter) {
|
2020-02-18 15:53:40 -06:00
|
|
|
// if response has already been written, skip.
|
|
|
|
if w.Written() {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-05-06 02:22:59 -05:00
|
|
|
if !strings.HasPrefix(ctx.Req.URL.Path, "/api/datasources/proxy/") {
|
|
|
|
AddNoCacheHeaders(ctx.Resp)
|
|
|
|
}
|
2019-05-06 02:56:23 -05:00
|
|
|
|
|
|
|
if !setting.AllowEmbedding {
|
|
|
|
AddXFrameOptionsDenyHeader(w)
|
|
|
|
}
|
2019-06-12 06:15:50 -05:00
|
|
|
|
|
|
|
AddSecurityHeaders(w)
|
2019-05-06 02:22:59 -05:00
|
|
|
})
|
2017-07-04 09:33:37 -05:00
|
|
|
}
|
|
|
|
}
|
2019-05-06 02:22:59 -05:00
|
|
|
|
2019-06-12 06:15:50 -05:00
|
|
|
// AddSecurityHeaders adds various HTTP(S) response headers that enable various security protections behaviors in the client's browser.
|
|
|
|
func AddSecurityHeaders(w macaron.ResponseWriter) {
|
2019-08-16 10:06:54 -05:00
|
|
|
if (setting.Protocol == setting.HTTPS || setting.Protocol == setting.HTTP2) && setting.StrictTransportSecurity {
|
2019-06-18 13:24:23 -05:00
|
|
|
strictHeaderValues := []string{fmt.Sprintf("max-age=%v", setting.StrictTransportSecurityMaxAge)}
|
2019-06-12 06:15:50 -05:00
|
|
|
if setting.StrictTransportSecurityPreload {
|
2019-06-18 13:24:23 -05:00
|
|
|
strictHeaderValues = append(strictHeaderValues, "preload")
|
2019-06-12 06:15:50 -05:00
|
|
|
}
|
|
|
|
if setting.StrictTransportSecuritySubDomains {
|
2019-06-18 13:24:23 -05:00
|
|
|
strictHeaderValues = append(strictHeaderValues, "includeSubDomains")
|
2019-06-12 06:15:50 -05:00
|
|
|
}
|
2019-06-18 13:24:23 -05:00
|
|
|
w.Header().Add("Strict-Transport-Security", strings.Join(strictHeaderValues, "; "))
|
2019-06-12 06:15:50 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
if setting.ContentTypeProtectionHeader {
|
|
|
|
w.Header().Add("X-Content-Type-Options", "nosniff")
|
|
|
|
}
|
|
|
|
|
|
|
|
if setting.XSSProtectionHeader {
|
2019-06-17 16:46:35 -05:00
|
|
|
w.Header().Add("X-XSS-Protection", "1; mode=block")
|
2019-06-12 06:15:50 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-06 02:22:59 -05:00
|
|
|
func AddNoCacheHeaders(w macaron.ResponseWriter) {
|
|
|
|
w.Header().Add("Cache-Control", "no-cache")
|
|
|
|
w.Header().Add("Pragma", "no-cache")
|
|
|
|
w.Header().Add("Expires", "-1")
|
|
|
|
}
|
2019-05-06 02:56:23 -05:00
|
|
|
|
|
|
|
func AddXFrameOptionsDenyHeader(w macaron.ResponseWriter) {
|
|
|
|
w.Header().Add("X-Frame-Options", "deny")
|
|
|
|
}
|