-
Notifications
You must be signed in to change notification settings - Fork 785
/
vault.go
328 lines (292 loc) · 9.84 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package vault
import (
"fmt"
"github.com/jenkins-x/jx/pkg/log"
"github.com/banzaicloud/bank-vaults/operator/pkg/apis/vault/v1alpha1"
"github.com/banzaicloud/bank-vaults/operator/pkg/client/clientset/versioned"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/kube/cluster"
"github.com/jenkins-x/jx/pkg/kube/serviceaccount"
"github.com/jenkins-x/jx/pkg/kube/services"
"github.com/jenkins-x/jx/pkg/vault"
"github.com/pkg/errors"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
const (
BankVaultsOperatorImage = "banzaicloud/vault-operator"
BankVaultsImage = "banzaicloud/bank-vaults"
BankVaultsImageTag = "0.4.7"
defaultNumVaults = 2
vaultImage = "vault"
vaultImageTag = "0.11.6"
gcpServiceAccountEnv = "GOOGLE_APPLICATION_CREDENTIALS"
gcpServiceAccountPath = "/etc/gcp/service-account.json"
vaultAuthName = "auth"
vaultAuthType = "kubernetes"
vaultAuthTTL = "1h"
vaultAuthSaSuffix = "auth-sa"
vaultRoleName = "vault-auth"
)
// Vault stores some details of a Vault resource
type Vault struct {
Name string
Namespace string
URL string
AuthServiceAccountName string
}
// GCPConfig keeps the configuration for Google Cloud
type GCPConfig struct {
ProjectId string
KmsKeyring string
KmsKey string
KmsLocation string
GcsBucket string
}
// GCSConfig Google Cloud Storage config for Vault backend
type GCSConfig struct {
Bucket string `json:"bucket"`
HaEnabled string `json:"ha_enabled"`
}
// VaultAuths list of vault authentications
type VaultAuths []VaultAuth
// VaultAuth vault auth configuration
type VaultAuth struct {
Roles []VaultRole `json:"roles"`
Type string `json:"type"`
}
// VaultRole role configuration for VaultAuth
type VaultRole struct {
BoundServiceAccountNames string `json:"bound_service_account_names"`
BoundServiceAccountNamespaces string `json:"bound_service_account_namespaces"`
Name string `json:"name"`
Policies string `json:"policies"`
TTL string `json:"ttl"`
}
// VaultPolicies list of vault policies
type VaultPolicies []VaultPolicy
// VaultPolicy vault policy
type VaultPolicy struct {
Name string `json:"name"`
Rules string `json:"rules"`
}
// Tcp address for vault server
type Tcp struct {
Address string `json:"address"`
TlsDisable bool `json:"tls_disable"`
}
// Listener vault server listener
type Listener struct {
Tcp Tcp `json:"tcp"`
}
// Telemetry address for telemetry server
type Telemetry struct {
StatsdAddress string `json:"statsd_address"`
}
// Storage configuration for Vault storage
type Storage struct {
GCS GCSConfig `json:"gcs"`
}
// SystemVaultName returns the name of the system vault based on the cluster name
func SystemVaultName(kuber kube.Kuber) (string, error) {
clusterName, err := cluster.ShortName(kuber)
if err != nil {
return "", err
}
return SystemVaultNameForCluster(clusterName), nil
}
// SystemVaultNameForCluster returns the system vault name from a given cluster name
func SystemVaultNameForCluster(clusterName string) string {
shortClusterName := cluster.ShortClusterName(clusterName)
fullName := fmt.Sprintf("%s-%s", vault.SystemVaultNamePrefix, shortClusterName)
return cluster.ShortNameN(fullName, 22)
}
// CreateVault creates a new vault backed by GCP KMS and storage
func CreateVault(kubeClient kubernetes.Interface, vaultOperatorClient versioned.Interface, name string, ns string,
gcpServiceAccountSecretName string, gcpConfig *GCPConfig, authServiceAccount string,
authServiceAccountNamespace string, secretsPathPrefix string) error {
err := createVaultServiceAccount(kubeClient, ns, name)
if err != nil {
return errors.Wrapf(err, "creating the vault service account '%s'", name)
}
err = ensureVaultRoleBinding(kubeClient, ns, vaultRoleName, name, name)
if err != nil {
return errors.Wrapf(err, "ensuring vault cluster role binding '%s' is created", name)
}
if secretsPathPrefix == "" {
secretsPathPrefix = vault.DefaultSecretsPathPrefix
}
pathRule := &vault.PathRule{
Path: []vault.PathPolicy{{
Prefix: secretsPathPrefix,
Capabilities: vault.DefaultSecretsCapabiltities,
}},
}
vaultRule, err := pathRule.String()
if err != nil {
return errors.Wrap(err, "encoding the policies for secret path")
}
vault := &v1alpha1.Vault{
TypeMeta: metav1.TypeMeta{
Kind: "Vault",
APIVersion: "vault.banzaicloud.com/v1alpha1",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: ns,
},
Spec: v1alpha1.VaultSpec{
Size: defaultNumVaults,
Image: vaultImage + ":" + vaultImageTag,
BankVaultsImage: BankVaultsImage + ":" + BankVaultsImageTag,
ServiceType: string(v1.ServiceTypeClusterIP),
ServiceAccount: name,
Config: map[string]interface{}{
"api_addr": fmt.Sprintf("http://%s.%s:8200", name, ns),
"disable_clustering": true,
"listener": Listener{
Tcp: Tcp{
Address: "0.0.0.0:8200",
TlsDisable: true,
},
},
"storage": Storage{
GCS: GCSConfig{
Bucket: gcpConfig.GcsBucket,
HaEnabled: "true",
},
},
"telemetry": Telemetry{
StatsdAddress: "localhost:9125",
},
"ui": true,
},
ExternalConfig: map[string]interface{}{
vaultAuthName: []VaultAuth{
{
Roles: []VaultRole{
{
BoundServiceAccountNames: authServiceAccount,
BoundServiceAccountNamespaces: authServiceAccountNamespace,
Name: authServiceAccount,
Policies: vault.PathRulesName,
TTL: vaultAuthTTL,
},
},
Type: vaultAuthType,
},
},
vault.PoliciesName: []VaultPolicy{
{
Name: vault.PathRulesName,
Rules: vaultRule,
},
},
},
UnsealConfig: v1alpha1.UnsealConfig{
Google: &v1alpha1.GoogleUnsealConfig{
KMSKeyRing: gcpConfig.KmsKeyring,
KMSCryptoKey: gcpConfig.KmsKey,
KMSLocation: gcpConfig.KmsLocation,
KMSProject: gcpConfig.ProjectId,
StorageBucket: gcpConfig.GcsBucket,
},
},
CredentialsConfig: v1alpha1.CredentialsConfig{
Env: gcpServiceAccountEnv,
Path: gcpServiceAccountPath,
SecretName: gcpServiceAccountSecretName,
},
},
}
_, err = vaultOperatorClient.Vault().Vaults(ns).Create(vault)
return err
}
func createVaultServiceAccount(client kubernetes.Interface, namespace string, name string) error {
_, err := serviceaccount.CreateServiceAccount(client, namespace, name)
if err != nil {
return errors.Wrap(err, "creating vault service account")
}
return nil
}
func ensureVaultRoleBinding(client kubernetes.Interface, namespace string, roleName string,
roleBindingName string, serviceAccount string) error {
apiGroups := []string{"authentication.k8s.io"}
resources := []string{"tokenreviews"}
verbs := []string{"*"}
found := kube.IsClusterRole(client, roleName)
if found {
err := kube.DeleteClusterRole(client, roleName)
if err != nil {
return errors.Wrapf(err, "deleting the existing cluster role '%s'", roleName)
}
}
err := kube.CreateClusterRole(client, namespace, roleName, apiGroups, resources, verbs)
if err != nil {
return errors.Wrapf(err, "creating the cluster role '%s' for vault", roleName)
}
found = kube.IsClusterRoleBinding(client, roleBindingName)
if found {
err := kube.DeleteClusterRoleBinding(client, roleBindingName)
if err != nil {
return errors.Wrapf(err, "deleting the existing cluster role binding '%s'", roleBindingName)
}
}
err = kube.CreateClusterRoleBinding(client, namespace, roleBindingName, serviceAccount, roleName)
if err != nil {
return errors.Wrapf(err, "creating the cluster role binding '%s' for vault", roleBindingName)
}
return nil
}
// FindVault checks if a vault is available
func FindVault(vaultOperatorClient versioned.Interface, name string, ns string) bool {
_, err := GetVault(vaultOperatorClient, name, ns)
if err != nil {
log.Warnf("could not find vault %s in namespace %s due to: %s\n", name, ns, err.Error())
return false
}
return true
}
// GetVault gets a specific vault
func GetVault(vaultOperatorClient versioned.Interface, name string, ns string) (*v1alpha1.Vault, error) {
return vaultOperatorClient.Vault().Vaults(ns).Get(name, metav1.GetOptions{})
}
// GetVaults returns all vaults available in a given namespaces
func GetVaults(client kubernetes.Interface, vaultOperatorClient versioned.Interface, ns string) ([]*Vault, error) {
vaultList, err := vaultOperatorClient.Vault().Vaults(ns).List(metav1.ListOptions{})
if err != nil {
return nil, errors.Wrapf(err, "listing vaults in namespace '%s'", ns)
}
vaults := []*Vault{}
for _, v := range vaultList.Items {
vaultName := v.Name
vaultAuthSaName := GetAuthSaName(v)
vaultURL, err := services.FindServiceURL(client, ns, vaultName)
if err != nil {
vaultURL = ""
}
vault := Vault{
Name: vaultName,
Namespace: ns,
URL: vaultURL,
AuthServiceAccountName: vaultAuthSaName,
}
vaults = append(vaults, &vault)
}
return vaults, nil
}
// DeleteVault delete a Vault resource
func DeleteVault(vaultOperatorClient versioned.Interface, name string, ns string) error {
return vaultOperatorClient.Vault().Vaults(ns).Delete(name, &metav1.DeleteOptions{})
}
// GetAuthSaName gets the Auth Service Account name for the vault
func GetAuthSaName(vault v1alpha1.Vault) string {
// This is nasty, but the ExternalConfig member of VaultSpec is just defined as a map[string]interface{} :-(
authArray := vault.Spec.ExternalConfig["auth"]
authObject := authArray.([]interface{})[0]
roleArray := authObject.(map[string]interface{})["roles"]
roleObject := roleArray.([]interface{})[0]
name := roleObject.(map[string]interface{})["name"]
return name.(string)
}