-
Notifications
You must be signed in to change notification settings - Fork 15
/
vault.go
174 lines (152 loc) · 4 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
package cke
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"net"
"net/http"
"net/url"
"time"
"github.com/cybozu-go/log"
vault "github.com/hashicorp/vault/api"
)
// CKESecret is the path of key-value secret engine for CKE.
const CKESecret = "cke/secrets"
// SSHSecret is the path of SSH private keys in Vault.
const SSHSecret = CKESecret + "/ssh"
// K8sSecret is the path of encryption keys used for Kubernetes Secrets.
const K8sSecret = CKESecret + "/k8s"
type anyMap = map[string]interface{}
// VaultConfig is data to store in etcd
type VaultConfig struct {
// Endpoint is the address of the Vault server.
Endpoint string `json:"endpoint"`
// CACert is x509 certificate in PEM format of the endpoint CA.
CACert string `json:"ca-cert"`
// RoleID is AppRole ID to login to Vault.
RoleID string `json:"role-id"`
// SecretID is AppRole secret to login to Vault.
SecretID string `json:"secret-id"`
}
// Validate validates the vault configuration
func (c *VaultConfig) Validate() error {
if len(c.Endpoint) == 0 {
return errors.New("endpoint is empty")
}
_, err := url.Parse(c.Endpoint)
if err != nil {
return err
}
if len(c.CACert) > 0 {
block, _ := pem.Decode([]byte(c.CACert))
if block == nil {
return errors.New("invalid PEM data")
}
_, err = x509.ParseCertificate(block.Bytes)
if err != nil {
return errors.New("invalid certificate")
}
}
if len(c.RoleID) == 0 {
return errors.New("role-id is empty")
}
if len(c.SecretID) == 0 {
return errors.New("secret-id is empty")
}
return nil
}
// VaultClient creates vault client.
// The client has logged-in to Vault using RoleID and SecretID in cfg.
func VaultClient(cfg *VaultConfig) (*vault.Client, *vault.Secret, error) {
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DisableKeepAlives: true,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConnsPerHost: -1,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
if len(cfg.CACert) > 0 {
cp := x509.NewCertPool()
if !cp.AppendCertsFromPEM([]byte(cfg.CACert)) {
return nil, nil, errors.New("invalid CA cert")
}
transport.TLSClientConfig = &tls.Config{
RootCAs: cp,
MinVersion: tls.VersionTLS12,
}
}
client, err := vault.NewClient(&vault.Config{
Address: cfg.Endpoint,
HttpClient: &http.Client{
Transport: transport,
},
})
if err != nil {
log.Error("failed to connect to vault", anyMap{
log.FnError: err,
"endpoint": cfg.Endpoint,
})
return nil, nil, err
}
secret, err := client.Logical().Write("auth/approle/login", anyMap{
"role_id": cfg.RoleID,
"secret_id": cfg.SecretID,
})
if err != nil {
log.Error("failed to login to vault", anyMap{
log.FnError: err,
"endpoint": cfg.Endpoint,
})
return nil, nil, err
}
// If cke accesses while vault is initializing, then vault returns io.EOF and the secret is nil
if secret == nil {
log.Error("failed to get secret", anyMap{
"endpoint": cfg.Endpoint,
})
return nil, nil, errors.New("failed to get secret")
}
client.SetToken(secret.Auth.ClientToken)
return client, secret, nil
}
// ConnectVault unmarshal data to get VaultConfig and call VaultClient
// with it. It then start renewing login token for long-running process.
func ConnectVault(ctx context.Context, data []byte) error {
c := new(VaultConfig)
err := json.Unmarshal(data, c)
if err != nil {
return err
}
client, secret, err := VaultClient(c)
if err != nil {
return err
}
watcher, err := client.NewLifetimeWatcher(&vault.LifetimeWatcherInput{
Secret: secret,
RenewBehavior: vault.RenewBehaviorIgnoreErrors,
})
if err != nil {
log.Error("failed to create vault renewer", anyMap{
log.FnError: err,
"endpoint": c.Endpoint,
})
return err
}
go watcher.Start()
go func() {
<-ctx.Done()
watcher.Stop()
}()
setVaultClient(client)
log.Info("connected to vault", anyMap{
"endpoint": c.Endpoint,
})
return nil
}