Fresh dep ensure

This commit is contained in:
Mike Cronce
2018-11-26 13:23:56 -05:00
parent 93cb8a04d7
commit 407478ab9a
9016 changed files with 551394 additions and 279685 deletions

View File

@ -17,9 +17,8 @@ go_library(
],
importpath = "k8s.io/kubernetes/pkg/credentialprovider",
deps = [
"//vendor/github.com/docker/docker/api/types:go_default_library",
"//vendor/github.com/golang/glog:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/util/sets:go_default_library",
"//vendor/k8s.io/klog:go_default_library",
],
)
@ -31,7 +30,6 @@ go_test(
"provider_test.go",
],
embed = [":go_default_library"],
deps = ["//vendor/github.com/docker/docker/api/types:go_default_library"],
)
filegroup(

View File

@ -16,7 +16,7 @@ go_library(
"//vendor/github.com/aws/aws-sdk-go/aws/request:go_default_library",
"//vendor/github.com/aws/aws-sdk-go/aws/session:go_default_library",
"//vendor/github.com/aws/aws-sdk-go/service/ecr:go_default_library",
"//vendor/github.com/golang/glog:go_default_library",
"//vendor/k8s.io/klog:go_default_library",
],
)

View File

@ -26,7 +26,8 @@ import (
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecr"
"github.com/golang/glog"
"k8s.io/klog"
"k8s.io/kubernetes/pkg/credentialprovider"
)
@ -46,7 +47,7 @@ func awsHandlerLogger(req *request.Request) {
name = req.Operation.Name
}
glog.V(3).Infof("AWS request: %s:%s in %s", service, name, *region)
klog.V(3).Infof("AWS request: %s:%s in %s", service, name, *region)
}
// An interface for testing purposes.
@ -100,7 +101,7 @@ func registryURL(region string) string {
// This should be called only if using the AWS cloud provider.
// This way, we avoid timeouts waiting for a non-existent provider.
func RegisterCredentialsProvider(region string) {
glog.V(4).Infof("registering credentials provider for AWS region %q", region)
klog.V(4).Infof("registering credentials provider for AWS region %q", region)
credentialprovider.RegisterCredentialProvider("aws-ecr-"+region,
&lazyEcrProvider{
@ -121,7 +122,7 @@ func (p *lazyEcrProvider) Enabled() bool {
// provider only when we actually need it the first time.
func (p *lazyEcrProvider) LazyProvide() *credentialprovider.DockerConfigEntry {
if p.actualProvider == nil {
glog.V(2).Infof("Creating ecrProvider for %s", p.region)
klog.V(2).Infof("Creating ecrProvider for %s", p.region)
p.actualProvider = &credentialprovider.CachingDockerConfigProvider{
Provider: newEcrProvider(p.region, nil),
// Refresh credentials a little earlier than expiration time
@ -160,7 +161,7 @@ func newEcrProvider(region string, getter tokenGetter) *ecrProvider {
// use ECR somehow?
func (p *ecrProvider) Enabled() bool {
if p.region == "" {
glog.Errorf("Called ecrProvider.Enabled() with no region set")
klog.Errorf("Called ecrProvider.Enabled() with no region set")
return false
}
@ -190,11 +191,11 @@ func (p *ecrProvider) Provide() credentialprovider.DockerConfig {
params := &ecr.GetAuthorizationTokenInput{}
output, err := p.getter.GetAuthorizationToken(params)
if err != nil {
glog.Errorf("while requesting ECR authorization token %v", err)
klog.Errorf("while requesting ECR authorization token %v", err)
return cfg
}
if output == nil {
glog.Errorf("Got back no ECR token")
klog.Errorf("Got back no ECR token")
return cfg
}
@ -203,7 +204,7 @@ func (p *ecrProvider) Provide() credentialprovider.DockerConfig {
data.AuthorizationToken != nil {
decodedToken, err := base64.StdEncoding.DecodeString(aws.StringValue(data.AuthorizationToken))
if err != nil {
glog.Errorf("while decoding token for endpoint %v %v", data.ProxyEndpoint, err)
klog.Errorf("while decoding token for endpoint %v %v", data.ProxyEndpoint, err)
return cfg
}
parts := strings.SplitN(string(decodedToken), ":", 2)
@ -216,7 +217,7 @@ func (p *ecrProvider) Provide() credentialprovider.DockerConfig {
Email: "not@val.id",
}
glog.V(3).Infof("Adding credentials for user %s in %s", user, p.region)
klog.V(3).Infof("Adding credentials for user %s in %s", user, p.region)
// Add our config entry for this region's registry URLs
cfg[p.regionURL] = entry

View File

@ -21,9 +21,9 @@ go_library(
"//vendor/github.com/Azure/go-autorest/autorest/adal:go_default_library",
"//vendor/github.com/Azure/go-autorest/autorest/azure:go_default_library",
"//vendor/github.com/dgrijalva/jwt-go:go_default_library",
"//vendor/github.com/ghodss/yaml:go_default_library",
"//vendor/github.com/golang/glog:go_default_library",
"//vendor/github.com/spf13/pflag:go_default_library",
"//vendor/k8s.io/klog:go_default_library",
"//vendor/sigs.k8s.io/yaml:go_default_library",
],
)

View File

@ -27,9 +27,9 @@ import (
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/ghodss/yaml"
"github.com/golang/glog"
"github.com/spf13/pflag"
"k8s.io/klog"
"sigs.k8s.io/yaml"
"k8s.io/kubernetes/pkg/cloudprovider/providers/azure/auth"
"k8s.io/kubernetes/pkg/credentialprovider"
@ -40,6 +40,8 @@ var flagConfigFile = pflag.String("azure-container-registry-config", "",
const dummyRegistryEmail = "name@contoso.com"
var containerRegistryUrls = []string{"*.azurecr.io", "*.azurecr.cn", "*.azurecr.de", "*.azurecr.us"}
// init registers the various means by which credentials may
// be resolved on Azure.
func init() {
@ -131,7 +133,7 @@ func (a *acrProvider) loadConfig(rdr io.Reader) error {
var err error
a.config, err = parseConfig(rdr)
if err != nil {
glog.Errorf("Failed to load azure credential file: %v", err)
klog.Errorf("Failed to load azure credential file: %v", err)
}
a.environment, err = auth.ParseAzureEnvironment(a.config.Cloud)
@ -144,26 +146,26 @@ func (a *acrProvider) loadConfig(rdr io.Reader) error {
func (a *acrProvider) Enabled() bool {
if a.file == nil || len(*a.file) == 0 {
glog.V(5).Infof("Azure config unspecified, disabling")
klog.V(5).Infof("Azure config unspecified, disabling")
return false
}
f, err := os.Open(*a.file)
if err != nil {
glog.Errorf("Failed to load config from file: %s", *a.file)
klog.Errorf("Failed to load config from file: %s", *a.file)
return false
}
defer f.Close()
err = a.loadConfig(f)
if err != nil {
glog.Errorf("Failed to load config from file: %s", *a.file)
klog.Errorf("Failed to load config from file: %s", *a.file)
return false
}
a.servicePrincipalToken, err = auth.GetServicePrincipalToken(a.config, a.environment)
if err != nil {
glog.Errorf("Failed to create service principal token: %v", err)
klog.Errorf("Failed to create service principal token: %v", err)
return false
}
@ -176,31 +178,33 @@ func (a *acrProvider) Provide() credentialprovider.DockerConfig {
ctx, cancel := getContextWithCancel()
defer cancel()
glog.V(4).Infof("listing registries")
result, err := a.registryClient.List(ctx)
if err != nil {
glog.Errorf("Failed to list registries: %v", err)
return cfg
}
if a.config.UseManagedIdentityExtension {
klog.V(4).Infof("listing registries")
result, err := a.registryClient.List(ctx)
if err != nil {
klog.Errorf("Failed to list registries: %v", err)
return cfg
}
for ix := range result {
loginServer := getLoginServer(result[ix])
var cred *credentialprovider.DockerConfigEntry
if a.config.UseManagedIdentityExtension {
cred, err = getACRDockerEntryFromARMToken(a, loginServer)
for ix := range result {
loginServer := getLoginServer(result[ix])
klog.V(2).Infof("loginServer: %s", loginServer)
cred, err := getACRDockerEntryFromARMToken(a, loginServer)
if err != nil {
continue
}
} else {
cred = &credentialprovider.DockerConfigEntry{
cfg[loginServer] = *cred
}
} else {
// Add our entry for each of the supported container registry URLs
for _, url := range containerRegistryUrls {
cred := &credentialprovider.DockerConfigEntry{
Username: a.config.AADClientID,
Password: a.config.AADClientSecret,
Email: dummyRegistryEmail,
}
cfg[url] = *cred
}
cfg[loginServer] = *cred
}
return cfg
}
@ -212,22 +216,22 @@ func getLoginServer(registry containerregistry.Registry) string {
func getACRDockerEntryFromARMToken(a *acrProvider, loginServer string) (*credentialprovider.DockerConfigEntry, error) {
armAccessToken := a.servicePrincipalToken.OAuthToken()
glog.V(4).Infof("discovering auth redirects for: %s", loginServer)
klog.V(4).Infof("discovering auth redirects for: %s", loginServer)
directive, err := receiveChallengeFromLoginServer(loginServer)
if err != nil {
glog.Errorf("failed to receive challenge: %s", err)
klog.Errorf("failed to receive challenge: %s", err)
return nil, err
}
glog.V(4).Infof("exchanging an acr refresh_token")
klog.V(4).Infof("exchanging an acr refresh_token")
registryRefreshToken, err := performTokenExchange(
loginServer, directive, a.config.TenantID, armAccessToken)
if err != nil {
glog.Errorf("failed to perform token exchange: %s", err)
klog.Errorf("failed to perform token exchange: %s", err)
return nil, err
}
glog.V(4).Infof("adding ACR docker config entry for: %s", loginServer)
klog.V(4).Infof("adding ACR docker config entry for: %s", loginServer)
return &credentialprovider.DockerConfigEntry{
Username: dockerTokenLoginUsernameGUID,
Password: registryRefreshToken,

View File

@ -43,19 +43,25 @@ func Test(t *testing.T) {
{
Name: to.StringPtr("foo"),
RegistryProperties: &containerregistry.RegistryProperties{
LoginServer: to.StringPtr("foo-microsoft.azurecr.io"),
LoginServer: to.StringPtr("*.azurecr.io"),
},
},
{
Name: to.StringPtr("bar"),
RegistryProperties: &containerregistry.RegistryProperties{
LoginServer: to.StringPtr("bar-microsoft.azurecr.io"),
LoginServer: to.StringPtr("*.azurecr.cn"),
},
},
{
Name: to.StringPtr("baz"),
RegistryProperties: &containerregistry.RegistryProperties{
LoginServer: to.StringPtr("baz-microsoft.azurecr.io"),
LoginServer: to.StringPtr("*.azurecr.de"),
},
},
{
Name: to.StringPtr("bus"),
RegistryProperties: &containerregistry.RegistryProperties{
LoginServer: to.StringPtr("*.azurecr.us"),
},
},
}

View File

@ -27,7 +27,7 @@ import (
"strings"
"sync"
"github.com/golang/glog"
"k8s.io/klog"
)
// DockerConfigJson represents ~/.docker/config.json file info
@ -95,21 +95,21 @@ func ReadDockercfgFile(searchPaths []string) (cfg DockerConfig, err error) {
for _, configPath := range searchPaths {
absDockerConfigFileLocation, err := filepath.Abs(filepath.Join(configPath, configFileName))
if err != nil {
glog.Errorf("while trying to canonicalize %s: %v", configPath, err)
klog.Errorf("while trying to canonicalize %s: %v", configPath, err)
continue
}
glog.V(4).Infof("looking for .dockercfg at %s", absDockerConfigFileLocation)
klog.V(4).Infof("looking for .dockercfg at %s", absDockerConfigFileLocation)
contents, err := ioutil.ReadFile(absDockerConfigFileLocation)
if os.IsNotExist(err) {
continue
}
if err != nil {
glog.V(4).Infof("while trying to read %s: %v", absDockerConfigFileLocation, err)
klog.V(4).Infof("while trying to read %s: %v", absDockerConfigFileLocation, err)
continue
}
cfg, err := readDockerConfigFileFromBytes(contents)
if err == nil {
glog.V(4).Infof("found .dockercfg at %s", absDockerConfigFileLocation)
klog.V(4).Infof("found .dockercfg at %s", absDockerConfigFileLocation)
return cfg, nil
}
}
@ -125,18 +125,18 @@ func ReadDockerConfigJSONFile(searchPaths []string) (cfg DockerConfig, err error
for _, configPath := range searchPaths {
absDockerConfigFileLocation, err := filepath.Abs(filepath.Join(configPath, configJsonFileName))
if err != nil {
glog.Errorf("while trying to canonicalize %s: %v", configPath, err)
klog.Errorf("while trying to canonicalize %s: %v", configPath, err)
continue
}
glog.V(4).Infof("looking for %s at %s", configJsonFileName, absDockerConfigFileLocation)
klog.V(4).Infof("looking for %s at %s", configJsonFileName, absDockerConfigFileLocation)
cfg, err = ReadSpecificDockerConfigJsonFile(absDockerConfigFileLocation)
if err != nil {
if !os.IsNotExist(err) {
glog.V(4).Infof("while trying to read %s: %v", absDockerConfigFileLocation, err)
klog.V(4).Infof("while trying to read %s: %v", absDockerConfigFileLocation, err)
}
continue
}
glog.V(4).Infof("found valid %s at %s", configJsonFileName, absDockerConfigFileLocation)
klog.V(4).Infof("found valid %s at %s", configJsonFileName, absDockerConfigFileLocation)
return cfg, nil
}
return nil, fmt.Errorf("couldn't find valid %s after checking in %v", configJsonFileName, searchPaths)
@ -188,7 +188,7 @@ func ReadUrl(url string, client *http.Client, header *http.Header) (body []byte,
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
glog.V(2).Infof("body of failing http response: %v", resp.Body)
klog.V(2).Infof("body of failing http response: %v", resp.Body)
return nil, &HttpError{
StatusCode: resp.StatusCode,
Url: url,
@ -213,7 +213,7 @@ func ReadDockerConfigFileFromUrl(url string, client *http.Client, header *http.H
func readDockerConfigFileFromBytes(contents []byte) (cfg DockerConfig, err error) {
if err = json.Unmarshal(contents, &cfg); err != nil {
glog.Errorf("while trying to parse blob %q: %v", contents, err)
klog.Errorf("while trying to parse blob %q: %v", contents, err)
return nil, err
}
return
@ -222,7 +222,7 @@ func readDockerConfigFileFromBytes(contents []byte) (cfg DockerConfig, err error
func readDockerConfigJsonFileFromBytes(contents []byte) (cfg DockerConfig, err error) {
var cfgJson DockerConfigJson
if err = json.Unmarshal(contents, &cfgJson); err != nil {
glog.Errorf("while trying to parse blob %q: %v", contents, err)
klog.Errorf("while trying to parse blob %q: %v", contents, err)
return nil, err
}
cfg = cfgJson.Auths

View File

@ -10,31 +10,23 @@ go_library(
name = "go_default_library",
srcs = [
"doc.go",
"jwt.go",
"metadata.go",
],
importpath = "k8s.io/kubernetes/pkg/credentialprovider/gcp",
deps = [
"//pkg/credentialprovider:go_default_library",
"//vendor/github.com/golang/glog:go_default_library",
"//vendor/github.com/spf13/pflag:go_default_library",
"//vendor/golang.org/x/oauth2:go_default_library",
"//vendor/golang.org/x/oauth2/google:go_default_library",
"//vendor/golang.org/x/oauth2/jwt:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/net:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/util/net:go_default_library",
"//vendor/k8s.io/klog:go_default_library",
],
)
go_test(
name = "go_default_test",
srcs = [
"jwt_test.go",
"metadata_test.go",
],
srcs = ["metadata_test.go"],
embed = [":go_default_library"],
deps = [
"//pkg/credentialprovider:go_default_library",
"//vendor/k8s.io/apimachinery/pkg/util/net:go_default_library",
"//staging/src/k8s.io/apimachinery/pkg/util/net:go_default_library",
],
)

View File

@ -1,120 +0,0 @@
/*
Copyright 2014 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 gcp_credentials
import (
"io/ioutil"
"time"
"github.com/golang/glog"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"golang.org/x/oauth2/jwt"
"k8s.io/kubernetes/pkg/credentialprovider"
"github.com/spf13/pflag"
)
const (
storageReadOnlyScope = "https://www.googleapis.com/auth/devstorage.read_only"
jwtFileFlagName = "google-json-key"
)
var (
flagJwtFile = pflag.String(jwtFileFlagName, "",
"The Google Cloud Platform Service Account JSON Key to use for authentication.")
)
// A DockerConfigProvider that reads its configuration from Google
// Compute Engine metadata.
type jwtProvider struct {
path *string
config *jwt.Config
tokenUrl string
}
// init registers the various means by which credentials may
// be resolved on GCP.
func init() {
pflag.CommandLine.MarkDeprecated(jwtFileFlagName, "Will be removed in a future version. "+
"To maintain node-level authentication, credentials should instead be included in a docker "+
"config.json file, located inside the Kubelet's --root-dir.")
credentialprovider.RegisterCredentialProvider("google-jwt-key",
&credentialprovider.CachingDockerConfigProvider{
Provider: &jwtProvider{
path: flagJwtFile,
},
Lifetime: 30 * time.Minute,
})
}
// Enabled implements DockerConfigProvider for the JSON Key based implementation.
func (j *jwtProvider) Enabled() bool {
if *j.path == "" {
return false
}
data, err := ioutil.ReadFile(*j.path)
if err != nil {
glog.Errorf("while reading file %s got %v", *j.path, err)
return false
}
config, err := google.JWTConfigFromJSON(data, storageReadOnlyScope)
if err != nil {
glog.Errorf("while parsing %s data got %v", *j.path, err)
return false
}
j.config = config
if j.tokenUrl != "" {
j.config.TokenURL = j.tokenUrl
}
return true
}
// LazyProvide implements DockerConfigProvider. Should never be called.
func (j *jwtProvider) LazyProvide() *credentialprovider.DockerConfigEntry {
return nil
}
// Provide implements DockerConfigProvider
func (j *jwtProvider) Provide() credentialprovider.DockerConfig {
cfg := credentialprovider.DockerConfig{}
ts := j.config.TokenSource(oauth2.NoContext)
token, err := ts.Token()
if err != nil {
glog.Errorf("while exchanging json key %s for access token %v", *j.path, err)
return cfg
}
if !token.Valid() {
glog.Errorf("Got back invalid token: %v", token)
return cfg
}
entry := credentialprovider.DockerConfigEntry{
Username: "_token",
Password: token.AccessToken,
Email: j.config.Email,
}
// Add our entry for each of the supported container registry URLs
for _, k := range containerRegistryUrls {
cfg[k] = entry
}
return cfg
}

View File

@ -1,127 +0,0 @@
/*
Copyright 2014 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 gcp_credentials
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"k8s.io/kubernetes/pkg/credentialprovider"
)
const email = "foo@bar.com"
// From oauth2/jwt_test.go
var (
dummyPrivateKey = `-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAx4fm7dngEmOULNmAs1IGZ9Apfzh+BkaQ1dzkmbUgpcoghucE
DZRnAGd2aPyB6skGMXUytWQvNYav0WTR00wFtX1ohWTfv68HGXJ8QXCpyoSKSSFY
fuP9X36wBSkSX9J5DVgiuzD5VBdzUISSmapjKm+DcbRALjz6OUIPEWi1Tjl6p5RK
1w41qdbmt7E5/kGhKLDuT7+M83g4VWhgIvaAXtnhklDAggilPPa8ZJ1IFe31lNlr
k4DRk38nc6sEutdf3RL7QoH7FBusI7uXV03DC6dwN1kP4GE7bjJhcRb/7jYt7CQ9
/E9Exz3c0yAp0yrTg0Fwh+qxfH9dKwN52S7SBwIDAQABAoIBAQCaCs26K07WY5Jt
3a2Cw3y2gPrIgTCqX6hJs7O5ByEhXZ8nBwsWANBUe4vrGaajQHdLj5OKfsIDrOvn
2NI1MqflqeAbu/kR32q3tq8/Rl+PPiwUsW3E6Pcf1orGMSNCXxeducF2iySySzh3
nSIhCG5uwJDWI7a4+9KiieFgK1pt/Iv30q1SQS8IEntTfXYwANQrfKUVMmVF9aIK
6/WZE2yd5+q3wVVIJ6jsmTzoDCX6QQkkJICIYwCkglmVy5AeTckOVwcXL0jqw5Kf
5/soZJQwLEyBoQq7Kbpa26QHq+CJONetPP8Ssy8MJJXBT+u/bSseMb3Zsr5cr43e
DJOhwsThAoGBAPY6rPKl2NT/K7XfRCGm1sbWjUQyDShscwuWJ5+kD0yudnT/ZEJ1
M3+KS/iOOAoHDdEDi9crRvMl0UfNa8MAcDKHflzxg2jg/QI+fTBjPP5GOX0lkZ9g
z6VePoVoQw2gpPFVNPPTxKfk27tEzbaffvOLGBEih0Kb7HTINkW8rIlzAoGBAM9y
1yr+jvfS1cGFtNU+Gotoihw2eMKtIqR03Yn3n0PK1nVCDKqwdUqCypz4+ml6cxRK
J8+Pfdh7D+ZJd4LEG6Y4QRDLuv5OA700tUoSHxMSNn3q9As4+T3MUyYxWKvTeu3U
f2NWP9ePU0lV8ttk7YlpVRaPQmc1qwooBA/z/8AdAoGAW9x0HWqmRICWTBnpjyxx
QGlW9rQ9mHEtUotIaRSJ6K/F3cxSGUEkX1a3FRnp6kPLcckC6NlqdNgNBd6rb2rA
cPl/uSkZP42Als+9YMoFPU/xrrDPbUhu72EDrj3Bllnyb168jKLa4VBOccUvggxr
Dm08I1hgYgdN5huzs7y6GeUCgYEAj+AZJSOJ6o1aXS6rfV3mMRve9bQ9yt8jcKXw
5HhOCEmMtaSKfnOF1Ziih34Sxsb7O2428DiX0mV/YHtBnPsAJidL0SdLWIapBzeg
KHArByIRkwE6IvJvwpGMdaex1PIGhx5i/3VZL9qiq/ElT05PhIb+UXgoWMabCp84
OgxDK20CgYAeaFo8BdQ7FmVX2+EEejF+8xSge6WVLtkaon8bqcn6P0O8lLypoOhd
mJAYH8WU+UAy9pecUnDZj14LAGNVmYcse8HFX71MoshnvCTFEPVo4rZxIAGwMpeJ
5jgQ3slYLpqrGlcbLgUXBUgzEO684Wk/UV9DFPlHALVqCfXQ9dpJPg==
-----END RSA PRIVATE KEY-----`
jsonKey = fmt.Sprintf(`{"private_key":"%[1]s", "client_email":"%[2]s", "type": "service_account"}`,
strings.Replace(dummyPrivateKey, "\n", "\\n", -1), email)
)
func TestJwtProvider(t *testing.T) {
token := "asdhflkjsdfkjhsdf"
// Modeled after oauth2/jwt_test.go
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(fmt.Sprintf(`{
"access_token": "%[1]s",
"scope": "user",
"token_type": "bearer",
"expires_in": 3600
}`, token)))
}))
defer ts.Close()
file, err := ioutil.TempFile(os.TempDir(), "temp")
if err != nil {
t.Fatalf("Error creating temp file: %v", err)
}
filename := file.Name()
defer os.Remove(filename)
_, err = file.WriteString(jsonKey)
if err != nil {
t.Fatalf("Error writing temp file: %v", err)
}
provider := &jwtProvider{
path: &filename,
tokenUrl: ts.URL,
}
if !provider.Enabled() {
t.Fatalf("Provider is unexpectedly disabled")
}
keyring := &credentialprovider.BasicDockerKeyring{}
keyring.Add(provider.Provide())
// Verify that we get the expected username/password combo for
// a gcr.io image name.
registryUrl := "gcr.io/foo/bar"
creds, ok := keyring.Lookup(registryUrl)
if !ok {
t.Errorf("Didn't find expected URL: %s", registryUrl)
return
}
if len(creds) > 1 {
t.Errorf("Got more hits than expected: %s", creds)
}
val := creds[0]
if "_token" != val.Username {
t.Errorf("Unexpected username value, want: _token, got: %s", val.Username)
}
if token != val.Password {
t.Errorf("Unexpected password value, want: %s, got: %s", token, val.Password)
}
if email != val.Email {
t.Errorf("Unexpected email value, want: %s, got: %s", email, val.Email)
}
}

View File

@ -23,8 +23,8 @@ import (
"strings"
"time"
"github.com/golang/glog"
utilnet "k8s.io/apimachinery/pkg/util/net"
"k8s.io/klog"
"k8s.io/kubernetes/pkg/credentialprovider"
)
@ -117,7 +117,7 @@ func init() {
func onGCEVM() bool {
data, err := ioutil.ReadFile(gceProductNameFile)
if err != nil {
glog.V(2).Infof("Error while reading product_name: %v", err)
klog.V(2).Infof("Error while reading product_name: %v", err)
return false
}
name := strings.TrimSpace(string(data))
@ -139,7 +139,7 @@ func (g *dockerConfigKeyProvider) Provide() credentialprovider.DockerConfig {
// Read the contents of the google-dockercfg metadata key and
// parse them as an alternate .dockercfg
if cfg, err := credentialprovider.ReadDockerConfigFileFromUrl(dockerConfigKey, g.Client, metadataHeader); err != nil {
glog.Errorf("while reading 'google-dockercfg' metadata: %v", err)
klog.Errorf("while reading 'google-dockercfg' metadata: %v", err)
} else {
return cfg
}
@ -156,17 +156,17 @@ func (g *dockerConfigUrlKeyProvider) LazyProvide() *credentialprovider.DockerCon
func (g *dockerConfigUrlKeyProvider) Provide() credentialprovider.DockerConfig {
// Read the contents of the google-dockercfg-url key and load a .dockercfg from there
if url, err := credentialprovider.ReadUrl(dockerConfigUrlKey, g.Client, metadataHeader); err != nil {
glog.Errorf("while reading 'google-dockercfg-url' metadata: %v", err)
klog.Errorf("while reading 'google-dockercfg-url' metadata: %v", err)
} else {
if strings.HasPrefix(string(url), "http") {
if cfg, err := credentialprovider.ReadDockerConfigFileFromUrl(string(url), g.Client, nil); err != nil {
glog.Errorf("while reading 'google-dockercfg-url'-specified url: %s, %v", string(url), err)
klog.Errorf("while reading 'google-dockercfg-url'-specified url: %s, %v", string(url), err)
} else {
return cfg
}
} else {
// TODO(mattmoor): support reading alternate scheme URLs (e.g. gs:// or s3://)
glog.Errorf("Unsupported URL scheme: %s", string(url))
klog.Errorf("Unsupported URL scheme: %s", string(url))
}
}
@ -209,7 +209,7 @@ func (g *containerRegistryProvider) Enabled() bool {
value := runWithBackoff(func() ([]byte, error) {
value, err := credentialprovider.ReadUrl(serviceAccounts, g.Client, metadataHeader)
if err != nil {
glog.V(2).Infof("Failed to Get service accounts from gce metadata server: %v", err)
klog.V(2).Infof("Failed to Get service accounts from gce metadata server: %v", err)
}
return value, err
})
@ -225,20 +225,20 @@ func (g *containerRegistryProvider) Enabled() bool {
}
}
if !defaultServiceAccountExists {
glog.V(2).Infof("'default' service account does not exist. Found following service accounts: %q", string(value))
klog.V(2).Infof("'default' service account does not exist. Found following service accounts: %q", string(value))
return false
}
url := metadataScopes + "?alt=json"
value = runWithBackoff(func() ([]byte, error) {
value, err := credentialprovider.ReadUrl(url, g.Client, metadataHeader)
if err != nil {
glog.V(2).Infof("Failed to Get scopes in default service account from gce metadata server: %v", err)
klog.V(2).Infof("Failed to Get scopes in default service account from gce metadata server: %v", err)
}
return value, err
})
var scopes []string
if err := json.Unmarshal(value, &scopes); err != nil {
glog.Errorf("Failed to unmarshal scopes: %v", err)
klog.Errorf("Failed to unmarshal scopes: %v", err)
return false
}
for _, v := range scopes {
@ -247,7 +247,7 @@ func (g *containerRegistryProvider) Enabled() bool {
return true
}
}
glog.Warningf("Google container registry is disabled, no storage scope is available: %s", value)
klog.Warningf("Google container registry is disabled, no storage scope is available: %s", value)
return false
}
@ -268,19 +268,19 @@ func (g *containerRegistryProvider) Provide() credentialprovider.DockerConfig {
tokenJsonBlob, err := credentialprovider.ReadUrl(metadataToken, g.Client, metadataHeader)
if err != nil {
glog.Errorf("while reading access token endpoint: %v", err)
klog.Errorf("while reading access token endpoint: %v", err)
return cfg
}
email, err := credentialprovider.ReadUrl(metadataEmail, g.Client, metadataHeader)
if err != nil {
glog.Errorf("while reading email endpoint: %v", err)
klog.Errorf("while reading email endpoint: %v", err)
return cfg
}
var parsedBlob tokenBlob
if err := json.Unmarshal([]byte(tokenJsonBlob), &parsedBlob); err != nil {
glog.Errorf("while parsing json blob %s: %v", tokenJsonBlob, err)
klog.Errorf("while parsing json blob %s: %v", tokenJsonBlob, err)
return cfg
}

View File

@ -70,7 +70,7 @@ func TestDockerKeyringFromGoogleDockerConfigMetadata(t *testing.T) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, sampleDockerConfig)
} else {
w.WriteHeader(http.StatusNotFound)
http.Error(w, "", http.StatusNotFound)
}
}))
defer server.Close()
@ -148,7 +148,7 @@ func TestDockerKeyringFromGoogleDockerConfigMetadataUrl(t *testing.T) {
w.Header().Set("Content-Type", "application/text")
fmt.Fprint(w, "http://foo.bar.com"+valueEndpoint)
} else {
w.WriteHeader(http.StatusNotFound)
http.Error(w, "", http.StatusNotFound)
}
}))
defer server.Close()
@ -232,7 +232,7 @@ func TestContainerRegistryBasics(t *testing.T) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "default/\ncustom")
} else {
w.WriteHeader(http.StatusNotFound)
http.Error(w, "", http.StatusNotFound)
}
}))
defer server.Close()
@ -291,7 +291,7 @@ func TestContainerRegistryNoServiceAccount(t *testing.T) {
}
fmt.Fprintln(w, string(bytes))
} else {
w.WriteHeader(http.StatusNotFound)
http.Error(w, "", http.StatusNotFound)
}
}))
defer server.Close()
@ -335,7 +335,7 @@ func TestContainerRegistryNoStorageScope(t *testing.T) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "default/\ncustom")
} else {
w.WriteHeader(http.StatusNotFound)
http.Error(w, "", http.StatusNotFound)
}
}))
defer server.Close()
@ -380,7 +380,7 @@ func TestComputePlatformScopeSubstitutesStorageScope(t *testing.T) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, "default/\ncustom")
} else {
w.WriteHeader(http.StatusNotFound)
http.Error(w, "", http.StatusNotFound)
}
}))
defer server.Close()
@ -410,7 +410,7 @@ func TestComputePlatformScopeSubstitutesStorageScope(t *testing.T) {
func TestAllProvidersNoMetadata(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
http.Error(w, "", http.StatusNotFound)
}))
defer server.Close()

View File

@ -23,9 +23,8 @@ import (
"sort"
"strings"
"github.com/golang/glog"
"k8s.io/klog"
dockertypes "github.com/docker/docker/api/types"
"k8s.io/apimachinery/pkg/util/sets"
)
@ -52,17 +51,39 @@ type lazyDockerKeyring struct {
Providers []DockerConfigProvider
}
// AuthConfig contains authorization information for connecting to a Registry
// This type mirrors "github.com/docker/docker/api/types.AuthConfig"
type AuthConfig struct {
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
Auth string `json:"auth,omitempty"`
// Email is an optional value associated with the username.
// This field is deprecated and will be removed in a later
// version of docker.
Email string `json:"email,omitempty"`
ServerAddress string `json:"serveraddress,omitempty"`
// IdentityToken is used to authenticate the user and get
// an access token for the registry.
IdentityToken string `json:"identitytoken,omitempty"`
// RegistryToken is a bearer token to be sent to a registry
RegistryToken string `json:"registrytoken,omitempty"`
}
// LazyAuthConfiguration wraps dockertypes.AuthConfig, potentially deferring its
// binding. If Provider is non-nil, it will be used to obtain new credentials
// by calling LazyProvide() on it.
type LazyAuthConfiguration struct {
dockertypes.AuthConfig
AuthConfig
Provider DockerConfigProvider
}
func DockerConfigEntryToLazyAuthConfiguration(ident DockerConfigEntry) LazyAuthConfiguration {
return LazyAuthConfiguration{
AuthConfig: dockertypes.AuthConfig{
AuthConfig: AuthConfig{
Username: ident.Username,
Password: ident.Password,
Email: ident.Email,
@ -92,7 +113,7 @@ func (dk *BasicDockerKeyring) Add(cfg DockerConfig) {
}
parsed, err := url.Parse(value)
if err != nil {
glog.Errorf("Entry %q in dockercfg invalid (%v), ignoring", loc, err)
klog.Errorf("Entry %q in dockercfg invalid (%v), ignoring", loc, err)
continue
}

View File

@ -21,8 +21,6 @@ import (
"fmt"
"reflect"
"testing"
dockertypes "github.com/docker/docker/api/types"
)
func TestUrlsMatch(t *testing.T) {
@ -505,7 +503,7 @@ func TestLazyKeyring(t *testing.T) {
func TestDockerKeyringLookup(t *testing.T) {
ada := LazyAuthConfiguration{
AuthConfig: dockertypes.AuthConfig{
AuthConfig: AuthConfig{
Username: "ada",
Password: "smash",
Email: "ada@example.com",
@ -513,7 +511,7 @@ func TestDockerKeyringLookup(t *testing.T) {
}
grace := LazyAuthConfiguration{
AuthConfig: dockertypes.AuthConfig{
AuthConfig: AuthConfig{
Username: "grace",
Password: "squash",
Email: "grace@example.com",
@ -576,7 +574,7 @@ func TestDockerKeyringLookup(t *testing.T) {
// NOTE: the above covers the case of a more specific match trumping just hostname.
func TestIssue3797(t *testing.T) {
rex := LazyAuthConfiguration{
AuthConfig: dockertypes.AuthConfig{
AuthConfig: AuthConfig{
Username: "rex",
Password: "tiny arms",
Email: "rex@example.com",

View File

@ -17,9 +17,11 @@ limitations under the License.
package credentialprovider
import (
"reflect"
"sort"
"sync"
"github.com/golang/glog"
"k8s.io/klog"
)
// All registered credential providers.
@ -36,9 +38,9 @@ func RegisterCredentialProvider(name string, provider DockerConfigProvider) {
defer providersMutex.Unlock()
_, found := providers[name]
if found {
glog.Fatalf("Credential provider %q was registered twice", name)
klog.Fatalf("Credential provider %q was registered twice", name)
}
glog.V(4).Infof("Registered credential provider %q", name)
klog.V(4).Infof("Registered credential provider %q", name)
providers[name] = provider
}
@ -49,11 +51,17 @@ func NewDockerKeyring() DockerKeyring {
Providers: make([]DockerConfigProvider, 0),
}
// TODO(mattmoor): iterating over the map is non-deterministic. We should
// introduce the notion of priorities for conflict resolution.
for name, provider := range providers {
keys := reflect.ValueOf(providers).MapKeys()
stringKeys := make([]string, len(keys))
for ix := range keys {
stringKeys[ix] = keys[ix].String()
}
sort.Strings(stringKeys)
for _, key := range stringKeys {
provider := providers[key]
if provider.Enabled() {
glog.V(4).Infof("Registering credential provider: %v", name)
klog.V(4).Infof("Registering credential provider: %v", key)
keyring.Providers = append(keyring.Providers, provider)
}
}

View File

@ -22,8 +22,7 @@ import (
"sync"
"time"
dockertypes "github.com/docker/docker/api/types"
"github.com/golang/glog"
"k8s.io/klog"
)
// DockerConfigProvider is the interface that registered extensions implement
@ -40,14 +39,12 @@ type DockerConfigProvider interface {
LazyProvide() *DockerConfigEntry
}
func LazyProvide(creds LazyAuthConfiguration) dockertypes.AuthConfig {
func LazyProvide(creds LazyAuthConfiguration) AuthConfig {
if creds.Provider != nil {
entry := *creds.Provider.LazyProvide()
return DockerConfigEntryToLazyAuthConfiguration(entry).AuthConfig
} else {
return creds.AuthConfig
}
return creds.AuthConfig
}
// A DockerConfigProvider that simply reads the .dockercfg file
@ -86,7 +83,7 @@ func (d *defaultDockerConfigProvider) Provide() DockerConfig {
if cfg, err := ReadDockerConfigFile(); err == nil {
return cfg
} else if !os.IsNotExist(err) {
glog.V(4).Infof("Unable to parse Docker config file: %v", err)
klog.V(4).Infof("Unable to parse Docker config file: %v", err)
}
return DockerConfig{}
}
@ -116,7 +113,7 @@ func (d *CachingDockerConfigProvider) Provide() DockerConfig {
return d.cacheDockerConfig
}
glog.V(2).Infof("Refreshing cache for provider: %v", reflect.TypeOf(d.Provider).String())
klog.V(2).Infof("Refreshing cache for provider: %v", reflect.TypeOf(d.Provider).String())
d.cacheDockerConfig = d.Provider.Provide()
d.expiration = time.Now().Add(d.Lifetime)
return d.cacheDockerConfig

View File

@ -25,8 +25,8 @@ go_library(
importpath = "k8s.io/kubernetes/pkg/credentialprovider/rancher",
deps = [
"//pkg/credentialprovider:go_default_library",
"//vendor/github.com/golang/glog:go_default_library",
"//vendor/github.com/rancher/go-rancher/client:go_default_library",
"//vendor/k8s.io/klog:go_default_library",
],
)

View File

@ -20,8 +20,8 @@ import (
"os"
"time"
"github.com/golang/glog"
"github.com/rancher/go-rancher/client"
"k8s.io/klog"
"k8s.io/kubernetes/pkg/credentialprovider"
)
@ -102,13 +102,13 @@ func (g *rancherCredentialsGetter) getCredentials() []registryCredential {
var registryCreds []registryCredential
credColl, err := g.client.RegistryCredential.List(client.NewListOpts())
if err != nil {
glog.Errorf("Failed to pull registry credentials from rancher %v", err)
klog.Errorf("Failed to pull registry credentials from rancher %v", err)
return registryCreds
}
for _, cred := range credColl.Data {
registry := &client.Registry{}
if err = g.client.GetLink(cred.Resource, "registry", registry); err != nil {
glog.Errorf("Failed to pull registry from rancher %v", err)
klog.Errorf("Failed to pull registry from rancher %v", err)
return registryCreds
}
registryCred := registryCredential{

View File

@ -7,7 +7,7 @@ go_library(
visibility = ["//visibility:public"],
deps = [
"//pkg/credentialprovider:go_default_library",
"//vendor/k8s.io/api/core/v1:go_default_library",
"//staging/src/k8s.io/api/core/v1:go_default_library",
],
)