-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathkeychain.go
254 lines (221 loc) · 7.64 KB
/
keychain.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
package auth
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"os"
"regexp"
ecr "github.com/awslabs/amazon-ecr-credential-helper/ecr-login"
"github.com/chrismellard/docker-credential-acr-env/pkg/credhelper"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/name"
"github.com/pkg/errors"
)
const EnvRegistryAuth = "CNB_REGISTRY_AUTH"
var (
amazonKeychain = authn.NewKeychainFromHelper(ecr.NewECRHelper(ecr.WithLogger(io.Discard)))
azureKeychain = authn.NewKeychainFromHelper(credhelper.NewACRCredentialsHelper())
)
// DefaultKeychain returns a keychain containing authentication configuration for the given images
// from the following sources, if they exist, in order of precedence:
// the provided environment variable
// the docker config.json file
// credential helpers for Amazon and Azure
func DefaultKeychain(images ...string) (authn.Keychain, error) {
envKeychain, err := NewEnvKeychain(EnvRegistryAuth)
if err != nil {
return nil, err
}
return authn.NewMultiKeychain(
envKeychain,
NewResolvedKeychain(authn.DefaultKeychain, images...),
NewResolvedKeychain(amazonKeychain, images...),
NewResolvedKeychain(azureKeychain, images...),
), nil
}
// NewEnvKeychain returns an authn.Keychain that uses the provided environment variable as a source of credentials.
// The value of the environment variable should be a JSON object that maps OCI registry hostnames to Authorization headers.
func NewEnvKeychain(envVar string) (authn.Keychain, error) {
authHeaders, err := ReadEnvVar(envVar)
if err != nil {
return nil, errors.Wrap(err, "reading auth env var")
}
return &EnvKeychain{AuthHeaders: authHeaders}, nil
}
// EnvKeychain is an implementation of authn.Keychain that stores credentials as auth headers.
type EnvKeychain struct {
AuthHeaders map[string]string
}
func (k *EnvKeychain) Resolve(resource authn.Resource) (authn.Authenticator, error) {
header, ok := k.AuthHeaders[resource.RegistryStr()]
if ok {
authConfig, err := authHeaderToConfig(header)
if err != nil {
return nil, errors.Wrap(err, "parsing auth header")
}
return &providedAuth{config: authConfig}, nil
}
return authn.Anonymous, nil
}
var (
basicAuthRegExp = regexp.MustCompile("(?i)^basic (.*)$")
bearerAuthRegExp = regexp.MustCompile("(?i)^bearer (.*)$")
identityTokenRegExp = regexp.MustCompile("(?i)^x-identity (.*)$")
)
func authHeaderToConfig(header string) (*authn.AuthConfig, error) {
if matches := basicAuthRegExp.FindAllStringSubmatch(header, -1); len(matches) != 0 {
return &authn.AuthConfig{
Auth: matches[0][1],
}, nil
}
if matches := bearerAuthRegExp.FindAllStringSubmatch(header, -1); len(matches) != 0 {
return &authn.AuthConfig{
RegistryToken: matches[0][1],
}, nil
}
if matches := identityTokenRegExp.FindAllStringSubmatch(header, -1); len(matches) != 0 {
return &authn.AuthConfig{
IdentityToken: matches[0][1],
}, nil
}
return nil, errors.New("unknown auth type from header")
}
type providedAuth struct {
config *authn.AuthConfig
}
func (p *providedAuth) Authorization() (*authn.AuthConfig, error) {
return p.config, nil
}
// NewResolvedKeychain resolves credentials for the given images from the given keychain and returns a new keychain
// that stores the pre-resolved credentials in memory and returns them on demand. This is useful in cases where the
// backing credential store may become inaccessible in the future.
func NewResolvedKeychain(keychain authn.Keychain, images ...string) authn.Keychain {
return &ResolvedKeychain{
AuthConfigs: buildAuthConfigs(keychain, images...),
}
}
func buildAuthConfigs(keychain authn.Keychain, images ...string) map[string]*authn.AuthConfig {
registryAuths := map[string]*authn.AuthConfig{}
for _, image := range images {
reference, authenticator, err := ReferenceForRepoName(keychain, image)
if err != nil {
continue
}
if authenticator == authn.Anonymous {
continue
}
authConfig, err := authenticator.Authorization()
if err != nil {
continue
}
if *authConfig == (authn.AuthConfig{}) {
continue
}
registryAuths[reference.Context().Registry.Name()] = authConfig
}
return registryAuths
}
// ResolvedKeychain is an implementation of authn.Keychain that stores credentials in memory.
type ResolvedKeychain struct {
AuthConfigs map[string]*authn.AuthConfig
}
func (k *ResolvedKeychain) Resolve(resource authn.Resource) (authn.Authenticator, error) {
authConfig, ok := k.AuthConfigs[resource.RegistryStr()]
if ok {
return &providedAuth{config: authConfig}, nil
}
return authn.Anonymous, nil
}
// ReadEnvVar parses an environment variable to produce a map of 'registry url' to 'authorization header'.
//
// Complementary to `BuildEnvVar`.
//
// Example Input:
//
// {"gcr.io": "Bearer asdf=", "docker.io": "Basic qwerty="}
//
// Example Output:
//
// gcr.io -> Bearer asdf=
// docker.io -> Basic qwerty=
func ReadEnvVar(envVar string) (map[string]string, error) {
authMap := map[string]string{}
env := os.Getenv(envVar)
if env != "" {
err := json.Unmarshal([]byte(env), &authMap)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse %s value", envVar)
}
}
return authMap, nil
}
// BuildEnvVar creates the contents to use for authentication environment variable.
//
// Complementary to `ReadEnvVar`.
func BuildEnvVar(keychain authn.Keychain, images ...string) (string, error) {
registryAuths := buildAuthHeaders(keychain, images...)
authData, err := json.Marshal(registryAuths)
if err != nil {
return "", err
}
return string(authData), nil
}
func buildAuthHeaders(keychain authn.Keychain, images ...string) map[string]string {
registryAuths := map[string]string{}
for _, image := range images {
reference, authenticator, err := ReferenceForRepoName(keychain, image)
if err != nil {
continue
}
if authenticator == authn.Anonymous {
continue
}
authConfig, err := authenticator.Authorization()
if err != nil {
continue
}
header, err := authConfigToHeader(authConfig)
if err != nil {
continue
}
registryAuths[reference.Context().Registry.Name()] = header
}
return registryAuths
}
// authConfigToHeader accepts an authn.AuthConfig and returns an Authorization header,
// or an error if the config cannot be processed.
// Note that when resolving credentials, the header is simply used to reconstruct the originally provided authn.AuthConfig,
// making it essentially a stringification (the actual value is unimportant as long as it is consistent and contains
// all the necessary information).
func authConfigToHeader(config *authn.AuthConfig) (string, error) {
if config.Auth != "" {
return fmt.Sprintf("Basic %s", config.Auth), nil
}
if config.RegistryToken != "" {
return fmt.Sprintf("Bearer %s", config.RegistryToken), nil
}
if config.Username != "" && config.Password != "" {
delimited := fmt.Sprintf("%s:%s", config.Username, config.Password)
encoded := base64.StdEncoding.EncodeToString([]byte(delimited))
return fmt.Sprintf("Basic %s", encoded), nil
}
if config.IdentityToken != "" {
// There isn't an Authorization header for identity tokens, but we just need a way to represent the data.
return fmt.Sprintf("X-Identity %s", config.IdentityToken), nil
}
return "", errors.New("failed to find authorization information")
}
// ReferenceForRepoName returns a reference and an authenticator for a given image name and keychain.
func ReferenceForRepoName(keychain authn.Keychain, ref string) (name.Reference, authn.Authenticator, error) {
var auth authn.Authenticator
r, err := name.ParseReference(ref, name.WeakValidation)
if err != nil {
return nil, nil, err
}
auth, err = keychain.Resolve(r.Context().Registry)
if err != nil {
return nil, nil, err
}
return r, auth, nil
}