2025-07-21 17:16:10 +03:00
|
|
|
package vault
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/base64"
|
|
|
|
"errors"
|
|
|
|
|
2025-07-27 19:02:05 +03:00
|
|
|
"code.uint32.ru/tiny/storage/internal/errinternal"
|
2025-07-21 17:16:10 +03:00
|
|
|
"github.com/hashicorp/vault/api"
|
|
|
|
)
|
|
|
|
|
2025-07-27 19:02:05 +03:00
|
|
|
var (
|
|
|
|
ErrNotFound = errinternal.ErrNotFound
|
|
|
|
)
|
|
|
|
|
2025-07-21 17:16:10 +03:00
|
|
|
type Storage struct {
|
2025-07-27 19:02:05 +03:00
|
|
|
kv *api.KVv1
|
|
|
|
// TODO: kv2: *api.KVv2
|
2025-07-21 17:16:10 +03:00
|
|
|
}
|
|
|
|
|
2025-07-27 19:02:05 +03:00
|
|
|
// New returns Storage writing to the specified vault path.
|
|
|
|
// Object will be base64 encoded and written to path/key.
|
|
|
|
func New(c *api.Client, path string) *Storage {
|
|
|
|
return &Storage{kv: c.KVv1(path)}
|
2025-07-21 17:16:10 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Storage) Save(key string, data []byte) error {
|
|
|
|
str := base64.StdEncoding.EncodeToString(data)
|
|
|
|
m := map[string]any{
|
|
|
|
"data": map[string]string{
|
|
|
|
"payload": str,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2025-07-27 19:02:05 +03:00
|
|
|
if err := s.kv.Put(context.Background(), "testkey", m); err != nil {
|
2025-07-21 17:16:10 +03:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Storage) Load(key string) ([]byte, error) {
|
2025-07-27 19:02:05 +03:00
|
|
|
m, err := s.kv.Get(context.Background(), key)
|
|
|
|
if err != nil && errors.Is(err, api.ErrSecretNotFound) {
|
|
|
|
return nil, errors.Join(ErrNotFound, err)
|
|
|
|
} else if err != nil {
|
2025-07-21 17:16:10 +03:00
|
|
|
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 {
|
2025-07-27 19:02:05 +03:00
|
|
|
if err := s.kv.Delete(context.Background(), key); err != nil {
|
2025-07-21 17:16:10 +03:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|