-
Notifications
You must be signed in to change notification settings - Fork 38.7k
/
azure_credentials.go
351 lines (302 loc) · 10.2 KB
/
azure_credentials.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
//go:build !providerless
// +build !providerless
/*
Copyright 2016 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 azure
import (
"context"
"errors"
"io"
"io/ioutil"
"os"
"regexp"
"strings"
"sync"
"time"
"github.com/Azure/azure-sdk-for-go/services/containerregistry/mgmt/2019-05-01/containerregistry"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/spf13/pflag"
"k8s.io/client-go/tools/cache"
"k8s.io/klog/v2"
"k8s.io/kubernetes/pkg/credentialprovider"
"k8s.io/legacy-cloud-providers/azure/auth"
"sigs.k8s.io/yaml"
)
var flagConfigFile = pflag.String("azure-container-registry-config", "",
"Path to the file containing Azure container registry configuration information.")
const (
dummyRegistryEmail = "name@contoso.com"
maxReadLength = 10 * 1 << 20 // 10MB
)
var (
containerRegistryUrls = []string{"*.azurecr.io", "*.azurecr.cn", "*.azurecr.de", "*.azurecr.us"}
acrRE = regexp.MustCompile(`.*\.azurecr\.io|.*\.azurecr\.cn|.*\.azurecr\.de|.*\.azurecr\.us`)
warnOnce sync.Once
)
// init registers the various means by which credentials may
// be resolved on Azure.
func init() {
credentialprovider.RegisterCredentialProvider(
"azure",
NewACRProvider(flagConfigFile),
)
}
type cacheEntry struct {
expiresAt time.Time
credentials credentialprovider.DockerConfigEntry
registry string
}
// acrExpirationPolicy implements ExpirationPolicy from client-go.
type acrExpirationPolicy struct{}
// stringKeyFunc returns the cache key as a string
func stringKeyFunc(obj interface{}) (string, error) {
key := obj.(*cacheEntry).registry
return key, nil
}
// IsExpired checks if the ACR credentials are expired.
func (p *acrExpirationPolicy) IsExpired(entry *cache.TimestampedEntry) bool {
return time.Now().After(entry.Obj.(*cacheEntry).expiresAt)
}
// RegistriesClient is a testable interface for the ACR client List operation.
type RegistriesClient interface {
List(ctx context.Context) ([]containerregistry.Registry, error)
}
// NewACRProvider parses the specified configFile and returns a DockerConfigProvider
func NewACRProvider(configFile *string) credentialprovider.DockerConfigProvider {
return &acrProvider{
file: configFile,
cache: cache.NewExpirationStore(stringKeyFunc, &acrExpirationPolicy{}),
}
}
type acrProvider struct {
file *string
config *auth.AzureAuthConfig
environment *azure.Environment
servicePrincipalToken *adal.ServicePrincipalToken
cache cache.Store
}
// ParseConfig returns a parsed configuration for an Azure cloudprovider config file
func parseConfig(configReader io.Reader) (*auth.AzureAuthConfig, error) {
var config auth.AzureAuthConfig
if configReader == nil {
return &config, nil
}
limitedReader := &io.LimitedReader{R: configReader, N: maxReadLength}
configContents, err := ioutil.ReadAll(limitedReader)
if err != nil {
return nil, err
}
if limitedReader.N <= 0 {
return nil, errors.New("the read limit is reached")
}
err = yaml.Unmarshal(configContents, &config)
if err != nil {
return nil, err
}
return &config, nil
}
func (a *acrProvider) loadConfig(rdr io.Reader) error {
var err error
a.config, err = parseConfig(rdr)
if err != nil {
klog.Errorf("Failed to load azure credential file: %v", err)
}
a.environment, err = auth.ParseAzureEnvironment(a.config.Cloud, a.config.ResourceManagerEndpoint, a.config.IdentitySystem)
if err != nil {
return err
}
return nil
}
func (a *acrProvider) Enabled() bool {
if a.file == nil || len(*a.file) == 0 {
klog.V(5).Infof("Azure config unspecified, disabling")
return false
}
if credentialprovider.AreLegacyCloudCredentialProvidersDisabled() {
warnOnce.Do(func() {
klog.V(4).Infof("Azure credential provider is now disabled. Please refer to sig-cloud-provider for guidance on external credential provider integration for Azure")
})
return false
}
f, err := os.Open(*a.file)
if err != nil {
klog.Errorf("Failed to load config from file: %s", *a.file)
return false
}
defer f.Close()
err = a.loadConfig(f)
if err != nil {
klog.Errorf("Failed to load config from file: %s", *a.file)
return false
}
a.servicePrincipalToken, err = auth.GetServicePrincipalToken(a.config, a.environment)
if err != nil {
klog.Errorf("Failed to create service principal token: %v", err)
}
return true
}
// getFromCache attempts to get credentials from the cache
func (a *acrProvider) getFromCache(loginServer string) (credentialprovider.DockerConfig, bool) {
cfg := credentialprovider.DockerConfig{}
obj, exists, err := a.cache.GetByKey(loginServer)
if err != nil {
klog.Errorf("error getting ACR credentials from cache: %v", err)
return cfg, false
}
if !exists {
return cfg, false
}
entry := obj.(*cacheEntry)
cfg[entry.registry] = entry.credentials
return cfg, true
}
// getFromACR gets credentials from ACR since they are not in the cache
func (a *acrProvider) getFromACR(loginServer string) (credentialprovider.DockerConfig, error) {
cfg := credentialprovider.DockerConfig{}
cred, err := getACRDockerEntryFromARMToken(a, loginServer)
if err != nil {
return cfg, err
}
entry := &cacheEntry{
expiresAt: time.Now().Add(10 * time.Minute),
credentials: *cred,
registry: loginServer,
}
if err := a.cache.Add(entry); err != nil {
return cfg, err
}
cfg[loginServer] = *cred
return cfg, nil
}
func (a *acrProvider) Provide(image string) credentialprovider.DockerConfig {
loginServer := a.parseACRLoginServerFromImage(image)
if loginServer == "" {
klog.V(2).Infof("image(%s) is not from ACR, return empty authentication", image)
return credentialprovider.DockerConfig{}
}
cfg := credentialprovider.DockerConfig{}
if a.config != nil && a.config.UseManagedIdentityExtension {
var exists bool
cfg, exists = a.getFromCache(loginServer)
if exists {
klog.V(4).Infof("Got ACR credentials from cache for %s", loginServer)
} else {
klog.V(2).Infof("unable to get ACR credentials from cache for %s, checking ACR API", loginServer)
var err error
cfg, err = a.getFromACR(loginServer)
if err != nil {
klog.Errorf("error getting credentials from ACR for %s %v", loginServer, err)
}
}
} else {
// Add our entry for each of the supported container registry URLs
for _, url := range containerRegistryUrls {
cred := &credentialprovider.DockerConfigEntry{
Username: a.config.AADClientID,
Password: a.config.AADClientSecret,
Email: dummyRegistryEmail,
}
cfg[url] = *cred
}
// Handle the custom cloud case
// In clouds where ACR is not yet deployed, the string will be empty
if a.environment != nil && strings.Contains(a.environment.ContainerRegistryDNSSuffix, ".azurecr.") {
customAcrSuffix := "*" + a.environment.ContainerRegistryDNSSuffix
hasBeenAdded := false
for _, url := range containerRegistryUrls {
if strings.EqualFold(url, customAcrSuffix) {
hasBeenAdded = true
break
}
}
if !hasBeenAdded {
cred := &credentialprovider.DockerConfigEntry{
Username: a.config.AADClientID,
Password: a.config.AADClientSecret,
Email: dummyRegistryEmail,
}
cfg[customAcrSuffix] = *cred
}
}
}
// add ACR anonymous repo support: use empty username and password for anonymous access
defaultConfigEntry := credentialprovider.DockerConfigEntry{
Username: "",
Password: "",
Email: dummyRegistryEmail,
}
cfg["*.azurecr.*"] = defaultConfigEntry
return cfg
}
func getLoginServer(registry containerregistry.Registry) string {
return *(*registry.RegistryProperties).LoginServer
}
func getACRDockerEntryFromARMToken(a *acrProvider, loginServer string) (*credentialprovider.DockerConfigEntry, error) {
if a.servicePrincipalToken == nil {
token, err := auth.GetServicePrincipalToken(a.config, a.environment)
if err != nil {
klog.Errorf("Failed to create service principal token: %v", err)
return nil, err
}
a.servicePrincipalToken = token
} else {
// Run EnsureFresh to make sure the token is valid and does not expire
if err := a.servicePrincipalToken.EnsureFresh(); err != nil {
klog.Errorf("Failed to ensure fresh service principal token: %v", err)
return nil, err
}
}
armAccessToken := a.servicePrincipalToken.OAuthToken()
klog.V(4).Infof("discovering auth redirects for: %s", loginServer)
directive, err := receiveChallengeFromLoginServer(loginServer)
if err != nil {
klog.Errorf("failed to receive challenge: %s", err)
return nil, err
}
klog.V(4).Infof("exchanging an acr refresh_token")
registryRefreshToken, err := performTokenExchange(
loginServer, directive, a.config.TenantID, armAccessToken)
if err != nil {
klog.Errorf("failed to perform token exchange: %s", err)
return nil, err
}
klog.V(4).Infof("adding ACR docker config entry for: %s", loginServer)
return &credentialprovider.DockerConfigEntry{
Username: dockerTokenLoginUsernameGUID,
Password: registryRefreshToken,
Email: dummyRegistryEmail,
}, nil
}
// parseACRLoginServerFromImage takes image as parameter and returns login server of it.
// Parameter `image` is expected in following format: foo.azurecr.io/bar/imageName:version
// If the provided image is not an acr image, this function will return an empty string.
func (a *acrProvider) parseACRLoginServerFromImage(image string) string {
match := acrRE.FindAllString(image, -1)
if len(match) == 1 {
return match[0]
}
// handle the custom cloud case
if a != nil && a.environment != nil {
cloudAcrSuffix := a.environment.ContainerRegistryDNSSuffix
cloudAcrSuffixLength := len(cloudAcrSuffix)
if cloudAcrSuffixLength > 0 {
customAcrSuffixIndex := strings.Index(image, cloudAcrSuffix)
if customAcrSuffixIndex != -1 {
endIndex := customAcrSuffixIndex + cloudAcrSuffixLength
return image[0:endIndex]
}
}
}
return ""
}