github.com/kubri/kubri@v0.5.1-0.20240317001612-bda2aaef967e/pkg/secret/secret.go (about) 1 package secret 2 3 import ( 4 "errors" 5 "os" 6 "path/filepath" 7 "strings" 8 ) 9 10 var ( 11 ErrKeyNotFound = errors.New("key not found") 12 ErrKeyExists = errors.New("key already exists") 13 ErrEnvironment = errors.New("key set via environment variable") 14 ) 15 16 func Get(key string) ([]byte, error) { 17 if data := getEnv(key); data != "" { 18 return []byte(data), nil 19 } 20 21 if path := getPathEnv(key); path != "" { 22 return os.ReadFile(path) 23 } 24 25 path := filepath.Join(dir(), key) 26 if _, err := os.Stat(path); err == nil { 27 return os.ReadFile(path) 28 } 29 30 return nil, ErrKeyNotFound 31 } 32 33 func Put(key string, data []byte) error { 34 if data := getEnv(key); data != "" { 35 return ErrEnvironment 36 } 37 38 if path := getPathEnv(key); path != "" { 39 if _, err := os.Stat(path); !os.IsNotExist(err) { 40 return ErrKeyExists 41 } 42 return os.WriteFile(path, data, 0o600) 43 } 44 45 path := filepath.Join(dir(), key) 46 if _, err := os.Stat(path); !os.IsNotExist(err) { 47 return ErrKeyExists 48 } 49 return os.WriteFile(path, data, 0o600) 50 } 51 52 func Delete(key string) error { 53 if data := getEnv(key); data != "" { 54 return ErrEnvironment 55 } 56 57 if path := getPathEnv(key); path != "" { 58 return os.Remove(path) 59 } 60 61 path := filepath.Join(dir(), key) 62 if _, err := os.Stat(path); err == nil { 63 return os.Remove(path) 64 } 65 66 return ErrKeyNotFound 67 } 68 69 func getEnv(key string) string { 70 return os.Getenv("KUBRI_" + strings.ToUpper(key)) 71 } 72 73 func getPathEnv(key string) string { 74 return os.Getenv("KUBRI_" + strings.ToUpper(key) + "_PATH") 75 } 76 77 func dir() string { 78 if dir := os.Getenv("KUBRI_PATH"); dir != "" { 79 return dir 80 } 81 dir, _ := os.UserConfigDir() 82 dir = filepath.Join(dir, "kubri") 83 _ = os.MkdirAll(dir, os.ModePerm) 84 return dir 85 }