forked from 99designs/keyring
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wincred.go
98 lines (80 loc) · 2.11 KB
/
wincred.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
//go:build windows
// +build windows
package keyring
import (
"strings"
"syscall"
"github.com/danieljoos/wincred"
)
// ERROR_NOT_FOUND from https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes--1000-1299-
const elementNotFoundError = syscall.Errno(1168)
type windowsKeyring struct {
name string
prefix string
}
func init() {
supportedBackends[WinCredBackend] = opener(func(cfg Config) (Keyring, error) {
name := cfg.ServiceName
if name == "" {
name = "default"
}
prefix := cfg.WinCredPrefix
if prefix == "" {
prefix = "keyring"
}
return &windowsKeyring{
name: name,
prefix: prefix,
}, nil
})
}
func (k *windowsKeyring) Get(key string) (Item, error) {
cred, err := wincred.GetGenericCredential(k.credentialName(key))
if err != nil {
if err == elementNotFoundError {
return Item{}, ErrKeyNotFound
}
return Item{}, err
}
item := Item{
Key: key,
Data: cred.CredentialBlob,
}
return item, nil
}
// GetMetadata for pass returns an error indicating that it's unsupported
// for this backend.
// TODO: This is a stub. Look into whether pass would support metadata in a usable way for keyring.
func (k *windowsKeyring) GetMetadata(_ string) (Metadata, error) {
return Metadata{}, ErrMetadataNotSupported
}
func (k *windowsKeyring) Set(item Item) error {
cred := wincred.NewGenericCredential(k.credentialName(item.Key))
cred.CredentialBlob = item.Data
return cred.Write()
}
func (k *windowsKeyring) Remove(key string) error {
cred, err := wincred.GetGenericCredential(k.credentialName(key))
if err != nil {
if err == elementNotFoundError {
return ErrKeyNotFound
}
return err
}
return cred.Delete()
}
func (k *windowsKeyring) Keys() ([]string, error) {
results := []string{}
if creds, err := wincred.List(); err == nil {
for _, cred := range creds {
prefix := k.credentialName("")
if strings.HasPrefix(cred.TargetName, prefix) {
results = append(results, strings.TrimPrefix(cred.TargetName, prefix))
}
}
}
return results, nil
}
func (k *windowsKeyring) credentialName(key string) string {
return k.prefix + ":" + k.name + ":" + key
}