-
Notifications
You must be signed in to change notification settings - Fork 340
/
passwordpersist_keyring.go
101 lines (79 loc) · 2.41 KB
/
passwordpersist_keyring.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
package passwordpersist
import (
"context"
"crypto/sha256"
"fmt"
"io"
"os/user"
"path/filepath"
"runtime"
"strings"
"github.com/pkg/errors"
"github.com/zalando/go-keyring"
)
// Keyring is a Strategy that persists the password in OS-specific keyring.
func Keyring() Strategy {
return keyringStrategy{}
}
type keyringStrategy struct{}
func (keyringStrategy) GetPassword(ctx context.Context, configFile string) (string, error) {
kr, err := keyring.Get(getKeyringItemID(configFile), keyringUsername(ctx))
switch {
case err == nil:
log(ctx).Debugf("password for %v retrieved from OS keyring", configFile)
return kr, nil
case errors.Is(err, keyring.ErrNotFound):
return "", ErrPasswordNotFound
case errors.Is(err, keyring.ErrUnsupportedPlatform):
return "", ErrPasswordNotFound
default:
return "", errors.Wrap(err, "error retrieving password from OS keyring")
}
}
func (keyringStrategy) PersistPassword(ctx context.Context, configFile, password string) error {
log(ctx).Debugf("saving password to OS keyring...")
err := keyring.Set(getKeyringItemID(configFile), keyringUsername(ctx), password)
switch {
case err == nil:
log(ctx).Debugf("Saved password in OS keyring")
return nil
case errors.Is(err, keyring.ErrUnsupportedPlatform):
return ErrUnsupported
default:
return errors.Wrap(err, "error saving password in OS keyring")
}
}
func (keyringStrategy) DeletePassword(ctx context.Context, configFile string) error {
err := keyring.Delete(getKeyringItemID(configFile), keyringUsername(ctx))
switch {
case err == nil:
log(ctx).Infof("deleted repository password for %v.", configFile)
return nil
case errors.Is(err, keyring.ErrUnsupportedPlatform):
return ErrUnsupported
case errors.Is(err, keyring.ErrNotFound):
return ErrPasswordNotFound
default:
return errors.Wrapf(err, "unable to delete keyring item %v", getKeyringItemID(configFile))
}
}
func getKeyringItemID(configFile string) string {
h := sha256.New()
io.WriteString(h, configFile) //nolint:errcheck
return fmt.Sprintf("%v-%x", filepath.Base(configFile), h.Sum(nil)[0:8])
}
func keyringUsername(ctx context.Context) string {
currentUser, err := user.Current()
if err != nil {
log(ctx).Errorf("Cannot determine keyring username: %s", err)
return "nobody"
}
u := currentUser.Username
if runtime.GOOS == "windows" {
if p := strings.Index(u, "\\"); p >= 0 {
// On Windows ignore domain name.
u = u[p+1:]
}
}
return u
}