/
vault_config.go
95 lines (79 loc) · 1.95 KB
/
vault_config.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
package types
import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/hashicorp/vault/api"
)
type VaultConfig struct {
Client *api.Client
Address string
TLS TLSConfig
AppRole AppRoleConfig
Secrets SecretConfig
}
func NewVaultConfig() *VaultConfig {
vc := &VaultConfig{}
return vc
}
func (vc *VaultConfig) MakeClient() (*api.Client, error) {
config := api.DefaultConfig()
config.ConfigureTLS(&api.TLSConfig{
CACert: vc.TLS.CAFile,
ClientCert: vc.TLS.CertFile,
ClientKey: vc.TLS.KeyFile,
Insecure: vc.TLS.Insecure,
})
config.Address = vc.Address
if client, err := api.NewClient(config); err != nil {
return nil, err
} else {
vc.Client = client
return client, nil
}
}
func (vc *VaultConfig) Login() (*api.Secret, error) {
var vaultLogin api.Secret
lResp, err := vc.DoRequest("POST", fmt.Sprintf("/v1/auth/%s/login", vc.AppRole.Path),
map[string]interface{}{"role_id": vc.AppRole.RoleID, "secret_id": vc.AppRole.SecretID})
if err != nil {
return &vaultLogin, err
}
lBody, _ := ioutil.ReadAll(lResp.Body)
err = json.Unmarshal(lBody, &vaultLogin)
if err != nil {
return &vaultLogin, err
}
if vaultLogin.Auth != nil && len(vaultLogin.Auth.ClientToken) > 0 {
vc.Client.SetToken(vaultLogin.Auth.ClientToken)
r, err := vc.Client.NewRenewer(&api.RenewerInput{
Secret: &vaultLogin,
})
if err != nil {
return nil, err
}
go r.Renew()
}
return &vaultLogin, nil
}
func (vc *VaultConfig) DoRequest(method string, path string, body interface{}) (*http.Response, error) {
if vc.Client == nil {
_, err := vc.MakeClient()
if err != nil {
return nil, err
}
}
client := &http.Client{}
trIgnore := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
createRequest := vc.Client.NewRequest(method, path)
createRequest.SetJSONBody(body)
request, _ := createRequest.ToHTTP()
if vc.TLS.Insecure {
client.Transport = trIgnore
}
return client.Do(request)
}