100 lines
1.6 KiB
Go
100 lines
1.6 KiB
Go
|
package vault
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"encoding/base64"
|
||
|
"errors"
|
||
|
|
||
|
"github.com/hashicorp/vault/api"
|
||
|
)
|
||
|
|
||
|
type Storage struct {
|
||
|
client *api.Client
|
||
|
path string
|
||
|
}
|
||
|
|
||
|
func Open(token string, path string, addr string) (*Storage, error) {
|
||
|
conf := &api.Config{
|
||
|
Address: addr,
|
||
|
}
|
||
|
|
||
|
c, err := api.NewClient(conf)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
c.SetToken(token)
|
||
|
|
||
|
return &Storage{client: c, path: path}, nil
|
||
|
}
|
||
|
|
||
|
func (s *Storage) Save(key string, data []byte) error {
|
||
|
kv := s.client.KVv1(s.path)
|
||
|
|
||
|
str := base64.StdEncoding.EncodeToString(data)
|
||
|
m := map[string]any{
|
||
|
"data": map[string]string{
|
||
|
"payload": str,
|
||
|
},
|
||
|
}
|
||
|
|
||
|
if err := kv.Put(context.Background(), "testkey", m); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (s *Storage) Load(key string) ([]byte, error) {
|
||
|
kv := s.client.KVv1(s.path)
|
||
|
|
||
|
m, err := kv.Get(context.Background(), key)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
data, ok := m.Data["data"] // map[string]any
|
||
|
if !ok {
|
||
|
return nil, errors.New("no data found")
|
||
|
}
|
||
|
|
||
|
payloadmap, ok := data.(map[string]any)
|
||
|
if !ok {
|
||
|
return nil, errors.New("no payload map")
|
||
|
}
|
||
|
|
||
|
rawb, ok := payloadmap["payload"]
|
||
|
if !ok {
|
||
|
return nil, errors.New("no payload bytes")
|
||
|
}
|
||
|
|
||
|
str, ok := rawb.(string)
|
||
|
if !ok {
|
||
|
return nil, errors.New("could not convert payload to bytes")
|
||
|
}
|
||
|
|
||
|
b := []byte{}
|
||
|
|
||
|
b, err = base64.StdEncoding.AppendDecode(b, []byte(str))
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
return b, nil
|
||
|
}
|
||
|
|
||
|
func (s *Storage) Delete(key string) error {
|
||
|
kv := s.client.KVv1(s.path)
|
||
|
|
||
|
if err := kv.Delete(context.Background(), key); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func (s *Storage) Close() error {
|
||
|
s.client.ClearToken()
|
||
|
return nil
|
||
|
}
|