-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
vaultfs.go
274 lines (221 loc) · 5.79 KB
/
vaultfs.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package vfs
import (
"context"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"strings"
vault "github.com/hashicorp/vault/api"
"k8s.io/klog/v2"
)
type VaultPath struct {
vaultClient *vault.Client
scheme string
mountPoint string
path string
}
var _ Path = &VaultPath{}
func newVaultPath(client *vault.Client, scheme string, path string) (*VaultPath, error) {
if scheme != "https://" && scheme != "http://" {
return nil, fmt.Errorf("scheme must be http:// or https://")
}
path = strings.TrimPrefix(path, "/")
dirs := strings.SplitN(path, "/", 2)
if len(dirs) != 2 {
return nil, fmt.Errorf("vault path must have both a mount point and a path. Got: %q", path)
}
if client == nil {
return nil, fmt.Errorf("vault path needs to have a vault client")
}
return &VaultPath{
vaultClient: client,
scheme: scheme,
mountPoint: dirs[0],
path: dirs[1],
}, nil
}
func (p *VaultPath) WriteFile(data io.ReadSeeker, acl ACL) error {
klog.V(4).Infof("Writing file %q", p)
file, err := encodeData(data)
if err != nil {
return err
}
payload := map[string]interface{}{
"data": map[string]interface{}{
"file": file,
},
}
_, err = p.vaultClient.Logical().Write(p.dataPath(), payload)
return err
}
func (p *VaultPath) CreateFile(data io.ReadSeeker, acl ACL) error {
file, _ := p.ReadFile()
if file == nil {
return p.WriteFile(data, acl)
} else {
return fmt.Errorf("file already exists: %v", p.path)
}
}
func (p *VaultPath) ReadFile() ([]byte, error) {
secret, err := p.vaultClient.Logical().Read(p.dataPath())
if err != nil {
return nil, err
}
if secret == nil || secret.Data["data"] == nil {
return nil, os.ErrNotExist
}
data := secret.Data["data"].(map[string]interface{})
encodedString := data["file"].(string)
return base64.StdEncoding.DecodeString(encodedString)
}
func (p *VaultPath) Remove() error {
klog.V(8).Infof("removing file %s", p)
_, err := p.vaultClient.Logical().Delete(p.dataPath())
return err
}
func (p *VaultPath) RemoveAllVersions() error {
klog.V(8).Infof("removing all versions of file %s", p)
data := map[string][]string{
"versions": {"1"},
}
_, err := p.vaultClient.Logical().DeleteWithData(p.dataPath(), data)
if err != nil {
return err
}
err = p.destroy()
if err != nil {
return err
}
err = p.deleteMetadata()
return err
}
func (p *VaultPath) Base() string {
return path.Base(p.path)
}
func (p *VaultPath) Path() string {
query := ""
if p.scheme == "http://" {
query = "?tls=false"
}
return fmt.Sprintf("vault://%s/%s/%s%s", strings.TrimPrefix(p.vaultClient.Address(), p.scheme), p.mountPoint, p.path, query)
}
func (p *VaultPath) ReadDir() ([]Path, error) {
secret, err := p.vaultClient.Logical().List(p.metadataPath())
if err != nil {
return nil, err
}
if secret == nil {
return nil, os.ErrNotExist
}
data := secret.Data["keys"].([]interface{})
paths := make([]Path, 0)
for _, key := range data {
path := p.Join(key.(string))
paths = append(paths, path)
}
return paths, nil
}
func (p *VaultPath) ReadTree() ([]Path, error) {
content, err := p.ReadDir()
files := make([]Path, 0)
if os.IsNotExist(err) {
return files, nil
}
if err != nil {
return nil, fmt.Errorf("error reading path %v, %v", p, err)
}
for _, path := range content {
if IsDirectory(path) {
subTree, err := path.ReadTree()
if err != nil {
return nil, err
}
files = append(files, subTree...)
} else {
files = append(files, path)
}
}
return files, nil
}
func (p *VaultPath) Join(relativePath ...string) Path {
args := []string{p.fullPath()}
args = append(args, relativePath...)
joined := path.Join(args...)
path, _ := newVaultPath(p.vaultClient, p.scheme, joined)
return path
}
func (p *VaultPath) WriteTo(out io.Writer) (int64, error) {
panic("writeTo not implemented")
}
func encodeData(data io.ReadSeeker) (string, error) {
pr, pw := io.Pipe()
encoder := base64.NewEncoder(base64.StdEncoding, pw)
go func() {
_, err := io.Copy(encoder, data)
encoder.Close()
if err != nil {
pw.CloseWithError(err)
} else {
pw.Close()
}
}()
out, err := ioutil.ReadAll(pr)
if err != nil {
return "", err
}
return string(out), nil
}
func (p *VaultPath) dataPath() string {
return p.mountPoint + "/data/" + p.path
}
func (p *VaultPath) metadataPath() string {
return p.mountPoint + "/metadata/" + p.path
}
func (p *VaultPath) fullPath() string {
return p.mountPoint + "/" + p.path
}
func (p *VaultPath) String() string {
return p.Path()
}
func (p VaultPath) destroy() error {
data := map[string][]string{
"versions": {"1"},
}
r := p.vaultClient.NewRequest("PUT", "/v1/"+p.mountPoint+"/destroy/"+p.path)
r.SetJSONBody(data)
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
resp, err := p.vaultClient.RawRequestWithContext(ctx, r)
if resp != nil {
defer resp.Body.Close()
}
return err
}
func (p VaultPath) deleteMetadata() error {
r := p.vaultClient.NewRequest("DELETE", "/v1/"+p.mountPoint+"/metadata/"+p.path)
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
resp, err := p.vaultClient.RawRequestWithContext(ctx, r)
if resp != nil {
defer resp.Body.Close()
}
return err
}
func (p VaultPath) SetClientToken(token string) {
p.vaultClient.SetToken(token)
}