-
Notifications
You must be signed in to change notification settings - Fork 88
/
ecr.go
97 lines (78 loc) · 2.59 KB
/
ecr.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package registry
import (
"encoding/base64"
"fmt"
"net/url"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ecr"
"github.com/pkg/errors"
)
type Login struct {
Username string
Password string
}
func IsECREndpoint(endpoint string) bool {
if !strings.HasPrefix(endpoint, "http") {
// url.Parse doesn't work without scheme
endpoint = fmt.Sprintf("https://%s", endpoint)
}
parsed, err := url.Parse(endpoint)
if err != nil {
return false
}
return strings.HasSuffix(parsed.Hostname(), ".amazonaws.com")
}
func GetECRLogin(ecrEndpoint, username, password string) (*Login, error) {
token, err := GetECRBasicAuthToken(ecrEndpoint, username, password)
if err != nil {
return nil, errors.Wrap(err, "failed to get basic auth token")
}
decoded, err := base64.StdEncoding.DecodeString(token)
if err != nil {
return nil, errors.Wrap(err, "failed to decode ECR token")
}
parts := strings.Split(string(decoded), ":")
if len(parts) != 2 {
return nil, errors.Wrap(err, "decode ECR token has invalid format")
}
return &Login{Username: parts[0], Password: parts[1]}, nil
}
func GetECRBasicAuthToken(ecrEndpoint, username, password string) (string, error) {
registry, zone, err := parseECREndpoint(ecrEndpoint)
if err != nil {
return "", errors.Wrap(err, "failed to parse ECR endpoint")
}
ecrService := getECRService(username, password, zone)
ecrToken, err := ecrService.GetAuthorizationToken(&ecr.GetAuthorizationTokenInput{
RegistryIds: []*string{
®istry,
},
})
if err != nil {
return "", errors.Wrap(err, "failed to get ECR token")
}
if len(ecrToken.AuthorizationData) == 0 {
return "", errors.Errorf("Repo %s not accessible with specified credentials", ecrEndpoint)
}
return *ecrToken.AuthorizationData[0].AuthorizationToken, nil
}
func getECRService(accessKeyID, secretAccessKey, zone string) *ecr.ECR {
awsConfig := &aws.Config{Region: aws.String(zone)}
if accessKeyID != "" && secretAccessKey != "" {
awsConfig.Credentials = credentials.NewStaticCredentials(accessKeyID, secretAccessKey, "")
}
return ecr.New(session.New(awsConfig))
}
func parseECREndpoint(endpoint string) (registry, zone string, err error) {
splitEndpoint := strings.Split(endpoint, ".")
if len(splitEndpoint) < 6 {
return "", "", errors.Errorf("invalid ECR endpoint: %s", endpoint)
}
if splitEndpoint[1] != "dkr" || splitEndpoint[2] != "ecr" {
return "", "", errors.Errorf("only dkr and ecr endpoints are supported: %s", endpoint)
}
return splitEndpoint[0], splitEndpoint[3], nil
}