diff --git a/pkg/auth/auth.go b/pkg/auth/auth.go new file mode 100644 index 0000000..bee2d61 --- /dev/null +++ b/pkg/auth/auth.go @@ -0,0 +1,50 @@ +package auth + +import ( + "encoding/base64" + "net/url" + "strings" + + "github.com/pkg/errors" + criv1 "k8s.io/cri-api/pkg/apis/runtime/v1alpha2" +) + +// Parse parses AuthConfig and returns username and password/secret required by containerd. +func Parse(auth *criv1.AuthConfig, host string) (string, string, error) { + if auth == nil { + return "", "", nil + } + if auth.ServerAddress != "" { + // Do not return the auth info when server address doesn't match. + u, err := url.Parse(auth.ServerAddress) + if err != nil { + return "", "", errors.Wrap(err, "parse server address") + } + if host != u.Host { + return "", "", nil + } + } + if auth.Username != "" { + return auth.Username, auth.Password, nil + } + if auth.IdentityToken != "" { + return "", auth.IdentityToken, nil + } + if auth.Auth != "" { + decLen := base64.StdEncoding.DecodedLen(len(auth.Auth)) + decoded := make([]byte, decLen) + _, err := base64.StdEncoding.Decode(decoded, []byte(auth.Auth)) + if err != nil { + return "", "", err + } + fields := strings.SplitN(string(decoded), ":", 2) + if len(fields) != 2 { + return "", "", errors.Errorf("invalid decoded auth: %q", decoded) + } + user, passwd := fields[0], fields[1] + return user, strings.Trim(passwd, "\x00"), nil + } + // TODO(random-liu): Support RegistryToken. + // An empty auth config is valid for anonymous registry + return "", "", nil +} diff --git a/pkg/server/images-push.go b/pkg/server/images-push.go index 9025a42..a5eac51 100644 --- a/pkg/server/images-push.go +++ b/pkg/server/images-push.go @@ -12,9 +12,9 @@ import ( "github.com/containerd/containerd/namespaces" "github.com/containerd/containerd/remotes" "github.com/containerd/containerd/remotes/docker" - "github.com/containerd/cri/pkg/server" ocispec "github.com/opencontainers/image-spec/specs-go/v1" imagesv1 "github.com/rancher/k3c/pkg/apis/services/images/v1alpha1" + "github.com/rancher/k3c/pkg/auth" "github.com/rancher/k3c/pkg/progress" "github.com/rancher/k3c/pkg/version" "github.com/sirupsen/logrus" @@ -31,7 +31,7 @@ func (i *Interface) Push(ctx context.Context, request *imagesv1.ImagePushRequest authorizer := docker.NewDockerAuthorizer( docker.WithAuthClient(http.DefaultClient), docker.WithAuthCreds(func(host string) (string, string, error) { - return server.ParseAuth(request.Auth, host) + return auth.Parse(request.Auth, host) }), docker.WithAuthHeader(http.Header{ "User-Agent": []string{fmt.Sprintf("k3c/%s", version.Version)},