-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaes_key.go
More file actions
91 lines (74 loc) · 1.88 KB
/
aes_key.go
File metadata and controls
91 lines (74 loc) · 1.88 KB
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
87
88
89
90
91
package vault
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/flowexec/vault/crypto"
)
type KeyResolver struct {
sources []KeySource
}
func NewKeyResolver(sources []KeySource) *KeyResolver {
if len(sources) == 0 {
sources = []KeySource{
{Type: envSource, Name: DefaultVaultKeyEnv},
}
}
return &KeyResolver{
sources: sources,
}
}
func (r *KeyResolver) ResolveKeys() ([]string, error) {
var keys []string
for _, source := range r.sources {
switch source.Type {
case envSource:
if key := r.fromEnvironment(source.Name); key != "" {
keys = append(keys, key)
}
case fileSource:
if key, err := r.fromFile(source.Path); err == nil && key != "" {
keys = append(keys, key)
}
}
}
if len(keys) == 0 {
return nil, fmt.Errorf("%w: no encryption keys found", ErrNoAccess)
}
return keys, nil
}
func (r *KeyResolver) TryDecrypt(encryptedData string) (string, string, error) {
keys, err := r.ResolveKeys()
if err != nil {
return "", "", err
}
for _, key := range keys {
decryptedData, err := crypto.DecryptValue(key, encryptedData)
if err != nil {
continue // try the next key
}
return decryptedData, key, nil
}
return "", "", fmt.Errorf("%w: failed to decrypt data with any available key", ErrDecryptionFailed)
}
func (r *KeyResolver) fromEnvironment(envVar string) string {
if envVar == "" {
envVar = DefaultVaultKeyEnv
}
return os.Getenv(envVar)
}
func (r *KeyResolver) fromFile(path string) (string, error) {
if path == "" {
return "", fmt.Errorf("key file path cannot be empty")
}
expandedPath, err := expandPath(path)
if err != nil {
return "", fmt.Errorf("failed to expand key file path %s: %w", path, err)
}
keyBytes, err := os.ReadFile(filepath.Clean(expandedPath))
if err != nil {
return "", fmt.Errorf("failed to read key file %s: %w", expandedPath, err)
}
return strings.TrimSpace(string(keyBytes)), nil
}