k8s.io/kubernetes@v1.31.0-alpha.0.0.20240520171757-56147500dadc/plugin/pkg/admission/certificates/util.go (about) 1 /* 2 Copyright 2020 The Kubernetes 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 certificates 18 19 import ( 20 "context" 21 "strings" 22 23 "k8s.io/apiserver/pkg/authentication/user" 24 "k8s.io/apiserver/pkg/authorization/authorizer" 25 "k8s.io/klog/v2" 26 ) 27 28 // IsAuthorizedForSignerName returns true if 'info' is authorized to perform the given 29 // 'verb' on the synthetic 'signers' resource with the given signerName. 30 // If the user does not have permission to perform the 'verb' on the given signerName, 31 // it will also perform an authorization check against {domain portion}/*, for example 32 // `kubernetes.io/*`. This allows an entity to be granted permission to 'verb' on all 33 // signerNames with a given 'domain portion'. 34 func IsAuthorizedForSignerName(ctx context.Context, authz authorizer.Authorizer, info user.Info, verb, signerName string) bool { 35 // First check if the user has explicit permission to 'verb' for the given signerName. 36 attr := buildAttributes(info, verb, signerName) 37 decision, reason, err := authz.Authorize(ctx, attr) 38 switch { 39 case err != nil: 40 klog.V(3).Infof("cannot authorize %q %q for policy: %v,%v", verb, attr.GetName(), reason, err) 41 case decision == authorizer.DecisionAllow: 42 return true 43 } 44 45 // If not, check if the user has wildcard permissions to 'verb' for the domain portion of the signerName, e.g. 46 // 'kubernetes.io/*'. 47 attr = buildWildcardAttributes(info, verb, signerName) 48 decision, reason, err = authz.Authorize(ctx, attr) 49 switch { 50 case err != nil: 51 klog.V(3).Infof("cannot authorize %q %q for policy: %v,%v", verb, attr.GetName(), reason, err) 52 case decision == authorizer.DecisionAllow: 53 return true 54 } 55 56 return false 57 } 58 59 func buildAttributes(info user.Info, verb, signerName string) authorizer.Attributes { 60 return authorizer.AttributesRecord{ 61 User: info, 62 Verb: verb, 63 Name: signerName, 64 APIGroup: "certificates.k8s.io", 65 APIVersion: "*", 66 Resource: "signers", 67 ResourceRequest: true, 68 } 69 } 70 71 func buildWildcardAttributes(info user.Info, verb, signerName string) authorizer.Attributes { 72 parts := strings.Split(signerName, "/") 73 domain := parts[0] 74 return buildAttributes(info, verb, domain+"/*") 75 }