github.com/polarismesh/polaris@v1.17.8/auth/defaultauth/common_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  	"fmt"
    22  	"time"
    23  
    24  	"github.com/golang/mock/gomock"
    25  	"github.com/google/uuid"
    26  	apisecurity "github.com/polarismesh/specification/source/go/api/v1/security"
    27  	"github.com/polarismesh/specification/source/go/api/v1/service_manage"
    28  	"golang.org/x/crypto/bcrypt"
    29  	"google.golang.org/protobuf/types/known/wrapperspb"
    30  
    31  	"github.com/polarismesh/polaris/auth/defaultauth"
    32  	"github.com/polarismesh/polaris/cache"
    33  	"github.com/polarismesh/polaris/common/metrics"
    34  	"github.com/polarismesh/polaris/common/model"
    35  	"github.com/polarismesh/polaris/common/utils"
    36  	storemock "github.com/polarismesh/polaris/store/mock"
    37  )
    38  
    39  func reset(strict bool) {
    40  	defaultauth.AuthOption = defaultauth.DefaultAuthConfig()
    41  	defaultauth.AuthOption.ClientOpen = true
    42  	defaultauth.AuthOption.ConsoleOpen = true
    43  	defaultauth.AuthOption.Strict = strict
    44  	defaultauth.AuthOption.ConsoleStrict = strict
    45  	defaultauth.AuthOption.ClientStrict = strict
    46  }
    47  
    48  func initCache(ctrl *gomock.Controller) (*cache.Config, *storemock.MockStore) {
    49  	metrics.InitMetrics()
    50  	/*
    51  		- name: service # 加载服务数据
    52  		  option:
    53  			disableBusiness: false # 不加载业务服务
    54  			needMeta: true # 加载服务元数据
    55  		- name: instance # 加载实例数据
    56  		  option:
    57  			disableBusiness: false # 不加载业务服务实例
    58  			needMeta: true # 加载实例元数据
    59  		- name: routingConfig # 加载路由数据
    60  		- name: rateLimitConfig # 加载限流数据
    61  		- name: circuitBreakerConfig # 加载熔断数据
    62  		- name: l5 # 加载l5数据
    63  		- name: users
    64  		- name: strategyRule
    65  		- name: namespace
    66  	*/
    67  	cfg := &cache.Config{
    68  		Open: true,
    69  		Resources: []cache.ConfigEntry{
    70  			{
    71  				Name: "service",
    72  				Option: map[string]interface{}{
    73  					"disableBusiness": false,
    74  					"needMeta":        true,
    75  				},
    76  			},
    77  			{
    78  				Name: "instance",
    79  			},
    80  			{
    81  				Name: "users",
    82  			},
    83  			{
    84  				Name: "strategyRule",
    85  			},
    86  			{
    87  				Name: "namespace",
    88  			},
    89  		},
    90  	}
    91  
    92  	storage := storemock.NewMockStore(ctrl)
    93  
    94  	mockTx := storemock.NewMockTx(ctrl)
    95  	mockTx.EXPECT().Commit().Return(nil).AnyTimes()
    96  	mockTx.EXPECT().Rollback().Return(nil).AnyTimes()
    97  	mockTx.EXPECT().CreateReadView().Return(nil).AnyTimes()
    98  
    99  	storage.EXPECT().StartReadTx().Return(mockTx, nil).AnyTimes()
   100  	storage.EXPECT().GetServicesCount().AnyTimes().Return(uint32(1), nil)
   101  	storage.EXPECT().GetInstancesCountTx(gomock.Any()).AnyTimes().Return(uint32(1), nil)
   102  	storage.EXPECT().GetMoreInstances(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(map[string]*model.Instance{
   103  		"123": {
   104  			Proto: &service_manage.Instance{
   105  				Id:   wrapperspb.String(uuid.NewString()),
   106  				Host: wrapperspb.String("127.0.0.1"),
   107  				Port: wrapperspb.UInt32(8080),
   108  			},
   109  			Valid: true,
   110  		},
   111  	}, nil).AnyTimes()
   112  	storage.EXPECT().GetUnixSecond(gomock.Any()).AnyTimes().Return(time.Now().Unix(), nil)
   113  
   114  	return cfg, storage
   115  }
   116  
   117  func createMockNamespace(total int, owner string) []*model.Namespace {
   118  	namespaces := make([]*model.Namespace, 0, total)
   119  
   120  	for i := 0; i < total; i++ {
   121  		namespaces = append(namespaces, &model.Namespace{
   122  			Name:  fmt.Sprintf("namespace_%d", i),
   123  			Owner: owner,
   124  			Valid: true,
   125  		})
   126  	}
   127  
   128  	return namespaces
   129  }
   130  
   131  func createMockService(namespaces []*model.Namespace) []*model.Service {
   132  	services := make([]*model.Service, 0, len(namespaces))
   133  
   134  	for i := 0; i < len(namespaces); i++ {
   135  		ns := namespaces[i]
   136  		services = append(services, &model.Service{
   137  			ID:        utils.NewUUID(),
   138  			Namespace: ns.Name,
   139  			Owner:     ns.Owner,
   140  			Name:      fmt.Sprintf("service_%d", i),
   141  			Valid:     true,
   142  		})
   143  	}
   144  
   145  	return services
   146  }
   147  
   148  // createMockUser 默认 users[0] 为 owner 用户
   149  func createMockUser(total int, prefix ...string) []*model.User {
   150  	users := make([]*model.User, 0, total)
   151  
   152  	ownerId := utils.NewUUID()
   153  
   154  	nameTemp := "user-%d"
   155  	if len(prefix) != 0 {
   156  		nameTemp = prefix[0] + nameTemp
   157  	}
   158  
   159  	for i := 0; i < total; i++ {
   160  		id := fmt.Sprintf("fake-user-id-%d-%s", i, utils.NewUUID())
   161  		if i == 0 {
   162  			id = ownerId
   163  		}
   164  		pwd, _ := bcrypt.GenerateFromPassword([]byte("polaris"), bcrypt.DefaultCost)
   165  		token, _ := defaultauth.TestCreateToken(id, "")
   166  		users = append(users, &model.User{
   167  			ID:       id,
   168  			Name:     fmt.Sprintf(nameTemp, i),
   169  			Password: string(pwd),
   170  			Owner: func() string {
   171  				if id == ownerId {
   172  					return ""
   173  				}
   174  				return ownerId
   175  			}(),
   176  			Source: "Polaris",
   177  			Mobile: "",
   178  			Email:  "",
   179  			Type: func() model.UserRoleType {
   180  				if id == ownerId {
   181  					return model.OwnerUserRole
   182  				}
   183  				return model.SubAccountUserRole
   184  			}(),
   185  			Token:       token,
   186  			TokenEnable: true,
   187  			Valid:       true,
   188  			CreateTime:  time.Time{},
   189  			ModifyTime:  time.Time{},
   190  		})
   191  	}
   192  	return users
   193  }
   194  
   195  func createApiMockUser(total int, prefix ...string) []*apisecurity.User {
   196  	users := make([]*apisecurity.User, 0, total)
   197  
   198  	models := createMockUser(total, prefix...)
   199  
   200  	for i := range models {
   201  		users = append(users, &apisecurity.User{
   202  			Name:     utils.NewStringValue("test-" + models[i].Name),
   203  			Password: utils.NewStringValue("123456"),
   204  			Source:   utils.NewStringValue("Polaris"),
   205  			Comment:  utils.NewStringValue(models[i].Comment),
   206  			Mobile:   utils.NewStringValue(models[i].Mobile),
   207  			Email:    utils.NewStringValue(models[i].Email),
   208  		})
   209  	}
   210  
   211  	return users
   212  }
   213  
   214  func createMockUserGroup(users []*model.User) []*model.UserGroupDetail {
   215  	groups := make([]*model.UserGroupDetail, 0, len(users))
   216  
   217  	for i := range users {
   218  		user := users[i]
   219  		id := utils.NewUUID()
   220  
   221  		token, _ := defaultauth.TestCreateToken("", id)
   222  
   223  		groups = append(groups, &model.UserGroupDetail{
   224  			UserGroup: &model.UserGroup{
   225  				ID:          id,
   226  				Name:        fmt.Sprintf("test-group-%d", i),
   227  				Owner:       users[0].ID,
   228  				Token:       token,
   229  				TokenEnable: true,
   230  				Valid:       true,
   231  				Comment:     "",
   232  				CreateTime:  time.Time{},
   233  				ModifyTime:  time.Time{},
   234  			},
   235  			UserIds: map[string]struct{}{
   236  				user.ID: {},
   237  			},
   238  		})
   239  	}
   240  
   241  	return groups
   242  }
   243  
   244  // createMockApiUserGroup
   245  func createMockApiUserGroup(users []*apisecurity.User) []*apisecurity.UserGroup {
   246  	musers := make([]*model.User, 0, len(users))
   247  	for i := range users {
   248  		musers = append(musers, &model.User{
   249  			ID: users[i].GetId().GetValue(),
   250  		})
   251  	}
   252  
   253  	models := createMockUserGroup(musers)
   254  	ret := make([]*apisecurity.UserGroup, 0, len(models))
   255  
   256  	for i := range models {
   257  		ret = append(ret, &apisecurity.UserGroup{
   258  			Name:    utils.NewStringValue(models[i].Name),
   259  			Comment: utils.NewStringValue(models[i].Comment),
   260  			Relation: &apisecurity.UserGroupRelation{
   261  				Users: []*apisecurity.User{
   262  					{
   263  						Id: utils.NewStringValue(users[i].GetId().GetValue()),
   264  					},
   265  				},
   266  			},
   267  		})
   268  	}
   269  
   270  	return ret
   271  }
   272  
   273  func createMockStrategy(users []*model.User, groups []*model.UserGroupDetail, services []*model.Service) ([]*model.StrategyDetail, []*model.StrategyDetail) {
   274  	strategies := make([]*model.StrategyDetail, 0, len(users)+len(groups))
   275  	defaultStrategies := make([]*model.StrategyDetail, 0, len(users)+len(groups))
   276  
   277  	owner := ""
   278  	for i := 0; i < len(users); i++ {
   279  		user := users[i]
   280  		if user.Owner == "" {
   281  			owner = user.ID
   282  			break
   283  		}
   284  	}
   285  
   286  	for i := 0; i < len(users); i++ {
   287  		user := users[i]
   288  		service := services[i]
   289  		id := utils.NewUUID()
   290  		strategies = append(strategies, &model.StrategyDetail{
   291  			ID:      id,
   292  			Name:    fmt.Sprintf("strategy_user_%s_%d", user.Name, i),
   293  			Action:  apisecurity.AuthAction_READ_WRITE.String(),
   294  			Comment: "",
   295  			Principals: []model.Principal{
   296  				{
   297  					PrincipalID:   user.ID,
   298  					PrincipalRole: model.PrincipalUser,
   299  				},
   300  			},
   301  			Default: false,
   302  			Owner:   owner,
   303  			Resources: []model.StrategyResource{
   304  				{
   305  					StrategyID: id,
   306  					ResType:    int32(apisecurity.ResourceType_Namespaces),
   307  					ResID:      service.Namespace,
   308  				},
   309  				{
   310  					StrategyID: id,
   311  					ResType:    int32(apisecurity.ResourceType_Services),
   312  					ResID:      service.ID,
   313  				},
   314  			},
   315  			Valid:      true,
   316  			Revision:   utils.NewUUID(),
   317  			CreateTime: time.Time{},
   318  			ModifyTime: time.Time{},
   319  		})
   320  
   321  		defaultStrategies = append(defaultStrategies, &model.StrategyDetail{
   322  			ID:      id,
   323  			Name:    fmt.Sprintf("strategy_default_user_%s_%d", user.Name, i),
   324  			Action:  apisecurity.AuthAction_READ_WRITE.String(),
   325  			Comment: "",
   326  			Principals: []model.Principal{
   327  				{
   328  					PrincipalID:   user.ID,
   329  					PrincipalRole: model.PrincipalUser,
   330  				},
   331  			},
   332  			Default: true,
   333  			Owner:   owner,
   334  			Resources: []model.StrategyResource{
   335  				{
   336  					StrategyID: id,
   337  					ResType:    int32(apisecurity.ResourceType_Namespaces),
   338  					ResID:      service.Namespace,
   339  				},
   340  				{
   341  					StrategyID: id,
   342  					ResType:    int32(apisecurity.ResourceType_Services),
   343  					ResID:      service.ID,
   344  				},
   345  			},
   346  			Valid:      true,
   347  			Revision:   utils.NewUUID(),
   348  			CreateTime: time.Time{},
   349  			ModifyTime: time.Time{},
   350  		})
   351  	}
   352  
   353  	for i := 0; i < len(groups); i++ {
   354  		group := groups[i]
   355  		service := services[len(users)+i]
   356  		id := utils.NewUUID()
   357  		strategies = append(strategies, &model.StrategyDetail{
   358  			ID:      id,
   359  			Name:    fmt.Sprintf("strategy_group_%s_%d", group.Name, i),
   360  			Action:  apisecurity.AuthAction_READ_WRITE.String(),
   361  			Comment: "",
   362  			Principals: []model.Principal{
   363  				{
   364  					PrincipalID:   group.ID,
   365  					PrincipalRole: model.PrincipalGroup,
   366  				},
   367  			},
   368  			Default: false,
   369  			Owner:   owner,
   370  			Resources: []model.StrategyResource{
   371  				{
   372  					StrategyID: id,
   373  					ResType:    int32(apisecurity.ResourceType_Namespaces),
   374  					ResID:      service.Namespace,
   375  				},
   376  				{
   377  					StrategyID: id,
   378  					ResType:    int32(apisecurity.ResourceType_Services),
   379  					ResID:      service.ID,
   380  				},
   381  			},
   382  			Valid:      true,
   383  			Revision:   utils.NewUUID(),
   384  			CreateTime: time.Time{},
   385  			ModifyTime: time.Time{},
   386  		})
   387  
   388  		defaultStrategies = append(defaultStrategies, &model.StrategyDetail{
   389  			ID:      id,
   390  			Name:    fmt.Sprintf("strategy_default_group_%s_%d", group.Name, i),
   391  			Action:  apisecurity.AuthAction_READ_WRITE.String(),
   392  			Comment: "",
   393  			Principals: []model.Principal{
   394  				{
   395  					PrincipalID:   group.ID,
   396  					PrincipalRole: model.PrincipalGroup,
   397  				},
   398  			},
   399  			Default: true,
   400  			Owner:   owner,
   401  			Resources: []model.StrategyResource{
   402  				{
   403  					StrategyID: id,
   404  					ResType:    int32(apisecurity.ResourceType_Namespaces),
   405  					ResID:      service.Namespace,
   406  				},
   407  				{
   408  					StrategyID: id,
   409  					ResType:    int32(apisecurity.ResourceType_Services),
   410  					ResID:      service.ID,
   411  				},
   412  			},
   413  			Valid:      true,
   414  			Revision:   utils.NewUUID(),
   415  			CreateTime: time.Time{},
   416  			ModifyTime: time.Time{},
   417  		})
   418  	}
   419  
   420  	return defaultStrategies, strategies
   421  }
   422  
   423  func convertServiceSliceToMap(services []*model.Service) map[string]*model.Service {
   424  	ret := make(map[string]*model.Service)
   425  
   426  	for i := range services {
   427  		service := services[i]
   428  		ret[service.ID] = service
   429  	}
   430  
   431  	return ret
   432  }