-
Notifications
You must be signed in to change notification settings - Fork 0
/
hcvault.go
98 lines (88 loc) · 1.69 KB
/
hcvault.go
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
92
93
94
95
96
97
98
package cvault
import (
"crypto/tls"
"crypto/x509"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/hashicorp/hcl/v2/hclsimple"
)
type inferFn = func() string
func InferVaultToken() string {
fn := combineInfers(
inferFromEnv,
inferFromHelper,
inferFromHomeToken,
)
return fn()
}
func combineInfers(fns ...inferFn) inferFn {
return func() string {
for _, fn := range fns {
if token := fn(); token != "" {
return token
}
}
return ""
}
}
func inferFromEnv() string {
return os.Getenv("VAULT_TOKEN")
}
func inferFromHomeToken() string {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
tokenPath := filepath.Join(home, ".vault-token")
fileToken, err := os.ReadFile(tokenPath)
if err != nil {
return ""
}
return string(fileToken)
}
func inferFromHelper() string {
cfgFile := func() string {
if f := os.Getenv("VAULT_CONFIG_FILE"); f != "" {
return f
}
home, _ := os.UserHomeDir()
return filepath.Join(home, ".vault")
}()
cfgData, err := os.ReadFile(cfgFile)
if err != nil {
return ""
}
config := struct {
TokenHelper string `hcl:"token_helper"`
}{}
if err := hclsimple.Decode("vault.hcl", cfgData, nil, &config); err != nil {
return ""
}
cmd := exec.Command(config.TokenHelper, "get")
out, err := cmd.Output()
if err != nil {
return ""
}
return strings.TrimSpace(string(out))
}
func InferVaultTlsConfig() (config *tls.Config) {
config = &tls.Config{}
caPath := os.Getenv("VAULT_CAPATH")
if caPath == "" {
return
}
pool, err := x509.SystemCertPool()
if err != nil {
return
}
certPem, err := ioutil.ReadFile(caPath)
if err != nil {
return
}
pool.AppendCertsFromPEM(certPem)
config.RootCAs = pool
return
}