-
-
Notifications
You must be signed in to change notification settings - Fork 478
/
kv.go
243 lines (218 loc) · 5.68 KB
/
kv.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
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
package secrets
import (
"bufio"
"bytes"
"fmt"
"io"
"sort"
"strings"
"github.com/gopasspw/gopass/pkg/debug"
"github.com/gopasspw/gopass/pkg/gopass"
)
var _ gopass.Secret = &KV{}
// NewKV creates a new KV secret
func NewKV() *KV {
return &KV{
data: make(map[string][]string, 10),
}
}
// NewKVWithData returns a new KV secret populated with data
func NewKVWithData(pw string, kvps map[string][]string, body string, converted bool) *KV {
kv := &KV{
password: pw,
data: make(map[string][]string, len(kvps)),
body: body,
fromMime: converted,
}
for k, v := range kvps {
kv.data[k] = v
}
return kv
}
// KV is a secret that contains a password line (maybe empty), any number of
// lines of key-value pairs (defined as: contains a colon) and any number of
// free text lines. This is the default secret format gopass uses and encourages.
// It should be compatible with most other password store implementations and
// works well with our vanity features (e.g. accessing single entries in secret).
//
// Format
// ------
// Line | Description
// ---- | -----------
// 0 | Password. Must contain the "password" or be empty. Can not be omitted.
// 1-n | Key-Value pairs, e.g. "key: value". Can be omitted but the secret
// | might get parsed as a "Plain" secret if zero key-value pairs are found.
// n+1 | Body. Can contain any number of characters that will be parsed as
// | UTF-8 and appended to an internal string. Note: Technically this can
// | be any kind of binary data but we neither support nor test this with
// | non-text data. Also we do not intent do support any kind of streaming
// | access, i.e. this is not intended for huge files.
//
// Example
// -------
// Line | Content
// ---- | -------
// 0 | foobar
// 1 | hello: world
// 2 | gopass: secret
// 3 | Yo
// 4 | Hi
//
// This would be parsed as a KV secret that contains:
// - password: "foobar"
// - key-value pairs:
// - "hello": "world"
// - "gopass": "secret"
// - body: "Yo\nHi"
type KV struct {
password string
data map[string][]string
body string
fromMime bool
}
// Bytes serializes
func (k *KV) Bytes() []byte {
buf := &bytes.Buffer{}
buf.WriteString(k.password)
buf.WriteString("\n")
for ik, key := range k.Keys() {
sv, ok := k.data[key]
if !ok {
continue
}
for iv, v := range sv {
_, _ = buf.WriteString(key)
_, _ = buf.WriteString(": ")
_, _ = buf.WriteString(v)
// the last one shouldn't add a newline, it's handled below
if iv < len(sv)-1 {
_, _ = buf.WriteString("\n")
}
}
// we must only add a final newline if the body is non-empty
if k.body != "" || ik < len(k.Keys())-1 {
_, _ = buf.WriteString("\n")
}
}
buf.WriteString(k.body)
return buf.Bytes()
}
// Keys returns all keys
func (k *KV) Keys() []string {
keys := make([]string, 0, len(k.data)+1)
for key := range k.data {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
// Get returns the first value of that key
func (k *KV) Get(key string) (string, bool) {
key = strings.ToLower(key)
if v, found := k.data[key]; found {
return v[0], true
}
return "", false
}
// Values returns all values for that key
func (k *KV) Values(key string) ([]string, bool) {
key = strings.ToLower(key)
v, found := k.data[key]
return v, found
}
// Set writes a single key
func (k *KV) Set(key string, value interface{}) error {
key = strings.ToLower(key)
if v, ok := k.data[key]; ok && len(v) > 1 {
return fmt.Errorf("cannot set key %s: this entry contains multiple same keys. Please use 'gopass edit' instead", key)
}
k.data[key] = []string{fmt.Sprintf("%s", value)}
return nil
}
// Add appends data to a given key
func (k *KV) Add(key string, value interface{}) error {
key = strings.ToLower(key)
k.data[key] = append(k.data[key], fmt.Sprintf("%s", value))
return nil
}
// Del removes a given key and all of its values
func (k *KV) Del(key string) bool {
key = strings.ToLower(key)
_, found := k.data[key]
delete(k.data, key)
return found
}
// Body returns the body
func (k *KV) Body() string {
return k.body
}
// Password returns the password
func (k *KV) Password() string {
return k.password
}
// SetPassword updates the password
func (k *KV) SetPassword(p string) {
k.password = p
}
// ParseKV tries to parse a KV secret
func ParseKV(in []byte) (*KV, error) {
k := &KV{
data: make(map[string][]string, 10),
}
r := bufio.NewReader(bytes.NewReader(in))
line, err := r.ReadString('\n')
if err != nil {
return nil, err
}
k.password = strings.TrimRight(line, "\n")
var sb strings.Builder
for {
line, err := r.ReadString('\n')
if err != nil && line == "" {
if err == io.EOF {
break
}
return nil, err
}
// append non KV pairs to the body
if !strings.Contains(line, ":") {
sb.WriteString(line)
continue
}
line = strings.TrimRight(line, "\n")
parts := strings.SplitN(line, ":", 2)
// should not happen
if len(parts) < 1 {
continue
}
for i, part := range parts {
parts[i] = strings.TrimSpace(part)
}
// we only store lower case keys for KV
parts[0] = strings.ToLower(parts[0])
// preserve key only entries
if len(parts) < 2 {
k.data[parts[0]] = append(k.data[parts[0]], "")
continue
}
k.data[parts[0]] = append(k.data[parts[0]], parts[1])
}
if len(k.data) < 1 {
debug.Log("no KV entries")
}
k.body = sb.String()
return k, nil
}
// Write appends the buffer to the secret's body
func (k *KV) Write(buf []byte) (int, error) {
k.body += string(buf)
return len(buf), nil
}
// FromMime returns whether this secret was converted from a Mime secret of not
func (k *KV) FromMime() bool {
return k.fromMime
}
// SafeStr always returnes "(elided)"
func (k *KV) SafeStr() string {
return "(elided)"
}