github.com/polarismesh/polaris@v1.17.8/auth/defaultauth/auth_checker_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  	"errors"
    23  	"testing"
    24  	"time"
    25  
    26  	"github.com/golang/mock/gomock"
    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  	"github.com/polarismesh/polaris/common/model"
    34  	"github.com/polarismesh/polaris/common/utils"
    35  	storemock "github.com/polarismesh/polaris/store/mock"
    36  )
    37  
    38  func Test_defaultAuthManager_ParseToken(t *testing.T) {
    39  	defaultauth.AuthOption.Salt = "polaris@a7b068ce3235442b"
    40  	token := "orRm9Zt7sMqQaAM5b7yHLXnhWsr5dfPT0jpRlQ+C0tdy2UmuDa/X3uFG"
    41  
    42  	authMgn := &defaultauth.DefaultAuthChecker{}
    43  
    44  	tokenInfo, err := authMgn.DecodeToken(token)
    45  
    46  	if err != nil {
    47  		t.Fatal(err)
    48  	}
    49  
    50  	t.Logf("%#v", tokenInfo)
    51  }
    52  
    53  func Test_DefaultAuthChecker_VerifyCredential(t *testing.T) {
    54  	reset(false)
    55  	ctrl := gomock.NewController(t)
    56  	defer ctrl.Finish()
    57  
    58  	users := createMockUser(10)
    59  
    60  	storage := storemock.NewMockStore(ctrl)
    61  
    62  	storage.EXPECT().GetServicesCount().AnyTimes().Return(uint32(1), nil)
    63  	storage.EXPECT().GetUnixSecond(gomock.Any()).AnyTimes().Return(time.Now().Unix(), nil)
    64  	storage.EXPECT().GetUsersForCache(gomock.Any(), gomock.Any()).AnyTimes().Return(users, nil)
    65  	storage.EXPECT().GetGroupsForCache(gomock.Any(), gomock.Any()).AnyTimes().Return([]*model.UserGroupDetail{}, nil)
    66  
    67  	ctx, cancel := context.WithCancel(context.Background())
    68  	cacheMgn, err := cache.TestCacheInitialize(ctx, &cache.Config{
    69  		Open: true,
    70  		Resources: []cache.ConfigEntry{
    71  			{
    72  				Name: "users",
    73  			},
    74  		},
    75  	}, storage)
    76  
    77  	if err != nil {
    78  		t.Fatal(err)
    79  	}
    80  
    81  	t.Cleanup(func() {
    82  		cancel()
    83  		cacheMgn.Close()
    84  	})
    85  
    86  	checker := &defaultauth.DefaultAuthChecker{}
    87  	checker.Initialize(&auth.Config{
    88  		User: &auth.UserConfig{
    89  			Name:   "",
    90  			Option: map[string]interface{}{},
    91  		},
    92  		Strategy: &auth.StrategyConfig{
    93  			Name: "",
    94  			Option: map[string]interface{}{
    95  				"": nil,
    96  			},
    97  		},
    98  	}, storage, cacheMgn)
    99  	checker.SetCacheMgr(cacheMgn)
   100  
   101  	t.Run("主账户正常情况", func(t *testing.T) {
   102  		reset(false)
   103  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[0].Token)
   104  		authCtx := model.NewAcquireContext(
   105  			model.WithRequestContext(ctx),
   106  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   107  		)
   108  
   109  		err = checker.VerifyCredential(authCtx)
   110  		t.Logf("%+v", err)
   111  		assert.NoError(t, err, "Should be verify success")
   112  		assert.Equal(t, users[0].ID, utils.ParseUserID(authCtx.GetRequestContext()), "user-id should be equal")
   113  		assert.True(t, utils.ParseIsOwner(authCtx.GetRequestContext()), "should be owner")
   114  	})
   115  
   116  	t.Run("子账户在Token被禁用情况下", func(t *testing.T) {
   117  		reset(false)
   118  		users[1].TokenEnable = false
   119  		// 让 cache 可以刷新到
   120  		time.Sleep(time.Second)
   121  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[1].Token)
   122  		authCtx := model.NewAcquireContext(
   123  			model.WithRequestContext(ctx),
   124  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   125  		)
   126  		err = checker.VerifyCredential(authCtx)
   127  		t.Logf("%+v", err)
   128  		assert.NoError(t, err, "Should be verify success")
   129  		assert.Equal(t, users[1].ID, utils.ParseUserID(authCtx.GetRequestContext()), "user-id should be equal")
   130  		assert.False(t, utils.ParseIsOwner(authCtx.GetRequestContext()), "should not be owner")
   131  		assert.True(t, authCtx.GetAttachment(model.TokenDetailInfoKey).(defaultauth.OperatorInfo).Disable, "should be disable")
   132  	})
   133  
   134  	t.Run("权限检查非严格模式-错误的token字符串-降级为匿名用户", func(t *testing.T) {
   135  		reset(false)
   136  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "Test_DefaultAuthChecker_VerifyCredential")
   137  		authCtx := model.NewAcquireContext(
   138  			model.WithRequestContext(ctx),
   139  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   140  		)
   141  		err = checker.VerifyCredential(authCtx)
   142  		t.Logf("%+v", err)
   143  		assert.NoError(t, err, "Should be verify success")
   144  		assert.True(t, authCtx.GetAttachment(model.TokenDetailInfoKey).(defaultauth.OperatorInfo).Anonymous, "should be anonymous")
   145  	})
   146  
   147  	t.Run("权限检查非严格模式-空token字符串-降级为匿名用户", func(t *testing.T) {
   148  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "")
   149  		authCtx := model.NewAcquireContext(
   150  			model.WithRequestContext(ctx),
   151  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   152  		)
   153  		err = checker.VerifyCredential(authCtx)
   154  		t.Logf("%+v", err)
   155  		assert.NoError(t, err, "Should be verify success")
   156  		assert.True(t, authCtx.GetAttachment(model.TokenDetailInfoKey).(defaultauth.OperatorInfo).Anonymous, "should be anonymous")
   157  	})
   158  
   159  	t.Run("权限检查非严格模式-错误的token字符串-访问鉴权模块", func(t *testing.T) {
   160  		reset(false)
   161  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "Test_DefaultAuthChecker_VerifyCredential")
   162  		authCtx := model.NewAcquireContext(
   163  			model.WithRequestContext(ctx),
   164  			model.WithModule(model.AuthModule),
   165  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   166  		)
   167  		err = checker.VerifyCredential(authCtx)
   168  		t.Logf("%+v", err)
   169  		assert.Error(t, err, "Should be verify fail")
   170  	})
   171  
   172  	t.Run("权限检查非严格模式-空token字符串-访问鉴权模块", func(t *testing.T) {
   173  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "")
   174  		authCtx := model.NewAcquireContext(
   175  			model.WithRequestContext(ctx),
   176  			model.WithModule(model.AuthModule),
   177  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   178  		)
   179  		err = checker.VerifyCredential(authCtx)
   180  		t.Logf("%+v", err)
   181  		assert.Error(t, err, "Should be verify fail")
   182  	})
   183  
   184  	t.Run("权限检查严格模式-token非法-不允许降级为匿名用户", func(t *testing.T) {
   185  		reset(true)
   186  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "Test_DefaultAuthChecker_VerifyCredential")
   187  		authCtx := model.NewAcquireContext(
   188  			model.WithRequestContext(ctx),
   189  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   190  		)
   191  		err = checker.VerifyCredential(authCtx)
   192  		t.Logf("%+v", err)
   193  		assert.Error(t, err, "Should be verify fail")
   194  		assert.True(t, errors.Is(err, model.ErrorTokenInvalid), "should be token-invalid error")
   195  	})
   196  
   197  	t.Run("权限检查严格模式-token为空-不允许降级为匿名用户", func(t *testing.T) {
   198  		reset(true)
   199  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "")
   200  		authCtx := model.NewAcquireContext(
   201  			model.WithRequestContext(ctx),
   202  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   203  		)
   204  		err = checker.VerifyCredential(authCtx)
   205  		t.Logf("%+v", err)
   206  		assert.Error(t, err, "Should be verify fail")
   207  		assert.True(t, errors.Is(err, model.ErrorTokenInvalid), "should be token-invalid error")
   208  	})
   209  }
   210  
   211  func Test_DefaultAuthChecker_CheckPermission_Write_NoStrict(t *testing.T) {
   212  	reset(false)
   213  	ctrl := gomock.NewController(t)
   214  	defer ctrl.Finish()
   215  
   216  	users := createMockUser(10)
   217  	groups := createMockUserGroup(users)
   218  
   219  	namespaces := createMockNamespace(len(users)+len(groups)+10, users[0].ID)
   220  	services := createMockService(namespaces)
   221  	serviceMap := convertServiceSliceToMap(services)
   222  	strategies, _ := createMockStrategy(users, groups, services[:len(users)+len(groups)])
   223  
   224  	cfg, storage := initCache(ctrl)
   225  
   226  	storage.EXPECT().GetUsersForCache(gomock.Any(), gomock.Any()).AnyTimes().Return(users, nil)
   227  	storage.EXPECT().GetGroupsForCache(gomock.Any(), gomock.Any()).AnyTimes().Return(groups, nil)
   228  	storage.EXPECT().GetStrategyDetailsForCache(gomock.Any(), gomock.Any()).AnyTimes().Return(strategies, nil)
   229  	storage.EXPECT().GetMoreNamespaces(gomock.Any()).AnyTimes().Return(namespaces, nil)
   230  	storage.EXPECT().GetMoreServices(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(serviceMap, nil)
   231  
   232  	ctx, cancel := context.WithCancel(context.Background())
   233  	cacheMgn, err := cache.TestCacheInitialize(ctx, cfg, storage)
   234  	if err != nil {
   235  		t.Fatal(err)
   236  	}
   237  
   238  	t.Cleanup(func() {
   239  		cancel()
   240  		cacheMgn.Close()
   241  	})
   242  
   243  	time.Sleep(time.Second)
   244  
   245  	checker := &defaultauth.DefaultAuthChecker{}
   246  	checker.SetCacheMgr(cacheMgn)
   247  
   248  	freeIndex := len(users) + len(groups) + 1
   249  
   250  	t.Run("权限检查非严格模式-主账户资源访问检查", func(t *testing.T) {
   251  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[0].Token)
   252  		authCtx := model.NewAcquireContext(
   253  			model.WithRequestContext(ctx),
   254  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   255  			model.WithOperation(model.Create),
   256  			model.WithModule(model.DiscoverModule),
   257  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   258  				apisecurity.ResourceType_Services: {
   259  					{
   260  						ID:    services[0].ID,
   261  						Owner: services[0].Owner,
   262  					},
   263  				},
   264  			}),
   265  		)
   266  
   267  		_, err = checker.CheckPermission(authCtx)
   268  		t.Logf("%+v", err)
   269  		assert.NoError(t, err, "Should be verify success")
   270  	})
   271  
   272  	t.Run("权限检查非严格模式-子账户资源访问检查(无操作权限)", func(t *testing.T) {
   273  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[1].Token)
   274  		authCtx := model.NewAcquireContext(
   275  			model.WithRequestContext(ctx),
   276  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   277  			model.WithOperation(model.Create),
   278  			model.WithModule(model.DiscoverModule),
   279  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   280  				apisecurity.ResourceType_Services: {
   281  					{
   282  						ID:    services[0].ID,
   283  						Owner: services[0].Owner,
   284  					},
   285  				},
   286  			}),
   287  		)
   288  
   289  		_, err = checker.CheckPermission(authCtx)
   290  		t.Logf("%+v", err)
   291  		assert.Error(t, err, "Should be verify fail")
   292  	})
   293  
   294  	t.Run("权限检查非严格模式-子账户资源访问检查(有操作权限)", func(t *testing.T) {
   295  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[1].Token)
   296  		authCtx := model.NewAcquireContext(
   297  			model.WithRequestContext(ctx),
   298  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   299  			model.WithOperation(model.Create),
   300  			model.WithModule(model.DiscoverModule),
   301  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   302  				apisecurity.ResourceType_Services: {
   303  					{
   304  						ID:    services[1].ID,
   305  						Owner: services[1].Owner,
   306  					},
   307  				},
   308  			}),
   309  		)
   310  
   311  		_, err = checker.CheckPermission(authCtx)
   312  		t.Logf("%+v", err)
   313  		assert.NoError(t, err, "Should be verify success")
   314  	})
   315  
   316  	t.Run("权限检查非严格模式-子账户资源访问检查(资源无绑定策略)", func(t *testing.T) {
   317  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[1].Token)
   318  		authCtx := model.NewAcquireContext(
   319  			model.WithRequestContext(ctx),
   320  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   321  			model.WithOperation(model.Create),
   322  			model.WithModule(model.DiscoverModule),
   323  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   324  				apisecurity.ResourceType_Services: {
   325  					{
   326  						ID:    services[freeIndex].ID,
   327  						Owner: services[freeIndex].Owner,
   328  					},
   329  				},
   330  			}),
   331  		)
   332  
   333  		_, err = checker.CheckPermission(authCtx)
   334  		t.Logf("%+v", err)
   335  		assert.NoError(t, err, "Should be verify success")
   336  	})
   337  
   338  	t.Run("权限检查非严格模式-子账户访问用户组资源检查(属于用户组成员)", func(t *testing.T) {
   339  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[1].Token)
   340  		authCtx := model.NewAcquireContext(
   341  			model.WithRequestContext(ctx),
   342  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   343  			model.WithOperation(model.Create),
   344  			model.WithModule(model.DiscoverModule),
   345  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   346  				apisecurity.ResourceType_Services: {
   347  					{
   348  						ID:    services[(len(users)-1)+2].ID,
   349  						Owner: services[(len(users)-1)+2].Owner,
   350  					},
   351  				},
   352  			}),
   353  		)
   354  
   355  		_, err = checker.CheckPermission(authCtx)
   356  		t.Logf("%+v", err)
   357  		assert.NoError(t, err, "Should be verify success")
   358  	})
   359  
   360  	t.Run("权限检查非严格模式-子账户访问用户组资源检查(不属于用户组成员)", func(t *testing.T) {
   361  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[1].Token)
   362  		authCtx := model.NewAcquireContext(
   363  			model.WithRequestContext(ctx),
   364  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   365  			model.WithOperation(model.Create),
   366  			model.WithModule(model.DiscoverModule),
   367  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   368  				apisecurity.ResourceType_Services: {
   369  					{
   370  						ID:    services[(len(users)-1)+4].ID,
   371  						Owner: services[(len(users)-1)+4].Owner,
   372  					},
   373  				},
   374  			}),
   375  		)
   376  
   377  		_, err = checker.CheckPermission(authCtx)
   378  		t.Logf("%+v", err)
   379  		assert.Error(t, err, "Should be verify fail")
   380  	})
   381  
   382  	t.Run("权限检查非严格模式-用户组访问组内成员资源检查", func(t *testing.T) {
   383  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, groups[1].Token)
   384  		authCtx := model.NewAcquireContext(
   385  			model.WithRequestContext(ctx),
   386  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   387  			// model.WithToken(groups[1].Token),
   388  			model.WithOperation(model.Create),
   389  			model.WithModule(model.DiscoverModule),
   390  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   391  				apisecurity.ResourceType_Services: {
   392  					{
   393  						ID:    services[0].ID,
   394  						Owner: services[0].Owner,
   395  					},
   396  				},
   397  			}),
   398  		)
   399  
   400  		_, err = checker.CheckPermission(authCtx)
   401  		t.Logf("%+v", err)
   402  		assert.Error(t, err, "Should be verify fail")
   403  	})
   404  
   405  	t.Run("权限检查非严格模式-token非法-匿名账户资源访问检查(资源无绑定策略)", func(t *testing.T) {
   406  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "users[1].Token")
   407  		authCtx := model.NewAcquireContext(
   408  			model.WithRequestContext(ctx),
   409  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   410  			model.WithOperation(model.Create),
   411  			model.WithModule(model.DiscoverModule),
   412  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   413  				apisecurity.ResourceType_Services: {
   414  					{
   415  						ID:    services[freeIndex].ID,
   416  						Owner: services[freeIndex].Owner,
   417  					},
   418  				},
   419  			}),
   420  		)
   421  
   422  		_, err = checker.CheckPermission(authCtx)
   423  		t.Logf("%+v", err)
   424  		assert.NoError(t, err, "Should be verify success")
   425  	})
   426  
   427  	t.Run("权限检查非严格模式-token为空-匿名账户资源访问检查(资源无绑定策略)", func(t *testing.T) {
   428  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "")
   429  		authCtx := model.NewAcquireContext(
   430  			model.WithRequestContext(ctx),
   431  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   432  			model.WithOperation(model.Create),
   433  			model.WithModule(model.DiscoverModule),
   434  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   435  				apisecurity.ResourceType_Services: {
   436  					{
   437  						ID:    services[freeIndex].ID,
   438  						Owner: services[freeIndex].Owner,
   439  					},
   440  				},
   441  			}),
   442  		)
   443  
   444  		_, err = checker.CheckPermission(authCtx)
   445  		t.Logf("%+v", err)
   446  		assert.NoError(t, err, "Should be verify success")
   447  	})
   448  }
   449  
   450  func Test_DefaultAuthChecker_CheckPermission_Write_Strict(t *testing.T) {
   451  	reset(true)
   452  	ctrl := gomock.NewController(t)
   453  	defer ctrl.Finish()
   454  
   455  	users := createMockUser(10)
   456  	groups := createMockUserGroup(users)
   457  
   458  	namespaces := createMockNamespace(len(users)+len(groups)+10, users[0].ID)
   459  	services := createMockService(namespaces)
   460  	serviceMap := convertServiceSliceToMap(services)
   461  	strategies, _ := createMockStrategy(users, groups, services[:len(users)+len(groups)])
   462  
   463  	cfg, storage := initCache(ctrl)
   464  
   465  	storage.EXPECT().GetUsersForCache(gomock.Any(), gomock.Any()).AnyTimes().Return(users, nil)
   466  	storage.EXPECT().GetGroupsForCache(gomock.Any(), gomock.Any()).AnyTimes().Return(groups, nil)
   467  	storage.EXPECT().GetStrategyDetailsForCache(gomock.Any(), gomock.Any()).AnyTimes().Return(strategies, nil)
   468  	storage.EXPECT().GetMoreNamespaces(gomock.Any()).AnyTimes().Return(namespaces, nil)
   469  	storage.EXPECT().GetMoreServices(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(serviceMap, nil)
   470  
   471  	ctx, cancel := context.WithCancel(context.Background())
   472  	cacheMgn, err := cache.TestCacheInitialize(ctx, cfg, storage)
   473  	if err != nil {
   474  		t.Fatal(err)
   475  	}
   476  
   477  	t.Cleanup(func() {
   478  		cancel()
   479  		cacheMgn.Close()
   480  	})
   481  
   482  	time.Sleep(time.Second)
   483  
   484  	checker := &defaultauth.DefaultAuthChecker{}
   485  	checker.SetCacheMgr(cacheMgn)
   486  
   487  	freeIndex := len(users) + len(groups) + 1
   488  
   489  	t.Run("权限检查严格模式-主账户操作资源", func(t *testing.T) {
   490  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[0].Token)
   491  		authCtx := model.NewAcquireContext(
   492  			model.WithRequestContext(ctx),
   493  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   494  			// model.WithToken(users[0].Token),
   495  			model.WithOperation(model.Create),
   496  			model.WithModule(model.DiscoverModule),
   497  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   498  				apisecurity.ResourceType_Services: {
   499  					{
   500  						ID:    services[0].ID,
   501  						Owner: services[0].Owner,
   502  					},
   503  				},
   504  			}),
   505  		)
   506  
   507  		_, err = checker.CheckPermission(authCtx)
   508  		t.Logf("%+v", err)
   509  		assert.NoError(t, err, "Should be verify success")
   510  	})
   511  
   512  	t.Run("权限检查严格模式-子账户操作资源(无操作权限)", func(t *testing.T) {
   513  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[1].Token)
   514  		authCtx := model.NewAcquireContext(
   515  			model.WithRequestContext(ctx),
   516  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   517  			// model.WithToken(users[1].Token),
   518  			model.WithOperation(model.Create),
   519  			model.WithModule(model.DiscoverModule),
   520  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   521  				apisecurity.ResourceType_Services: {
   522  					{
   523  						ID:    services[0].ID,
   524  						Owner: services[0].Owner,
   525  					},
   526  				},
   527  			}),
   528  		)
   529  		_, err = checker.CheckPermission(authCtx)
   530  		t.Logf("%+v", err)
   531  		assert.Error(t, err, "Should be verify fail")
   532  	})
   533  
   534  	t.Run("权限检查严格模式-子账户操作资源(有操作权限)", func(t *testing.T) {
   535  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[1].Token)
   536  		authCtx := model.NewAcquireContext(
   537  			model.WithRequestContext(ctx),
   538  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   539  			// model.WithToken(users[1].Token),
   540  			model.WithOperation(model.Create),
   541  			model.WithModule(model.DiscoverModule),
   542  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   543  				apisecurity.ResourceType_Services: {
   544  					{
   545  						ID:    services[1].ID,
   546  						Owner: services[1].Owner,
   547  					},
   548  				},
   549  			}),
   550  		)
   551  		_, err = checker.CheckPermission(authCtx)
   552  		t.Logf("%+v", err)
   553  		assert.NoError(t, err, "Should be verify success")
   554  	})
   555  
   556  	t.Run("权限检查严格模式-token非法-匿名账户操作资源(资源有策略)", func(t *testing.T) {
   557  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "Test_DefaultAuthChecker_VerifyCredential")
   558  		authCtx := model.NewAcquireContext(
   559  			model.WithRequestContext(ctx),
   560  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   561  			// model.WithToken("Test_DefaultAuthChecker_VerifyCredential"),
   562  			model.WithOperation(model.Create),
   563  			model.WithModule(model.DiscoverModule),
   564  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   565  				apisecurity.ResourceType_Services: {
   566  					{
   567  						ID:    services[1].ID,
   568  						Owner: services[1].Owner,
   569  					},
   570  				},
   571  			}),
   572  		)
   573  		_, err = checker.CheckPermission(authCtx)
   574  		t.Logf("%+v", err)
   575  		assert.Error(t, err, "Should be verify fail")
   576  	})
   577  
   578  	t.Run("权限检查严格模式-token为空-匿名账户操作资源(资源有策略)", func(t *testing.T) {
   579  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "")
   580  		authCtx := model.NewAcquireContext(
   581  			model.WithRequestContext(ctx),
   582  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   583  			// model.WithToken(""),
   584  			model.WithModule(model.DiscoverModule),
   585  			model.WithOperation(model.Create),
   586  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   587  				apisecurity.ResourceType_Services: {
   588  					{
   589  						ID:    services[1].ID,
   590  						Owner: services[1].Owner,
   591  					},
   592  				},
   593  			}),
   594  		)
   595  		_, err = checker.CheckPermission(authCtx)
   596  		t.Logf("%+v", err)
   597  		assert.Error(t, err, "Should be verify fail")
   598  	})
   599  
   600  	t.Run("权限检查严格模式-token非法-匿名账户操作资源(资源没有策略)", func(t *testing.T) {
   601  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "Test_DefaultAuthChecker_VerifyCredential")
   602  		authCtx := model.NewAcquireContext(
   603  			model.WithRequestContext(ctx),
   604  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   605  			// model.WithToken("Test_DefaultAuthChecker_VerifyCredential"),
   606  			model.WithOperation(model.Create),
   607  			model.WithModule(model.DiscoverModule),
   608  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   609  				apisecurity.ResourceType_Services: {
   610  					{
   611  						ID:    services[freeIndex].ID,
   612  						Owner: services[freeIndex].Owner,
   613  					},
   614  				},
   615  			}),
   616  		)
   617  		_, err = checker.CheckPermission(authCtx)
   618  		t.Logf("%+v", err)
   619  		assert.Error(t, err, "Should be verify fail")
   620  	})
   621  
   622  	t.Run("权限检查严格模式-token为空-匿名账户操作资源(资源没有策略)", func(t *testing.T) {
   623  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "")
   624  		authCtx := model.NewAcquireContext(
   625  			model.WithRequestContext(ctx),
   626  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   627  			// model.WithToken(""),
   628  			model.WithOperation(model.Create),
   629  			model.WithModule(model.DiscoverModule),
   630  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   631  				apisecurity.ResourceType_Services: {
   632  					{
   633  						ID:    services[freeIndex].ID,
   634  						Owner: services[freeIndex].Owner,
   635  					},
   636  				},
   637  			}),
   638  		)
   639  		_, err = checker.CheckPermission(authCtx)
   640  		t.Logf("%+v", err)
   641  		assert.Error(t, err, "Should be verify fail")
   642  	})
   643  }
   644  
   645  func Test_DefaultAuthChecker_CheckPermission_Read_NoStrict(t *testing.T) {
   646  	reset(false)
   647  	ctrl := gomock.NewController(t)
   648  	defer ctrl.Finish()
   649  
   650  	users := createMockUser(10)
   651  	groups := createMockUserGroup(users)
   652  
   653  	namespaces := createMockNamespace(len(users)+len(groups)+10, users[0].ID)
   654  	services := createMockService(namespaces)
   655  	serviceMap := convertServiceSliceToMap(services)
   656  	strategies, _ := createMockStrategy(users, groups, services[:len(users)+len(groups)])
   657  
   658  	cfg, storage := initCache(ctrl)
   659  
   660  	storage.EXPECT().GetUsersForCache(gomock.Any(), gomock.Any()).AnyTimes().Return(users, nil)
   661  	storage.EXPECT().GetGroupsForCache(gomock.Any(), gomock.Any()).AnyTimes().Return(groups, nil)
   662  	storage.EXPECT().GetStrategyDetailsForCache(gomock.Any(), gomock.Any()).AnyTimes().Return(strategies, nil)
   663  	storage.EXPECT().GetMoreNamespaces(gomock.Any()).AnyTimes().Return(namespaces, nil)
   664  	storage.EXPECT().GetMoreServices(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(serviceMap, nil)
   665  
   666  	ctx, cancel := context.WithCancel(context.Background())
   667  	cacheMgn, err := cache.TestCacheInitialize(ctx, cfg, storage)
   668  	if err != nil {
   669  		t.Fatal(err)
   670  	}
   671  
   672  	t.Cleanup(func() {
   673  		cancel()
   674  		cacheMgn.Close()
   675  	})
   676  
   677  	time.Sleep(time.Second)
   678  
   679  	checker := &defaultauth.DefaultAuthChecker{}
   680  	checker.SetCacheMgr(cacheMgn)
   681  
   682  	freeIndex := len(users) + len(groups) + 1
   683  
   684  	t.Run("权限检查非严格模式-主账户正常读操作", func(t *testing.T) {
   685  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[0].Token)
   686  		authCtx := model.NewAcquireContext(
   687  			model.WithRequestContext(ctx),
   688  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   689  			// model.WithToken(users[0].Token),
   690  			model.WithOperation(model.Read),
   691  			model.WithModule(model.DiscoverModule),
   692  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   693  				apisecurity.ResourceType_Services: {
   694  					{
   695  						ID:    services[0].ID,
   696  						Owner: services[0].Owner,
   697  					},
   698  				},
   699  			}),
   700  		)
   701  		_, err = checker.CheckPermission(authCtx)
   702  		t.Logf("%+v", err)
   703  		assert.NoError(t, err, "Should be verify success")
   704  	})
   705  
   706  	t.Run("权限检查非严格模式-子账户正常读操作-资源有权限", func(t *testing.T) {
   707  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[1].Token)
   708  		authCtx := model.NewAcquireContext(
   709  			model.WithRequestContext(ctx),
   710  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   711  			// model.WithToken(users[1].Token),
   712  			model.WithOperation(model.Read),
   713  			model.WithModule(model.DiscoverModule),
   714  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   715  				apisecurity.ResourceType_Services: {
   716  					{
   717  						ID:    services[1].ID,
   718  						Owner: services[1].Owner,
   719  					},
   720  				},
   721  			}),
   722  		)
   723  		_, err = checker.CheckPermission(authCtx)
   724  		t.Logf("%+v", err)
   725  		assert.NoError(t, err, "Should be verify success")
   726  	})
   727  
   728  	t.Run("权限检查非严格模式-子账户正常读操作-资源无权限", func(t *testing.T) {
   729  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[1].Token)
   730  		authCtx := model.NewAcquireContext(
   731  			model.WithRequestContext(ctx),
   732  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   733  			// model.WithToken(users[1].Token),
   734  			model.WithOperation(model.Read),
   735  			model.WithModule(model.DiscoverModule),
   736  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   737  				apisecurity.ResourceType_Services: {
   738  					{
   739  						ID:    services[0].ID,
   740  						Owner: services[0].Owner,
   741  					},
   742  				},
   743  			}),
   744  		)
   745  		_, err = checker.CheckPermission(authCtx)
   746  		t.Logf("%+v", err)
   747  		assert.NoError(t, err, "Should be verify success")
   748  	})
   749  
   750  	t.Run("权限检查非严格模式-子账户正常读操作-资源无绑定策略", func(t *testing.T) {
   751  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[1].Token)
   752  		authCtx := model.NewAcquireContext(
   753  			model.WithRequestContext(ctx),
   754  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   755  			// model.WithToken(users[1].Token),
   756  			model.WithOperation(model.Read),
   757  			model.WithModule(model.DiscoverModule),
   758  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   759  				apisecurity.ResourceType_Services: {
   760  					{
   761  						ID:    services[freeIndex].ID,
   762  						Owner: services[freeIndex].Owner,
   763  					},
   764  				},
   765  			}),
   766  		)
   767  		_, err = checker.CheckPermission(authCtx)
   768  		t.Logf("%+v", err)
   769  		assert.NoError(t, err, "Should be verify success")
   770  	})
   771  
   772  	t.Run("权限检查非严格模式-匿名账户正常读操作-token为空-资源有策略", func(t *testing.T) {
   773  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "")
   774  		authCtx := model.NewAcquireContext(
   775  			model.WithRequestContext(ctx),
   776  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   777  			// model.WithToken(""),
   778  			model.WithOperation(model.Read),
   779  			model.WithModule(model.DiscoverModule),
   780  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   781  				apisecurity.ResourceType_Services: {
   782  					{
   783  						ID:    services[0].ID,
   784  						Owner: services[0].Owner,
   785  					},
   786  				},
   787  			}),
   788  		)
   789  		_, err = checker.CheckPermission(authCtx)
   790  		t.Logf("%+v", err)
   791  		assert.NoError(t, err, "Should be verify success")
   792  	})
   793  
   794  	t.Run("权限检查非严格模式-匿名账户正常读操作-token为空-资源无策略", func(t *testing.T) {
   795  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "")
   796  		authCtx := model.NewAcquireContext(
   797  			model.WithRequestContext(ctx),
   798  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   799  			// model.WithToken(""),
   800  			model.WithOperation(model.Read),
   801  			model.WithModule(model.DiscoverModule),
   802  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   803  				apisecurity.ResourceType_Services: {
   804  					{
   805  						ID:    services[freeIndex].ID,
   806  						Owner: services[freeIndex].Owner,
   807  					},
   808  				},
   809  			}),
   810  		)
   811  		_, err = checker.CheckPermission(authCtx)
   812  		t.Logf("%+v", err)
   813  		assert.NoError(t, err, "Should be verify success")
   814  	})
   815  
   816  	t.Run("权限检查非严格模式-匿名账户正常读操作-token非法-资源有策略", func(t *testing.T) {
   817  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "Test_DefaultAuthChecker_VerifyCredential")
   818  		authCtx := model.NewAcquireContext(
   819  			model.WithRequestContext(ctx),
   820  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   821  			// model.WithToken("Test_DefaultAuthChecker_VerifyCredential"),
   822  			model.WithOperation(model.Read),
   823  			model.WithModule(model.DiscoverModule),
   824  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   825  				apisecurity.ResourceType_Services: {
   826  					{
   827  						ID:    services[0].ID,
   828  						Owner: services[0].Owner,
   829  					},
   830  				},
   831  			}),
   832  		)
   833  		_, err = checker.CheckPermission(authCtx)
   834  		t.Logf("%+v", err)
   835  		assert.NoError(t, err, "Should be verify success")
   836  	})
   837  
   838  	t.Run("权限检查非严格模式-匿名账户正常读操作-token非法-资源无策略", func(t *testing.T) {
   839  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "Test_DefaultAuthChecker_VerifyCredential")
   840  		authCtx := model.NewAcquireContext(
   841  			model.WithRequestContext(ctx),
   842  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   843  			// model.WithToken("Test_DefaultAuthChecker_VerifyCredential"),
   844  			model.WithOperation(model.Read),
   845  			model.WithModule(model.DiscoverModule),
   846  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   847  				apisecurity.ResourceType_Services: {
   848  					{
   849  						ID:    services[freeIndex].ID,
   850  						Owner: services[freeIndex].Owner,
   851  					},
   852  				},
   853  			}),
   854  		)
   855  		_, err = checker.CheckPermission(authCtx)
   856  		t.Logf("%+v", err)
   857  		assert.NoError(t, err, "Should be verify success")
   858  	})
   859  }
   860  
   861  func Test_DefaultAuthChecker_CheckPermission_Read_Strict(t *testing.T) {
   862  	reset(true)
   863  	ctrl := gomock.NewController(t)
   864  	defer ctrl.Finish()
   865  
   866  	users := createMockUser(10)
   867  	groups := createMockUserGroup(users)
   868  
   869  	namespaces := createMockNamespace(len(users)+len(groups)+10, users[0].ID)
   870  	services := createMockService(namespaces)
   871  	serviceMap := convertServiceSliceToMap(services)
   872  	strategies, _ := createMockStrategy(users, groups, services[:len(users)+len(groups)])
   873  
   874  	cfg, storage := initCache(ctrl)
   875  
   876  	storage.EXPECT().GetUsersForCache(gomock.Any(), gomock.Any()).AnyTimes().Return(users, nil)
   877  	storage.EXPECT().GetGroupsForCache(gomock.Any(), gomock.Any()).AnyTimes().Return(groups, nil)
   878  	storage.EXPECT().GetStrategyDetailsForCache(gomock.Any(), gomock.Any()).AnyTimes().Return(strategies, nil)
   879  	storage.EXPECT().GetMoreNamespaces(gomock.Any()).AnyTimes().Return(namespaces, nil)
   880  	storage.EXPECT().GetMoreServices(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(serviceMap, nil)
   881  
   882  	ctx, cancel := context.WithCancel(context.Background())
   883  	cacheMgn, err := cache.TestCacheInitialize(ctx, cfg, storage)
   884  	if err != nil {
   885  		t.Fatal(err)
   886  	}
   887  
   888  	t.Cleanup(func() {
   889  		cancel()
   890  		cacheMgn.Close()
   891  	})
   892  
   893  	time.Sleep(time.Second)
   894  
   895  	checker := &defaultauth.DefaultAuthChecker{}
   896  	checker.SetCacheMgr(cacheMgn)
   897  
   898  	freeIndex := len(users) + len(groups) + 1
   899  
   900  	t.Run("权限检查严格模式-主账户正常读操作", func(t *testing.T) {
   901  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[0].Token)
   902  		authCtx := model.NewAcquireContext(
   903  			model.WithRequestContext(ctx),
   904  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   905  			// model.WithToken(users[0].Token),
   906  			model.WithOperation(model.Read),
   907  			model.WithModule(model.DiscoverModule),
   908  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   909  				apisecurity.ResourceType_Services: {
   910  					{
   911  						ID:    services[0].ID,
   912  						Owner: services[0].Owner,
   913  					},
   914  				},
   915  			}),
   916  		)
   917  		_, err = checker.CheckPermission(authCtx)
   918  		t.Logf("%+v", err)
   919  		assert.NoError(t, err, "Should be verify success")
   920  	})
   921  
   922  	t.Run("权限检查严格模式-子账户正常读操作-资源有权限", func(t *testing.T) {
   923  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[1].Token)
   924  		authCtx := model.NewAcquireContext(
   925  			model.WithRequestContext(ctx),
   926  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   927  			// model.WithToken(users[1].Token),
   928  			model.WithOperation(model.Read),
   929  			model.WithModule(model.DiscoverModule),
   930  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   931  				apisecurity.ResourceType_Services: {
   932  					{
   933  						ID:    services[1].ID,
   934  						Owner: services[1].Owner,
   935  					},
   936  				},
   937  			}),
   938  		)
   939  		_, err = checker.CheckPermission(authCtx)
   940  		t.Logf("%+v", err)
   941  		assert.NoError(t, err, "Should be verify success")
   942  	})
   943  
   944  	t.Run("权限检查严格模式-子账户正常读操作-资源无权限", func(t *testing.T) {
   945  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[1].Token)
   946  		authCtx := model.NewAcquireContext(
   947  			model.WithRequestContext(ctx),
   948  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   949  			// model.WithToken(users[1].Token),
   950  			model.WithOperation(model.Read),
   951  			model.WithModule(model.DiscoverModule),
   952  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   953  				apisecurity.ResourceType_Services: {
   954  					{
   955  						ID:    services[0].ID,
   956  						Owner: services[0].Owner,
   957  					},
   958  				},
   959  			}),
   960  		)
   961  		_, err = checker.CheckPermission(authCtx)
   962  		t.Logf("%+v", err)
   963  		assert.NoError(t, err, "Should be verify success")
   964  	})
   965  
   966  	t.Run("权限检查严格模式-子账户正常读操作-资源无绑定策略", func(t *testing.T) {
   967  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, users[1].Token)
   968  		authCtx := model.NewAcquireContext(
   969  			model.WithRequestContext(ctx),
   970  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   971  			// model.WithToken(users[1].Token),
   972  			model.WithOperation(model.Read),
   973  			model.WithModule(model.DiscoverModule),
   974  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   975  				apisecurity.ResourceType_Services: {
   976  					{
   977  						ID:    services[freeIndex].ID,
   978  						Owner: services[freeIndex].Owner,
   979  					},
   980  				},
   981  			}),
   982  		)
   983  		_, err = checker.CheckPermission(authCtx)
   984  		t.Logf("%+v", err)
   985  		assert.NoError(t, err, "Should be verify success")
   986  	})
   987  
   988  	t.Run("权限检查严格模式-匿名账户正常读操作-token为空-资源有策略", func(t *testing.T) {
   989  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "")
   990  		authCtx := model.NewAcquireContext(
   991  			model.WithRequestContext(ctx),
   992  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
   993  			// model.WithToken(""),
   994  			model.WithOperation(model.Read),
   995  			model.WithModule(model.DiscoverModule),
   996  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
   997  				apisecurity.ResourceType_Services: {
   998  					{
   999  						ID:    services[0].ID,
  1000  						Owner: services[0].Owner,
  1001  					},
  1002  				},
  1003  			}),
  1004  		)
  1005  		_, err = checker.CheckPermission(authCtx)
  1006  		t.Logf("%+v", err)
  1007  		assert.Error(t, err, "Should be verify fail")
  1008  	})
  1009  
  1010  	t.Run("权限检查严格模式-匿名账户正常读操作-token为空-资源无策略", func(t *testing.T) {
  1011  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "")
  1012  		authCtx := model.NewAcquireContext(
  1013  			model.WithRequestContext(ctx),
  1014  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
  1015  			// model.WithToken(""),
  1016  			model.WithOperation(model.Read),
  1017  			model.WithModule(model.DiscoverModule),
  1018  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
  1019  				apisecurity.ResourceType_Services: {
  1020  					{
  1021  						ID:    services[freeIndex].ID,
  1022  						Owner: services[freeIndex].Owner,
  1023  					},
  1024  				},
  1025  			}),
  1026  		)
  1027  		_, err = checker.CheckPermission(authCtx)
  1028  		t.Logf("%+v", err)
  1029  		assert.Error(t, err, "Should be verify fail")
  1030  	})
  1031  
  1032  	t.Run("权限检查严格模式-匿名账户正常读操作-token非法-资源有策略", func(t *testing.T) {
  1033  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "Test_DefaultAuthChecker_VerifyCredential")
  1034  		authCtx := model.NewAcquireContext(
  1035  			model.WithRequestContext(ctx),
  1036  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
  1037  			// model.WithToken("Test_DefaultAuthChecker_VerifyCredential"),
  1038  			model.WithOperation(model.Read),
  1039  			model.WithModule(model.DiscoverModule),
  1040  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
  1041  				apisecurity.ResourceType_Services: {
  1042  					{
  1043  						ID:    services[0].ID,
  1044  						Owner: services[0].Owner,
  1045  					},
  1046  				},
  1047  			}),
  1048  		)
  1049  		_, err = checker.CheckPermission(authCtx)
  1050  		t.Logf("%+v", err)
  1051  		assert.Error(t, err, "Should be verify fail")
  1052  	})
  1053  
  1054  	t.Run("权限检查严格模式-匿名账户正常读操作-token非法-资源无策略", func(t *testing.T) {
  1055  		ctx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "Test_DefaultAuthChecker_VerifyCredential")
  1056  		authCtx := model.NewAcquireContext(
  1057  			model.WithRequestContext(ctx),
  1058  			model.WithMethod("Test_DefaultAuthChecker_VerifyCredential"),
  1059  			// model.WithToken("Test_DefaultAuthChecker_VerifyCredential"),
  1060  			model.WithOperation(model.Read),
  1061  			model.WithModule(model.DiscoverModule),
  1062  			model.WithAccessResources(map[apisecurity.ResourceType][]model.ResourceEntry{
  1063  				apisecurity.ResourceType_Services: {
  1064  					{
  1065  						ID:    services[freeIndex].ID,
  1066  						Owner: services[freeIndex].Owner,
  1067  					},
  1068  				},
  1069  			}),
  1070  		)
  1071  		_, err = checker.CheckPermission(authCtx)
  1072  		t.Logf("%+v", err)
  1073  		assert.Error(t, err, "Should be verify fail")
  1074  	})
  1075  }
  1076  
  1077  func Test_DefaultAuthChecker_Initialize(t *testing.T) {
  1078  	reset(true)
  1079  
  1080  	ctrl := gomock.NewController(t)
  1081  	defer ctrl.Finish()
  1082  
  1083  	users := createMockUser(10)
  1084  
  1085  	storage := storemock.NewMockStore(ctrl)
  1086  	storage.EXPECT().GetUnixSecond(gomock.Any()).AnyTimes().Return(time.Now().Unix(), nil)
  1087  	storage.EXPECT().GetUsersForCache(gomock.Any(), gomock.Any()).AnyTimes().Return(users, nil)
  1088  	storage.EXPECT().GetGroupsForCache(gomock.Any(), gomock.Any()).AnyTimes().Return([]*model.UserGroupDetail{}, nil)
  1089  
  1090  	ctx, cancel := context.WithCancel(context.Background())
  1091  	cacheMgn, err := cache.TestCacheInitialize(ctx, &cache.Config{
  1092  		Open: true,
  1093  		Resources: []cache.ConfigEntry{
  1094  			{
  1095  				Name: "users",
  1096  			},
  1097  		},
  1098  	}, storage)
  1099  
  1100  	if err != nil {
  1101  		t.Fatal(err)
  1102  	}
  1103  
  1104  	t.Cleanup(func() {
  1105  		cancel()
  1106  		cacheMgn.Close()
  1107  	})
  1108  
  1109  	t.Run("使用未迁移至auth.user.option及auth.strategy.option的配置", func(t *testing.T) {
  1110  		reset(true)
  1111  		authChecker := &defaultauth.DefaultAuthChecker{}
  1112  		cfg := &auth.Config{}
  1113  		cfg.SetDefault()
  1114  		cfg.Name = ""
  1115  		cfg.Option = map[string]interface{}{
  1116  			"consoleOpen": true,
  1117  			"clientOpen":  true,
  1118  			"salt":        "polarismesh@2021",
  1119  			"strict":      false,
  1120  		}
  1121  		err := authChecker.Initialize(cfg, storage, cacheMgn)
  1122  		assert.NoError(t, err)
  1123  		assert.Equal(t, &defaultauth.AuthConfig{
  1124  			ConsoleOpen:   true,
  1125  			ClientOpen:    true,
  1126  			Salt:          "polarismesh@2021",
  1127  			Strict:        false,
  1128  			ConsoleStrict: true,
  1129  			ClientStrict:  false,
  1130  		}, defaultauth.AuthOption)
  1131  	})
  1132  
  1133  	t.Run("使用完全迁移至auth.user.option及auth.strategy.option的配置", func(t *testing.T) {
  1134  		reset(true)
  1135  		authChecker := &defaultauth.DefaultAuthChecker{}
  1136  
  1137  		cfg := &auth.Config{}
  1138  		cfg.SetDefault()
  1139  		cfg.User = &auth.UserConfig{
  1140  			Name:   "",
  1141  			Option: map[string]interface{}{"salt": "polarismesh@2021"},
  1142  		}
  1143  		cfg.Strategy = &auth.StrategyConfig{
  1144  			Name: "",
  1145  			Option: map[string]interface{}{
  1146  				"consoleOpen": true,
  1147  				"clientOpen":  true,
  1148  				"strict":      false,
  1149  			},
  1150  		}
  1151  
  1152  		err := authChecker.Initialize(cfg, storage, cacheMgn)
  1153  		assert.NoError(t, err)
  1154  		assert.Equal(t, &defaultauth.AuthConfig{
  1155  			ConsoleOpen:   true,
  1156  			ClientOpen:    true,
  1157  			Salt:          "polarismesh@2021",
  1158  			Strict:        false,
  1159  			ConsoleStrict: true,
  1160  		}, defaultauth.AuthOption)
  1161  	})
  1162  
  1163  	t.Run("使用部分迁移至auth.user.option及auth.strategy.option的配置(应当报错)", func(t *testing.T) {
  1164  		reset(true)
  1165  		authChecker := &defaultauth.DefaultAuthChecker{}
  1166  		cfg := &auth.Config{}
  1167  		cfg.SetDefault()
  1168  		cfg.Name = ""
  1169  		cfg.Option = map[string]interface{}{
  1170  			"clientOpen": true,
  1171  			"strict":     false,
  1172  		}
  1173  		cfg.User = &auth.UserConfig{
  1174  			Name:   "",
  1175  			Option: map[string]interface{}{"salt": "polarismesh@2021"},
  1176  		}
  1177  		cfg.Strategy = &auth.StrategyConfig{
  1178  			Name: "",
  1179  			Option: map[string]interface{}{
  1180  				"consoleOpen": true,
  1181  			},
  1182  		}
  1183  
  1184  		err := authChecker.Initialize(cfg, storage, cacheMgn)
  1185  		assert.NoError(t, err)
  1186  	})
  1187  
  1188  }