Skip to content

Commit

Permalink
Merge pull request #241 from ktock/kcauth
Browse files Browse the repository at this point in the history
Refactor keychain
  • Loading branch information
AkihiroSuda authored Jan 15, 2021
2 parents 7f45f74 + aeb7486 commit 880da3a
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 65 deletions.
48 changes: 48 additions & 0 deletions cmd/containerd-stargz-grpc/keychain/dockerconfig.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
Copyright The containerd 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 keychain

import (
"context"

"github.com/containerd/containerd/log"
"github.com/docker/cli/cli/config"
)

func NewDockerconfigKeychain(ctx context.Context) func(host string) (string, string, error) {
cf, err := config.Load("")
if err != nil {
log.G(ctx).WithError(err).Warnf("failed to load docker config file")
return func(host string) (string, string, error) {
return "", "", nil
}
}
return func(host string) (string, string, error) {
if host == "docker.io" || host == "registry-1.docker.io" {
// Creds of docker.io is stored keyed by "https://index.docker.io/v1/".
host = "https://index.docker.io/v1/"
}
ac, err := cf.GetAuthConfig(host)
if err != nil {
return "", "", err
}
if ac.IdentityToken != "" {
return "", ac.IdentityToken, nil
}
return ac.Username, ac.Password, nil
}
}
55 changes: 14 additions & 41 deletions cmd/containerd-stargz-grpc/keychain/kubeconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,6 @@ import (

"github.com/containerd/containerd/log"
dcfile "github.com/docker/cli/cli/config/configfile"
dctypes "github.com/docker/cli/cli/config/types"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/name"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
Expand Down Expand Up @@ -66,24 +63,13 @@ func WithKubeconfigPath(path string) KubeconfigOption {
// everything, including booting containerd/kubelet/apiserver and configuring
// users/roles.
// TODO: support update of kubeconfig file
func NewKubeconfigKeychain(ctx context.Context, opts ...KubeconfigOption) authn.Keychain {
func NewKubeconfigKeychain(ctx context.Context, opts ...KubeconfigOption) func(string) (string, string, error) {
var kcOpts options
for _, o := range opts {
o(&kcOpts)
}
return newKeychain(ctx, kcOpts.kubeconfigPath)
}

type authenticator struct {
keychain *keychain
target authn.Resource
}

func (at *authenticator) Authorization() (*authn.AuthConfig, error) {
if ac, found := at.keychain.lookup(at.target); found {
return ac, nil
}
return nil, fmt.Errorf("creds for %q not found", at.target.String())
kc := newKeychain(ctx, kcOpts.kubeconfigPath)
return kc.credentials
}

func newKeychain(ctx context.Context, kubeconfigPath string) *keychain {
Expand Down Expand Up @@ -147,36 +133,23 @@ type keychain struct {
informer cache.SharedIndexInformer
}

func (kc *keychain) Resolve(target authn.Resource) (authn.Authenticator, error) {
if _, found := kc.lookup(target); found {
return &authenticator{
keychain: kc,
target: target,
}, nil
func (kc *keychain) credentials(host string) (string, string, error) {
if host == "docker.io" || host == "registry-1.docker.io" {
// Creds of "docker.io" is stored keyed by "https://index.docker.io/v1/".
host = "https://index.docker.io/v1/"
}
return authn.Anonymous, nil
}

func (kc *keychain) lookup(target authn.Resource) (*authn.AuthConfig, bool) {
key := target.RegistryStr()
if key == name.DefaultRegistry {
key = authn.DefaultAuthKey
}
empty := dctypes.AuthConfig{}
kc.configMu.Lock()
defer kc.configMu.Unlock()
for _, cfg := range kc.config {
if acfg, err := cfg.GetAuthConfig(key); err == nil && acfg != empty {
return &authn.AuthConfig{
Username: acfg.Username,
Password: acfg.Password,
Auth: acfg.Auth,
IdentityToken: acfg.IdentityToken,
RegistryToken: acfg.RegistryToken,
}, true
if acfg, err := cfg.GetAuthConfig(host); err == nil {
if acfg.IdentityToken != "" {
return "", acfg.IdentityToken, nil
} else if !(acfg.Username == "" && acfg.Password == "") {
return acfg.Username, acfg.Password, nil
}
}
}
return nil, false
return "", "", nil
}

func (kc *keychain) startSyncSecrets(ctx context.Context, client kubernetes.Interface) error {
Expand Down
35 changes: 11 additions & 24 deletions cmd/containerd-stargz-grpc/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ import (
stargzfs "github.com/containerd/stargz-snapshotter/fs"
"github.com/containerd/stargz-snapshotter/fs/source"
snbase "github.com/containerd/stargz-snapshotter/snapshot"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/name"
"github.com/hashicorp/go-multierror"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
Expand Down Expand Up @@ -77,17 +75,17 @@ func main() {
}

// Prepare kubeconfig-based keychain if required
kc := authn.DefaultKeychain
credsFuncs := []func(string) (string, string, error){keychain.NewDockerconfigKeychain(ctx)}
if config.KubeconfigKeychainConfig.EnableKeychain {
var opts []keychain.KubeconfigOption
if kcp := config.KubeconfigKeychainConfig.KubeconfigPath; kcp != "" {
opts = append(opts, keychain.WithKubeconfigPath(kcp))
}
kc = authn.NewMultiKeychain(kc, keychain.NewKubeconfigKeychain(ctx, opts...))
credsFuncs = append(credsFuncs, keychain.NewKubeconfigKeychain(ctx, opts...))
}

// Use RegistryHosts based on ResolverConfig and keychain
hosts := hostsFromConfig(config.ResolverConfig, kc)
hosts := hostsFromConfig(config.ResolverConfig, credsFuncs...)

// Configure filesystem and snapshotter
fs, err := stargzfs.NewFilesystem(filepath.Join(*rootDir, "stargz"),
Expand Down Expand Up @@ -149,7 +147,7 @@ func waitForSIGINT() {
<-c
}

func hostsFromConfig(cfg ResolverConfig, keychain authn.Keychain) docker.RegistryHosts {
func hostsFromConfig(cfg ResolverConfig, credsFuncs ...func(string) (string, string, error)) docker.RegistryHosts {
return func(host string) (hosts []docker.RegistryHost, _ error) {
for _, h := range append(cfg.Host[host].Mirrors, MirrorConfig{
Host: host,
Expand All @@ -164,25 +162,14 @@ func hostsFromConfig(cfg ResolverConfig, keychain authn.Keychain) docker.Registr
Authorizer: docker.NewDockerAuthorizer(
docker.WithAuthClient(tr),
docker.WithAuthCreds(func(host string) (string, string, error) {
if host == "registry-1.docker.io" {
host = "index.docker.io"
for _, f := range credsFuncs {
if username, secret, err := f(host); err != nil {
return "", "", err
} else if !(username == "" && secret == "") {
return username, secret, nil
}
}
reg, err := name.NewRegistry(host)
if err != nil {
return "", "", err
}
authn, err := keychain.Resolve(reg)
if err != nil {
return "", "", err
}
acfg, err := authn.Authorization()
if err != nil {
return "", "", err
}
if acfg.IdentityToken != "" {
return "", acfg.IdentityToken, nil
}
return acfg.Username, acfg.Password, nil
return "", "", nil
})),
}
if localhost, _ := docker.MatchLocalhost(config.Host); localhost || h.Insecure {
Expand Down

0 comments on commit 880da3a

Please sign in to comment.