forked from zalando/go-keyring
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keyring_unix.go
123 lines (96 loc) · 2.36 KB
/
keyring_unix.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
//go:build (dragonfly && cgo) || (freebsd && cgo) || linux || netbsd || openbsd
package keyring
import (
"fmt"
dbus "github.com/godbus/dbus/v5"
ss "github.com/zalando/go-keyring/secret_service"
)
type secretServiceProvider struct{}
// Set stores user and pass in the keyring under the defined service
// name.
func (s secretServiceProvider) Set(service, user, pass string) error {
svc, err := ss.NewSecretService()
if err != nil {
return err
}
// open a session
session, err := svc.OpenSession()
if err != nil {
return err
}
defer svc.Close(session)
attributes := map[string]string{
"username": user,
"service": service,
}
secret := ss.NewSecret(session.Path(), pass)
collection := svc.GetLoginCollection()
err = svc.Unlock(collection.Path())
if err != nil {
return err
}
err = svc.CreateItem(collection,
fmt.Sprintf("Password for '%s' on '%s'", user, service),
attributes, secret)
if err != nil {
return err
}
return nil
}
// findItem looksup an item by service and user.
func (s secretServiceProvider) findItem(svc *ss.SecretService, service, user string) (dbus.ObjectPath, error) {
collection := svc.GetLoginCollection()
search := map[string]string{
"username": user,
"service": service,
}
err := svc.Unlock(collection.Path())
if err != nil {
return "", err
}
results, err := svc.SearchItems(collection, search)
if err != nil {
return "", err
}
if len(results) == 0 {
return "", ErrNotFound
}
return results[0], nil
}
// Get gets a secret from the keyring given a service name and a user.
func (s secretServiceProvider) Get(service, user string) (string, error) {
svc, err := ss.NewSecretService()
if err != nil {
return "", err
}
item, err := s.findItem(svc, service, user)
if err != nil {
return "", err
}
// open a session
session, err := svc.OpenSession()
if err != nil {
return "", err
}
defer svc.Close(session)
secret, err := svc.GetSecret(item, session.Path())
if err != nil {
return "", err
}
return string(secret.Value), nil
}
// Delete deletes a secret, identified by service & user, from the keyring.
func (s secretServiceProvider) Delete(service, user string) error {
svc, err := ss.NewSecretService()
if err != nil {
return err
}
item, err := s.findItem(svc, service, user)
if err != nil {
return err
}
return svc.Delete(item)
}
func init() {
provider = secretServiceProvider{}
}