-
Notifications
You must be signed in to change notification settings - Fork 312
/
main.go
268 lines (225 loc) · 7.28 KB
/
main.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/*
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-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/ecr"
"github.com/aws/aws-sdk-go-v2/service/ecrpublic"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/component-base/logs"
"k8s.io/klog/v2"
v1 "k8s.io/kubelet/pkg/apis/credentialprovider/v1"
)
const ecrPublicRegion string = "us-east-1"
const ecrPublicHost string = "public.ecr.aws"
var ecrPrivateHostPattern = regexp.MustCompile(`^(\d{12})\.dkr[\.\-]ecr(\-fips)?\.([a-zA-Z0-9][a-zA-Z0-9-_]*)\.(amazonaws\.com(?:\.cn)?|on\.(?:aws|amazonwebservices\.com\.cn)|sc2s\.sgov\.gov|c2s\.ic\.gov|cloud\.adc-e\.uk|csp\.hci\.ic\.gov)$`)
// ECR abstracts the calls we make to aws-sdk for testing purposes
type ECR interface {
GetAuthorizationToken(ctx context.Context, params *ecr.GetAuthorizationTokenInput, optFns ...func(*ecr.Options)) (*ecr.GetAuthorizationTokenOutput, error)
}
// ECRPublic abstracts the calls we make to aws-sdk for testing purposes
type ECRPublic interface {
GetAuthorizationToken(ctx context.Context, params *ecrpublic.GetAuthorizationTokenInput, optFns ...func(*ecrpublic.Options)) (*ecrpublic.GetAuthorizationTokenOutput, error)
}
type ecrPlugin struct {
ecr ECR
ecrPublic ECRPublic
}
func defaultECRProvider(ctx context.Context, region string) (ECR, error) {
var cfg aws.Config
var err error
if region != "" {
klog.Warningf("No region found in the image reference, the default region will be used. Please refer to AWS SDK documentation for configuration purpose.")
cfg, err = config.LoadDefaultConfig(ctx,
config.WithRegion(region),
)
} else {
cfg, err = config.LoadDefaultConfig(ctx)
}
if err != nil {
return nil, err
}
return ecr.NewFromConfig(cfg), nil
}
func publicECRProvider(ctx context.Context) (ECRPublic, error) {
// ECR public registries are only in one region and only accessible from regions
// in the "aws" partition.
cfg, err := config.LoadDefaultConfig(ctx,
config.WithRegion(ecrPublicRegion),
)
if err != nil {
return nil, err
}
return ecrpublic.NewFromConfig(cfg), nil
}
type credsData struct {
authToken *string
expiresAt *time.Time
}
func (e *ecrPlugin) getPublicCredsData(ctx context.Context) (*credsData, error) {
klog.Infof("Getting creds for public registry")
var err error
if e.ecrPublic == nil {
e.ecrPublic, err = publicECRProvider(ctx)
}
if err != nil {
return nil, err
}
output, err := e.ecrPublic.GetAuthorizationToken(ctx, &ecrpublic.GetAuthorizationTokenInput{})
if err != nil {
return nil, err
}
if output == nil {
return nil, errors.New("response output from ECR was nil")
}
if output.AuthorizationData == nil {
return nil, errors.New("authorization data was empty")
}
return &credsData{
authToken: output.AuthorizationData.AuthorizationToken,
expiresAt: output.AuthorizationData.ExpiresAt,
}, nil
}
func (e *ecrPlugin) getPrivateCredsData(ctx context.Context, imageHost string, image string) (*credsData, error) {
klog.Infof("Getting creds for private image %s", image)
var err error
if e.ecr == nil {
region := parseRegionFromECRPrivateHost(imageHost)
e.ecr, err = defaultECRProvider(ctx, region)
if err != nil {
return nil, err
}
}
output, err := e.ecr.GetAuthorizationToken(ctx, &ecr.GetAuthorizationTokenInput{})
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")
}
return &credsData{
authToken: output.AuthorizationData[0].AuthorizationToken,
expiresAt: output.AuthorizationData[0].ExpiresAt,
}, nil
}
func (e *ecrPlugin) GetCredentials(ctx context.Context, image string, args []string) (*v1.CredentialProviderResponse, error) {
var creds *credsData
var err error
imageHost, err := parseHostFromImageReference(image)
if err != nil {
return nil, err
}
if imageHost == ecrPublicHost {
creds, err = e.getPublicCredsData(ctx)
} else {
creds, err = e.getPrivateCredsData(ctx, imageHost, image)
}
if err != nil {
return nil, err
}
if creds.authToken == nil {
return nil, errors.New("authorization token in response was nil")
}
decodedToken, err := base64.StdEncoding.DecodeString(aws.ToString(creds.authToken))
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")
}
cacheDuration := getCacheDuration(creds.expiresAt)
return &v1.CredentialProviderResponse{
CacheKeyType: v1.RegistryPluginCacheKeyType,
CacheDuration: cacheDuration,
Auth: map[string]v1.AuthConfig{
imageHost: {
Username: parts[0],
Password: parts[1],
},
},
}, nil
}
// getCacheDuration calculates the credentials cache duration based on the ExpiresAt time from the authorization data
func getCacheDuration(expiresAt *time.Time) *metav1.Duration {
var cacheDuration *metav1.Duration
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.Second * time.Duration((expiresAt.Unix()-time.Now().Unix())/2)
if duration > 0 {
cacheDuration = &metav1.Duration{Duration: duration}
}
}
return cacheDuration
}
// parseHostFromImageReference parses the hostname from an image reference
func parseHostFromImageReference(image string) (string, error) {
// a URL needs a scheme to be parsed correctly
if !strings.Contains(image, "://") {
image = "https://" + image
}
parsed, err := url.Parse(image)
if err != nil {
return "", fmt.Errorf("error parsing image reference %s: %v", image, err)
}
return parsed.Hostname(), nil
}
func parseRegionFromECRPrivateHost(host string) string {
splitHost := ecrPrivateHostPattern.FindStringSubmatch(host)
if len(splitHost) != 5 {
return ""
}
return splitHost[3]
}
func main() {
logs.InitLogs()
defer logs.FlushLogs()
if err := newCredentialProviderCommand().Execute(); err != nil {
os.Exit(1)
}
}
var gitVersion string
func newCredentialProviderCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "ecr-credential-provider",
Short: "ECR credential provider for kubelet",
Version: gitVersion,
Run: func(cmd *cobra.Command, args []string) {
p := NewCredentialProvider(&ecrPlugin{})
if err := p.Run(context.TODO()); err != nil {
klog.Errorf("Error running credential provider plugin: %v", err)
os.Exit(1)
}
},
}
return cmd
}