AuthN: Add post auth hook for oauth token refresh (#61608)

* AuthN: rename package to sync

* AuthN: rename sync files

* Ouath: Add mock for OauthTokenService

* AuthN: Implement access token refresh hook

* AuthN: remove feature check from hook

* AuthN: register post auth hook for oauth token refresh
This commit is contained in:
Karl Persson
2023-01-18 10:47:09 +01:00
committed by GitHub
parent 29119a7d08
commit 412d80b498
8 changed files with 278 additions and 5 deletions
@@ -0,0 +1,79 @@
package sync
import (
"context"
"errors"
"time"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/auth"
"github.com/grafana/grafana/pkg/services/authn"
"github.com/grafana/grafana/pkg/services/oauthtoken"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/util/errutil"
)
var (
errExpiredAccessToken = errutil.NewBase(errutil.StatusUnauthorized, "oauth.expired-token")
)
func ProvideOauthTokenSync(service oauthtoken.OAuthTokenService, sessionService auth.UserTokenService) *OauthTokenSync {
return &OauthTokenSync{
log.New("oauth_token.sync"),
service,
sessionService,
}
}
type OauthTokenSync struct {
log log.Logger
service oauthtoken.OAuthTokenService
sessionService auth.UserTokenService
}
func (s *OauthTokenSync) SyncOauthToken(ctx context.Context, identity *authn.Identity, _ *authn.Request) error {
namespace, id := identity.NamespacedID()
// only perform oauth token check if identity is a user
if namespace != authn.NamespaceUser {
return nil
}
// not authenticated through session tokens, so we can skip this hook
if identity.SessionToken == nil {
return nil
}
token, exists, _ := s.service.HasOAuthEntry(ctx, &user.SignedInUser{UserID: id})
// user is not authenticated through oauth so skip further checks
if !exists {
return nil
}
// token has no expire time configured, so we don't have to refresh it
if token.OAuthExpiry.IsZero() {
return nil
}
// token has not expired, so we don't have to refresh it
if !token.OAuthExpiry.Round(0).Add(-oauthtoken.ExpiryDelta).Before(time.Now()) {
return nil
}
if err := s.service.TryTokenRefresh(ctx, token); err != nil {
if !errors.Is(err, oauthtoken.ErrNoRefreshTokenFound) {
s.log.FromContext(ctx).Error("could not refresh oauth access token for user", "userId", id, "err", err)
}
if err := s.service.InvalidateOAuthTokens(ctx, token); err != nil {
s.log.FromContext(ctx).Error("could not invalidate OAuth tokens", "userId", id, "err", err)
}
if err := s.sessionService.RevokeToken(ctx, identity.SessionToken, false); err != nil {
s.log.FromContext(ctx).Error("could not revoke token", "userId", id, "tokenId", identity.SessionToken.Id, "err", err)
}
return errExpiredAccessToken.Errorf("oauth access token could not be refreshed: %w", auth.ErrInvalidSessionToken)
}
return nil
}
@@ -0,0 +1,134 @@
package sync
import (
"context"
"errors"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/auth"
"github.com/grafana/grafana/pkg/services/auth/authtest"
"github.com/grafana/grafana/pkg/services/authn"
"github.com/grafana/grafana/pkg/services/oauthtoken/oauthtokentest"
"github.com/grafana/grafana/pkg/services/user"
)
func TestOauthTokenSync_SyncOauthToken(t *testing.T) {
type testCase struct {
desc string
identity *authn.Identity
expectedHasEntryToken *models.UserAuth
expectHasEntryCalled bool
expectedTryRefreshErr error
expectTryRefreshTokenCalled bool
expectRevokeTokenCalled bool
expectInvalidateOauthTokensCalled bool
expectedErr error
}
tests := []testCase{
{
desc: "should skip sync when identity is not a user",
identity: &authn.Identity{ID: "service-account:1"},
},
{
desc: "should skip sync when identity is a user but is not authenticated with session token",
identity: &authn.Identity{ID: "user:1"},
},
{
desc: "should skip sync when user has session but is not authenticated with oauth",
identity: &authn.Identity{ID: "user:1", SessionToken: &auth.UserToken{}},
expectHasEntryCalled: true,
},
{
desc: "should skip sync for when access token don't have expire time",
identity: &authn.Identity{ID: "user:1", SessionToken: &auth.UserToken{}},
expectHasEntryCalled: true,
expectedHasEntryToken: &models.UserAuth{},
},
{
desc: "should skip sync when access token has no expired yet",
identity: &authn.Identity{ID: "user:1", SessionToken: &auth.UserToken{}},
expectHasEntryCalled: true,
expectedHasEntryToken: &models.UserAuth{OAuthExpiry: time.Now().Add(10 * time.Minute)},
},
{
desc: "should skip sync when access token has no expired yet",
identity: &authn.Identity{ID: "user:1", SessionToken: &auth.UserToken{}},
expectHasEntryCalled: true,
expectedHasEntryToken: &models.UserAuth{OAuthExpiry: time.Now().Add(10 * time.Minute)},
},
{
desc: "should refresh access token when is has expired",
identity: &authn.Identity{ID: "user:1", SessionToken: &auth.UserToken{}},
expectHasEntryCalled: true,
expectTryRefreshTokenCalled: true,
expectedHasEntryToken: &models.UserAuth{OAuthExpiry: time.Now().Add(-10 * time.Minute)},
},
{
desc: "should invalidate access token and session token if access token can't be refreshed",
identity: &authn.Identity{ID: "user:1", SessionToken: &auth.UserToken{}},
expectHasEntryCalled: true,
expectedTryRefreshErr: errors.New("some err"),
expectTryRefreshTokenCalled: true,
expectInvalidateOauthTokensCalled: true,
expectRevokeTokenCalled: true,
expectedHasEntryToken: &models.UserAuth{OAuthExpiry: time.Now().Add(-10 * time.Minute)},
expectedErr: errExpiredAccessToken,
},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
var (
hasEntryCalled bool
tryRefreshCalled bool
invalidateTokensCalled bool
revokeTokenCalled bool
)
service := &oauthtokentest.MockOauthTokenService{
HasOAuthEntryFunc: func(ctx context.Context, usr *user.SignedInUser) (*models.UserAuth, bool, error) {
hasEntryCalled = true
return tt.expectedHasEntryToken, tt.expectedHasEntryToken != nil, nil
},
InvalidateOAuthTokensFunc: func(ctx context.Context, usr *models.UserAuth) error {
invalidateTokensCalled = true
return nil
},
TryTokenRefreshFunc: func(ctx context.Context, usr *models.UserAuth) error {
tryRefreshCalled = true
return tt.expectedTryRefreshErr
},
}
sessionService := &authtest.FakeUserAuthTokenService{
RevokeTokenProvider: func(ctx context.Context, token *auth.UserToken, soft bool) error {
revokeTokenCalled = true
return nil
},
}
sync := &OauthTokenSync{
log: log.NewNopLogger(),
service: service,
sessionService: sessionService,
}
err := sync.SyncOauthToken(context.Background(), tt.identity, nil)
assert.ErrorIs(t, err, tt.expectedErr)
assert.Equal(t, tt.expectHasEntryCalled, hasEntryCalled)
assert.Equal(t, tt.expectTryRefreshTokenCalled, tryRefreshCalled)
assert.Equal(t, tt.expectInvalidateOauthTokensCalled, invalidateTokensCalled)
assert.Equal(t, tt.expectRevokeTokenCalled, revokeTokenCalled)
})
}
}
@@ -0,0 +1,124 @@
package sync
import (
"context"
"errors"
"sort"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/authn"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/user"
)
func ProvideOrgSync(userService user.Service, orgService org.Service, accessControl accesscontrol.Service) *OrgSync {
return &OrgSync{userService, orgService, accessControl, log.New("org.sync")}
}
type OrgSync struct {
userService user.Service
orgService org.Service
accessControl accesscontrol.Service
log log.Logger
}
func (s *OrgSync) SyncOrgUser(ctx context.Context, id *authn.Identity, _ *authn.Request) error {
if !id.ClientParams.SyncUser {
return nil
}
namespace, userID := id.NamespacedID()
if namespace != "user" || userID <= 0 {
s.log.Warn("invalid namespace %q for user ID %q", namespace, userID)
return nil
}
s.log.Debug("syncing organization roles", "id", userID, "extOrgRoles", id.OrgRoles)
// don't sync org roles if none is specified
if len(id.OrgRoles) == 0 {
s.log.Debug("not syncing organization roles since external user doesn't have any")
return nil
}
orgsQuery := &org.GetUserOrgListQuery{UserID: userID}
result, err := s.orgService.GetUserOrgList(ctx, orgsQuery)
if err != nil {
s.log.Error("failed to get user's organizations", "userId", userID, "error", err)
return nil
}
handledOrgIds := map[int64]bool{}
deleteOrgIds := []int64{}
// update existing org roles
for _, orga := range result {
handledOrgIds[orga.OrgID] = true
extRole := id.OrgRoles[orga.OrgID]
if extRole == "" {
deleteOrgIds = append(deleteOrgIds, orga.OrgID)
} else if extRole != orga.Role {
// update role
cmd := &org.UpdateOrgUserCommand{OrgID: orga.OrgID, UserID: userID, Role: extRole}
if err := s.orgService.UpdateOrgUser(ctx, cmd); err != nil {
s.log.Error("failed to update active org user", "userId", userID, "error", err)
return nil
}
}
}
orgIDs := make([]int64, 0, len(id.OrgRoles))
// add any new org roles
for orgId, orgRole := range id.OrgRoles {
orgIDs = append(orgIDs, orgId)
if _, exists := handledOrgIds[orgId]; exists {
continue
}
// add role
cmd := &org.AddOrgUserCommand{UserID: userID, Role: orgRole, OrgID: orgId}
err := s.orgService.AddOrgUser(ctx, cmd)
if err != nil && !errors.Is(err, org.ErrOrgNotFound) {
s.log.Error("failed to update active org user", "userId", userID, "error", err)
return nil
}
}
// delete any removed org roles
for _, orgId := range deleteOrgIds {
s.log.Debug("Removing user's organization membership as part of syncing with OAuth login",
"userId", userID, "orgId", orgId)
cmd := &org.RemoveOrgUserCommand{OrgID: orgId, UserID: userID}
if err := s.orgService.RemoveOrgUser(ctx, cmd); err != nil {
if errors.Is(err, org.ErrLastOrgAdmin) {
s.log.Error(err.Error(), "userId", cmd.UserID, "orgId", cmd.OrgID)
continue
}
s.log.Error("failed to delete user org membership", "userId", userID, "error", err)
return nil
}
if err := s.accessControl.DeleteUserPermissions(ctx, orgId, cmd.UserID); err != nil {
s.log.Error("failed to delete permissions for user", "error", err, "userID", cmd.UserID, "orgID", orgId)
return nil
}
}
// Note: sort all org ids to not make it flaky, for now we default to the lowest id
sort.Slice(orgIDs, func(i, j int) bool { return orgIDs[i] < orgIDs[j] })
// update user's default org if needed
if _, ok := id.OrgRoles[id.OrgID]; !ok {
if len(orgIDs) > 0 {
id.OrgID = orgIDs[0]
return s.userService.SetUsingOrg(ctx, &user.SetUsingOrgCommand{
UserID: userID,
OrgID: id.OrgID,
})
}
}
return nil
}
@@ -0,0 +1,125 @@
package sync
import (
"context"
"testing"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/models/roletype"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/accesscontrol/actest"
"github.com/grafana/grafana/pkg/services/authn"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/org/orgtest"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/services/user/usertest"
"github.com/stretchr/testify/assert"
)
func TestOrgSync_SyncOrgUser(t *testing.T) {
orgService := &orgtest.FakeOrgService{ExpectedUserOrgDTO: []*org.UserOrgDTO{
{
OrgID: 1,
Role: org.RoleEditor,
},
{
OrgID: 3,
Role: org.RoleViewer,
},
},
ExpectedOrgListResponse: orgtest.OrgListResponse{
{
OrgID: 3,
Response: nil,
},
},
}
acService := &actest.FakeService{}
userService := &usertest.FakeUserService{ExpectedUser: &user.User{
ID: 1,
Login: "test",
Name: "test",
Email: "test",
}}
type fields struct {
userService user.Service
orgService org.Service
accessControl accesscontrol.Service
log log.Logger
}
type args struct {
ctx context.Context
id *authn.Identity
}
tests := []struct {
name string
fields fields
args args
wantErr bool
wantID *authn.Identity
}{
{
name: "add user to multiple orgs",
fields: fields{
userService: userService,
orgService: orgService,
accessControl: acService,
log: log.NewNopLogger(),
},
args: args{
ctx: context.Background(),
id: &authn.Identity{
ID: "user:1",
Login: "test",
Name: "test",
Email: "test",
OrgRoles: map[int64]roletype.RoleType{1: org.RoleAdmin, 2: org.RoleEditor},
IsGrafanaAdmin: ptrBool(false),
ClientParams: authn.ClientParams{
SyncUser: true,
LookUpParams: models.UserLookupParams{
UserID: nil,
Email: ptrString("test"),
Login: nil,
},
},
},
},
wantID: &authn.Identity{
ID: "user:1",
Login: "test",
Name: "test",
Email: "test",
OrgRoles: map[int64]roletype.RoleType{1: org.RoleAdmin, 2: org.RoleEditor},
OrgID: 1, //set using org
IsGrafanaAdmin: ptrBool(false),
ClientParams: authn.ClientParams{
SyncUser: true,
LookUpParams: models.UserLookupParams{
UserID: nil,
Email: ptrString("test"),
Login: nil,
},
},
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &OrgSync{
userService: tt.fields.userService,
orgService: tt.fields.orgService,
accessControl: tt.fields.accessControl,
log: tt.fields.log,
}
if err := s.SyncOrgUser(tt.args.ctx, tt.args.id, nil); (err != nil) != tt.wantErr {
t.Errorf("OrgSync.SyncOrgUser() error = %v, wantErr %v", err, tt.wantErr)
}
assert.EqualValues(t, tt.wantID, tt.args.id)
})
}
}
@@ -0,0 +1,305 @@
package sync
import (
"context"
"errors"
"fmt"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/authn"
"github.com/grafana/grafana/pkg/services/login"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/services/quota"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/util/errutil"
)
var (
errSyncUserForbidden = errutil.NewBase(errutil.StatusForbidden,
"user.sync.forbidden", errutil.WithPublicMessage("User sync forbidden"))
errSyncUserInternal = errutil.NewBase(errutil.StatusInternal,
"user.sync.forbidden", errutil.WithPublicMessage("User sync failed"))
errUserProtection = errutil.NewBase(errutil.StatusForbidden,
"user.sync.protectedrole", errutil.WithPublicMessage("Unable to sync due to protected role"))
)
func ProvideUserSync(userService user.Service,
userProtectionService login.UserProtectionService,
authInfoService login.AuthInfoService, quotaService quota.Service) *UserSync {
return &UserSync{
userService: userService,
authInfoService: authInfoService,
userProtectionService: userProtectionService,
quotaService: quotaService,
log: log.New("user.sync"),
}
}
type UserSync struct {
userService user.Service
authInfoService login.AuthInfoService
userProtectionService login.UserProtectionService
quotaService quota.Service
log log.Logger
}
// SyncUser syncs a user with the database
func (s *UserSync) SyncUser(ctx context.Context, id *authn.Identity, _ *authn.Request) error {
if !id.ClientParams.SyncUser {
return nil
}
// Does user exist in the database?
usr, errUserInDB := s.UserInDB(ctx, &id.AuthModule, &id.AuthID, id.ClientParams.LookUpParams)
if errUserInDB != nil && !errors.Is(errUserInDB, user.ErrUserNotFound) {
s.log.Error("error retrieving user", "error", errUserInDB,
"auth_module", id.AuthModule, "auth_id", id.AuthID,
"lookup_params", id.ClientParams.LookUpParams,
)
return errSyncUserInternal.Errorf("unable to retrieve user")
}
if errors.Is(errUserInDB, user.ErrUserNotFound) {
if !id.ClientParams.AllowSignUp {
s.log.Warn("not allowing login, user not found in internal user database and allow signup = false",
"auth_module", id.AuthModule)
return errSyncUserForbidden.Errorf("%w", login.ErrSignupNotAllowed)
}
// quota check (FIXME: (jguer) this should be done in the user service)
// we may insert in both user and org_user tables
// therefore we need to query check quota for both user and org services
for _, srv := range []string{user.QuotaTargetSrv, org.QuotaTargetSrv} {
limitReached, errLimit := s.quotaService.CheckQuotaReached(ctx, quota.TargetSrv(srv), nil)
if errLimit != nil {
s.log.Error("error getting user quota", "error", errLimit)
return errSyncUserInternal.Errorf("%w", login.ErrGettingUserQuota)
}
if limitReached {
return errSyncUserForbidden.Errorf("%w", login.ErrUsersQuotaReached)
}
}
// create user
var errCreate error
usr, errCreate = s.createUser(ctx, id)
if errCreate != nil {
s.log.Error("error creating user", "error", errCreate,
"auth_module", id.AuthModule, "auth_id", id.AuthID,
"id_login", id.Login, "id_email", id.Email,
)
return errSyncUserInternal.Errorf("unable to create user")
}
}
if errProtection := s.userProtectionService.AllowUserMapping(usr, id.AuthModule); errProtection != nil {
return errUserProtection.Errorf("user mapping not allowed: %w", errProtection)
}
// update user
if errUpdate := s.updateUserAttributes(ctx, usr, id); errUpdate != nil {
s.log.Error("error creating user", "error", errUpdate,
"auth_module", id.AuthModule, "auth_id", id.AuthID,
"login", usr.Login, "email", usr.Email,
"id_login", id.Login, "id_email", id.Email,
)
return errSyncUserInternal.Errorf("unable to update user")
}
syncUserToIdentity(usr, id)
// persist latest auth info token
if errAuthInfo := s.updateAuthInfo(ctx, id); errAuthInfo != nil {
s.log.Error("error creating user", "error", errAuthInfo,
"auth_module", id.AuthModule, "auth_id", id.AuthID,
)
return errSyncUserInternal.Errorf("unable to update auth info")
}
return nil
}
// syncUserToIdentity syncs a user to an identity.
// This is used to update the identity with the latest user information.
func syncUserToIdentity(usr *user.User, id *authn.Identity) {
id.ID = fmt.Sprintf("user:%d", usr.ID)
id.Login = usr.Login
id.Email = usr.Email
id.Name = usr.Name
id.IsGrafanaAdmin = &usr.IsAdmin
}
func (s *UserSync) updateAuthInfo(ctx context.Context, id *authn.Identity) error {
if id.AuthModule != "" && id.OAuthToken != nil && id.AuthID != "" {
return nil
}
namespace, userID := id.NamespacedID()
if namespace != "user" && userID <= 0 { // FIXME: constant namespace
return fmt.Errorf("invalid namespace %q for user ID %q", namespace, userID)
}
updateCmd := &models.UpdateAuthInfoCommand{
AuthModule: id.AuthModule,
AuthId: id.AuthID,
UserId: userID,
OAuthToken: id.OAuthToken,
}
s.log.Debug("Updating user_auth info", "user_id", userID)
return s.authInfoService.UpdateAuthInfo(ctx, updateCmd)
}
func (s *UserSync) updateUserAttributes(ctx context.Context, usr *user.User, id *authn.Identity) error {
// sync user info
updateCmd := &user.UpdateUserCommand{
UserID: usr.ID,
}
needsUpdate := false
if id.Login != "" && id.Login != usr.Login {
updateCmd.Login = id.Login
usr.Login = id.Login
needsUpdate = true
}
if id.Email != "" && id.Email != usr.Email {
updateCmd.Email = id.Email
usr.Email = id.Email
needsUpdate = true
}
if id.Name != "" && id.Name != usr.Name {
updateCmd.Name = id.Name
usr.Name = id.Name
needsUpdate = true
}
if needsUpdate {
s.log.Debug("Syncing user info", "id", usr.ID, "update", updateCmd)
if err := s.userService.Update(ctx, updateCmd); err != nil {
return err
}
}
if usr.IsDisabled && id.ClientParams.EnableDisabledUsers {
usr.IsDisabled = false
if errDisableUser := s.userService.Disable(ctx,
&user.DisableUserCommand{
UserID: usr.ID, IsDisabled: false}); errDisableUser != nil {
return errDisableUser
}
}
// Sync isGrafanaAdmin permission
if id.IsGrafanaAdmin != nil && *id.IsGrafanaAdmin != usr.IsAdmin {
usr.IsAdmin = *id.IsGrafanaAdmin
if errPerms := s.userService.UpdatePermissions(ctx, usr.ID, *id.IsGrafanaAdmin); errPerms != nil {
return errPerms
}
}
return nil
}
func (s *UserSync) createUser(ctx context.Context, id *authn.Identity) (*user.User, error) {
isAdmin := false
if id.IsGrafanaAdmin != nil {
isAdmin = *id.IsGrafanaAdmin
}
// TODO: add quota check
usr, errCreateUser := s.userService.Create(ctx, &user.CreateUserCommand{
Login: id.Login,
Email: id.Email,
Name: id.Name,
IsAdmin: isAdmin,
SkipOrgSetup: len(id.OrgRoles) > 0,
})
if errCreateUser != nil {
return nil, errCreateUser
}
if id.AuthModule != "" && id.AuthID != "" {
if errSetAuth := s.authInfoService.SetAuthInfo(ctx, &models.SetAuthInfoCommand{
UserId: usr.ID,
AuthModule: id.AuthModule,
AuthId: id.AuthID,
OAuthToken: id.OAuthToken,
}); errSetAuth != nil {
return nil, errSetAuth
}
}
return usr, nil
}
// Does user exist in the database?
// Check first authinfo table, then user table
// return user id if found, 0 if not found
func (s *UserSync) UserInDB(ctx context.Context,
authID *string,
authModule *string,
params models.UserLookupParams) (*user.User, error) {
// Check authinfo table
if authID != nil && authModule != nil {
query := &models.GetAuthInfoQuery{
AuthModule: *authModule,
AuthId: *authID,
}
errGetAuthInfo := s.authInfoService.GetAuthInfo(ctx, query)
if errGetAuthInfo == nil {
usr, errGetByID := s.userService.GetByID(ctx, &user.GetUserByIDQuery{ID: query.Result.UserId})
if errGetByID == nil {
return usr, nil
}
if !errors.Is(errGetByID, user.ErrUserNotFound) {
return nil, errGetByID
}
}
if !errors.Is(errGetAuthInfo, user.ErrUserNotFound) {
return nil, errGetAuthInfo
}
}
// Check user table to grab existing user
return s.LookupByOneOf(ctx, &params)
}
func (s *UserSync) LookupByOneOf(ctx context.Context, params *models.UserLookupParams) (*user.User, error) {
var usr *user.User
var err error
// If not found, try to find the user by id
if params.UserID != nil && *params.UserID != 0 {
usr, err = s.userService.GetByID(ctx, &user.GetUserByIDQuery{ID: *params.UserID})
if err != nil && !errors.Is(err, user.ErrUserNotFound) {
return nil, err
}
}
// If not found, try to find the user by email address
if usr == nil && params.Email != nil && *params.Email != "" {
usr, err = s.userService.GetByEmail(ctx, &user.GetUserByEmailQuery{Email: *params.Email})
if err != nil && !errors.Is(err, user.ErrUserNotFound) {
return nil, err
}
}
// If not found, try to find the user by login
if usr == nil && params.Login != nil && *params.Login != "" {
usr, err = s.userService.GetByLogin(ctx, &user.GetUserByLoginQuery{LoginOrEmail: *params.Login})
if err != nil && !errors.Is(err, user.ErrUserNotFound) {
return nil, err
}
}
if usr == nil || usr.ID == 0 { // id check as safeguard against returning empty user
return nil, user.ErrUserNotFound
}
return usr, nil
}
@@ -0,0 +1,440 @@
package sync
import (
"context"
"testing"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/authn"
"github.com/grafana/grafana/pkg/services/login"
"github.com/grafana/grafana/pkg/services/login/authinfoservice"
"github.com/grafana/grafana/pkg/services/login/logintest"
"github.com/grafana/grafana/pkg/services/quota"
"github.com/grafana/grafana/pkg/services/quota/quotatest"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/services/user/usertest"
"github.com/stretchr/testify/require"
)
func ptrString(s string) *string {
return &s
}
func ptrBool(b bool) *bool {
return &b
}
func ptrInt64(i int64) *int64 {
return &i
}
func TestUserSync_SyncUser(t *testing.T) {
userProtection := &authinfoservice.OSSUserProtectionImpl{}
authFakeNil := &logintest.AuthInfoServiceFake{
ExpectedUser: nil,
ExpectedError: user.ErrUserNotFound,
SetAuthInfoFn: func(ctx context.Context, cmd *models.SetAuthInfoCommand) error {
return nil
},
UpdateAuthInfoFn: func(ctx context.Context, cmd *models.UpdateAuthInfoCommand) error {
return nil
},
}
authFakeUserID := &logintest.AuthInfoServiceFake{
ExpectedUser: nil,
ExpectedError: nil,
ExpectedUserAuth: &models.UserAuth{
AuthModule: "oauth",
AuthId: "2032",
UserId: 1,
Id: 1}}
userService := &usertest.FakeUserService{ExpectedUser: &user.User{
ID: 1,
Login: "test",
Name: "test",
Email: "test",
}}
userServiceMod := &usertest.FakeUserService{ExpectedUser: &user.User{
ID: 3,
Login: "test",
Name: "test",
Email: "test",
IsDisabled: true,
IsAdmin: false,
}}
userServiceNil := &usertest.FakeUserService{
ExpectedUser: nil,
ExpectedError: user.ErrUserNotFound,
CreateFn: func(ctx context.Context, cmd *user.CreateUserCommand) (*user.User, error) {
return &user.User{
ID: 2,
Login: cmd.Login,
Name: cmd.Name,
Email: cmd.Email,
IsAdmin: cmd.IsAdmin,
}, nil
},
}
type fields struct {
userService user.Service
authInfoService login.AuthInfoService
quotaService quota.Service
}
type args struct {
ctx context.Context
id *authn.Identity
}
tests := []struct {
name string
fields fields
args args
wantErr bool
wantID *authn.Identity
}{
{
name: "no sync",
fields: fields{
userService: userService,
authInfoService: authFakeNil,
quotaService: &quotatest.FakeQuotaService{},
},
args: args{
ctx: context.Background(),
id: &authn.Identity{
ID: "",
Login: "test",
Name: "test",
Email: "test",
ClientParams: authn.ClientParams{
LookUpParams: models.UserLookupParams{
UserID: nil,
Email: ptrString("test"),
Login: nil,
},
},
},
},
wantErr: false,
wantID: &authn.Identity{
ID: "",
Login: "test",
Name: "test",
Email: "test",
ClientParams: authn.ClientParams{
LookUpParams: models.UserLookupParams{
UserID: nil,
Email: ptrString("test"),
Login: nil,
},
},
},
},
{
name: "sync - user found in DB - by email",
fields: fields{
userService: userService,
authInfoService: authFakeNil,
quotaService: &quotatest.FakeQuotaService{},
},
args: args{
ctx: context.Background(),
id: &authn.Identity{
ID: "",
Login: "test",
Name: "test",
Email: "test",
ClientParams: authn.ClientParams{
SyncUser: true,
LookUpParams: models.UserLookupParams{
UserID: nil,
Email: ptrString("test"),
Login: nil,
},
},
},
},
wantErr: false,
wantID: &authn.Identity{
ID: "user:1",
Login: "test",
Name: "test",
Email: "test",
IsGrafanaAdmin: ptrBool(false),
ClientParams: authn.ClientParams{
SyncUser: true,
LookUpParams: models.UserLookupParams{
UserID: nil,
Email: ptrString("test"),
Login: nil,
},
},
},
},
{
name: "sync - user found in DB - by login",
fields: fields{
userService: userService,
authInfoService: authFakeNil,
quotaService: &quotatest.FakeQuotaService{},
},
args: args{
ctx: context.Background(),
id: &authn.Identity{
ID: "",
Login: "test",
Name: "test",
Email: "test",
ClientParams: authn.ClientParams{
SyncUser: true,
LookUpParams: models.UserLookupParams{
UserID: nil,
Email: nil,
Login: ptrString("test"),
},
},
},
},
wantErr: false,
wantID: &authn.Identity{
ID: "user:1",
Login: "test",
Name: "test",
Email: "test",
IsGrafanaAdmin: ptrBool(false),
ClientParams: authn.ClientParams{
LookUpParams: models.UserLookupParams{
UserID: nil,
Email: nil,
Login: ptrString("test"),
},
SyncUser: true,
},
},
},
{
name: "sync - user found in DB - by ID",
fields: fields{
userService: userService,
authInfoService: authFakeNil,
quotaService: &quotatest.FakeQuotaService{},
},
args: args{
ctx: context.Background(),
id: &authn.Identity{
ID: "",
Login: "test",
Name: "test",
Email: "test",
ClientParams: authn.ClientParams{
SyncUser: true,
LookUpParams: models.UserLookupParams{
UserID: ptrInt64(1),
Email: nil,
Login: nil,
},
},
},
},
wantErr: false,
wantID: &authn.Identity{
ID: "user:1",
Login: "test",
Name: "test",
Email: "test",
IsGrafanaAdmin: ptrBool(false),
ClientParams: authn.ClientParams{
SyncUser: true,
LookUpParams: models.UserLookupParams{
UserID: ptrInt64(1),
Email: nil,
Login: nil,
},
},
},
},
{
name: "sync - user found in authInfo",
fields: fields{
userService: userService,
authInfoService: authFakeUserID,
quotaService: &quotatest.FakeQuotaService{},
},
args: args{
ctx: context.Background(),
id: &authn.Identity{
ID: "",
Login: "test",
Name: "test",
Email: "test",
ClientParams: authn.ClientParams{
SyncUser: true,
LookUpParams: models.UserLookupParams{
UserID: nil,
Email: nil,
Login: nil,
},
},
},
},
wantErr: false,
wantID: &authn.Identity{
ID: "user:1",
Login: "test",
Name: "test",
Email: "test",
IsGrafanaAdmin: ptrBool(false),
ClientParams: authn.ClientParams{
SyncUser: true,
LookUpParams: models.UserLookupParams{
UserID: nil,
Email: nil,
Login: nil,
},
},
},
},
{
name: "sync - user needs to be created - disabled signup",
fields: fields{
userService: userService,
authInfoService: authFakeNil,
quotaService: &quotatest.FakeQuotaService{},
},
args: args{
ctx: context.Background(),
id: &authn.Identity{
ID: "",
Login: "test",
Name: "test",
Email: "test",
AuthModule: "oauth",
AuthID: "2032",
ClientParams: authn.ClientParams{
SyncUser: true,
LookUpParams: models.UserLookupParams{
UserID: nil,
Email: nil,
Login: nil,
},
},
},
},
wantErr: true,
},
{
name: "sync - user needs to be created - enabled signup",
fields: fields{
userService: userServiceNil,
authInfoService: authFakeNil,
quotaService: &quotatest.FakeQuotaService{},
},
args: args{
ctx: context.Background(),
id: &authn.Identity{
ID: "",
Login: "test_create",
Name: "test_create",
IsGrafanaAdmin: ptrBool(true),
Email: "test_create",
AuthModule: "oauth",
AuthID: "2032",
ClientParams: authn.ClientParams{
SyncUser: true,
AllowSignUp: true,
EnableDisabledUsers: true,
LookUpParams: models.UserLookupParams{
UserID: nil,
Email: ptrString("test_create"),
Login: nil,
},
},
},
},
wantErr: false,
wantID: &authn.Identity{
ID: "user:2",
Login: "test_create",
Name: "test_create",
Email: "test_create",
AuthModule: "oauth",
AuthID: "2032",
IsGrafanaAdmin: ptrBool(true),
ClientParams: authn.ClientParams{
SyncUser: true,
AllowSignUp: true,
EnableDisabledUsers: true,
LookUpParams: models.UserLookupParams{
UserID: nil,
Email: ptrString("test_create"),
Login: nil,
},
},
},
},
{
name: "sync - needs full update",
fields: fields{
userService: userServiceMod,
authInfoService: authFakeNil,
quotaService: &quotatest.FakeQuotaService{},
},
args: args{
ctx: context.Background(),
id: &authn.Identity{
ID: "",
Login: "test_mod",
Name: "test_mod",
Email: "test_mod",
IsDisabled: false,
IsGrafanaAdmin: ptrBool(true),
ClientParams: authn.ClientParams{
SyncUser: true,
EnableDisabledUsers: true,
LookUpParams: models.UserLookupParams{
UserID: ptrInt64(3),
Email: nil,
Login: nil,
},
},
},
},
wantErr: false,
wantID: &authn.Identity{
ID: "user:3",
Login: "test_mod",
Name: "test_mod",
Email: "test_mod",
IsDisabled: false,
IsGrafanaAdmin: ptrBool(true),
ClientParams: authn.ClientParams{
SyncUser: true,
EnableDisabledUsers: true,
LookUpParams: models.UserLookupParams{
UserID: ptrInt64(3),
Email: nil,
Login: nil,
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := ProvideUserSync(tt.fields.userService, userProtection, tt.fields.authInfoService, tt.fields.quotaService)
err := s.SyncUser(tt.args.ctx, tt.args.id, nil)
if tt.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
require.EqualValues(t, tt.wantID, tt.args.id)
})
}
}