github.com/oam-dev/kubevela@v1.9.11/pkg/auth/userinfo_test.go (about) 1 /* 2 Copyright 2022 The KubeVela 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 auth 18 19 import ( 20 "testing" 21 22 "github.com/stretchr/testify/require" 23 authv1 "k8s.io/api/authentication/v1" 24 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 25 "k8s.io/apiserver/pkg/authentication/user" 26 utilfeature "k8s.io/apiserver/pkg/util/feature" 27 featuregatetesting "k8s.io/component-base/featuregate/testing" 28 29 "github.com/oam-dev/kubevela/apis/core.oam.dev/v1beta1" 30 "github.com/oam-dev/kubevela/pkg/features" 31 "github.com/oam-dev/kubevela/pkg/oam" 32 ) 33 34 func TestContextWithUserInfo(t *testing.T) { 35 defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.AuthenticateApplication, true)() 36 AuthenticationWithUser = true 37 defer func() { 38 AuthenticationWithUser = false 39 }() 40 testCases := map[string]struct { 41 UserInfo *authv1.UserInfo 42 ServiceAccount string 43 ExpectUserInfo user.Info 44 }{ 45 "empty": { 46 ExpectUserInfo: &user.DefaultInfo{ 47 Name: user.Anonymous, 48 Groups: []string{}, 49 }, 50 }, 51 "service-account": { 52 ServiceAccount: "sa", 53 ExpectUserInfo: &user.DefaultInfo{ 54 Name: "system:serviceaccount:default:sa", 55 Groups: []string{}, 56 }, 57 }, 58 "user-with-groups": { 59 UserInfo: &authv1.UserInfo{ 60 Username: "user", 61 Groups: []string{"group0", "kubevela:group1", "kubevela:group2"}, 62 }, 63 ServiceAccount: "override", 64 ExpectUserInfo: &user.DefaultInfo{ 65 Name: "user", 66 Groups: []string{"kubevela:group1", "kubevela:group2"}, 67 }, 68 }, 69 } 70 for name, tt := range testCases { 71 t.Run(name, func(t *testing.T) { 72 r := require.New(t) 73 app := &v1beta1.Application{} 74 app.SetNamespace("default") 75 if tt.UserInfo != nil { 76 SetUserInfoInAnnotation(&app.ObjectMeta, *tt.UserInfo) 77 } 78 if tt.ServiceAccount != "" { 79 metav1.SetMetaDataAnnotation(&app.ObjectMeta, oam.AnnotationApplicationServiceAccountName, tt.ServiceAccount) 80 } 81 r.Equal(tt.ExpectUserInfo, GetUserInfoInAnnotation(&app.ObjectMeta)) 82 }) 83 } 84 }