-
Notifications
You must be signed in to change notification settings - Fork 76
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
NOTE: The config loader should be split into go-base repo. Have it here just for simple test.
- Loading branch information
Showing
7 changed files
with
1,354 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
/* | ||
Copyright 2018 The Kubernetes Authors. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package config | ||
|
||
import ( | ||
"io/ioutil" | ||
"time" | ||
) | ||
|
||
var ( | ||
// time.Duration that prevents the client dropping valid credential | ||
// due to time skew | ||
expirySkewPreventionDelay = 5 * time.Minute | ||
) | ||
|
||
// Read authentication from kube-config user section if exists. | ||
// | ||
// This function goes through various authentication methods in user | ||
// section of kube-config and stops if it finds a valid authentication | ||
// method. The order of authentication methods is: | ||
// | ||
// 1. GCP auth-provider | ||
// 2. token_data | ||
// 3. token field (point to a token file) | ||
// 4. username/password | ||
func (l *KubeConfigLoader) loadAuthentication() { | ||
// The function walks though authentication methods. It doesn't fail on | ||
// single method loading failure. It is each loading function's responsiblity | ||
// to log meaningful failure message. Kubeconfig is allowed to have no user | ||
// in current context, therefore it is allowed that no authentication is loaded. | ||
|
||
if l.loadGCPToken() || l.loadUserToken() || l.loadUserPassToken() { | ||
return | ||
} | ||
} | ||
|
||
func (l *KubeConfigLoader) loadUserToken() bool { | ||
if l.user.Token == "" && l.user.TokenFile == "" { | ||
return false | ||
} | ||
// Token takes precedence than TokenFile | ||
if l.user.Token != "" { | ||
l.restConfig.token = "Bearer " + l.user.Token | ||
return true | ||
} | ||
|
||
// Read TokenFile | ||
token, err := ioutil.ReadFile(l.user.TokenFile) | ||
if err != nil { | ||
// A user may not provide any TokenFile, so we don't log error here | ||
return false | ||
} | ||
l.restConfig.token = "Bearer " + string(token) | ||
return true | ||
} | ||
|
||
func (l *KubeConfigLoader) loadUserPassToken() bool { | ||
if l.user.Username != "" && l.user.Password != "" { | ||
l.restConfig.token = basicAuthToken(l.user.Username, l.user.Password) | ||
return true | ||
} | ||
return false | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
/* | ||
Copyright 2018 The Kubernetes Authors. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package config | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
|
||
"github.com/golang/glog" | ||
"golang.org/x/oauth2" | ||
"golang.org/x/oauth2/google" | ||
) | ||
|
||
const ( | ||
gcpRFC3339Format = "2006-01-02 15:04:05" | ||
) | ||
|
||
// GoogleCredentialLoader defines the interface for getting GCP token | ||
type GoogleCredentialLoader interface { | ||
GetGoogleCredentials() (*oauth2.Token, error) | ||
} | ||
|
||
func (l *KubeConfigLoader) loadGCPToken() bool { | ||
if l.user.AuthProvider == nil || l.user.AuthProvider.Name != "gcp" { | ||
return false | ||
} | ||
|
||
// Refresh GCP token if necessary | ||
if l.user.AuthProvider.Config == nil { | ||
if err := l.refreshGCPToken(); err != nil { | ||
glog.Errorf("failed to refresh GCP token: %v", err) | ||
return false | ||
} | ||
} | ||
if _, ok := l.user.AuthProvider.Config["expiry"]; !ok { | ||
if err := l.refreshGCPToken(); err != nil { | ||
glog.Errorf("failed to refresh GCP token: %v", err) | ||
return false | ||
} | ||
} | ||
expired, err := isExpired(l.user.AuthProvider.Config["expiry"]) | ||
if err != nil { | ||
glog.Errorf("failed to determine if GCP token is expired: %v", err) | ||
return false | ||
} | ||
|
||
if expired { | ||
if err := l.refreshGCPToken(); err != nil { | ||
glog.Errorf("failed to refresh GCP token: %v", err) | ||
return false | ||
} | ||
} | ||
|
||
// Use GCP access token | ||
l.restConfig.token = "Bearer " + l.user.AuthProvider.Config["access-token"] | ||
return true | ||
} | ||
|
||
func (l *KubeConfigLoader) refreshGCPToken() error { | ||
if l.user.AuthProvider.Config == nil { | ||
l.user.AuthProvider.Config = map[string]string{} | ||
} | ||
|
||
// Get *oauth2.Token through Google APIs | ||
if l.gcLoader == nil { | ||
l.gcLoader = DefaultGoogleCredentialLoader{} | ||
} | ||
credentials, err := l.gcLoader.GetGoogleCredentials() | ||
if err != nil { | ||
return err | ||
} | ||
|
||
// Store credentials to Config | ||
l.user.AuthProvider.Config["access-token"] = credentials.AccessToken | ||
l.user.AuthProvider.Config["expiry"] = credentials.Expiry.Format(gcpRFC3339Format) | ||
|
||
setUserWithName(l.rawConfig.AuthInfos, l.currentContext.AuthInfo, &l.user) | ||
// Persist kube config file | ||
if !l.skipConfigPersist { | ||
if err := l.persistConfig(); err != nil { | ||
return err | ||
} | ||
} | ||
return nil | ||
} | ||
|
||
// DefaultGoogleCredentialLoader provides the default method for getting GCP token | ||
type DefaultGoogleCredentialLoader struct{} | ||
|
||
// GetGoogleCredentials fetches GCP using default locations | ||
func (l DefaultGoogleCredentialLoader) GetGoogleCredentials() (*oauth2.Token, error) { | ||
credentials, err := google.FindDefaultCredentials(context.Background(), "https://www.googleapis.com/auth/cloud-platform") | ||
if err != nil { | ||
return nil, fmt.Errorf("failed to get Google credentials: %v", err) | ||
} | ||
return credentials.TokenSource.Token() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
/* | ||
Copyright 2018 The Kubernetes Authors. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package config | ||
|
||
import ( | ||
"crypto/tls" | ||
"crypto/x509" | ||
"fmt" | ||
"io/ioutil" | ||
"net" | ||
"net/http" | ||
"os" | ||
|
||
"k8s.io/client/kubernetes/client" | ||
) | ||
|
||
const ( | ||
serviceHostEnvName = "KUBERNETES_SERVICE_HOST" | ||
servicePortEnvName = "KUBERNETES_SERVICE_PORT" | ||
serviceTokenFilename = "/var/run/secrets/kubernetes.io/serviceaccount/token" | ||
serviceCertFilename = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" | ||
) | ||
|
||
// InClusterConfig returns a config object which uses the service account | ||
// kubernetes gives to pods. It's intended for clients that expect to be | ||
// running inside a pod running on kubernetes. It will return an error if | ||
// called from a process not running in a kubernetes environment. | ||
func InClusterConfig() (*client.Configuration, error) { | ||
host, port := os.Getenv(serviceHostEnvName), os.Getenv(servicePortEnvName) | ||
if len(host) == 0 || len(port) == 0 { | ||
return nil, fmt.Errorf("unable to load in-cluster configuration, %v and %v must be defined", serviceHostEnvName, servicePortEnvName) | ||
} | ||
|
||
token, err := ioutil.ReadFile(serviceTokenFilename) | ||
if err != nil { | ||
return nil, err | ||
} | ||
caCert, err := ioutil.ReadFile(serviceCertFilename) | ||
if err != nil { | ||
return nil, err | ||
} | ||
caCertPool := x509.NewCertPool() | ||
caCertPool.AppendCertsFromPEM(caCert) | ||
c := &http.Client{ | ||
Transport: &http.Transport{ | ||
TLSClientConfig: &tls.Config{ | ||
RootCAs: caCertPool, | ||
}, | ||
}, | ||
} | ||
|
||
return &client.Configuration{ | ||
BasePath: "https://" + net.JoinHostPort(host, port), | ||
Host: net.JoinHostPort(host, port), | ||
Scheme: "https", | ||
DefaultHeader: map[string]string{"Authentication": "Bearer " + string(token)}, | ||
UserAgent: defaultUserAgent, | ||
HTTPClient: c, | ||
}, nil | ||
} |
Oops, something went wrong.