-
Notifications
You must be signed in to change notification settings - Fork 1
/
kubernetes.go
108 lines (85 loc) · 2.53 KB
/
kubernetes.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
107
108
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
// location of k8s service account token
const tokenFilePath = "/var/run/secrets/kubernetes.io/serviceaccount/token"
// location of k8s namespace
const namespaceFilePath = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"
// get token service account token
func getK8SServiceAccountToken() (string, error) {
var token string
fileContent, err := ioutil.ReadFile(tokenFilePath)
if err != nil {
log.Fatal(err)
}
token = string([]byte(fileContent))
return token, nil
}
func getK8SServiceRole() (string, error) {
var token string
fileContent, err := ioutil.ReadFile(namespaceFilePath)
if err != nil {
log.Fatal(err)
}
token = string([]byte(fileContent))
return token, nil
}
// getVaultAuthToken - login at vault and retrive vault auth token
func getVaultAuthToken(vaultSecretURL, authToken, authRole string) (string, error) {
var token string
var parsedResponse map[string]interface{}
var requstPayload = []byte(fmt.Sprintf(`{"jwt": "%s", "role": "%s"}`, authToken, authRole))
vaultLoginURL, err := getVaultLoginURL(vaultSecretURL)
if err != nil {
return token, err
}
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: vaultSkipTLS}
client := &http.Client{
Timeout: time.Second * requestTimeout,
}
request, err := http.NewRequest("POST", vaultLoginURL, bytes.NewBuffer(requstPayload))
if err != nil {
return token, err
}
response, err := client.Do(request)
if err != nil {
return token, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return token, fmt.Errorf("vault response code: %d", response.StatusCode)
}
respBodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
return token, err
}
if err := json.Unmarshal(respBodyBytes, &parsedResponse); err != nil {
return token, err
}
token = parsedResponse["auth"].(map[string]interface{})["client_token"].(string)
return token, nil
}
func getK8SVaultToken(vaultSecretURL string) (string, error) {
var token string
serviceToken, err := getK8SServiceAccountToken()
if err != nil {
return token, fmt.Errorf("failed to get k8s service account token - %s", err)
}
serviceRole, err := getK8SServiceRole()
if err != nil {
return token, fmt.Errorf("failed to get k8s namespace - %s", err)
}
token, err = getVaultAuthToken(vaultSecretURL, serviceToken, serviceRole)
if err != nil {
return token, fmt.Errorf("failed to auth at vault - %s", err)
}
return token, nil
}