2014-12-29 13:36:08 +01:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
2018-01-16 12:32:42 +01:00
|
|
|
"context"
|
2016-10-08 01:20:45 -05:00
|
|
|
"crypto/rand"
|
2019-01-22 15:20:44 +01:00
|
|
|
"crypto/sha256"
|
2016-10-08 01:20:45 -05:00
|
|
|
"encoding/base64"
|
2019-01-22 15:20:44 +01:00
|
|
|
"encoding/hex"
|
2020-09-04 14:54:59 +02:00
|
|
|
"errors"
|
2016-10-11 02:51:44 -04:00
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2017-02-09 14:01:53 -05:00
|
|
|
"net/url"
|
2014-12-29 13:36:08 +01:00
|
|
|
|
2014-12-30 10:10:13 +01:00
|
|
|
"golang.org/x/oauth2"
|
|
|
|
|
2018-03-23 15:50:07 -04:00
|
|
|
"github.com/grafana/grafana/pkg/bus"
|
2019-05-13 14:45:54 +08:00
|
|
|
"github.com/grafana/grafana/pkg/infra/log"
|
2019-02-23 23:35:26 +01:00
|
|
|
"github.com/grafana/grafana/pkg/infra/metrics"
|
2018-02-08 17:13:58 -05:00
|
|
|
"github.com/grafana/grafana/pkg/login"
|
2019-02-23 23:39:05 +01:00
|
|
|
"github.com/grafana/grafana/pkg/login/social"
|
2020-12-11 11:44:44 +01:00
|
|
|
"github.com/grafana/grafana/pkg/middleware/cookies"
|
2020-03-04 12:57:20 +01:00
|
|
|
"github.com/grafana/grafana/pkg/models"
|
2015-02-05 10:37:13 +01:00
|
|
|
"github.com/grafana/grafana/pkg/setting"
|
2014-12-29 13:36:08 +01:00
|
|
|
)
|
|
|
|
|
2019-01-22 15:20:44 +01:00
|
|
|
var (
|
|
|
|
oauthLogger = log.New("oauth")
|
|
|
|
OauthStateCookieName = "oauth_state"
|
|
|
|
)
|
2017-02-01 16:32:51 +03:00
|
|
|
|
2019-10-08 18:57:53 +02:00
|
|
|
func GenStateString() (string, error) {
|
2016-10-11 02:51:44 -04:00
|
|
|
rnd := make([]byte, 32)
|
2019-10-08 18:57:53 +02:00
|
|
|
if _, err := rand.Read(rnd); err != nil {
|
|
|
|
oauthLogger.Error("failed to generate state string", "err", err)
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return base64.URLEncoding.EncodeToString(rnd), nil
|
2016-10-08 01:20:45 -05:00
|
|
|
}
|
|
|
|
|
2020-03-04 12:57:20 +01:00
|
|
|
func (hs *HTTPServer) OAuthLogin(ctx *models.ReqContext) {
|
2020-11-06 10:01:13 +01:00
|
|
|
loginInfo := models.LoginInfo{
|
|
|
|
AuthModule: "oauth",
|
2020-09-04 14:54:59 +02:00
|
|
|
}
|
2014-12-29 13:36:08 +01:00
|
|
|
if setting.OAuthService == nil {
|
2020-09-04 14:54:59 +02:00
|
|
|
hs.handleOAuthLoginError(ctx, loginInfo, LoginError{
|
|
|
|
HttpStatus: http.StatusNotFound,
|
|
|
|
PublicMessage: "OAuth not enabled",
|
|
|
|
})
|
2014-12-29 13:36:08 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
name := ctx.Params(":name")
|
2020-11-06 10:01:13 +01:00
|
|
|
loginInfo.AuthModule = name
|
2014-12-29 13:36:08 +01:00
|
|
|
connect, ok := social.SocialMap[name]
|
|
|
|
if !ok {
|
2020-09-04 14:54:59 +02:00
|
|
|
hs.handleOAuthLoginError(ctx, loginInfo, LoginError{
|
|
|
|
HttpStatus: http.StatusNotFound,
|
|
|
|
PublicMessage: fmt.Sprintf("No OAuth with name %s configured", name),
|
|
|
|
})
|
2014-12-29 13:36:08 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-10-12 15:12:21 +02:00
|
|
|
errorParam := ctx.Query("error")
|
|
|
|
if errorParam != "" {
|
2016-10-11 02:51:44 -04:00
|
|
|
errorDesc := ctx.Query("error_description")
|
2017-10-12 15:12:21 +02:00
|
|
|
oauthLogger.Error("failed to login ", "error", errorParam, "errorDesc", errorDesc)
|
2020-09-04 14:54:59 +02:00
|
|
|
hs.handleOAuthLoginErrorWithRedirect(ctx, loginInfo, login.ErrProviderDeniedRequest, "error", errorParam, "errorDesc", errorDesc)
|
2016-10-11 02:51:44 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2014-12-29 13:36:08 +01:00
|
|
|
code := ctx.Query("code")
|
|
|
|
if code == "" {
|
2019-10-08 18:57:53 +02:00
|
|
|
state, err := GenStateString()
|
|
|
|
if err != nil {
|
|
|
|
ctx.Logger.Error("Generating state string failed", "err", err)
|
2020-09-04 14:54:59 +02:00
|
|
|
hs.handleOAuthLoginError(ctx, loginInfo, LoginError{
|
|
|
|
HttpStatus: http.StatusInternalServerError,
|
|
|
|
PublicMessage: "An internal error occurred",
|
|
|
|
})
|
2019-10-08 18:57:53 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-01-22 15:20:44 +01:00
|
|
|
hashedState := hashStatecode(state, setting.OAuthService.OAuthInfos[name].ClientSecret)
|
2020-12-11 11:44:44 +01:00
|
|
|
cookies.WriteCookie(ctx.Resp, OauthStateCookieName, hashedState, hs.Cfg.OAuthCookieMaxAge, hs.CookieOptionsFromCfg)
|
2016-10-28 03:00:47 -07:00
|
|
|
if setting.OAuthService.OAuthInfos[name].HostedDomain == "" {
|
|
|
|
ctx.Redirect(connect.AuthCodeURL(state, oauth2.AccessTypeOnline))
|
2016-12-14 12:15:35 +09:00
|
|
|
} else {
|
2017-06-05 10:09:27 +02:00
|
|
|
ctx.Redirect(connect.AuthCodeURL(state, oauth2.SetAuthURLParam("hd", setting.OAuthService.OAuthInfos[name].HostedDomain), oauth2.AccessTypeOnline))
|
2016-10-28 03:00:47 -07:00
|
|
|
}
|
2016-10-08 01:20:45 -05:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-01-24 19:04:58 +01:00
|
|
|
cookieState := ctx.GetCookie(OauthStateCookieName)
|
2019-01-22 15:20:44 +01:00
|
|
|
|
|
|
|
// delete cookie
|
2020-12-11 11:44:44 +01:00
|
|
|
cookies.DeleteCookie(ctx.Resp, OauthStateCookieName, hs.CookieOptionsFromCfg)
|
2019-01-22 15:20:44 +01:00
|
|
|
|
2019-01-24 19:04:58 +01:00
|
|
|
if cookieState == "" {
|
2020-09-04 14:54:59 +02:00
|
|
|
hs.handleOAuthLoginError(ctx, loginInfo, LoginError{
|
|
|
|
HttpStatus: http.StatusInternalServerError,
|
|
|
|
PublicMessage: "login.OAuthLogin(missing saved state)",
|
|
|
|
})
|
2017-10-12 15:24:20 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-01-22 15:20:44 +01:00
|
|
|
queryState := hashStatecode(ctx.Query("state"), setting.OAuthService.OAuthInfos[name].ClientSecret)
|
2019-01-24 19:04:58 +01:00
|
|
|
oauthLogger.Info("state check", "queryState", queryState, "cookieState", cookieState)
|
|
|
|
if cookieState != queryState {
|
2020-09-04 14:54:59 +02:00
|
|
|
hs.handleOAuthLoginError(ctx, loginInfo, LoginError{
|
|
|
|
HttpStatus: http.StatusInternalServerError,
|
|
|
|
PublicMessage: "login.OAuthLogin(state mismatch)",
|
|
|
|
})
|
2014-12-29 13:36:08 +01:00
|
|
|
return
|
|
|
|
}
|
2018-05-28 20:47:48 +02:00
|
|
|
|
2020-09-11 11:25:03 -04:00
|
|
|
oauthClient, err := social.GetOAuthHttpClient(name)
|
|
|
|
if err != nil {
|
|
|
|
ctx.Logger.Error("Failed to create OAuth http client", "error", err)
|
|
|
|
hs.handleOAuthLoginError(ctx, loginInfo, LoginError{
|
|
|
|
HttpStatus: http.StatusInternalServerError,
|
|
|
|
PublicMessage: "login.OAuthLogin(" + err.Error() + ")",
|
|
|
|
})
|
|
|
|
return
|
2016-10-11 02:51:44 -04:00
|
|
|
}
|
|
|
|
|
2017-10-06 15:23:06 +01:00
|
|
|
oauthCtx := context.WithValue(context.Background(), oauth2.HTTPClient, oauthClient)
|
2017-10-06 15:16:26 +01:00
|
|
|
|
2016-10-11 02:51:44 -04:00
|
|
|
// get token from provider
|
|
|
|
token, err := connect.Exchange(oauthCtx, code)
|
2014-12-29 13:36:08 +01:00
|
|
|
if err != nil {
|
2020-09-04 14:54:59 +02:00
|
|
|
hs.handleOAuthLoginError(ctx, loginInfo, LoginError{
|
|
|
|
HttpStatus: http.StatusInternalServerError,
|
|
|
|
PublicMessage: "login.OAuthLogin(NewTransportWithCode)",
|
|
|
|
Err: err,
|
|
|
|
})
|
2014-12-29 13:36:08 +01:00
|
|
|
return
|
|
|
|
}
|
2016-11-15 14:36:21 -05:00
|
|
|
// token.TokenType was defaulting to "bearer", which is out of spec, so we explicitly set to "Bearer"
|
|
|
|
token.TokenType = "Bearer"
|
2014-12-29 13:36:08 +01:00
|
|
|
|
2018-01-18 17:17:51 -05:00
|
|
|
oauthLogger.Debug("OAuthLogin Got token", "token", token)
|
2014-12-29 13:36:08 +01:00
|
|
|
|
2016-10-11 02:51:44 -04:00
|
|
|
// set up oauth2 client
|
|
|
|
client := connect.Client(oauthCtx, token)
|
|
|
|
|
|
|
|
// get user info
|
2018-01-18 17:17:51 -05:00
|
|
|
userInfo, err := connect.UserInfo(client, token)
|
2014-12-29 13:36:08 +01:00
|
|
|
if err != nil {
|
2020-11-19 13:34:28 +01:00
|
|
|
var sErr *social.Error
|
|
|
|
if errors.As(err, &sErr) {
|
2020-09-04 14:54:59 +02:00
|
|
|
hs.handleOAuthLoginErrorWithRedirect(ctx, loginInfo, sErr)
|
2015-04-28 20:22:45 -07:00
|
|
|
} else {
|
2020-09-04 14:54:59 +02:00
|
|
|
hs.handleOAuthLoginError(ctx, loginInfo, LoginError{
|
|
|
|
HttpStatus: http.StatusInternalServerError,
|
|
|
|
PublicMessage: fmt.Sprintf("login.OAuthLogin(get info from %s)", name),
|
|
|
|
Err: err,
|
|
|
|
})
|
2015-04-28 20:22:45 -07:00
|
|
|
}
|
2014-12-29 13:36:08 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-01-18 17:17:51 -05:00
|
|
|
oauthLogger.Debug("OAuthLogin got user info", "userInfo", userInfo)
|
2015-04-06 14:16:22 +02:00
|
|
|
|
2017-05-26 08:35:32 -04:00
|
|
|
// validate that we got at least an email address
|
|
|
|
if userInfo.Email == "" {
|
2020-09-04 14:54:59 +02:00
|
|
|
hs.handleOAuthLoginErrorWithRedirect(ctx, loginInfo, login.ErrNoEmail)
|
2017-05-26 08:35:32 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-04-06 14:16:22 +02:00
|
|
|
// validate that the email is allowed to login to grafana
|
|
|
|
if !connect.IsEmailAllowed(userInfo.Email) {
|
2020-09-04 14:54:59 +02:00
|
|
|
hs.handleOAuthLoginErrorWithRedirect(ctx, loginInfo, login.ErrEmailNotAllowed)
|
2015-04-06 14:16:22 +02:00
|
|
|
return
|
|
|
|
}
|
2014-12-29 13:36:08 +01:00
|
|
|
|
2020-11-06 10:01:13 +01:00
|
|
|
loginInfo.ExternalUser = *buildExternalUserInfo(token, userInfo, name)
|
|
|
|
loginInfo.User, err = syncUser(ctx, &loginInfo.ExternalUser, connect)
|
2020-07-31 20:29:27 +02:00
|
|
|
if err != nil {
|
2020-09-04 14:54:59 +02:00
|
|
|
hs.handleOAuthLoginErrorWithRedirect(ctx, loginInfo, err)
|
2020-07-31 20:29:27 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// login
|
2020-09-04 14:54:59 +02:00
|
|
|
if err := hs.loginUserWithUser(loginInfo.User, ctx); err != nil {
|
|
|
|
hs.handleOAuthLoginErrorWithRedirect(ctx, loginInfo, err)
|
2020-07-31 20:29:27 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-11-06 10:01:13 +01:00
|
|
|
loginInfo.HTTPStatus = http.StatusOK
|
|
|
|
hs.HooksService.RunLoginHook(&loginInfo, ctx)
|
2020-07-31 20:29:27 +02:00
|
|
|
metrics.MApiLoginOAuth.Inc()
|
|
|
|
|
|
|
|
if redirectTo, err := url.QueryUnescape(ctx.GetCookie("redirect_to")); err == nil && len(redirectTo) > 0 {
|
|
|
|
if err := hs.ValidateRedirectTo(redirectTo); err == nil {
|
2020-12-11 11:44:44 +01:00
|
|
|
cookies.DeleteCookie(ctx.Resp, "redirect_to", hs.CookieOptionsFromCfg)
|
2020-07-31 20:29:27 +02:00
|
|
|
ctx.Redirect(redirectTo)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
log.Debugf("Ignored invalid redirect_to cookie value: %v", redirectTo)
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx.Redirect(setting.AppSubUrl + "/")
|
|
|
|
}
|
|
|
|
|
2020-09-04 14:54:59 +02:00
|
|
|
// buildExternalUserInfo returns a ExternalUserInfo struct from OAuth user profile
|
|
|
|
func buildExternalUserInfo(token *oauth2.Token, userInfo *social.BasicUserInfo, name string) *models.ExternalUserInfo {
|
|
|
|
oauthLogger.Debug("Building external user info from OAuth user info")
|
|
|
|
|
2020-03-04 12:57:20 +01:00
|
|
|
extUser := &models.ExternalUserInfo{
|
2020-07-31 20:29:27 +02:00
|
|
|
AuthModule: fmt.Sprintf("oauth_%s", name),
|
2019-02-01 19:40:57 -05:00
|
|
|
OAuthToken: token,
|
2018-02-08 17:13:58 -05:00
|
|
|
AuthId: userInfo.Id,
|
|
|
|
Name: userInfo.Name,
|
|
|
|
Login: userInfo.Login,
|
|
|
|
Email: userInfo.Email,
|
2020-03-04 12:57:20 +01:00
|
|
|
OrgRoles: map[int64]models.RoleType{},
|
2019-07-01 12:30:17 +03:00
|
|
|
Groups: userInfo.Groups,
|
2018-02-08 17:13:58 -05:00
|
|
|
}
|
2014-12-29 13:36:08 +01:00
|
|
|
|
2018-02-08 17:13:58 -05:00
|
|
|
if userInfo.Role != "" {
|
2020-03-04 12:57:20 +01:00
|
|
|
rt := models.RoleType(userInfo.Role)
|
2019-11-05 21:56:42 +01:00
|
|
|
if rt.IsValid() {
|
2020-07-31 09:41:13 +02:00
|
|
|
// The user will be assigned a role in either the auto-assigned organization or in the default one
|
2020-02-19 17:38:53 +01:00
|
|
|
var orgID int64
|
|
|
|
if setting.AutoAssignOrg && setting.AutoAssignOrgId > 0 {
|
|
|
|
orgID = int64(setting.AutoAssignOrgId)
|
2020-07-31 20:29:27 +02:00
|
|
|
logger.Debug("The user has a role assignment and organization membership is auto-assigned",
|
|
|
|
"role", userInfo.Role, "orgId", orgID)
|
2020-02-19 17:38:53 +01:00
|
|
|
} else {
|
|
|
|
orgID = int64(1)
|
2020-07-31 20:29:27 +02:00
|
|
|
logger.Debug("The user has a role assignment and organization membership is not auto-assigned",
|
|
|
|
"role", userInfo.Role, "orgId", orgID)
|
2020-02-19 17:38:53 +01:00
|
|
|
}
|
|
|
|
extUser.OrgRoles[orgID] = rt
|
2019-11-05 21:56:42 +01:00
|
|
|
}
|
2018-02-08 17:13:58 -05:00
|
|
|
}
|
2014-12-29 13:36:08 +01:00
|
|
|
|
2020-09-04 14:54:59 +02:00
|
|
|
return extUser
|
|
|
|
}
|
|
|
|
|
|
|
|
// syncUser syncs a Grafana user profile with the corresponding OAuth profile.
|
|
|
|
func syncUser(
|
|
|
|
ctx *models.ReqContext,
|
|
|
|
extUser *models.ExternalUserInfo,
|
|
|
|
connect social.SocialConnector,
|
|
|
|
) (*models.User, error) {
|
|
|
|
oauthLogger.Debug("Syncing Grafana user with corresponding OAuth profile")
|
2020-07-31 20:29:27 +02:00
|
|
|
// add/update user in Grafana
|
2020-03-04 12:57:20 +01:00
|
|
|
cmd := &models.UpsertUserCommand{
|
2018-03-23 15:50:07 -04:00
|
|
|
ReqContext: ctx,
|
|
|
|
ExternalUser: extUser,
|
2018-02-08 17:13:58 -05:00
|
|
|
SignupAllowed: connect.IsSignupAllowed(),
|
|
|
|
}
|
2020-07-31 20:29:27 +02:00
|
|
|
if err := bus.Dispatch(cmd); err != nil {
|
|
|
|
return nil, err
|
2014-12-29 13:36:08 +01:00
|
|
|
}
|
|
|
|
|
2019-07-23 13:12:55 +03:00
|
|
|
// Do not expose disabled status,
|
|
|
|
// just show incorrect user credentials error (see #17947)
|
2019-07-05 12:35:04 +03:00
|
|
|
if cmd.Result.IsDisabled {
|
2019-07-23 13:12:55 +03:00
|
|
|
oauthLogger.Warn("User is disabled", "user", cmd.Result.Login)
|
2020-07-31 20:29:27 +02:00
|
|
|
return nil, login.ErrInvalidCredentials
|
2020-03-23 13:37:53 +01:00
|
|
|
}
|
2014-12-29 13:36:08 +01:00
|
|
|
|
2020-07-31 20:29:27 +02:00
|
|
|
return cmd.Result, nil
|
2014-12-29 13:36:08 +01:00
|
|
|
}
|
2017-02-01 16:32:51 +03:00
|
|
|
|
2019-01-22 15:20:44 +01:00
|
|
|
func hashStatecode(code, seed string) string {
|
|
|
|
hashBytes := sha256.Sum256([]byte(code + setting.SecretKey + seed))
|
|
|
|
return hex.EncodeToString(hashBytes[:])
|
|
|
|
}
|
2020-09-04 14:54:59 +02:00
|
|
|
|
|
|
|
type LoginError struct {
|
|
|
|
HttpStatus int
|
|
|
|
PublicMessage string
|
|
|
|
Err error
|
|
|
|
}
|
|
|
|
|
2020-11-06 10:01:13 +01:00
|
|
|
func (hs *HTTPServer) handleOAuthLoginError(ctx *models.ReqContext, info models.LoginInfo, err LoginError) {
|
2020-09-04 14:54:59 +02:00
|
|
|
ctx.Handle(err.HttpStatus, err.PublicMessage, err.Err)
|
|
|
|
|
2020-11-06 10:01:13 +01:00
|
|
|
info.Error = err.Err
|
|
|
|
if info.Error == nil {
|
|
|
|
info.Error = errors.New(err.PublicMessage)
|
2020-09-04 14:54:59 +02:00
|
|
|
}
|
2020-11-06 10:01:13 +01:00
|
|
|
info.HTTPStatus = err.HttpStatus
|
2020-09-04 14:54:59 +02:00
|
|
|
|
2020-11-06 10:01:13 +01:00
|
|
|
hs.HooksService.RunLoginHook(&info, ctx)
|
2020-09-04 14:54:59 +02:00
|
|
|
}
|
|
|
|
|
2020-11-06 10:01:13 +01:00
|
|
|
func (hs *HTTPServer) handleOAuthLoginErrorWithRedirect(ctx *models.ReqContext, info models.LoginInfo, err error, v ...interface{}) {
|
2020-09-04 14:54:59 +02:00
|
|
|
hs.redirectWithError(ctx, err, v...)
|
|
|
|
|
2020-11-06 10:01:13 +01:00
|
|
|
info.Error = err
|
|
|
|
hs.HooksService.RunLoginHook(&info, ctx)
|
2020-09-04 14:54:59 +02:00
|
|
|
}
|