mirror of
https://github.com/ceph/ceph-csi.git
synced 2025-06-14 18:53:35 +00:00
rebase: update replaced k8s.io modules to v0.33.0
Signed-off-by: Niels de Vos <ndevos@ibm.com>
This commit is contained in:
committed by
mergify[bot]
parent
dd77e72800
commit
107407b44b
8
e2e/vendor/k8s.io/kubernetes/pkg/credentialprovider/OWNERS
generated
vendored
Normal file
8
e2e/vendor/k8s.io/kubernetes/pkg/credentialprovider/OWNERS
generated
vendored
Normal file
@ -0,0 +1,8 @@
|
||||
# See the OWNERS docs at https://go.k8s.io/owners
|
||||
|
||||
approvers:
|
||||
- sig-auth-authenticators-approvers
|
||||
reviewers:
|
||||
- sig-auth-authenticators-reviewers
|
||||
labels:
|
||||
- sig/auth
|
319
e2e/vendor/k8s.io/kubernetes/pkg/credentialprovider/config.go
generated
vendored
Normal file
319
e2e/vendor/k8s.io/kubernetes/pkg/credentialprovider/config.go
generated
vendored
Normal file
@ -0,0 +1,319 @@
|
||||
/*
|
||||
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 credentialprovider
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"k8s.io/klog/v2"
|
||||
)
|
||||
|
||||
const (
|
||||
maxReadLength = 10 * 1 << 20 // 10MB
|
||||
)
|
||||
|
||||
// DockerConfigJSON represents ~/.docker/config.json file info
|
||||
// see https://github.com/docker/docker/pull/12009
|
||||
type DockerConfigJSON struct {
|
||||
Auths DockerConfig `json:"auths"`
|
||||
// +optional
|
||||
HTTPHeaders map[string]string `json:"HttpHeaders,omitempty"`
|
||||
}
|
||||
|
||||
// DockerConfig represents the config file used by the docker CLI.
|
||||
// This config that represents the credentials that should be used
|
||||
// when pulling images from specific image repositories.
|
||||
type DockerConfig map[string]DockerConfigEntry
|
||||
|
||||
// DockerConfigEntry wraps a docker config as a entry
|
||||
type DockerConfigEntry struct {
|
||||
Username string
|
||||
Password string
|
||||
Email string
|
||||
Provider DockerConfigProvider
|
||||
}
|
||||
|
||||
var (
|
||||
preferredPathLock sync.Mutex
|
||||
preferredPath = ""
|
||||
workingDirPath = ""
|
||||
homeDirPath, _ = os.UserHomeDir()
|
||||
rootDirPath = "/"
|
||||
homeJSONDirPath = filepath.Join(homeDirPath, ".docker")
|
||||
rootJSONDirPath = filepath.Join(rootDirPath, ".docker")
|
||||
|
||||
configFileName = ".dockercfg"
|
||||
configJSONFileName = "config.json"
|
||||
)
|
||||
|
||||
// SetPreferredDockercfgPath set preferred docker config path
|
||||
func SetPreferredDockercfgPath(path string) {
|
||||
preferredPathLock.Lock()
|
||||
defer preferredPathLock.Unlock()
|
||||
preferredPath = path
|
||||
}
|
||||
|
||||
// GetPreferredDockercfgPath get preferred docker config path
|
||||
func GetPreferredDockercfgPath() string {
|
||||
preferredPathLock.Lock()
|
||||
defer preferredPathLock.Unlock()
|
||||
return preferredPath
|
||||
}
|
||||
|
||||
// DefaultDockercfgPaths returns default search paths of .dockercfg
|
||||
func DefaultDockercfgPaths() []string {
|
||||
return []string{GetPreferredDockercfgPath(), workingDirPath, homeDirPath, rootDirPath}
|
||||
}
|
||||
|
||||
// DefaultDockerConfigJSONPaths returns default search paths of .docker/config.json
|
||||
func DefaultDockerConfigJSONPaths() []string {
|
||||
return []string{GetPreferredDockercfgPath(), workingDirPath, homeJSONDirPath, rootJSONDirPath}
|
||||
}
|
||||
|
||||
// ReadDockercfgFile attempts to read a legacy dockercfg file from the given paths.
|
||||
// if searchPaths is empty, the default paths are used.
|
||||
func ReadDockercfgFile(searchPaths []string) (cfg DockerConfig, err error) {
|
||||
if len(searchPaths) == 0 {
|
||||
searchPaths = DefaultDockercfgPaths()
|
||||
}
|
||||
|
||||
for _, configPath := range searchPaths {
|
||||
absDockerConfigFileLocation, err := filepath.Abs(filepath.Join(configPath, configFileName))
|
||||
if err != nil {
|
||||
klog.Errorf("while trying to canonicalize %s: %v", configPath, err)
|
||||
continue
|
||||
}
|
||||
klog.V(4).Infof("looking for .dockercfg at %s", absDockerConfigFileLocation)
|
||||
contents, err := os.ReadFile(absDockerConfigFileLocation)
|
||||
if os.IsNotExist(err) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
klog.V(4).Infof("while trying to read %s: %v", absDockerConfigFileLocation, err)
|
||||
continue
|
||||
}
|
||||
cfg, err := ReadDockerConfigFileFromBytes(contents)
|
||||
if err != nil {
|
||||
klog.V(4).Infof("couldn't get the config from %q contents: %v", absDockerConfigFileLocation, err)
|
||||
continue
|
||||
}
|
||||
|
||||
klog.V(4).Infof("found .dockercfg at %s", absDockerConfigFileLocation)
|
||||
return cfg, nil
|
||||
|
||||
}
|
||||
return nil, fmt.Errorf("couldn't find valid .dockercfg after checking in %v", searchPaths)
|
||||
}
|
||||
|
||||
// ReadDockerConfigJSONFile attempts to read a docker config.json file from the given paths.
|
||||
// if searchPaths is empty, the default paths are used.
|
||||
func ReadDockerConfigJSONFile(searchPaths []string) (cfg DockerConfig, err error) {
|
||||
if len(searchPaths) == 0 {
|
||||
searchPaths = DefaultDockerConfigJSONPaths()
|
||||
}
|
||||
for _, configPath := range searchPaths {
|
||||
absDockerConfigFileLocation, err := filepath.Abs(filepath.Join(configPath, configJSONFileName))
|
||||
if err != nil {
|
||||
klog.Errorf("while trying to canonicalize %s: %v", configPath, err)
|
||||
continue
|
||||
}
|
||||
klog.V(4).Infof("looking for %s at %s", configJSONFileName, absDockerConfigFileLocation)
|
||||
cfg, err = ReadSpecificDockerConfigJSONFile(absDockerConfigFileLocation)
|
||||
if err != nil {
|
||||
if !os.IsNotExist(err) {
|
||||
klog.V(4).Infof("while trying to read %s: %v", absDockerConfigFileLocation, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
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)
|
||||
|
||||
}
|
||||
|
||||
// ReadSpecificDockerConfigJSONFile attempts to read docker configJSON from a given file path.
|
||||
func ReadSpecificDockerConfigJSONFile(filePath string) (cfg DockerConfig, err error) {
|
||||
var contents []byte
|
||||
|
||||
if contents, err = os.ReadFile(filePath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return readDockerConfigJSONFileFromBytes(contents)
|
||||
}
|
||||
|
||||
// ReadDockerConfigFile read a docker config file from default path
|
||||
func ReadDockerConfigFile() (cfg DockerConfig, err error) {
|
||||
if cfg, err := ReadDockerConfigJSONFile(nil); err == nil {
|
||||
return cfg, nil
|
||||
}
|
||||
// Can't find latest config file so check for the old one
|
||||
return ReadDockercfgFile(nil)
|
||||
}
|
||||
|
||||
// HTTPError wraps a non-StatusOK error code as an error.
|
||||
type HTTPError struct {
|
||||
StatusCode int
|
||||
URL string
|
||||
}
|
||||
|
||||
// Error implements error
|
||||
func (he *HTTPError) Error() string {
|
||||
return fmt.Sprintf("http status code: %d while fetching url %s",
|
||||
he.StatusCode, he.URL)
|
||||
}
|
||||
|
||||
// ReadURL read contents from given url
|
||||
func ReadURL(url string, client *http.Client, header *http.Header) (body []byte, err error) {
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if header != nil {
|
||||
req.Header = *header
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
klog.V(2).InfoS("Failed to read URL", "statusCode", resp.StatusCode, "URL", url)
|
||||
return nil, &HTTPError{
|
||||
StatusCode: resp.StatusCode,
|
||||
URL: url,
|
||||
}
|
||||
}
|
||||
|
||||
limitedReader := &io.LimitedReader{R: resp.Body, N: maxReadLength}
|
||||
contents, err := io.ReadAll(limitedReader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if limitedReader.N <= 0 {
|
||||
return nil, errors.New("the read limit is reached")
|
||||
}
|
||||
|
||||
return contents, nil
|
||||
}
|
||||
|
||||
// ReadDockerConfigFileFromBytes read a docker config file from the given bytes
|
||||
func ReadDockerConfigFileFromBytes(contents []byte) (cfg DockerConfig, err error) {
|
||||
if err = json.Unmarshal(contents, &cfg); err != nil {
|
||||
return nil, errors.New("error occurred while trying to unmarshal json")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func readDockerConfigJSONFileFromBytes(contents []byte) (cfg DockerConfig, err error) {
|
||||
var cfgJSON DockerConfigJSON
|
||||
if err = json.Unmarshal(contents, &cfgJSON); err != nil {
|
||||
return nil, errors.New("error occurred while trying to unmarshal json")
|
||||
}
|
||||
cfg = cfgJSON.Auths
|
||||
return
|
||||
}
|
||||
|
||||
// dockerConfigEntryWithAuth is used solely for deserializing the Auth field
|
||||
// into a dockerConfigEntry during JSON deserialization.
|
||||
type dockerConfigEntryWithAuth struct {
|
||||
// +optional
|
||||
Username string `json:"username,omitempty"`
|
||||
// +optional
|
||||
Password string `json:"password,omitempty"`
|
||||
// +optional
|
||||
Email string `json:"email,omitempty"`
|
||||
// +optional
|
||||
Auth string `json:"auth,omitempty"`
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements the json.Unmarshaler interface.
|
||||
func (ident *DockerConfigEntry) UnmarshalJSON(data []byte) error {
|
||||
var tmp dockerConfigEntryWithAuth
|
||||
err := json.Unmarshal(data, &tmp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ident.Username = tmp.Username
|
||||
ident.Password = tmp.Password
|
||||
ident.Email = tmp.Email
|
||||
|
||||
if len(tmp.Auth) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
ident.Username, ident.Password, err = decodeDockerConfigFieldAuth(tmp.Auth)
|
||||
return err
|
||||
}
|
||||
|
||||
// MarshalJSON implements the json.Marshaler interface.
|
||||
func (ident DockerConfigEntry) MarshalJSON() ([]byte, error) {
|
||||
toEncode := dockerConfigEntryWithAuth{ident.Username, ident.Password, ident.Email, ""}
|
||||
toEncode.Auth = encodeDockerConfigFieldAuth(ident.Username, ident.Password)
|
||||
|
||||
return json.Marshal(toEncode)
|
||||
}
|
||||
|
||||
// decodeDockerConfigFieldAuth deserializes the "auth" field from dockercfg into a
|
||||
// username and a password. The format of the auth field is base64(<username>:<password>).
|
||||
func decodeDockerConfigFieldAuth(field string) (username, password string, err error) {
|
||||
|
||||
var decoded []byte
|
||||
|
||||
// StdEncoding can only decode padded string
|
||||
// RawStdEncoding can only decode unpadded string
|
||||
if strings.HasSuffix(strings.TrimSpace(field), "=") {
|
||||
// decode padded data
|
||||
decoded, err = base64.StdEncoding.DecodeString(field)
|
||||
} else {
|
||||
// decode unpadded data
|
||||
decoded, err = base64.RawStdEncoding.DecodeString(field)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.SplitN(string(decoded), ":", 2)
|
||||
if len(parts) != 2 {
|
||||
err = fmt.Errorf("unable to parse auth field, must be formatted as base64(username:password)")
|
||||
return
|
||||
}
|
||||
|
||||
username = parts[0]
|
||||
password = parts[1]
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func encodeDockerConfigFieldAuth(username, password string) string {
|
||||
fieldValue := username + ":" + password
|
||||
|
||||
return base64.StdEncoding.EncodeToString([]byte(fieldValue))
|
||||
}
|
19
e2e/vendor/k8s.io/kubernetes/pkg/credentialprovider/doc.go
generated
vendored
Normal file
19
e2e/vendor/k8s.io/kubernetes/pkg/credentialprovider/doc.go
generated
vendored
Normal file
@ -0,0 +1,19 @@
|
||||
/*
|
||||
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 credentialprovider supplies interfaces and implementations for
|
||||
// docker registry providers to expose their authentication scheme.
|
||||
package credentialprovider
|
367
e2e/vendor/k8s.io/kubernetes/pkg/credentialprovider/keyring.go
generated
vendored
Normal file
367
e2e/vendor/k8s.io/kubernetes/pkg/credentialprovider/keyring.go
generated
vendored
Normal file
@ -0,0 +1,367 @@
|
||||
/*
|
||||
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 credentialprovider
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"k8s.io/apimachinery/pkg/util/sets"
|
||||
utilfeature "k8s.io/apiserver/pkg/util/feature"
|
||||
"k8s.io/klog/v2"
|
||||
"k8s.io/kubernetes/pkg/features"
|
||||
)
|
||||
|
||||
// DockerKeyring tracks a set of docker registry credentials, maintaining a
|
||||
// reverse index across the registry endpoints. A registry endpoint is made
|
||||
// up of a host (e.g. registry.example.com), but it may also contain a path
|
||||
// (e.g. registry.example.com/foo) This index is important for two reasons:
|
||||
// - registry endpoints may overlap, and when this happens we must find the
|
||||
// most specific match for a given image
|
||||
// - iterating a map does not yield predictable results
|
||||
type DockerKeyring interface {
|
||||
Lookup(image string) ([]TrackedAuthConfig, bool)
|
||||
}
|
||||
|
||||
// BasicDockerKeyring is a trivial map-backed implementation of DockerKeyring
|
||||
type BasicDockerKeyring struct {
|
||||
index []string
|
||||
creds map[string][]TrackedAuthConfig
|
||||
}
|
||||
|
||||
// providersDockerKeyring is an implementation of DockerKeyring that
|
||||
// materializes its dockercfg based on a set of dockerConfigProviders.
|
||||
type providersDockerKeyring struct {
|
||||
Providers []DockerConfigProvider
|
||||
}
|
||||
|
||||
// TrackedAuthConfig wraps the AuthConfig and adds information about the source
|
||||
// of the credentials.
|
||||
type TrackedAuthConfig struct {
|
||||
AuthConfig
|
||||
AuthConfigHash string
|
||||
|
||||
Source *CredentialSource
|
||||
}
|
||||
|
||||
// NewTrackedAuthConfig initializes the TrackedAuthConfig structure by adding
|
||||
// the source information to the supplied AuthConfig. It also counts a hash of the
|
||||
// AuthConfig and keeps it in the returned structure.
|
||||
//
|
||||
// The supplied CredentialSource is only used when the "KubeletEnsureSecretPulledImages"
|
||||
// is enabled, the same applies for counting the hash.
|
||||
func NewTrackedAuthConfig(c *AuthConfig, src *CredentialSource) *TrackedAuthConfig {
|
||||
if c == nil {
|
||||
panic("cannot construct TrackedAuthConfig with a nil AuthConfig")
|
||||
}
|
||||
|
||||
authConfig := &TrackedAuthConfig{
|
||||
AuthConfig: *c,
|
||||
}
|
||||
|
||||
if utilfeature.DefaultFeatureGate.Enabled(features.KubeletEnsureSecretPulledImages) {
|
||||
authConfig.Source = src
|
||||
authConfig.AuthConfigHash = hashAuthConfig(c)
|
||||
}
|
||||
return authConfig
|
||||
}
|
||||
|
||||
type CredentialSource struct {
|
||||
Secret SecretCoordinates
|
||||
}
|
||||
|
||||
type SecretCoordinates struct {
|
||||
UID string
|
||||
Namespace string
|
||||
Name string
|
||||
}
|
||||
|
||||
// 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"`
|
||||
}
|
||||
|
||||
// Add inserts the docker config `cfg` into the basic docker keyring. It attaches
|
||||
// the `src` information that describes where the docker config `cfg` comes from.
|
||||
// `src` is nil if the docker config is globally available on the node.
|
||||
func (dk *BasicDockerKeyring) Add(src *CredentialSource, cfg DockerConfig) {
|
||||
if dk.index == nil {
|
||||
dk.index = make([]string, 0)
|
||||
dk.creds = make(map[string][]TrackedAuthConfig)
|
||||
}
|
||||
for loc, ident := range cfg {
|
||||
creds := AuthConfig{
|
||||
Username: ident.Username,
|
||||
Password: ident.Password,
|
||||
Email: ident.Email,
|
||||
}
|
||||
|
||||
value := loc
|
||||
if !strings.HasPrefix(value, "https://") && !strings.HasPrefix(value, "http://") {
|
||||
value = "https://" + value
|
||||
}
|
||||
parsed, err := url.Parse(value)
|
||||
if err != nil {
|
||||
klog.Errorf("Entry %q in dockercfg invalid (%v), ignoring", loc, err)
|
||||
continue
|
||||
}
|
||||
|
||||
// The docker client allows exact matches:
|
||||
// foo.bar.com/namespace
|
||||
// Or hostname matches:
|
||||
// foo.bar.com
|
||||
// It also considers /v2/ and /v1/ equivalent to the hostname
|
||||
// See ResolveAuthConfig in docker/registry/auth.go.
|
||||
effectivePath := parsed.Path
|
||||
if strings.HasPrefix(effectivePath, "/v2/") || strings.HasPrefix(effectivePath, "/v1/") {
|
||||
effectivePath = effectivePath[3:]
|
||||
}
|
||||
var key string
|
||||
if (len(effectivePath) > 0) && (effectivePath != "/") {
|
||||
key = parsed.Host + effectivePath
|
||||
} else {
|
||||
key = parsed.Host
|
||||
}
|
||||
trackedCreds := NewTrackedAuthConfig(&creds, src)
|
||||
|
||||
dk.creds[key] = append(dk.creds[key], *trackedCreds)
|
||||
dk.index = append(dk.index, key)
|
||||
}
|
||||
|
||||
eliminateDupes := sets.NewString(dk.index...)
|
||||
dk.index = eliminateDupes.List()
|
||||
|
||||
// Update the index used to identify which credentials to use for a given
|
||||
// image. The index is reverse-sorted so more specific paths are matched
|
||||
// first. For example, if for the given image "gcr.io/etcd-development/etcd",
|
||||
// credentials for "quay.io/coreos" should match before "quay.io".
|
||||
sort.Sort(sort.Reverse(sort.StringSlice(dk.index)))
|
||||
}
|
||||
|
||||
const (
|
||||
defaultRegistryHost = "index.docker.io"
|
||||
defaultRegistryKey = defaultRegistryHost + "/v1/"
|
||||
)
|
||||
|
||||
// isDefaultRegistryMatch determines whether the given image will
|
||||
// pull from the default registry (DockerHub) based on the
|
||||
// characteristics of its name.
|
||||
func isDefaultRegistryMatch(image string) bool {
|
||||
parts := strings.SplitN(image, "/", 2)
|
||||
|
||||
if len(parts[0]) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
if len(parts) == 1 {
|
||||
// e.g. library/ubuntu
|
||||
return true
|
||||
}
|
||||
|
||||
if parts[0] == "docker.io" || parts[0] == "index.docker.io" {
|
||||
// resolve docker.io/image and index.docker.io/image as default registry
|
||||
return true
|
||||
}
|
||||
|
||||
// From: http://blog.docker.com/2013/07/how-to-use-your-own-registry/
|
||||
// Docker looks for either a “.” (domain separator) or “:” (port separator)
|
||||
// to learn that the first part of the repository name is a location and not
|
||||
// a user name.
|
||||
return !strings.ContainsAny(parts[0], ".:")
|
||||
}
|
||||
|
||||
// ParseSchemelessURL parses a schemeless url and returns a url.URL
|
||||
// url.Parse require a scheme, but ours don't have schemes. Adding a
|
||||
// scheme to make url.Parse happy, then clear out the resulting scheme.
|
||||
func ParseSchemelessURL(schemelessURL string) (*url.URL, error) {
|
||||
parsed, err := url.Parse("https://" + schemelessURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// clear out the resulting scheme
|
||||
parsed.Scheme = ""
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
// SplitURL splits the host name into parts, as well as the port
|
||||
func SplitURL(url *url.URL) (parts []string, port string) {
|
||||
host, port, err := net.SplitHostPort(url.Host)
|
||||
if err != nil {
|
||||
// could not parse port
|
||||
host, port = url.Host, ""
|
||||
}
|
||||
return strings.Split(host, "."), port
|
||||
}
|
||||
|
||||
// URLsMatchStr is wrapper for URLsMatch, operating on strings instead of URLs.
|
||||
func URLsMatchStr(glob string, target string) (bool, error) {
|
||||
globURL, err := ParseSchemelessURL(glob)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
targetURL, err := ParseSchemelessURL(target)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return URLsMatch(globURL, targetURL)
|
||||
}
|
||||
|
||||
// URLsMatch checks whether the given target url matches the glob url, which may have
|
||||
// glob wild cards in the host name.
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// globURL=*.docker.io, targetURL=blah.docker.io => match
|
||||
// globURL=*.docker.io, targetURL=not.right.io => no match
|
||||
//
|
||||
// Note that we don't support wildcards in ports and paths yet.
|
||||
func URLsMatch(globURL *url.URL, targetURL *url.URL) (bool, error) {
|
||||
globURLParts, globPort := SplitURL(globURL)
|
||||
targetURLParts, targetPort := SplitURL(targetURL)
|
||||
if globPort != targetPort {
|
||||
// port doesn't match
|
||||
return false, nil
|
||||
}
|
||||
if len(globURLParts) != len(targetURLParts) {
|
||||
// host name does not have the same number of parts
|
||||
return false, nil
|
||||
}
|
||||
if !strings.HasPrefix(targetURL.Path, globURL.Path) {
|
||||
// the path of the credential must be a prefix
|
||||
return false, nil
|
||||
}
|
||||
for k, globURLPart := range globURLParts {
|
||||
targetURLPart := targetURLParts[k]
|
||||
matched, err := filepath.Match(globURLPart, targetURLPart)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !matched {
|
||||
// glob mismatch for some part
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
// everything matches
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Lookup implements the DockerKeyring method for fetching credentials based on image name.
|
||||
// Multiple credentials may be returned if there are multiple potentially valid credentials
|
||||
// available. This allows for rotation.
|
||||
func (dk *BasicDockerKeyring) Lookup(image string) ([]TrackedAuthConfig, bool) {
|
||||
// range over the index as iterating over a map does not provide a predictable ordering
|
||||
ret := []TrackedAuthConfig{}
|
||||
for _, k := range dk.index {
|
||||
// both k and image are schemeless URLs because even though schemes are allowed
|
||||
// in the credential configurations, we remove them in Add.
|
||||
if matched, _ := URLsMatchStr(k, image); matched {
|
||||
ret = append(ret, dk.creds[k]...)
|
||||
}
|
||||
}
|
||||
|
||||
if len(ret) > 0 {
|
||||
return ret, true
|
||||
}
|
||||
|
||||
// Use credentials for the default registry if provided, and appropriate
|
||||
if isDefaultRegistryMatch(image) {
|
||||
if auth, ok := dk.creds[defaultRegistryHost]; ok {
|
||||
return auth, true
|
||||
}
|
||||
}
|
||||
|
||||
return []TrackedAuthConfig{}, false
|
||||
}
|
||||
|
||||
// Lookup implements the DockerKeyring method for fetching credentials
|
||||
// based on image name.
|
||||
func (dk *providersDockerKeyring) Lookup(image string) ([]TrackedAuthConfig, bool) {
|
||||
keyring := &BasicDockerKeyring{}
|
||||
|
||||
for _, p := range dk.Providers {
|
||||
// TODO: the source should probably change once we depend on service accounts (KEP-4412).
|
||||
// Perhaps `Provide()` should return the source modified to accommodate this?
|
||||
keyring.Add(nil, p.Provide(image))
|
||||
}
|
||||
|
||||
return keyring.Lookup(image)
|
||||
}
|
||||
|
||||
// FakeKeyring a fake config credentials
|
||||
type FakeKeyring struct {
|
||||
auth []TrackedAuthConfig
|
||||
ok bool
|
||||
}
|
||||
|
||||
// Lookup implements the DockerKeyring method for fetching credentials based on image name
|
||||
// return fake auth and ok
|
||||
func (f *FakeKeyring) Lookup(image string) ([]TrackedAuthConfig, bool) {
|
||||
return f.auth, f.ok
|
||||
}
|
||||
|
||||
// UnionDockerKeyring delegates to a set of keyrings.
|
||||
type UnionDockerKeyring []DockerKeyring
|
||||
|
||||
// Lookup implements the DockerKeyring method for fetching credentials based on image name.
|
||||
// return each credentials
|
||||
func (k UnionDockerKeyring) Lookup(image string) ([]TrackedAuthConfig, bool) {
|
||||
authConfigs := []TrackedAuthConfig{}
|
||||
for _, subKeyring := range k {
|
||||
if subKeyring == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
currAuthResults, _ := subKeyring.Lookup(image)
|
||||
authConfigs = append(authConfigs, currAuthResults...)
|
||||
}
|
||||
|
||||
return authConfigs, (len(authConfigs) > 0)
|
||||
}
|
||||
|
||||
func hashAuthConfig(creds *AuthConfig) string {
|
||||
credBytes, err := json.Marshal(creds)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
hash := sha256.New()
|
||||
hash.Write([]byte(credBytes))
|
||||
return hex.EncodeToString(hash.Sum(nil))
|
||||
}
|
113
e2e/vendor/k8s.io/kubernetes/pkg/credentialprovider/provider.go
generated
vendored
Normal file
113
e2e/vendor/k8s.io/kubernetes/pkg/credentialprovider/provider.go
generated
vendored
Normal file
@ -0,0 +1,113 @@
|
||||
/*
|
||||
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 credentialprovider
|
||||
|
||||
import (
|
||||
"os"
|
||||
"reflect"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"k8s.io/klog/v2"
|
||||
)
|
||||
|
||||
// DockerConfigProvider is the interface that registered extensions implement
|
||||
// to materialize 'dockercfg' credentials.
|
||||
type DockerConfigProvider interface {
|
||||
// Enabled returns true if the config provider is enabled.
|
||||
// Implementations can be blocking - e.g. metadata server unavailable.
|
||||
Enabled() bool
|
||||
// Provide returns docker configuration.
|
||||
// Implementations can be blocking - e.g. metadata server unavailable.
|
||||
// The image is passed in as context in the event that the
|
||||
// implementation depends on information in the image name to return
|
||||
// credentials; implementations are safe to ignore the image.
|
||||
Provide(image string) DockerConfig
|
||||
}
|
||||
|
||||
// A DockerConfigProvider that simply reads the .dockercfg file
|
||||
type defaultDockerConfigProvider struct{}
|
||||
|
||||
// CachingDockerConfigProvider implements DockerConfigProvider by composing
|
||||
// with another DockerConfigProvider and caching the DockerConfig it provides
|
||||
// for a pre-specified lifetime.
|
||||
type CachingDockerConfigProvider struct {
|
||||
Provider DockerConfigProvider
|
||||
Lifetime time.Duration
|
||||
|
||||
// ShouldCache is an optional function that returns true if the specific config should be cached.
|
||||
// If nil, all configs are treated as cacheable.
|
||||
ShouldCache func(DockerConfig) bool
|
||||
|
||||
// cache fields
|
||||
cacheDockerConfig DockerConfig
|
||||
expiration time.Time
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// Enabled implements dockerConfigProvider
|
||||
func (d *defaultDockerConfigProvider) Enabled() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Provide implements dockerConfigProvider
|
||||
func (d *defaultDockerConfigProvider) Provide(image string) DockerConfig {
|
||||
// Read the standard Docker credentials from .dockercfg
|
||||
if cfg, err := ReadDockerConfigFile(); err == nil {
|
||||
return cfg
|
||||
} else if !os.IsNotExist(err) {
|
||||
klog.V(2).Infof("Docker config file not found: %v", err)
|
||||
}
|
||||
return DockerConfig{}
|
||||
}
|
||||
|
||||
// Enabled implements dockerConfigProvider
|
||||
func (d *CachingDockerConfigProvider) Enabled() bool {
|
||||
return d.Provider.Enabled()
|
||||
}
|
||||
|
||||
// Provide implements dockerConfigProvider
|
||||
func (d *CachingDockerConfigProvider) Provide(image string) DockerConfig {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
// If the cache hasn't expired, return our cache
|
||||
if time.Now().Before(d.expiration) {
|
||||
return d.cacheDockerConfig
|
||||
}
|
||||
|
||||
klog.V(2).Infof("Refreshing cache for provider: %v", reflect.TypeOf(d.Provider).String())
|
||||
config := d.Provider.Provide(image)
|
||||
if d.ShouldCache == nil || d.ShouldCache(config) {
|
||||
d.cacheDockerConfig = config
|
||||
d.expiration = time.Now().Add(d.Lifetime)
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
// NewDefaultDockerKeyring creates a DockerKeyring to use for resolving credentials,
|
||||
// which returns the default credentials from the .dockercfg file.
|
||||
func NewDefaultDockerKeyring() DockerKeyring {
|
||||
return &providersDockerKeyring{
|
||||
Providers: []DockerConfigProvider{
|
||||
&CachingDockerConfigProvider{
|
||||
Provider: &defaultDockerConfigProvider{},
|
||||
Lifetime: 5 * time.Minute,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user