forked from knative/func
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcredentials.go
More file actions
542 lines (458 loc) · 15.8 KB
/
credentials.go
File metadata and controls
542 lines (458 loc) · 15.8 KB
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
package creds
import (
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
dockerConfig "github.com/containers/image/v5/pkg/docker/config"
containersTypes "github.com/containers/image/v5/types"
"github.com/docker/docker-credential-helpers/client"
"github.com/docker/docker-credential-helpers/credentials"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/name"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/google/go-containerregistry/pkg/v1/remote/transport"
"knative.dev/func/pkg/oci"
)
type CredentialsCallback func(registry string) (oci.Credentials, error)
var ErrUnauthorized = errors.New("bad credentials")
var ErrCredentialsNotFound = errors.New("credentials not found")
// localhostRegex matches localhost or 127.0.0.1 with optional port
var localhostRegex = regexp.MustCompile(`^(localhost|127\.0\.0\.1)(:[0-9]+)?$`)
// IsLocalRegistry checks if a registry is localhost or 127.0.0.1 with optional port
func IsLocalRegistry(registry string) bool {
return localhostRegex.MatchString(registry)
}
// VerifyCredentialsCallback checks if credentials are authorized for image push.
// If credentials are incorrect this callback shall return ErrUnauthorized.
type VerifyCredentialsCallback func(ctx context.Context, image string, credentials oci.Credentials) error
type keyChain struct {
user string
pwd string
}
func (k keyChain) Resolve(resource authn.Resource) (authn.Authenticator, error) {
return &authn.Basic{
Username: k.user,
Password: k.pwd,
}, nil
}
// CheckAuth verifies that credentials can be used for image push
func CheckAuth(ctx context.Context, image string, credentials oci.Credentials, trans http.RoundTripper) error {
ref, err := name.ParseReference(image)
if err != nil {
return fmt.Errorf("cannot parse image reference: %w", err)
}
kc := keyChain{
user: credentials.Username,
pwd: credentials.Password,
}
err = remote.CheckPushPermission(ref, kc, trans)
if err != nil {
var transportErr *transport.Error
if errors.As(err, &transportErr) && transportErr.StatusCode == 401 {
return ErrUnauthorized
}
return err
}
return nil
}
type ChooseCredentialHelperCallback func(available []string) (string, error)
type credentialsProvider struct {
promptForCredentials CredentialsCallback
verifyCredentials VerifyCredentialsCallback
promptForCredentialStore ChooseCredentialHelperCallback
credentialLoaders []CredentialsCallback
authFilePath string
transport http.RoundTripper
}
type Opt func(opts *credentialsProvider)
// WithAuthFilePath sets a custom path to a docker-config file containing registry credentials.
// If not specified, the default path (configPath/auth.json) will be used.
func WithAuthFilePath(path string) Opt {
return func(opts *credentialsProvider) {
opts.authFilePath = path
}
}
// WithPromptForCredentials sets custom callback that is supposed to
// interactively ask for credentials in case the credentials cannot be found in configuration files.
// The callback may be called multiple times in case incorrect credentials were returned before.
func WithPromptForCredentials(cbk CredentialsCallback) Opt {
return func(opts *credentialsProvider) {
opts.promptForCredentials = cbk
}
}
// WithVerifyCredentials sets custom callback for credentials validation.
func WithVerifyCredentials(cbk VerifyCredentialsCallback) Opt {
return func(opts *credentialsProvider) {
opts.verifyCredentials = cbk
}
}
// WithPromptForCredentialStore sets custom callback that is supposed to
// interactively ask user which credentials store/helper is used to store credentials obtained
// from user.
func WithPromptForCredentialStore(cbk ChooseCredentialHelperCallback) Opt {
return func(opts *credentialsProvider) {
opts.promptForCredentialStore = cbk
}
}
func WithTransport(transport http.RoundTripper) Opt {
return func(opts *credentialsProvider) {
opts.transport = transport
}
}
// WithAdditionalCredentialLoaders adds custom callbacks for credential retrieval.
// The callbacks shall return ErrCredentialsNotFound if the credentials are not found.
// The callbacks are supposed to be non-interactive as opposed to WithPromptForCredentials.
//
// This might be useful when credentials are shared with some other service.
//
// Example: OpenShift builtin registry shares credentials with the cluster (k8s) credentials.
func WithAdditionalCredentialLoaders(loaders ...CredentialsCallback) Opt {
return func(opts *credentialsProvider) {
opts.credentialLoaders = append(opts.credentialLoaders, loaders...)
}
}
// NewCredentialsProvider returns new CredentialsProvider that tries to get credentials from docker/func config files.
//
// In case getting credentials from the config files fails
// the caller provided callback (see WithPromptForCredentials) will be invoked to obtain credentials.
// The callback may be called multiple times in case the returned credentials
// are not correct (see WithVerifyCredentials).
//
// When the callback succeeds the credentials will be saved by using helper defined in the func config.
// If the helper is not defined in the config file
// it may be picked by provided callback (see WithPromptForCredentialStore).
// The picked value will be saved in the func config.
//
// To verify that credentials are correct custom callback can be used (see WithVerifyCredentials).
func NewCredentialsProvider(configPath string, opts ...Opt) oci.CredentialsProvider {
var c credentialsProvider
for _, o := range opts {
o(&c)
}
if c.transport == nil {
c.transport = http.DefaultTransport
}
if c.verifyCredentials == nil {
c.verifyCredentials = func(ctx context.Context, registry string, credentials oci.Credentials) error {
return CheckAuth(ctx, registry, credentials, c.transport)
}
}
if c.promptForCredentialStore == nil {
c.promptForCredentialStore = func(available []string) (string, error) {
return "", nil
}
}
// default credential loaders map -- load only those that should be there.
var defaultCredentialLoaders = []CredentialsCallback{}
// Add localhost registry handler first - anonymous auth for localhost registries
defaultCredentialLoaders = append(defaultCredentialLoaders,
func(registry string) (oci.Credentials, error) {
// Check if this is a localhost registry that should use anonymous auth
if IsLocalRegistry(registry) {
// Return empty credentials for anonymous auth
return oci.Credentials{}, nil
}
return oci.Credentials{}, ErrCredentialsNotFound
})
// Set authFilePath if not already set by WithAuthFilePath option
if c.authFilePath == "" {
c.authFilePath = filepath.Join(configPath, "auth.json")
}
sys := &containersTypes.SystemContext{
AuthFilePath: c.authFilePath,
}
if _, err := os.Stat(c.authFilePath); err == nil {
defaultCredentialLoaders = append(defaultCredentialLoaders,
func(registry string) (oci.Credentials, error) {
return getCredentialsByCredentialHelper(c.authFilePath, registry)
})
}
// add only if home dir is defined -- for .docker/config.json creds
home, err := os.UserHomeDir()
if err == nil {
dockerConfigPath := filepath.Join(home, ".docker", "config.json")
defaultCredentialLoaders = append(defaultCredentialLoaders,
func(registry string) (oci.Credentials, error) {
return getCredentialsByCredentialHelper(dockerConfigPath, registry)
})
}
defaultCredentialLoaders = append(defaultCredentialLoaders,
func(registry string) (oci.Credentials, error) {
creds, err := dockerConfig.GetCredentials(sys, registry)
if err != nil {
return oci.Credentials{}, err
}
if creds.Username == "" || creds.Password == "" {
return oci.Credentials{}, ErrCredentialsNotFound
}
return oci.Credentials{
Username: creds.Username,
Password: creds.Password,
}, nil
})
defaultCredentialLoaders = append(defaultCredentialLoaders,
func(registry string) (oci.Credentials, error) {
// Fallback onto default docker config locations
emptySys := &containersTypes.SystemContext{}
creds, err := dockerConfig.GetCredentials(emptySys, registry)
if err != nil {
return oci.Credentials{}, err
}
return oci.Credentials{
Username: creds.Username,
Password: creds.Password,
}, nil
})
defaultCredentialLoaders = append(defaultCredentialLoaders,
func(registry string) (oci.Credentials, error) { // empty credentials provider for unsecured registries
return oci.Credentials{}, nil
})
c.credentialLoaders = append(c.credentialLoaders, defaultCredentialLoaders...)
return c.getCredentials
}
func (c *credentialsProvider) getCredentials(ctx context.Context, image string) (oci.Credentials, error) {
var err error
result := oci.Credentials{}
ref, err := name.ParseReference(image)
if err != nil {
return oci.Credentials{}, fmt.Errorf("cannot parse the image reference: %w", err)
}
registry := ref.Context().RegistryStr()
for _, load := range c.credentialLoaders {
result, err = load(registry)
if err != nil {
if errors.Is(err, ErrCredentialsNotFound) {
continue
}
return oci.Credentials{}, err
}
err = c.verifyCredentials(ctx, image, result)
if err == nil {
return result, nil
} else {
if !errors.Is(err, ErrUnauthorized) {
return oci.Credentials{}, err
}
}
}
if c.promptForCredentials == nil {
return oci.Credentials{}, ErrCredentialsNotFound
}
// this is [registry] / [repository]
// this is index.io / user/imagename
repository := registry + "/" + ref.Context().RepositoryStr()
// the trying-to-actually-authorize cycle
for {
// use repo here to print it out in prompt
result, err = c.promptForCredentials(repository)
if err != nil {
return oci.Credentials{}, err
}
err = c.verifyCredentials(ctx, image, result)
if err == nil {
err = setCredentialsByCredentialHelper(c.authFilePath, registry, result.Username, result.Password)
if err != nil {
// This shouldn't be fatal error.
if strings.Contains(err.Error(), "not implemented") {
fmt.Fprintf(os.Stderr, "the cred-helper does not support write operation (consider changing the cred-helper it in auth.json)\n")
return oci.Credentials{}, nil
}
if !errors.Is(err, errNoCredentialHelperConfigured) {
return oci.Credentials{}, err
}
helpers := listCredentialHelpers()
helper, err := c.promptForCredentialStore(helpers)
if err != nil {
return oci.Credentials{}, err
}
helper = strings.TrimPrefix(helper, "docker-credential-")
err = setCredentialHelperToConfig(c.authFilePath, helper)
if err != nil {
return oci.Credentials{}, fmt.Errorf("faild to set the helper to the config: %w", err)
}
err = setCredentialsByCredentialHelper(c.authFilePath, registry, result.Username, result.Password)
if err != nil {
// This shouldn't be fatal error.
if strings.Contains(err.Error(), "not implemented") {
fmt.Fprintf(os.Stderr, "the cred-helper does not support write operation (consider changing the cred-helper it in auth.json)\n")
return oci.Credentials{}, nil
}
if !errors.Is(err, errNoCredentialHelperConfigured) {
return oci.Credentials{}, err
}
}
}
return result, nil
} else {
if errors.Is(err, ErrUnauthorized) {
continue
}
return oci.Credentials{}, err
}
}
}
var errNoCredentialHelperConfigured = errors.New("no credential helper configure")
func getCredentialHelperFromConfig(confFilePath string) (string, error) {
data, err := os.ReadFile(confFilePath)
if err != nil {
return "", err
}
conf := struct {
Store string `json:"credsStore"`
}{}
err = json.Unmarshal(data, &conf)
if err != nil {
return "", err
}
return conf.Store, nil
}
func setCredentialHelperToConfig(confFilePath, helper string) error {
var err error
configData := make(map[string]interface{})
if data, err := os.ReadFile(confFilePath); err == nil {
err = json.Unmarshal(data, &configData)
if err != nil {
return err
}
}
configData["credsStore"] = helper
data, err := json.MarshalIndent(&configData, "", " ")
if err != nil {
return err
}
// create config path if doesnt exist
err = os.MkdirAll(filepath.Dir(confFilePath), 0755)
if err != nil {
return err
}
err = os.WriteFile(confFilePath, data, 0600)
if err != nil {
return err
}
return nil
}
func getCredentialsByCredentialHelper(confFilePath, registry string) (oci.Credentials, error) {
result := oci.Credentials{}
helper, err := getCredentialHelperFromConfig(confFilePath)
if err != nil && !os.IsNotExist(err) {
return result, fmt.Errorf("failed to get helper from config: %w", err)
}
if helper == "" {
return result, ErrCredentialsNotFound
}
helperName := fmt.Sprintf("docker-credential-%s", helper)
p := client.NewShellProgramFunc(helperName)
credentialsMap, err := client.List(p)
if err != nil {
// Handle missing credential helper gracefully
errStr := err.Error()
if os.IsNotExist(err) ||
strings.Contains(errStr, "executable file not found") ||
strings.Contains(errStr, "not found in $PATH") ||
strings.Contains(errStr, helperName) {
// Log warning but don't fail - the credential helper is not available
fmt.Fprintf(os.Stderr, "Warning: credential helper %s not found, skipping: %v\n", helperName, err)
return result, ErrCredentialsNotFound
}
return result, fmt.Errorf("failed to list credentials: %w", err)
}
for serverUrl := range credentialsMap {
if RegistryEquals(serverUrl, registry) {
creds, err := client.Get(p, serverUrl)
if err != nil {
return result, fmt.Errorf("failed to get credentials: %w", err)
}
result.Username = creds.Username
result.Password = creds.Secret
return result, nil
}
}
return result, fmt.Errorf("failed to get credentials from helper specified in ~/.docker/config.json: %w", ErrCredentialsNotFound)
}
func setCredentialsByCredentialHelper(confFilePath, registry, username, secret string) error {
helper, err := getCredentialHelperFromConfig(confFilePath)
if helper == "" || os.IsNotExist(err) {
return errNoCredentialHelperConfigured
}
if err != nil {
return fmt.Errorf("failed to get helper from config: %w", err)
}
helperName := fmt.Sprintf("docker-credential-%s", helper)
p := client.NewShellProgramFunc(helperName)
return client.Store(p, &credentials.Credentials{ServerURL: registry, Username: username, Secret: secret})
}
func listCredentialHelpers() []string {
path := os.Getenv("PATH")
paths := strings.Split(path, string(os.PathListSeparator))
helpers := make(map[string]bool)
for _, p := range paths {
fss, err := os.ReadDir(p)
if err != nil {
continue
}
for _, fi := range fss {
if fi.IsDir() {
continue
}
if !strings.HasPrefix(fi.Name(), "docker-credential-") {
continue
}
if runtime.GOOS == "windows" {
ext := filepath.Ext(fi.Name())
if ext != ".exe" && ext != ".bat" {
continue
}
}
helpers[fi.Name()] = true
}
}
result := make([]string, 0, len(helpers))
for h := range helpers {
result = append(result, h)
}
return result
}
func hostPort(registry string) (host string, port string) {
if !strings.Contains(registry, "://") {
h, p, err := net.SplitHostPort(registry)
if err == nil {
host, port = h, p
return
}
registry = "https://" + registry
}
u, err := url.Parse(registry)
if err != nil {
panic(err)
}
host = u.Hostname()
port = u.Port()
return
}
// RegistryEquals checks whether registry matches in host and port
// with exception where empty port matches standard ports (80,443)
func RegistryEquals(regA, regB string) bool {
h1, p1 := hostPort(regA)
h2, p2 := hostPort(regB)
isStdPort := func(p string) bool { return p == "443" || p == "80" }
portEq := p1 == p2 ||
(p1 == "" && isStdPort(p2)) ||
(isStdPort(p1) && p2 == "")
if h1 == h2 && portEq {
return true
}
if strings.HasSuffix(h1, "docker.io") &&
strings.HasSuffix(h2, "docker.io") {
return true
}
return false
}