k8s.io/apiserver@v0.31.1/pkg/authorization/path/path.go (about) 1 /* 2 Copyright 2018 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 path 18 19 import ( 20 "context" 21 "fmt" 22 "strings" 23 24 "k8s.io/apimachinery/pkg/util/sets" 25 "k8s.io/apiserver/pkg/authorization/authorizer" 26 ) 27 28 // NewAuthorizer returns an authorizer which accepts a given set of paths. 29 // Each path is either a fully matching path or it ends in * in case a prefix match is done. A leading / is optional. 30 func NewAuthorizer(alwaysAllowPaths []string) (authorizer.Authorizer, error) { 31 var prefixes []string 32 paths := sets.NewString() 33 for _, p := range alwaysAllowPaths { 34 p = strings.TrimPrefix(p, "/") 35 if len(p) == 0 { 36 // matches "/" 37 paths.Insert(p) 38 continue 39 } 40 if strings.ContainsRune(p[:len(p)-1], '*') { 41 return nil, fmt.Errorf("only trailing * allowed in %q", p) 42 } 43 if strings.HasSuffix(p, "*") { 44 prefixes = append(prefixes, p[:len(p)-1]) 45 } else { 46 paths.Insert(p) 47 } 48 } 49 50 return authorizer.AuthorizerFunc(func(ctx context.Context, a authorizer.Attributes) (authorizer.Decision, string, error) { 51 if a.IsResourceRequest() { 52 return authorizer.DecisionNoOpinion, "", nil 53 } 54 55 pth := strings.TrimPrefix(a.GetPath(), "/") 56 if paths.Has(pth) { 57 return authorizer.DecisionAllow, "", nil 58 } 59 60 for _, prefix := range prefixes { 61 if strings.HasPrefix(pth, prefix) { 62 return authorizer.DecisionAllow, "", nil 63 } 64 } 65 66 return authorizer.DecisionNoOpinion, "", nil 67 }), nil 68 }