/
secret.go
86 lines (80 loc) · 2.49 KB
/
secret.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
package cloud
import (
"bytes"
"context"
"fmt"
"net/http"
"strings"
"github.com/pkg/errors"
)
func (c *Client) Remove(ctx context.Context, path string) error {
if path == "" || path[0] != '/' {
return errors.Errorf("invalid path")
}
status, body, err := c.doCall(ctx, "DELETE", fmt.Sprintf("/api/v0/secrets%s", path), withAuth())
if err != nil {
return err
}
if status != http.StatusNoContent {
msg, err := getMessageFromJSON(bytes.NewReader(body))
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to decode response body (status code: %d)", status))
}
return errors.Errorf("failed to remove secret: %s", msg)
}
return nil
}
func (c *Client) List(ctx context.Context, path string) ([]string, error) {
if path != "" && !strings.HasSuffix(path, "/") {
return nil, errors.Errorf("invalid path")
}
status, body, err := c.doCall(ctx, "GET", fmt.Sprintf("/api/v0/secrets%s", path), withAuth())
if err != nil {
return nil, err
}
if status != http.StatusOK {
msg, err := getMessageFromJSON(bytes.NewReader(body))
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("failed to decode response body (status code: %d)", status))
}
return nil, errors.Errorf("failed to list secrets: %s", msg)
}
if len(body) == 0 {
return []string{}, nil
}
return strings.Split(string(body), "\n"), nil
}
func (c *Client) Get(ctx context.Context, path string) ([]byte, error) {
if path == "" || path[0] != '/' || strings.HasSuffix(path, "/") {
return nil, errors.Errorf("invalid path")
}
status, body, err := c.doCall(ctx, "GET", fmt.Sprintf("/api/v0/secrets%s", path), withAuth())
if err != nil {
return nil, err
}
if status != http.StatusOK {
msg, err := getMessageFromJSON(bytes.NewReader(body))
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("failed to decode response body (status code: %d)", status))
}
return nil, errors.Errorf("failed to get secret: %s", msg)
}
return body, nil
}
func (c *Client) Set(ctx context.Context, path string, data []byte) error {
if path == "" || path[0] != '/' {
return errors.Errorf("invalid path")
}
status, body, err := c.doCall(ctx, "PUT", fmt.Sprintf("/api/v0/secrets%s", path), withAuth(), withBody(data))
if err != nil {
return err
}
if status != http.StatusCreated {
msg, err := getMessageFromJSON(bytes.NewReader(body))
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to decode response body (status code: %d)", status))
}
return errors.Errorf("failed to set secret: %s", msg)
}
return nil
}