Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ECR creds provider #157

Merged
merged 1 commit into from
Dec 16, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
/aws-cloud-controller-manager
/ecr-credential-provider
/cloudconfig

.vscode/
ayberk marked this conversation as resolved.
Show resolved Hide resolved
6 changes: 6 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ aws-cloud-controller-manager: $(SOURCES)
-o=aws-cloud-controller-manager \
cmd/aws-cloud-controller-manager/main.go

ecr-credential-provider: $(shell find ./cmd/ecr-credential-provider -name '*.go')
GO111MODULE=on CGO_ENABLED=0 GOOS=$(GOOS) GOPROXY=$(GOPROXY) go build \
-ldflags="-w -s -X 'main.version=$(VERSION)'" \
-o=ecr-credential-provider \
cmd/ecr-credential-provider/*.go
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think the *.go is necessary, can just be cmd/ecr-credential-provider or cmd/ecr-credential-provider/main.go

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately that doesn't work. I either need to build all go files together or move the framework into /pkg. Otherwise it complains about undefined NewCredentialProvider.

It's completely counter-intuitive to me, but based on my research go doesn't like having it in the main package.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I haven't seen the need to use *.go, what do you mean by 'doesn't work'?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ip-172-31-62-224  cloud-provider-aws git:(ecr_creds_provider) ✗ 12/15 17:25 make ecr-credential-provider
GO111MODULE=on CGO_ENABLED=0 GOOS=linux GOPROXY=https://proxy.golang.org,direct go build \
        -ldflags="-w -s -X 'main.version=ec091a51-dirty'" \
        -o=ecr-credential-provider \
        cmd/ecr-credential-provider/main.go
# command-line-arguments
cmd/ecr-credential-provider/main.go:154:7: undefined: NewCredentialProvider
Makefile:30: recipe for target 'ecr-credential-provider' failed
make: *** [ecr-credential-provider] Error 2

Which is interesting because vscode can correctly locate it.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok I think we can just fix this in a follow up PR if necessary, not a big deal


.PHONY: docker-build
docker-build:
docker build \
Expand Down
159 changes: 159 additions & 0 deletions cmd/ecr-credential-provider/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
/*
Copyright 2020 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 main

import (
"context"
"encoding/base64"
"errors"
"fmt"
"net/url"
"os"
"regexp"
"strings"
"time"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecr"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/klog/v2"
"k8s.io/kubelet/pkg/apis/credentialprovider/v1alpha1"
)

var ecrPattern = regexp.MustCompile(`^(\d{12})\.dkr\.ecr(\-fips)?\.([a-zA-Z0-9][a-zA-Z0-9-_]*)\.(amazonaws\.com(\.cn)?|sc2s\.sgov\.gov|c2s\.ic\.gov)$`)

// ECR abstracts the calls we make to aws-sdk for testing purposes
type ECR interface {
GetAuthorizationToken(input *ecr.GetAuthorizationTokenInput) (*ecr.GetAuthorizationTokenOutput, error)
}

type ecrPlugin struct {
ecr ECR
}

func defaultECRProvider(region string, registryID string) (*ecr.ECR, error) {
sess, err := session.NewSessionWithOptions(session.Options{
Config: aws.Config{Region: aws.String(region)},
SharedConfigState: session.SharedConfigEnable,
})
if err != nil {
return nil, err
}

return ecr.New(sess), nil
}

func (e *ecrPlugin) GetCredentials(ctx context.Context, image string, args []string) (*v1alpha1.CredentialProviderResponse, error) {
registryID, region, registry, err := parseRepoURL(image)
if err != nil {
return nil, err
}

if e.ecr == nil {
e.ecr, err = defaultECRProvider(region, registryID)
if err != nil {
return nil, err
}
}

output, err := e.ecr.GetAuthorizationToken(&ecr.GetAuthorizationTokenInput{
RegistryIds: []*string{aws.String(registryID)},
})
if err != nil {
return nil, err
}

if output == nil {
return nil, errors.New("response output from ECR was nil")
}

if len(output.AuthorizationData) == 0 {
return nil, errors.New("authorization data was empty")
}

data := output.AuthorizationData[0]
if data.AuthorizationToken == nil {
return nil, errors.New("authorization token in response was nil")
}

decodedToken, err := base64.StdEncoding.DecodeString(aws.StringValue(data.AuthorizationToken))
if err != nil {
return nil, err
}

parts := strings.SplitN(string(decodedToken), ":", 2)
if len(parts) != 2 {
return nil, errors.New("error parsing username and password from authorization token")
}

var cacheDuration *metav1.Duration
expiresAt := data.ExpiresAt
if expiresAt == nil {
// explicitly set cache duration to 0 if expiresAt was nil so that
// kubelet does not cache it in-memory
cacheDuration = &metav1.Duration{Duration: 0}
} else {
// halving duration in order to compensate for the time loss between
// the token creation and passing it all the way to kubelet.
duration := time.Duration((expiresAt.Unix() - time.Now().Unix()) / 2)
if duration > 0 {
cacheDuration = &metav1.Duration{Duration: duration}
}
}

return &v1alpha1.CredentialProviderResponse{
CacheKeyType: v1alpha1.RegistryPluginCacheKeyType,
CacheDuration: cacheDuration,
Auth: map[string]v1alpha1.AuthConfig{
registry: {
Username: parts[0],
Password: parts[1],
},
},
}, nil

}

// parseRepoURL parses and splits the registry URL
// returns (registryID, region, registry).
// <registryID>.dkr.ecr(-fips).<region>.amazonaws.com(.cn)
func parseRepoURL(image string) (string, string, string, error) {
if !strings.Contains(image, "https://") {
image = "https://" + image
}
parsed, err := url.Parse(image)
if err != nil {
return "", "", "", fmt.Errorf("error parsing image %s: %v", image, err)
}

splitURL := ecrPattern.FindStringSubmatch(parsed.Hostname())
if len(splitURL) < 4 {
return "", "", "", fmt.Errorf("%s is not a valid ECR repository URL", parsed.Hostname())
}

return splitURL[1], splitURL[3], parsed.Hostname(), nil
}

func main() {
p := NewCredentialProvider(&ecrPlugin{})
if err := p.Run(context.TODO()); err != nil {
klog.Errorf("Error running credential provider plugin: %v", err)
os.Exit(1)
}
}
Loading