github.com/polarismesh/polaris@v1.17.8/auth/defaultauth/user_test.go (about)

     1  /**
     2   * Tencent is pleased to support the open source community by making Polaris available.
     3   *
     4   * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
     5   *
     6   * Licensed under the BSD 3-Clause License (the "License");
     7   * you may not use this file except in compliance with the License.
     8   * You may obtain a copy of the License at
     9   *
    10   * https://opensource.org/licenses/BSD-3-Clause
    11   *
    12   * Unless required by applicable law or agreed to in writing, software distributed
    13   * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
    14   * CONDITIONS OF ANY KIND, either express or implied. See the License for the
    15   * specific language governing permissions and limitations under the License.
    16   */
    17  
    18  package defaultauth_test
    19  
    20  import (
    21  	"context"
    22  	"testing"
    23  	"time"
    24  
    25  	"github.com/golang/mock/gomock"
    26  	"github.com/golang/protobuf/ptypes/wrappers"
    27  	apisecurity "github.com/polarismesh/specification/source/go/api/v1/security"
    28  	"github.com/stretchr/testify/assert"
    29  
    30  	"github.com/polarismesh/polaris/auth"
    31  	"github.com/polarismesh/polaris/auth/defaultauth"
    32  	"github.com/polarismesh/polaris/cache"
    33  	api "github.com/polarismesh/polaris/common/api/v1"
    34  	commonlog "github.com/polarismesh/polaris/common/log"
    35  	"github.com/polarismesh/polaris/common/model"
    36  	"github.com/polarismesh/polaris/common/utils"
    37  	storemock "github.com/polarismesh/polaris/store/mock"
    38  )
    39  
    40  type UserTest struct {
    41  	admin    *model.User
    42  	ownerOne *model.User
    43  	ownerTwo *model.User
    44  
    45  	users     []*model.User
    46  	newUsers  []*model.User
    47  	groups    []*model.UserGroupDetail
    48  	newGroups []*model.UserGroupDetail
    49  	allGroups []*model.UserGroupDetail
    50  
    51  	storage  *storemock.MockStore
    52  	cacheMgn *cache.CacheManager
    53  	checker  auth.AuthChecker
    54  
    55  	svr *defaultauth.UserAuthAbility
    56  
    57  	cancel context.CancelFunc
    58  	ctrl   *gomock.Controller
    59  }
    60  
    61  func newUserTest(t *testing.T) *UserTest {
    62  	reset(false)
    63  	ctrl := gomock.NewController(t)
    64  
    65  	commonlog.GetScopeOrDefaultByName(commonlog.AuthLoggerName).SetOutputLevel(commonlog.DebugLevel)
    66  	commonlog.GetScopeOrDefaultByName(commonlog.ConfigLoggerName).SetOutputLevel(commonlog.DebugLevel)
    67  
    68  	users := createMockUser(10, "one")
    69  	newUsers := createMockUser(10, "two")
    70  	admin := createMockUser(1, "admin")[0]
    71  	admin.Type = model.AdminUserRole
    72  	admin.Owner = ""
    73  	groups := createMockUserGroup(users)
    74  
    75  	storage := storemock.NewMockStore(ctrl)
    76  	storage.EXPECT().GetUnixSecond(gomock.Any()).AnyTimes().Return(time.Now().Unix(), nil)
    77  	storage.EXPECT().GetServicesCount().AnyTimes().Return(uint32(1), nil)
    78  	storage.EXPECT().AddUser(gomock.Any()).AnyTimes().Return(nil)
    79  	storage.EXPECT().GetUserByName(gomock.Eq("create-user-1"), gomock.Any()).AnyTimes().Return(nil, nil)
    80  	storage.EXPECT().GetUserByName(gomock.Eq("create-user-2"), gomock.Any()).AnyTimes().Return(&model.User{
    81  		Name: "create-user-2",
    82  	}, nil)
    83  
    84  	allUsers := append(append(users, newUsers...), admin)
    85  
    86  	storage.EXPECT().GetUsersForCache(gomock.Any(), gomock.Any()).AnyTimes().Return(allUsers, nil)
    87  	storage.EXPECT().GetGroupsForCache(gomock.Any(), gomock.Any()).AnyTimes().Return(groups, nil)
    88  	storage.EXPECT().UpdateUser(gomock.Any()).AnyTimes().Return(nil)
    89  	storage.EXPECT().DeleteUser(gomock.Any()).AnyTimes().Return(nil)
    90  
    91  	cfg := &cache.Config{
    92  		Open: true,
    93  		Resources: []cache.ConfigEntry{
    94  			{
    95  				Name: "users",
    96  			},
    97  		},
    98  	}
    99  
   100  	ctx, cancel := context.WithCancel(context.Background())
   101  	cacheMgn, err := cache.TestCacheInitialize(ctx, cfg, storage)
   102  	if err != nil {
   103  		t.Fatal(err)
   104  	}
   105  
   106  	time.Sleep(5 * time.Second)
   107  
   108  	checker := &defaultauth.DefaultAuthChecker{}
   109  	checker.SetCacheMgr(cacheMgn)
   110  
   111  	svr := defaultauth.NewUserAuthAbility(
   112  		checker,
   113  		defaultauth.NewServer(storage, nil, cacheMgn, checker),
   114  	)
   115  
   116  	return &UserTest{
   117  		admin:    admin,
   118  		ownerOne: users[0],
   119  		ownerTwo: newUsers[0],
   120  
   121  		users:    users,
   122  		newUsers: newUsers,
   123  		groups:   groups,
   124  
   125  		storage:  storage,
   126  		cacheMgn: cacheMgn,
   127  		checker:  checker,
   128  		svr:      svr,
   129  
   130  		cancel: cancel,
   131  		ctrl:   ctrl,
   132  	}
   133  }
   134  
   135  func (g *UserTest) Clean() {
   136  	g.ctrl.Finish()
   137  	g.cancel()
   138  	_ = g.cacheMgn.Close()
   139  	time.Sleep(2 * time.Second)
   140  }
   141  
   142  func Test_server_CreateUsers(t *testing.T) {
   143  
   144  	userTest := newUserTest(t)
   145  
   146  	defer userTest.Clean()
   147  
   148  	t.Run("主账户创建账户-成功", func(t *testing.T) {
   149  		createUsersReq := []*apisecurity.User{
   150  			{
   151  				Id:       &wrappers.StringValue{Value: utils.NewUUID()},
   152  				Name:     &wrappers.StringValue{Value: "create-user-1"},
   153  				Password: &wrappers.StringValue{Value: "create-user-1"},
   154  			},
   155  		}
   156  
   157  		userTest.storage.EXPECT().GetUser(gomock.Eq(userTest.ownerOne.ID)).Return(userTest.ownerOne, nil)
   158  
   159  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.ownerOne.Token)
   160  		resp := userTest.svr.CreateUsers(reqCtx, createUsersReq)
   161  
   162  		t.Logf("CreateUsers resp : %+v", resp)
   163  		assert.Equal(t, api.ExecuteSuccess, resp.Code.GetValue(), "create users must success")
   164  	})
   165  
   166  	t.Run("主账户创建账户-无用户名-失败", func(t *testing.T) {
   167  		createUsersReq := []*apisecurity.User{
   168  			{
   169  				Id: &wrappers.StringValue{Value: utils.NewUUID()},
   170  			},
   171  		}
   172  
   173  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   174  		resp := userTest.svr.CreateUsers(reqCtx, createUsersReq)
   175  
   176  		t.Logf("CreateUsers resp : %+v", resp)
   177  		assert.Equal(t, api.InvalidUserName, resp.Responses[0].Code.GetValue(), "create users must fail")
   178  	})
   179  
   180  	t.Run("主账户创建账户-密码错误-失败", func(t *testing.T) {
   181  		createUsersReq := []*apisecurity.User{
   182  			{
   183  				Id:       &wrappers.StringValue{Value: utils.NewUUID()},
   184  				Name:     &wrappers.StringValue{Value: "create-user-1"},
   185  				Password: &wrappers.StringValue{Value: ""},
   186  			},
   187  		}
   188  
   189  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   190  		resp := userTest.svr.CreateUsers(reqCtx, createUsersReq)
   191  
   192  		t.Logf("CreateUsers resp : %+v", resp)
   193  		assert.Equal(t, api.InvalidUserPassword, resp.Responses[0].Code.GetValue(), "create users must fail")
   194  	})
   195  
   196  	t.Run("主账户创建账户-同名用户-失败", func(t *testing.T) {
   197  		createUsersReq := []*apisecurity.User{
   198  			{
   199  				Id:       &wrappers.StringValue{Value: utils.NewUUID()},
   200  				Name:     &wrappers.StringValue{Value: "create-user-2"},
   201  				Password: &wrappers.StringValue{Value: "create-user-2"},
   202  			},
   203  		}
   204  
   205  		userTest.storage.EXPECT().GetUser(gomock.Eq(userTest.ownerOne.ID)).Return(userTest.ownerOne, nil)
   206  
   207  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   208  		resp := userTest.svr.CreateUsers(reqCtx, createUsersReq)
   209  
   210  		t.Logf("CreateUsers resp : %+v", resp)
   211  		assert.Equal(t, api.UserExisted, resp.Responses[0].Code.GetValue(), "create users must fail")
   212  	})
   213  
   214  	t.Run("主账户创建账户-与主账户同名", func(t *testing.T) {
   215  		createUsersReq := []*apisecurity.User{
   216  			{
   217  				Id:       &wrappers.StringValue{Value: utils.NewUUID()},
   218  				Name:     &wrappers.StringValue{Value: userTest.ownerOne.Name},
   219  				Password: &wrappers.StringValue{Value: "create-user-2"},
   220  			},
   221  		}
   222  
   223  		userTest.storage.EXPECT().GetUser(gomock.Eq(userTest.ownerOne.ID)).Return(userTest.ownerOne, nil)
   224  
   225  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.ownerOne.Token)
   226  		resp := userTest.svr.CreateUsers(reqCtx, createUsersReq)
   227  
   228  		t.Logf("CreateUsers resp : %+v", resp)
   229  		assert.Equal(t, api.UserExisted, resp.Responses[0].Code.GetValue(), "create users must fail")
   230  	})
   231  
   232  	t.Run("主账户创建账户-token为空-失败", func(t *testing.T) {
   233  		createUsersReq := []*apisecurity.User{
   234  			{
   235  				Id:       &wrappers.StringValue{Value: utils.NewUUID()},
   236  				Name:     &wrappers.StringValue{Value: "create-user-2"},
   237  				Password: &wrappers.StringValue{Value: "create-user-2"},
   238  			},
   239  		}
   240  
   241  		resp := userTest.svr.CreateUsers(context.Background(), createUsersReq)
   242  		t.Logf("CreateUsers resp : %+v", resp)
   243  		assert.Equal(t, api.EmptyAutToken, resp.Responses[0].Code.GetValue(), "create users must fail")
   244  	})
   245  
   246  	t.Run("主账户创建账户-token非法-失败", func(t *testing.T) {
   247  		createUsersReq := []*apisecurity.User{
   248  			{
   249  				Id:       &wrappers.StringValue{Value: utils.NewUUID()},
   250  				Name:     &wrappers.StringValue{Value: "create-user-2"},
   251  				Password: &wrappers.StringValue{Value: "create-user-2"},
   252  			},
   253  		}
   254  
   255  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "utils.ContextAuthTokenKey")
   256  		resp := userTest.svr.CreateUsers(reqCtx, createUsersReq)
   257  		t.Logf("CreateUsers resp : %+v", resp)
   258  		assert.Equal(t, api.AuthTokenVerifyException, resp.Responses[0].Code.GetValue(), "create users must fail")
   259  	})
   260  
   261  	t.Run("主账户创建账户-token被禁用-失败", func(t *testing.T) {
   262  		userTest.users[0].TokenEnable = false
   263  		// 让 cache 可以刷新到
   264  		time.Sleep(time.Second)
   265  
   266  		createUsersReq := []*apisecurity.User{
   267  			{
   268  				Id:       &wrappers.StringValue{Value: utils.NewUUID()},
   269  				Name:     &wrappers.StringValue{Value: "create-user-2"},
   270  				Password: &wrappers.StringValue{Value: "create-user-2"},
   271  			},
   272  		}
   273  
   274  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   275  		resp := userTest.svr.CreateUsers(reqCtx, createUsersReq)
   276  
   277  		t.Logf("CreateUsers resp : %+v", resp)
   278  		assert.Equal(t, api.TokenDisabled, resp.Responses[0].Code.GetValue(), "create users must fail")
   279  
   280  		userTest.users[0].TokenEnable = true
   281  		time.Sleep(time.Second)
   282  	})
   283  
   284  	t.Run("子主账户创建账户-失败", func(t *testing.T) {
   285  		createUsersReq := []*apisecurity.User{
   286  			{
   287  				Id:       &wrappers.StringValue{Value: utils.NewUUID()},
   288  				Name:     &wrappers.StringValue{Value: "create-user-1"},
   289  				Password: &wrappers.StringValue{Value: "create-user-1"},
   290  			},
   291  		}
   292  
   293  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[1].Token)
   294  		resp := userTest.svr.CreateUsers(reqCtx, createUsersReq)
   295  
   296  		t.Logf("CreateUsers resp : %+v", resp)
   297  		assert.Equal(t, api.OperationRoleException, resp.Responses[0].Code.GetValue(), "create users must fail")
   298  	})
   299  
   300  	t.Run("用户组token创建账户-失败", func(t *testing.T) {
   301  		createUsersReq := []*apisecurity.User{
   302  			{
   303  				Id:       &wrappers.StringValue{Value: utils.NewUUID()},
   304  				Name:     &wrappers.StringValue{Value: "create-user-1"},
   305  				Password: &wrappers.StringValue{Value: "create-user-1"},
   306  			},
   307  		}
   308  
   309  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.groups[1].Token)
   310  		resp := userTest.svr.CreateUsers(reqCtx, createUsersReq)
   311  
   312  		t.Logf("CreateUsers resp : %+v", resp)
   313  		assert.Equal(t, api.OperationRoleException, resp.Responses[0].Code.GetValue(), "create users must fail")
   314  	})
   315  }
   316  
   317  func Test_server_UpdateUser(t *testing.T) {
   318  
   319  	userTest := newUserTest(t)
   320  	defer userTest.Clean()
   321  
   322  	t.Run("主账户更新账户信息-正常更新自己的信息", func(t *testing.T) {
   323  		req := &apisecurity.User{
   324  			Id:      &wrappers.StringValue{Value: userTest.users[0].ID},
   325  			Comment: &wrappers.StringValue{Value: "update owner account info"},
   326  		}
   327  
   328  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[0], nil)
   329  
   330  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   331  		resp := userTest.svr.UpdateUser(reqCtx, req)
   332  
   333  		t.Logf("UpdateUsers resp : %+v", resp)
   334  		assert.Equal(t, api.ExecuteSuccess, resp.Code.GetValue(), "update user must success")
   335  	})
   336  
   337  	t.Run("主账户更新账户信息-更新不存在的子账户", func(t *testing.T) {
   338  		uid := utils.NewUUID()
   339  		req := &apisecurity.User{
   340  			Id:      &wrappers.StringValue{Value: uid},
   341  			Comment: &wrappers.StringValue{Value: "update owner account info"},
   342  		}
   343  
   344  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(nil, nil)
   345  
   346  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   347  		resp := userTest.svr.UpdateUser(reqCtx, req)
   348  
   349  		t.Logf("UpdateUsers resp : %+v", resp)
   350  		assert.Equal(t, api.NotFoundUser, resp.Code.GetValue(), "update user must fail")
   351  	})
   352  
   353  	t.Run("主账户更新账户信息-更新不属于自己的子账户", func(t *testing.T) {
   354  		uid := utils.NewUUID()
   355  		req := &apisecurity.User{
   356  			Id:      &wrappers.StringValue{Value: uid},
   357  			Comment: &wrappers.StringValue{Value: "update owner account info"},
   358  		}
   359  
   360  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(&model.User{
   361  			ID:    uid,
   362  			Owner: utils.NewUUID(),
   363  		}, nil)
   364  
   365  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   366  		resp := userTest.svr.UpdateUser(reqCtx, req)
   367  
   368  		t.Logf("UpdateUsers resp : %+v", resp)
   369  		assert.Equal(t, api.NotAllowedAccess, resp.Code.GetValue(), "update user must fail")
   370  	})
   371  
   372  	t.Run("子账户更新账户信息-正常更新自己的信息", func(t *testing.T) {
   373  		req := &apisecurity.User{
   374  			Id:      &wrappers.StringValue{Value: userTest.users[1].ID},
   375  			Comment: &wrappers.StringValue{Value: "update owner account info"},
   376  		}
   377  
   378  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[1], nil)
   379  
   380  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[1].Token)
   381  		resp := userTest.svr.UpdateUser(reqCtx, req)
   382  
   383  		t.Logf("UpdateUsers resp : %+v", resp)
   384  		assert.Equal(t, api.ExecuteSuccess, resp.Code.GetValue(), "update user must fail")
   385  	})
   386  
   387  	t.Run("子账户更新账户信息-更新别的账户", func(t *testing.T) {
   388  		req := &apisecurity.User{
   389  			Id:      &wrappers.StringValue{Value: userTest.users[2].ID},
   390  			Comment: &wrappers.StringValue{Value: "update owner account info"},
   391  		}
   392  
   393  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[2], nil)
   394  
   395  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[1].Token)
   396  		resp := userTest.svr.UpdateUser(reqCtx, req)
   397  
   398  		t.Logf("UpdateUsers resp : %+v", resp)
   399  		assert.Equal(t, api.NotAllowedAccess, resp.Code.GetValue(), "update user must fail")
   400  	})
   401  
   402  	t.Run("用户组Token更新账户信息-更新别的账户", func(t *testing.T) {
   403  		req := &apisecurity.User{
   404  			Id:      &wrappers.StringValue{Value: userTest.users[2].ID},
   405  			Comment: &wrappers.StringValue{Value: "update owner account info"},
   406  		}
   407  
   408  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.groups[1].Token)
   409  		resp := userTest.svr.UpdateUser(reqCtx, req)
   410  
   411  		t.Logf("UpdateUsers resp : %+v", resp)
   412  		assert.Equal(t, api.OperationRoleException, resp.Code.GetValue(), "update user must fail")
   413  	})
   414  }
   415  
   416  func Test_server_UpdateUserPassword(t *testing.T) {
   417  
   418  	userTest := newUserTest(t)
   419  	defer userTest.Clean()
   420  
   421  	t.Run("主账户正常更新自身账户密码", func(t *testing.T) {
   422  		req := &apisecurity.ModifyUserPassword{
   423  			Id:          &wrappers.StringValue{Value: userTest.users[0].ID},
   424  			OldPassword: &wrappers.StringValue{Value: "polaris"},
   425  			NewPassword: &wrappers.StringValue{Value: "polaris@2021"},
   426  		}
   427  
   428  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[0], nil)
   429  
   430  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   431  		resp := userTest.svr.UpdateUserPassword(reqCtx, req)
   432  		t.Logf("CreateUsers resp : %+v", resp)
   433  		assert.Equal(t, api.ExecuteSuccess, resp.Code.GetValue(), "update user must success")
   434  	})
   435  
   436  	t.Run("主账户正常更新自身账户密码-新密码非法", func(t *testing.T) {
   437  		req := &apisecurity.ModifyUserPassword{
   438  			Id:          &wrappers.StringValue{Value: userTest.users[0].ID},
   439  			OldPassword: &wrappers.StringValue{Value: "polaris"},
   440  			NewPassword: &wrappers.StringValue{Value: "pola"},
   441  		}
   442  
   443  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[0], nil)
   444  
   445  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   446  		resp := userTest.svr.UpdateUserPassword(reqCtx, req)
   447  		t.Logf("CreateUsers resp : %+v", resp)
   448  		assert.Equal(t, api.ExecuteException, resp.Code.GetValue(), "update user must fail")
   449  
   450  		req = &apisecurity.ModifyUserPassword{
   451  			Id:          &wrappers.StringValue{Value: userTest.users[0].ID},
   452  			OldPassword: &wrappers.StringValue{Value: "polaris"},
   453  			NewPassword: &wrappers.StringValue{Value: ""},
   454  		}
   455  
   456  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[0], nil)
   457  
   458  		reqCtx = context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   459  		resp = userTest.svr.UpdateUserPassword(reqCtx, req)
   460  		t.Logf("CreateUsers resp : %+v", resp)
   461  		assert.Equal(t, api.ExecuteException, resp.Code.GetValue(), "update user must fail")
   462  
   463  		req = &apisecurity.ModifyUserPassword{
   464  			Id:          &wrappers.StringValue{Value: userTest.users[0].ID},
   465  			OldPassword: &wrappers.StringValue{Value: "polaris"},
   466  			NewPassword: &wrappers.StringValue{Value: "polarispolarispolarispolaris"},
   467  		}
   468  
   469  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[0], nil)
   470  
   471  		reqCtx = context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   472  		resp = userTest.svr.UpdateUserPassword(reqCtx, req)
   473  		t.Logf("CreateUsers resp : %+v", resp)
   474  		assert.Equal(t, api.ExecuteException, resp.Code.GetValue(), "update user must fail")
   475  	})
   476  
   477  	t.Run("主账户正常更新子账户密码", func(t *testing.T) {
   478  		req := &apisecurity.ModifyUserPassword{
   479  			Id:          &wrappers.StringValue{Value: userTest.users[1].ID},
   480  			NewPassword: &wrappers.StringValue{Value: "polaris@sub"},
   481  		}
   482  
   483  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[1], nil)
   484  
   485  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   486  		resp := userTest.svr.UpdateUserPassword(reqCtx, req)
   487  		t.Logf("CreateUsers resp : %+v", resp)
   488  		assert.Equal(t, api.ExecuteSuccess, resp.Code.GetValue(), "update user must success")
   489  	})
   490  
   491  	t.Run("主账户正常更新子账户密码-子账户非自己", func(t *testing.T) {
   492  
   493  		uid := utils.NewUUID()
   494  
   495  		req := &apisecurity.ModifyUserPassword{
   496  			Id:          &wrappers.StringValue{Value: uid},
   497  			NewPassword: &wrappers.StringValue{Value: "polaris@subaccount"},
   498  		}
   499  
   500  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(&model.User{
   501  			ID:    uid,
   502  			Owner: utils.NewUUID(),
   503  		}, nil)
   504  
   505  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   506  		resp := userTest.svr.UpdateUserPassword(reqCtx, req)
   507  		t.Logf("CreateUsers resp : %+v", resp)
   508  		assert.Equal(t, api.NotAllowedAccess, resp.Code.GetValue(), "update user must fail")
   509  	})
   510  
   511  	t.Run("子账户更新账户密码-自身-携带正确原密码", func(t *testing.T) {
   512  		req := &apisecurity.ModifyUserPassword{
   513  			Id:          &wrappers.StringValue{Value: userTest.users[2].ID},
   514  			OldPassword: &wrappers.StringValue{Value: "polaris"},
   515  			NewPassword: &wrappers.StringValue{Value: "users[1].Password"},
   516  		}
   517  
   518  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[2], nil)
   519  
   520  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[2].Token)
   521  		resp := userTest.svr.UpdateUserPassword(reqCtx, req)
   522  		t.Logf("CreateUsers resp : %+v", resp)
   523  		assert.Equal(t, api.ExecuteSuccess, resp.Code.GetValue(), "update user must fail")
   524  	})
   525  
   526  	t.Run("子账户更新账户密码-自身-携带错误原密码", func(t *testing.T) {
   527  		req := &apisecurity.ModifyUserPassword{
   528  			Id:          &wrappers.StringValue{Value: userTest.users[1].ID},
   529  			OldPassword: &wrappers.StringValue{Value: "users[1].Password"},
   530  			NewPassword: &wrappers.StringValue{Value: "users[1].Password"},
   531  		}
   532  
   533  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[1], nil)
   534  
   535  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[1].Token)
   536  		resp := userTest.svr.UpdateUserPassword(reqCtx, req)
   537  		t.Logf("CreateUsers resp : %+v", resp)
   538  		assert.Equal(t, api.ExecuteException, resp.Code.GetValue(), "update user must fail")
   539  	})
   540  
   541  	t.Run("子账户更新账户密码-自身-无携带原密码", func(t *testing.T) {
   542  		req := &apisecurity.ModifyUserPassword{
   543  			Id:          &wrappers.StringValue{Value: userTest.users[1].ID},
   544  			NewPassword: &wrappers.StringValue{Value: "users[1].Password"},
   545  		}
   546  
   547  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[1], nil)
   548  
   549  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[1].Token)
   550  		resp := userTest.svr.UpdateUserPassword(reqCtx, req)
   551  		t.Logf("CreateUsers resp : %+v", resp)
   552  		assert.Equal(t, api.ExecuteException, resp.Code.GetValue(), "update user must fail")
   553  	})
   554  
   555  	t.Run("子账户更新账户密码-不是自己", func(t *testing.T) {
   556  		req := &apisecurity.ModifyUserPassword{
   557  			Id:          &wrappers.StringValue{Value: userTest.users[2].ID},
   558  			NewPassword: &wrappers.StringValue{Value: "users[2].Password"},
   559  		}
   560  
   561  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[2], nil)
   562  
   563  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[1].Token)
   564  		resp := userTest.svr.UpdateUserPassword(reqCtx, req)
   565  		t.Logf("CreateUsers resp : %+v", resp)
   566  		assert.Equal(t, api.NotAllowedAccess, resp.Code.GetValue(), "update user must fail")
   567  	})
   568  }
   569  
   570  func Test_server_DeleteUser(t *testing.T) {
   571  	userTest := newUserTest(t)
   572  	defer userTest.Clean()
   573  
   574  	t.Run("主账户删除自己", func(t *testing.T) {
   575  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[0], nil)
   576  
   577  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   578  		resp := userTest.svr.DeleteUser(reqCtx, &apisecurity.User{
   579  			Id: utils.NewStringValue(userTest.users[0].ID),
   580  		})
   581  
   582  		assert.True(t, resp.GetCode().Value == api.NotAllowedAccess, resp.Info.GetValue())
   583  	})
   584  
   585  	t.Run("主账户删除另外一个主账户", func(t *testing.T) {
   586  		uid := utils.NewUUID()
   587  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(&model.User{
   588  			ID:    uid,
   589  			Type:  model.OwnerUserRole,
   590  			Owner: "",
   591  		}, nil)
   592  
   593  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   594  		resp := userTest.svr.DeleteUser(reqCtx, &apisecurity.User{
   595  			Id: utils.NewStringValue(uid),
   596  		})
   597  
   598  		assert.True(t, resp.GetCode().Value == api.NotAllowedAccess, resp.Info.GetValue())
   599  	})
   600  
   601  	t.Run("主账户删除自己的子账户", func(t *testing.T) {
   602  		userTest.storage.EXPECT().GetUser(gomock.Eq(userTest.users[1].ID)).Return(userTest.users[1], nil)
   603  
   604  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   605  		resp := userTest.svr.DeleteUser(reqCtx, &apisecurity.User{
   606  			Id: utils.NewStringValue(userTest.users[1].ID),
   607  		})
   608  
   609  		assert.True(t, resp.GetCode().Value == api.ExecuteSuccess, resp.Info.GetValue())
   610  	})
   611  
   612  	t.Run("主账户删除不是自己的子账户", func(t *testing.T) {
   613  		uid := utils.NewUUID()
   614  		oid := utils.NewUUID()
   615  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(&model.User{
   616  			ID:    uid,
   617  			Type:  model.OwnerUserRole,
   618  			Owner: oid,
   619  		}, nil)
   620  
   621  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[0].Token)
   622  		resp := userTest.svr.DeleteUser(reqCtx, &apisecurity.User{
   623  			Id: utils.NewStringValue(uid),
   624  		})
   625  
   626  		assert.True(t, resp.GetCode().Value == api.NotAllowedAccess, resp.Info.GetValue())
   627  	})
   628  
   629  	t.Run("管理员删除主账户-主账户下没有子账户", func(t *testing.T) {
   630  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[0], nil)
   631  		userTest.storage.EXPECT().GetSubCount(gomock.Any()).Return(uint32(0), nil)
   632  
   633  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.admin.Token)
   634  		resp := userTest.svr.DeleteUser(reqCtx, &apisecurity.User{
   635  			Id: utils.NewStringValue(userTest.users[0].ID),
   636  		})
   637  
   638  		assert.True(t, resp.GetCode().Value == api.ExecuteSuccess, resp.Info.GetValue())
   639  	})
   640  
   641  	t.Run("管理员删除主账户-主账户下还有子账户", func(t *testing.T) {
   642  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[0], nil)
   643  		userTest.storage.EXPECT().GetSubCount(gomock.Any()).Return(uint32(1), nil)
   644  
   645  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.admin.Token)
   646  		resp := userTest.svr.DeleteUser(reqCtx, &apisecurity.User{
   647  			Id: utils.NewStringValue(userTest.users[0].ID),
   648  		})
   649  
   650  		assert.True(t, resp.GetCode().Value == api.SubAccountExisted, resp.Info.GetValue())
   651  	})
   652  
   653  	t.Run("子账户删除用户", func(t *testing.T) {
   654  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[1].Token)
   655  		resp := userTest.svr.DeleteUser(reqCtx, &apisecurity.User{
   656  			Id: utils.NewStringValue(userTest.users[0].ID),
   657  		})
   658  
   659  		assert.True(t, resp.GetCode().Value == api.OperationRoleException, resp.Info.GetValue())
   660  	})
   661  }
   662  
   663  func Test_server_GetUserToken(t *testing.T) {
   664  
   665  	userTest := newUserTest(t)
   666  	defer userTest.Clean()
   667  
   668  	t.Run("主账户查询自己的Token", func(t *testing.T) {
   669  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.ownerOne.Token)
   670  
   671  		resp := userTest.svr.GetUserToken(reqCtx, &apisecurity.User{
   672  			Id: utils.NewStringValue(userTest.users[0].ID),
   673  		})
   674  
   675  		assert.True(t, resp.GetCode().Value == api.ExecuteSuccess, resp.Info.GetValue())
   676  	})
   677  
   678  	t.Run("子账户查询自己的Token", func(t *testing.T) {
   679  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[1].Token)
   680  
   681  		resp := userTest.svr.GetUserToken(reqCtx, &apisecurity.User{
   682  			Id: utils.NewStringValue(userTest.users[1].ID),
   683  		})
   684  
   685  		assert.True(t, resp.GetCode().Value == api.ExecuteSuccess, resp.Info.GetValue())
   686  	})
   687  
   688  	t.Run("主账户查询子账户的Token", func(t *testing.T) {
   689  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.ownerOne.Token)
   690  
   691  		resp := userTest.svr.GetUserToken(reqCtx, &apisecurity.User{
   692  			Id: utils.NewStringValue(userTest.users[1].ID),
   693  		})
   694  
   695  		assert.True(t, resp.GetCode().Value == api.ExecuteSuccess, resp.Info.GetValue())
   696  	})
   697  
   698  	t.Run("主账户查询别的主账户的Token", func(t *testing.T) {
   699  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.ownerOne.Token)
   700  
   701  		resp := userTest.svr.GetUserToken(reqCtx, &apisecurity.User{
   702  			Id: utils.NewStringValue(userTest.ownerTwo.ID),
   703  		})
   704  
   705  		assert.True(t, resp.GetCode().Value == api.NotAllowedAccess, resp.Info.GetValue())
   706  	})
   707  
   708  	t.Run("主账户查询不属于自己子账户的Token", func(t *testing.T) {
   709  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.ownerOne.Token)
   710  
   711  		resp := userTest.svr.GetUserToken(reqCtx, &apisecurity.User{
   712  			Id: utils.NewStringValue(userTest.newUsers[1].ID),
   713  		})
   714  
   715  		assert.True(t, resp.GetCode().Value == api.NotAllowedAccess, resp.Info.GetValue())
   716  	})
   717  }
   718  
   719  func Test_server_RefreshUserToken(t *testing.T) {
   720  
   721  	userTest := newUserTest(t)
   722  	defer userTest.Clean()
   723  
   724  	t.Run("主账户刷新自己的Token", func(t *testing.T) {
   725  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.ownerOne.Token)
   726  
   727  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[0], nil)
   728  
   729  		resp := userTest.svr.ResetUserToken(reqCtx, &apisecurity.User{
   730  			Id: utils.NewStringValue(userTest.users[0].ID),
   731  		})
   732  
   733  		assert.True(t, resp.GetCode().Value == api.ExecuteSuccess, resp.Info.GetValue())
   734  	})
   735  
   736  	t.Run("子账户刷新自己的Token", func(t *testing.T) {
   737  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[1].Token)
   738  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[1], nil)
   739  		resp := userTest.svr.ResetUserToken(reqCtx, &apisecurity.User{
   740  			Id: utils.NewStringValue(userTest.users[1].ID),
   741  		})
   742  
   743  		assert.True(t, resp.GetCode().Value == api.ExecuteSuccess, resp.Info.GetValue())
   744  	})
   745  
   746  	t.Run("主账户刷新子账户的Token", func(t *testing.T) {
   747  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.ownerOne.Token)
   748  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.users[1], nil)
   749  		resp := userTest.svr.ResetUserToken(reqCtx, &apisecurity.User{
   750  			Id: utils.NewStringValue(userTest.users[1].ID),
   751  		})
   752  
   753  		assert.True(t, resp.GetCode().Value == api.ExecuteSuccess, resp.Info.GetValue())
   754  	})
   755  
   756  	t.Run("主账户刷新别的主账户的Token", func(t *testing.T) {
   757  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.ownerOne.Token)
   758  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.ownerTwo, nil)
   759  		resp := userTest.svr.ResetUserToken(reqCtx, &apisecurity.User{
   760  			Id: utils.NewStringValue(userTest.ownerTwo.ID),
   761  		})
   762  
   763  		assert.True(t, resp.GetCode().Value == api.NotAllowedAccess, resp.Info.GetValue())
   764  	})
   765  
   766  	t.Run("主账户刷新不属于自己子账户的Token", func(t *testing.T) {
   767  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.ownerOne.Token)
   768  		userTest.storage.EXPECT().GetUser(gomock.Any()).Return(userTest.newUsers[1], nil)
   769  		resp := userTest.svr.ResetUserToken(reqCtx, &apisecurity.User{
   770  			Id: utils.NewStringValue(userTest.newUsers[1].ID),
   771  		})
   772  
   773  		assert.True(t, resp.GetCode().Value == api.NotAllowedAccess, resp.Info.GetValue())
   774  	})
   775  }
   776  
   777  func Test_server_UpdateUserToken(t *testing.T) {
   778  
   779  	userTest := newUserTest(t)
   780  	defer userTest.Clean()
   781  
   782  	t.Run("主账户刷新自己的Token状态", func(t *testing.T) {
   783  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.ownerOne.Token)
   784  
   785  		userTest.storage.EXPECT().GetUser(gomock.Eq(userTest.users[0].ID)).Return(userTest.users[0], nil)
   786  
   787  		resp := userTest.svr.UpdateUserToken(reqCtx, &apisecurity.User{
   788  			Id: utils.NewStringValue(userTest.users[0].ID),
   789  		})
   790  
   791  		assert.True(t, resp.GetCode().Value == api.NotAllowedAccess, resp.Info.GetValue())
   792  	})
   793  
   794  	t.Run("子账户刷新自己的Token状态", func(t *testing.T) {
   795  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.users[4].Token)
   796  		resp := userTest.svr.UpdateUserToken(reqCtx, &apisecurity.User{
   797  			Id: utils.NewStringValue(userTest.users[4].ID),
   798  		})
   799  
   800  		assert.True(t, resp.GetCode().Value == api.OperationRoleException, resp.Info.GetValue())
   801  	})
   802  
   803  	t.Run("主账户刷新子账户的Token状态", func(t *testing.T) {
   804  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.ownerOne.Token)
   805  		userTest.storage.EXPECT().GetUser(gomock.Eq(userTest.users[3].ID)).Return(userTest.users[3], nil)
   806  		resp := userTest.svr.UpdateUserToken(reqCtx, &apisecurity.User{
   807  			Id: utils.NewStringValue(userTest.users[3].ID),
   808  		})
   809  
   810  		assert.True(t, resp.GetCode().Value == api.ExecuteSuccess, resp.Info.GetValue())
   811  	})
   812  
   813  	t.Run("主账户刷新别的主账户的Token状态", func(t *testing.T) {
   814  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.ownerOne.Token)
   815  
   816  		t.Logf("operator-id : %s, user-two-owner : %s", userTest.ownerOne.ID, userTest.ownerTwo.Owner)
   817  
   818  		userTest.storage.EXPECT().GetUser(gomock.Eq(userTest.ownerTwo.ID)).Return(userTest.ownerTwo, nil)
   819  		resp := userTest.svr.UpdateUserToken(reqCtx, &apisecurity.User{
   820  			Id: utils.NewStringValue(userTest.ownerTwo.ID),
   821  		})
   822  
   823  		assert.Truef(t, resp.GetCode().Value == api.NotAllowedAccess, "code=%d, msg=%s", resp.Code.GetValue(), resp.Info.GetValue())
   824  	})
   825  
   826  	t.Run("主账户刷新不属于自己子账户的Token状态", func(t *testing.T) {
   827  		reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, userTest.ownerOne.Token)
   828  		userTest.storage.EXPECT().GetUser(gomock.Eq(userTest.newUsers[3].ID)).Return(userTest.newUsers[3], nil)
   829  		resp := userTest.svr.UpdateUserToken(reqCtx, &apisecurity.User{
   830  			Id: utils.NewStringValue(userTest.newUsers[3].ID),
   831  		})
   832  
   833  		assert.True(t, resp.GetCode().Value == api.NotAllowedAccess, resp.Info.GetValue())
   834  	})
   835  }
   836  
   837  func Test_AuthServer_NormalOperateUser(t *testing.T) {
   838  	suit := &AuthTestSuit{}
   839  	if err := suit.Initialize(); err != nil {
   840  		t.Fatal(err)
   841  	}
   842  	t.Cleanup(func() {
   843  		suit.cleanAllAuthStrategy()
   844  		suit.cleanAllUser()
   845  		suit.cleanAllUserGroup()
   846  		suit.Destroy()
   847  	})
   848  
   849  	users := createApiMockUser(10, "test")
   850  
   851  	t.Run("正常创建用户", func(t *testing.T) {
   852  		resp := suit.UserServer().CreateUsers(suit.DefaultCtx, users)
   853  
   854  		if !respSuccess(resp) {
   855  			t.Fatal(resp.GetInfo().GetValue())
   856  		}
   857  	})
   858  
   859  	t.Run("非正常创建用户-直接操作存储层", func(t *testing.T) {
   860  		err := suit.Storage.AddUser(&model.User{})
   861  		assert.Error(t, err)
   862  	})
   863  
   864  	t.Run("正常更新用户", func(t *testing.T) {
   865  		users[0].Comment = utils.NewStringValue("update user comment")
   866  		resp := suit.UserServer().UpdateUser(suit.DefaultCtx, users[0])
   867  
   868  		if !respSuccess(resp) {
   869  			t.Fatal(resp.GetInfo().GetValue())
   870  		}
   871  
   872  		qresp := suit.UserServer().GetUsers(suit.DefaultCtx, map[string]string{
   873  			"id": users[0].GetId().GetValue(),
   874  		})
   875  
   876  		if !respSuccess(resp) {
   877  			t.Fatal(resp.GetInfo().GetValue())
   878  		}
   879  
   880  		assert.Equal(t, 1, int(qresp.Amount.GetValue()))
   881  		assert.Equal(t, 1, int(qresp.Size.GetValue()))
   882  
   883  		retUsers := qresp.GetUsers()[0]
   884  		assert.Equal(t, users[0].GetComment().GetValue(), retUsers.GetComment().GetValue())
   885  	})
   886  
   887  	t.Run("正常删除用户", func(t *testing.T) {
   888  		resp := suit.UserServer().DeleteUsers(suit.DefaultCtx, []*apisecurity.User{users[3]})
   889  
   890  		if !respSuccess(resp) {
   891  			t.Fatal(resp.GetInfo().GetValue())
   892  		}
   893  
   894  		qresp := suit.UserServer().GetUsers(suit.DefaultCtx, map[string]string{
   895  			"id": users[3].GetId().GetValue(),
   896  		})
   897  
   898  		if !respSuccess(resp) {
   899  			t.Fatal(resp.GetInfo().GetValue())
   900  		}
   901  
   902  		assert.Equal(t, 0, int(qresp.Amount.GetValue()))
   903  		assert.Equal(t, 0, int(qresp.Size.GetValue()))
   904  	})
   905  
   906  	t.Run("正常更新用户Token", func(t *testing.T) {
   907  		resp := suit.UserServer().ResetUserToken(suit.DefaultCtx, users[0])
   908  
   909  		if !respSuccess(resp) {
   910  			t.Fatal(resp.GetInfo().GetValue())
   911  		}
   912  
   913  		_ = suit.CacheMgr().TestUpdate()
   914  
   915  		qresp := suit.UserServer().GetUserToken(suit.DefaultCtx, users[0])
   916  		if !respSuccess(qresp) {
   917  			t.Fatal(resp.GetInfo().GetValue())
   918  		}
   919  		assert.Equal(t, resp.GetUser().GetAuthToken().GetValue(), qresp.GetUser().GetAuthToken().GetValue())
   920  	})
   921  }