85 lines
2.0 KiB
Go
85 lines
2.0 KiB
Go
package secretstore
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"errors"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
type Store struct{ root string }
|
|
|
|
func New(root string) (*Store, error) {
|
|
root = strings.TrimSpace(root)
|
|
if root == "" {
|
|
return nil, errors.New("secret root is required")
|
|
}
|
|
if err := os.MkdirAll(root, 0700); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := os.Chmod(root, 0700); err != nil {
|
|
return nil, err
|
|
}
|
|
return &Store{root: root}, nil
|
|
}
|
|
func (s *Store) Put(kind, value string) (string, error) {
|
|
kind = strings.TrimSpace(kind)
|
|
value = strings.TrimSpace(value)
|
|
if kind == "" || value == "" {
|
|
return "", errors.New("secret kind and value are required")
|
|
}
|
|
if strings.ContainsAny(kind, "/\\") || kind == "." || kind == ".." {
|
|
return "", errors.New("invalid secret kind")
|
|
}
|
|
b := make([]byte, 16)
|
|
if _, err := rand.Read(b); err != nil {
|
|
return "", err
|
|
}
|
|
ref := kind + "-" + hex.EncodeToString(b)
|
|
tmp, err := os.CreateTemp(s.root, ".new-")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
tmpName := tmp.Name()
|
|
defer os.Remove(tmpName)
|
|
if err = tmp.Chmod(0600); err == nil {
|
|
_, err = tmp.WriteString(value)
|
|
}
|
|
if err == nil {
|
|
err = tmp.Sync()
|
|
}
|
|
closeErr := tmp.Close()
|
|
if err == nil {
|
|
err = closeErr
|
|
}
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if err = os.Rename(tmpName, filepath.Join(s.root, ref)); err != nil {
|
|
return "", err
|
|
}
|
|
return ref, nil
|
|
}
|
|
func (s *Store) Get(ref string) (string, error) {
|
|
if ref == "" || filepath.Base(ref) != ref {
|
|
return "", errors.New("invalid secret reference")
|
|
}
|
|
b, err := os.ReadFile(filepath.Join(s.root, ref))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return string(b), nil
|
|
}
|
|
func (s *Store) Configured(ref string) bool {
|
|
_, err := os.Stat(filepath.Join(s.root, filepath.Base(ref)))
|
|
return ref != "" && filepath.Base(ref) == ref && err == nil
|
|
}
|
|
func (s *Store) Delete(ref string) error {
|
|
if ref == "" || filepath.Base(ref) != ref {
|
|
return errors.New("invalid secret reference")
|
|
}
|
|
return os.Remove(filepath.Join(s.root, ref))
|
|
}
|