1/* 2Copyright 2016 The Kubernetes Authors. 3 4Licensed under the Apache License, Version 2.0 (the "License"); 5you may not use this file except in compliance with the License. 6You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10Unless required by applicable law or agreed to in writing, software 11distributed under the License is distributed on an "AS IS" BASIS, 12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13See the License for the specific language governing permissions and 14limitations under the License. 15*/ 16 17package rest 18 19import ( 20 "fmt" 21 "net/http" 22 "sync" 23 24 "k8s.io/klog/v2" 25 26 clientcmdapi "k8s.io/client-go/tools/clientcmd/api" 27) 28 29type AuthProvider interface { 30 // WrapTransport allows the plugin to create a modified RoundTripper that 31 // attaches authorization headers (or other info) to requests. 32 WrapTransport(http.RoundTripper) http.RoundTripper 33 // Login allows the plugin to initialize its configuration. It must not 34 // require direct user interaction. 35 Login() error 36} 37 38// Factory generates an AuthProvider plugin. 39// clusterAddress is the address of the current cluster. 40// config is the initial configuration for this plugin. 41// persister allows the plugin to save updated configuration. 42type Factory func(clusterAddress string, config map[string]string, persister AuthProviderConfigPersister) (AuthProvider, error) 43 44// AuthProviderConfigPersister allows a plugin to persist configuration info 45// for just itself. 46type AuthProviderConfigPersister interface { 47 Persist(map[string]string) error 48} 49 50type noopPersister struct{} 51 52func (n *noopPersister) Persist(_ map[string]string) error { 53 // no operation persister 54 return nil 55} 56 57// All registered auth provider plugins. 58var pluginsLock sync.Mutex 59var plugins = make(map[string]Factory) 60 61func RegisterAuthProviderPlugin(name string, plugin Factory) error { 62 pluginsLock.Lock() 63 defer pluginsLock.Unlock() 64 if _, found := plugins[name]; found { 65 return fmt.Errorf("auth Provider Plugin %q was registered twice", name) 66 } 67 klog.V(4).Infof("Registered Auth Provider Plugin %q", name) 68 plugins[name] = plugin 69 return nil 70} 71 72func GetAuthProvider(clusterAddress string, apc *clientcmdapi.AuthProviderConfig, persister AuthProviderConfigPersister) (AuthProvider, error) { 73 pluginsLock.Lock() 74 defer pluginsLock.Unlock() 75 p, ok := plugins[apc.Name] 76 if !ok { 77 return nil, fmt.Errorf("no Auth Provider found for name %q", apc.Name) 78 } 79 if persister == nil { 80 persister = &noopPersister{} 81 } 82 return p(clusterAddress, apc.Config, persister) 83} 84