This repository has been archived by the owner on Aug 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
vault.go
106 lines (86 loc) · 2.46 KB
/
vault.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
99
100
101
102
103
104
105
106
package main
import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"time"
)
const vaultSkipTLS = true
const requestTimeout = 10
const vaultAuthEndpoint = "/v1/auth/kubernetes/login"
// generate url to k8s login provider from VaultSecretURL
func getVaultLoginURL(URL string) (string, error) {
var vaultAuthURL string
parsedURL, err := url.Parse(URL)
if err != nil {
log.Fatal(err)
}
vaultAuthURL = fmt.Sprintf("%s://%s%s", parsedURL.Scheme, parsedURL.Host, vaultAuthEndpoint)
return vaultAuthURL, nil
}
// get secret from vault
func getVaultSecret(URL, authToken string) (string, error) {
var secrets string
var parsedResponse map[string]interface{}
var parsedResponseSecretData interface{}
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: vaultSkipTLS}
client := &http.Client{
Timeout: time.Second * requestTimeout,
}
request, err := http.NewRequest("GET", URL, nil)
if err != nil {
return secrets, err
}
request.Header.Add("X-Vault-Token", authToken)
response, err := client.Do(request)
if err != nil {
return secrets, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return secrets, fmt.Errorf("vault response code: %d", response.StatusCode)
}
respBodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
return secrets, err
}
if err := json.Unmarshal(respBodyBytes, &parsedResponse); err != nil {
return secrets, err
}
if parsedResponse["data"].(map[string]interface{})["metadata"] != nil {
// vault v2 secret
parsedResponseSecretData = parsedResponse["data"].(map[string]interface{})["data"]
} else {
// vault v1 secret
parsedResponseSecretData = parsedResponse["data"].(map[string]interface{})
}
// convert map of interface to JSON string
secretsJSON, err := json.Marshal(parsedResponseSecretData)
if err != nil {
return secrets, err
}
secrets = string(secretsJSON)
return secrets, nil
}
// get secret from vault
func vaultGetSecret(config applicationConfig) (string, error) {
vaultToken := config.VaultToken
var secrets string
var err error
// issue new vault token if it was not set from config
if config.VaultToken == "" {
vaultToken, err = getK8SVaultToken(config.VaultSecretURL)
if err != nil {
return secrets, err
}
}
secrets, err = getVaultSecret(config.VaultSecretURL, vaultToken)
if err != nil {
return secrets, fmt.Errorf("failed to retrive vault secrets - %s", err)
}
return secrets, nil
}