github.com/kubewharf/katalyst-core@v0.5.3/pkg/util/credential/authorization/dynamic.go (about) 1 /* 2 Copyright 2022 The Katalyst Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package authorization 18 19 import ( 20 "context" 21 "sync" 22 "time" 23 24 "k8s.io/apimachinery/pkg/util/wait" 25 26 "github.com/kubewharf/katalyst-core/pkg/config/agent/dynamic" 27 "github.com/kubewharf/katalyst-core/pkg/config/generic" 28 "github.com/kubewharf/katalyst-core/pkg/util/credential" 29 ) 30 31 const ( 32 secretSyncInterval = 30 * time.Second 33 ) 34 35 func NewDynamicConfAccessControl(_ *generic.AuthConfiguration, dynamicConfig *dynamic.DynamicAgentConfiguration) (AccessControl, error) { 36 return &dynamicConfAccessControl{ 37 dynamicConfig: dynamicConfig, 38 subjectToPermissions: map[string][]PermissionType{}, 39 }, nil 40 } 41 42 type dynamicConfAccessControl struct { 43 mutex sync.RWMutex 44 45 dynamicConfig *dynamic.DynamicAgentConfiguration 46 subjectToPermissions AuthRule 47 } 48 49 func (s *dynamicConfAccessControl) Run(ctx context.Context) { 50 go wait.Until(s.updateAuthInfoFromDynamicConf, secretSyncInterval, ctx.Done()) 51 } 52 53 func (s *dynamicConfAccessControl) Verify(authInfo credential.AuthInfo, targetResource PermissionType) error { 54 s.mutex.RLock() 55 defer s.mutex.RUnlock() 56 57 return verify(authInfo, targetResource, s.subjectToPermissions) 58 } 59 60 func (s *dynamicConfAccessControl) updateAuthInfoFromDynamicConf() { 61 dynamicConfiguration := s.dynamicConfig.GetDynamicConfiguration() 62 newRule := make(AuthRule) 63 for _, policy := range dynamicConfiguration.AccessControlPolicies { 64 permissions := policy.PolicyRule.Resources 65 rule := make([]PermissionType, 0, len(permissions)) 66 for i := range permissions { 67 rule = append(rule, PermissionType(permissions[i])) 68 } 69 newRule[policy.Username] = rule 70 } 71 s.mutex.Lock() 72 s.subjectToPermissions = newRule 73 s.mutex.Unlock() 74 }