| 1 |
/* |
| 2 |
Copyright The containerd 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 resolver |
| 18 |
|
| 19 |
// ===== |
| 20 |
// This is CRI-plugin-compatible registry hosts configuration. |
| 21 |
// Some functions are ported from https://github.com/containerd/containerd/blob/v1.5.2/pkg/cri as noted on each one. |
| 22 |
// TODO: import them from CRI package once we drop support to continerd v1.5.x (cri v1alpha2) |
| 23 |
// ===== |
| 24 |
|
| 25 |
import ( |
| 26 |
"context" |
| 27 |
"crypto/tls" |
| 28 |
"crypto/x509" |
| 29 |
"encoding/base64" |
| 30 |
"errors" |
| 31 |
"fmt" |
| 32 |
"net" |
| 33 |
"net/http" |
| 34 |
"net/url" |
| 35 |
"os" |
| 36 |
"path/filepath" |
| 37 |
"strings" |
| 38 |
|
| 39 |
"github.com/containerd/containerd/errdefs" |
| 40 |
"github.com/containerd/containerd/reference" |
| 41 |
"github.com/containerd/containerd/remotes/docker" |
| 42 |
dconfig "github.com/containerd/containerd/remotes/docker/config" |
| 43 |
"github.com/containerd/stargz-snapshotter/fs/source" |
| 44 |
rhttp "github.com/hashicorp/go-retryablehttp" |
| 45 |
runtime "k8s.io/cri-api/pkg/apis/runtime/v1" |
| 46 |
) |
| 47 |
|
| 48 |
// Registry is registry settings configured |
| 49 |
type Registry struct { |
| 50 |
// ConfigPath is a path to the root directory containing registry-specific |
| 51 |
// configurations. |
| 52 |
// If ConfigPath is set, the rest of the registry specific options are ignored. |
| 53 |
ConfigPath string `toml:"config_path" json:"configPath"` |
| 54 |
// Mirrors are namespace to mirror mapping for all namespaces. |
| 55 |
// This option will not be used when ConfigPath is provided. |
| 56 |
// DEPRECATED: Use ConfigPath instead. Remove in containerd 1.7. |
| 57 |
Mirrors map[string]Mirror `toml:"mirrors" json:"mirrors"` |
| 58 |
// Configs are configs for each registry. |
| 59 |
// The key is the domain name or IP of the registry. |
| 60 |
// This option will be fully deprecated for ConfigPath in the future. |
| 61 |
Configs map[string]RegistryConfig `toml:"configs" json:"configs"` |
| 62 |
} |
| 63 |
|
| 64 |
// Mirror contains the config related to the registry mirror |
| 65 |
type Mirror struct { |
| 66 |
// Endpoints are endpoints for a namespace. CRI plugin will try the endpoints |
| 67 |
// one by one until a working one is found. The endpoint must be a valid url |
| 68 |
// with host specified. |
| 69 |
// The scheme, host and path from the endpoint URL will be used. |
| 70 |
Endpoints []string `toml:"endpoint" json:"endpoint"` |
| 71 |
} |
| 72 |
|
| 73 |
// RegistryConfig contains configuration used to communicate with the registry. |
| 74 |
type RegistryConfig struct { |
| 75 |
// Auth contains information to authenticate to the registry. |
| 76 |
Auth *AuthConfig `toml:"auth" json:"auth"` |
| 77 |
// TLS is a pair of CA/Cert/Key which then are used when creating the transport |
| 78 |
// that communicates with the registry. |
| 79 |
// This field will not be used when ConfigPath is provided. |
| 80 |
// DEPRECATED: Use ConfigPath instead. Remove in containerd 1.7. |
| 81 |
TLS *TLSConfig `toml:"tls" json:"tls"` |
| 82 |
} |
| 83 |
|
| 84 |
// AuthConfig contains the config related to authentication to a specific registry |
| 85 |
type AuthConfig struct { |
| 86 |
// Username is the username to login the registry. |
| 87 |
Username string `toml:"username" json:"username"` |
| 88 |
// Password is the password to login the registry. |
| 89 |
Password string `toml:"password" json:"password"` |
| 90 |
// Auth is a base64 encoded string from the concatenation of the username, |
| 91 |
// a colon, and the password. |
| 92 |
Auth string `toml:"auth" json:"auth"` |
| 93 |
// IdentityToken is used to authenticate the user and get |
| 94 |
// an access token for the registry. |
| 95 |
IdentityToken string `toml:"identitytoken" json:"identitytoken"` |
| 96 |
} |
| 97 |
|
| 98 |
// TLSConfig contains the CA/Cert/Key used for a registry |
| 99 |
type TLSConfig struct { |
| 100 |
InsecureSkipVerify bool `toml:"insecure_skip_verify" json:"insecure_skip_verify"` |
| 101 |
CAFile string `toml:"ca_file" json:"caFile"` |
| 102 |
CertFile string `toml:"cert_file" json:"certFile"` |
| 103 |
KeyFile string `toml:"key_file" json:"keyFile"` |
| 104 |
} |
| 105 |
|
| 106 |
// RegistryHostsFromCRIConfig creates RegistryHosts (a set of registry configuration) from CRI-plugin-compatible config. |
| 107 |
// NOTE: ported from https://github.com/containerd/containerd/blob/v1.5.2/pkg/cri/server/image_pull.go#L332-L405 |
| 108 |
func RegistryHostsFromCRIConfig(ctx context.Context, config Registry, credsFuncs ...Credential) source.RegistryHosts { |
| 109 |
paths := filepath.SplitList(config.ConfigPath) |
| 110 |
if len(paths) > 0 { |
| 111 |
return func(ref reference.Spec) ([]docker.RegistryHost, error) { |
| 112 |
hostOptions := dconfig.HostOptions{} |
| 113 |
hostOptions.Credentials = multiCredsFuncs(ref, append(credsFuncs, func(host string, ref reference.Spec) (string, string, error) { |
| 114 |
config := config.Configs[host] |
| 115 |
if config.Auth != nil { |
| 116 |
return ParseAuth(toRuntimeAuthConfig(*config.Auth), host) |
| 117 |
} |
| 118 |
return "", "", nil |
| 119 |
})...) |
| 120 |
hostOptions.HostDir = hostDirFromRoots(paths) |
| 121 |
return dconfig.ConfigureHosts(ctx, hostOptions)(ref.Hostname()) |
| 122 |
} |
| 123 |
} |
| 124 |
return func(ref reference.Spec) ([]docker.RegistryHost, error) { |
| 125 |
host := ref.Hostname() |
| 126 |
var registries []docker.RegistryHost |
| 127 |
|
| 128 |
endpoints, err := registryEndpoints(config, host) |
| 129 |
if err != nil { |
| 130 |
return nil, fmt.Errorf("get registry endpoints: %w", err) |
| 131 |
} |
| 132 |
for _, e := range endpoints { |
| 133 |
u, err := url.Parse(e) |
| 134 |
if err != nil { |
| 135 |
return nil, fmt.Errorf("parse registry endpoint %q from mirrors: %w", e, err) |
| 136 |
} |
| 137 |
|
| 138 |
var ( |
| 139 |
rclient = rhttp.NewClient() |
| 140 |
config = config.Configs[u.Host] |
| 141 |
) |
| 142 |
|
| 143 |
rclient.Logger = nil // disable logging every request |
| 144 |
|
| 145 |
if config.TLS != nil { |
| 146 |
if tr, ok := rclient.HTTPClient.Transport.(*http.Transport); ok { |
| 147 |
tr.TLSClientConfig, err = getTLSConfig(*config.TLS) |
| 148 |
if err != nil { |
| 149 |
return nil, fmt.Errorf("get TLSConfig for registry %q: %w", e, err) |
| 150 |
} |
| 151 |
} else { |
| 152 |
return nil, errors.New("TLS config cannot be applied; Client.Transport is not *http.Transport") |
| 153 |
} |
| 154 |
} |
| 155 |
|
| 156 |
client := rclient.StandardClient() |
| 157 |
authorizer := docker.NewDockerAuthorizer( |
| 158 |
docker.WithAuthClient(client), |
| 159 |
docker.WithAuthCreds(multiCredsFuncs(ref, credsFuncs...))) |
| 160 |
|
| 161 |
if u.Path == "" { |
| 162 |
u.Path = "/v2" |
| 163 |
} |
| 164 |
|
| 165 |
registries = append(registries, docker.RegistryHost{ |
| 166 |
Client: client, |
| 167 |
Authorizer: authorizer, |
| 168 |
Host: u.Host, |
| 169 |
Scheme: u.Scheme, |
| 170 |
Path: u.Path, |
| 171 |
Capabilities: docker.HostCapabilityResolve | docker.HostCapabilityPull, |
| 172 |
}) |
| 173 |
} |
| 174 |
return registries, nil |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
// NOTE: Ported from https://github.com/containerd/containerd/blob/v1.5.2/pkg/cri/server/image_pull.go#L316-L330 |
| 179 |
func hostDirFromRoots(roots []string) func(string) (string, error) { |
| 180 |
rootfn := make([]func(string) (string, error), len(roots)) |
| 181 |
for i := range roots { |
| 182 |
rootfn[i] = dconfig.HostDirFromRoot(roots[i]) |
| 183 |
} |
| 184 |
return func(host string) (dir string, err error) { |
| 185 |
for _, fn := range rootfn { |
| 186 |
dir, err = fn(host) |
| 187 |
if (err != nil && !errdefs.IsNotFound(err)) || (dir != "") { |
| 188 |
break |
| 189 |
} |
| 190 |
} |
| 191 |
return |
| 192 |
} |
| 193 |
} |
| 194 |
|
| 195 |
// toRuntimeAuthConfig converts cri plugin auth config to runtime auth config. |
| 196 |
// NOTE: Ported from https://github.com/containerd/containerd/blob/v1.5.2/pkg/cri/server/helpers.go#L295-L303 |
| 197 |
func toRuntimeAuthConfig(a AuthConfig) *runtime.AuthConfig { |
| 198 |
return &runtime.AuthConfig{ |
| 199 |
Username: a.Username, |
| 200 |
Password: a.Password, |
| 201 |
Auth: a.Auth, |
| 202 |
IdentityToken: a.IdentityToken, |
| 203 |
} |
| 204 |
} |
| 205 |
|
| 206 |
// getTLSConfig returns a TLSConfig configured with a CA/Cert/Key specified by registryTLSConfig |
| 207 |
// NOTE: Ported from https://github.com/containerd/containerd/blob/v1.5.2/pkg/cri/server/image_pull.go#L316-L330 |
| 208 |
func getTLSConfig(registryTLSConfig TLSConfig) (*tls.Config, error) { |
| 209 |
var ( |
| 210 |
tlsConfig = &tls.Config{} |
| 211 |
cert tls.Certificate |
| 212 |
err error |
| 213 |
) |
| 214 |
if registryTLSConfig.CertFile != "" && registryTLSConfig.KeyFile == "" { |
| 215 |
return nil, fmt.Errorf("cert file %q was specified, but no corresponding key file was specified", registryTLSConfig.CertFile) |
| 216 |
} |
| 217 |
if registryTLSConfig.CertFile == "" && registryTLSConfig.KeyFile != "" { |
| 218 |
return nil, fmt.Errorf("key file %q was specified, but no corresponding cert file was specified", registryTLSConfig.KeyFile) |
| 219 |
} |
| 220 |
if registryTLSConfig.CertFile != "" && registryTLSConfig.KeyFile != "" { |
| 221 |
cert, err = tls.LoadX509KeyPair(registryTLSConfig.CertFile, registryTLSConfig.KeyFile) |
| 222 |
if err != nil { |
| 223 |
return nil, fmt.Errorf("failed to load cert file: %w", err) |
| 224 |
} |
| 225 |
if len(cert.Certificate) != 0 { |
| 226 |
tlsConfig.Certificates = []tls.Certificate{cert} |
| 227 |
} |
| 228 |
tlsConfig.BuildNameToCertificate() // nolint:staticcheck |
| 229 |
} |
| 230 |
|
| 231 |
if registryTLSConfig.CAFile != "" { |
| 232 |
caCertPool, err := x509.SystemCertPool() |
| 233 |
if err != nil { |
| 234 |
return nil, fmt.Errorf("failed to get system cert pool: %w", err) |
| 235 |
} |
| 236 |
caCert, err := os.ReadFile(registryTLSConfig.CAFile) |
| 237 |
if err != nil { |
| 238 |
return nil, fmt.Errorf("failed to load CA file: %w", err) |
| 239 |
} |
| 240 |
caCertPool.AppendCertsFromPEM(caCert) |
| 241 |
tlsConfig.RootCAs = caCertPool |
| 242 |
} |
| 243 |
|
| 244 |
tlsConfig.InsecureSkipVerify = registryTLSConfig.InsecureSkipVerify |
| 245 |
return tlsConfig, nil |
| 246 |
} |
| 247 |
|
| 248 |
// defaultScheme returns the default scheme for a registry host. |
| 249 |
// NOTE: Ported from https://github.com/containerd/containerd/blob/v1.5.2/pkg/cri/server/image_pull.go#L316-L330 |
| 250 |
func defaultScheme(host string) string { |
| 251 |
if h, _, err := net.SplitHostPort(host); err == nil { |
| 252 |
host = h |
| 253 |
} |
| 254 |
if host == "localhost" || host == "127.0.0.1" || host == "::1" { |
| 255 |
return "http" |
| 256 |
} |
| 257 |
return "https" |
| 258 |
} |
| 259 |
|
| 260 |
// addDefaultScheme returns the endpoint with default scheme |
| 261 |
// NOTE: Ported from https://github.com/containerd/containerd/blob/v1.5.2/pkg/cri/server/image_pull.go#L316-L330 |
| 262 |
func addDefaultScheme(endpoint string) (string, error) { |
| 263 |
if strings.Contains(endpoint, "://") { |
| 264 |
return endpoint, nil |
| 265 |
} |
| 266 |
ue := "dummy://" + endpoint |
| 267 |
u, err := url.Parse(ue) |
| 268 |
if err != nil { |
| 269 |
return "", err |
| 270 |
} |
| 271 |
return fmt.Sprintf("%s://%s", defaultScheme(u.Host), endpoint), nil |
| 272 |
} |
| 273 |
|
| 274 |
// registryEndpoints returns endpoints for a given host. |
| 275 |
// It adds default registry endpoint if it does not exist in the passed-in endpoint list. |
| 276 |
// It also supports wildcard host matching with `*`. |
| 277 |
// NOTE: Ported from https://github.com/containerd/containerd/blob/v1.5.2/pkg/cri/server/image_pull.go#L431-L464 |
| 278 |
func registryEndpoints(config Registry, host string) ([]string, error) { |
| 279 |
var endpoints []string |
| 280 |
_, ok := config.Mirrors[host] |
| 281 |
if ok { |
| 282 |
endpoints = config.Mirrors[host].Endpoints |
| 283 |
} else { |
| 284 |
endpoints = config.Mirrors["*"].Endpoints |
| 285 |
} |
| 286 |
defaultHost, err := docker.DefaultHost(host) |
| 287 |
if err != nil { |
| 288 |
return nil, fmt.Errorf("get default host: %w", err) |
| 289 |
} |
| 290 |
for i := range endpoints { |
| 291 |
en, err := addDefaultScheme(endpoints[i]) |
| 292 |
if err != nil { |
| 293 |
return nil, fmt.Errorf("parse endpoint url: %w", err) |
| 294 |
} |
| 295 |
endpoints[i] = en |
| 296 |
} |
| 297 |
for _, e := range endpoints { |
| 298 |
u, err := url.Parse(e) |
| 299 |
if err != nil { |
| 300 |
return nil, fmt.Errorf("parse endpoint url: %w", err) |
| 301 |
} |
| 302 |
if u.Host == host { |
| 303 |
// Do not add default if the endpoint already exists. |
| 304 |
return endpoints, nil |
| 305 |
} |
| 306 |
} |
| 307 |
return append(endpoints, defaultScheme(defaultHost)+"://"+defaultHost), nil |
| 308 |
} |
| 309 |
|
| 310 |
// ParseAuth parses AuthConfig and returns username and password/secret required by containerd. |
| 311 |
// NOTE: Ported from https://github.com/containerd/containerd/blob/v1.5.2/pkg/cri/server/image_pull.go#L176-L214 |
| 312 |
func ParseAuth(auth *runtime.AuthConfig, host string) (string, string, error) { |
| 313 |
if auth == nil { |
| 314 |
return "", "", nil |
| 315 |
} |
| 316 |
if auth.ServerAddress != "" { |
| 317 |
// Do not return the auth info when server address doesn't match. |
| 318 |
u, err := url.Parse(auth.ServerAddress) |
| 319 |
if err != nil { |
| 320 |
return "", "", fmt.Errorf("parse server address: %w", err) |
| 321 |
} |
| 322 |
if host != u.Host { |
| 323 |
return "", "", nil |
| 324 |
} |
| 325 |
} |
| 326 |
if auth.Username != "" { |
| 327 |
return auth.Username, auth.Password, nil |
| 328 |
} |
| 329 |
if auth.IdentityToken != "" { |
| 330 |
return "", auth.IdentityToken, nil |
| 331 |
} |
| 332 |
if auth.Auth != "" { |
| 333 |
decLen := base64.StdEncoding.DecodedLen(len(auth.Auth)) |
| 334 |
decoded := make([]byte, decLen) |
| 335 |
_, err := base64.StdEncoding.Decode(decoded, []byte(auth.Auth)) |
| 336 |
if err != nil { |
| 337 |
return "", "", err |
| 338 |
} |
| 339 |
fields := strings.SplitN(string(decoded), ":", 2) |
| 340 |
if len(fields) != 2 { |
| 341 |
return "", "", fmt.Errorf("invalid decoded auth: %q", decoded) |
| 342 |
} |
| 343 |
user, passwd := fields[0], fields[1] |
| 344 |
return user, strings.Trim(passwd, "\x00"), nil |
| 345 |
} |
| 346 |
// TODO(random-liu): Support RegistryToken. |
| 347 |
// An empty auth config is valid for anonymous registry |
| 348 |
return "", "", nil |
| 349 |
} |