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
|
package auth
import (
"crypto/rand"
"encoding/base64"
"fmt"
"strings"
"time"
"github.com/git-bug/git-bug/bridge/core"
"github.com/git-bug/git-bug/repository"
)
type credentialBase struct {
target string
createTime time.Time
salt []byte
meta map[string]string
}
func newCredentialBase(target string) *credentialBase {
return &credentialBase{
target: target,
createTime: time.Now(),
salt: makeSalt(),
}
}
func makeSalt() []byte {
result := make([]byte, 16)
_, err := rand.Read(result)
if err != nil {
panic(err)
}
return result
}
func newCredentialBaseFromData(data map[string]string) (*credentialBase, error) {
base := &credentialBase{
target: data[keyringKeyTarget],
meta: metaFromData(data),
}
if createTime, ok := data[keyringKeyCreateTime]; ok {
t, err := repository.ParseTimestamp(createTime)
if err != nil {
return nil, err
}
base.createTime = t
} else {
return nil, fmt.Errorf("missing create time")
}
salt, err := saltFromData(data)
if err != nil {
return nil, err
}
base.salt = salt
return base, nil
}
func metaFromData(data map[string]string) map[string]string {
result := make(map[string]string)
for key, val := range data {
if strings.HasPrefix(key, keyringKeyPrefixMeta) {
key = strings.TrimPrefix(key, keyringKeyPrefixMeta)
result[key] = val
}
}
if len(result) == 0 {
return nil
}
return result
}
func saltFromData(data map[string]string) ([]byte, error) {
val, ok := data[keyringKeySalt]
if !ok {
return nil, fmt.Errorf("no credential salt found")
}
return base64.StdEncoding.DecodeString(val)
}
func (cb *credentialBase) Target() string {
return cb.target
}
func (cb *credentialBase) CreateTime() time.Time {
return cb.createTime
}
func (cb *credentialBase) Salt() []byte {
return cb.salt
}
func (cb *credentialBase) validate() error {
if cb.target == "" {
return fmt.Errorf("missing target")
}
if cb.createTime.IsZero() || cb.createTime.Equal(time.Time{}) {
return fmt.Errorf("missing creation time")
}
if !core.TargetExist(cb.target) {
return fmt.Errorf("unknown target")
}
return nil
}
func (cb *credentialBase) Metadata() map[string]string {
return cb.meta
}
func (cb *credentialBase) GetMetadata(key string) (string, bool) {
val, ok := cb.meta[key]
return val, ok
}
func (cb *credentialBase) SetMetadata(key string, value string) {
if cb.meta == nil {
cb.meta = make(map[string]string)
}
cb.meta[key] = value
}
|