-
Notifications
You must be signed in to change notification settings - Fork 272
/
azure_credentials.go
215 lines (183 loc) · 6.77 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
/*
Copyright 2021 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 credentialprovider
import (
"context"
"errors"
"fmt"
"io"
"os"
"regexp"
"strings"
"time"
providerconfig "sigs.k8s.io/cloud-provider-azure/pkg/provider/config"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autorest/autorest/azure"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/klog/v2"
"k8s.io/kubelet/pkg/apis/credentialprovider/v1alpha1"
)
// Refer: https://github.com/kubernetes/kubernetes/blob/master/pkg/credentialprovider/azure/azure_credentials.go
const (
maxReadLength = 10 * 1 << 20 // 10MB
defaultCacheTTL = 5 * time.Minute
)
var (
containerRegistryUrls = []string{"*.azurecr.io", "*.azurecr.cn", "*.azurecr.de", "*.azurecr.us"}
acrRE = regexp.MustCompile(`.*\.azurecr\.io|.*\.azurecr\.cn|.*\.azurecr\.de|.*\.azurecr\.us`)
)
// CredentialProvider is an interface implemented by the kubelet credential provider plugin to fetch
// the username/password based on the provided image name.
type CredentialProvider interface {
GetCredentials(ctx context.Context, image string, args []string) (response *v1alpha1.CredentialProviderResponse, err error)
}
// acrProvider implements the credential provider interface for Azure Container Registry.
type acrProvider struct {
config *providerconfig.AzureAuthConfig
environment *azure.Environment
servicePrincipalToken *adal.ServicePrincipalToken
}
// NewAcrProvider creates a new instance of the ACR provider.
func NewAcrProvider(configFile string) (CredentialProvider, error) {
if len(configFile) == 0 {
return nil, errors.New("no azure credential file is provided")
}
f, err := os.Open(configFile)
if err != nil {
return nil, fmt.Errorf("failed to load config from file %s: %w", configFile, err)
}
defer f.Close()
return newAcrProviderFromConfigReader(f)
}
func newAcrProviderFromConfigReader(configReader io.Reader) (*acrProvider, error) {
config, env, err := providerconfig.ParseAzureAuthConfig(configReader)
if err != nil {
return nil, fmt.Errorf("failed to load config: %w", err)
}
servicePrincipalToken, err := providerconfig.GetServicePrincipalToken(config, env, env.ServiceManagementEndpoint)
if err != nil {
return nil, fmt.Errorf("failed to create service principal token: %w", err)
}
return &acrProvider{
config: config,
environment: env,
servicePrincipalToken: servicePrincipalToken,
}, nil
}
func (a *acrProvider) GetCredentials(ctx context.Context, image string, args []string) (*v1alpha1.CredentialProviderResponse, error) {
loginServer := a.parseACRLoginServerFromImage(image)
if loginServer == "" {
klog.V(2).Infof("image(%s) is not from ACR, return empty authentication", image)
return &v1alpha1.CredentialProviderResponse{
CacheKeyType: v1alpha1.RegistryPluginCacheKeyType,
CacheDuration: &metav1.Duration{Duration: 0},
Auth: map[string]v1alpha1.AuthConfig{},
}, nil
}
response := &v1alpha1.CredentialProviderResponse{
CacheKeyType: v1alpha1.RegistryPluginCacheKeyType,
CacheDuration: &metav1.Duration{Duration: defaultCacheTTL},
Auth: map[string]v1alpha1.AuthConfig{
// empty username and password for anonymous ACR access
"*.azurecr.*": {
Username: "",
Password: "",
},
},
}
if a.config.UseManagedIdentityExtension {
username, password, err := a.getFromACR(loginServer)
if err != nil {
klog.Errorf("error getting credentials from ACR for %s: %w", loginServer, err)
return nil, err
}
response.Auth[loginServer] = v1alpha1.AuthConfig{
Username: username,
Password: password,
}
} else {
// Add our entry for each of the supported container registry URLs
for _, url := range containerRegistryUrls {
cred := v1alpha1.AuthConfig{
Username: a.config.AADClientID,
Password: a.config.AADClientSecret,
}
response.Auth[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 := v1alpha1.AuthConfig{
Username: a.config.AADClientID,
Password: a.config.AADClientSecret,
}
response.Auth[customAcrSuffix] = cred
}
}
}
return response, nil
}
// getFromACR gets credentials from ACR.
func (a *acrProvider) getFromACR(loginServer string) (string, string, error) {
// 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 "", "", err
}
armAccessToken := a.servicePrincipalToken.OAuthToken()
klog.V(4).Infof("discovering auth redirects for: %s", loginServer)
directive, err := receiveChallengeFromLoginServer(loginServer, "https")
if err != nil {
klog.Errorf("failed to receive challenge: %s", err)
return "", "", 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 "", "", err
}
return dockerTokenLoginUsernameGUID, registryRefreshToken, 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 ""
}