/
vault.go
280 lines (229 loc) · 7.91 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
package vault
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/go-acme/lego/v4/acme"
"github.com/go-acme/lego/v4/registration"
"github.com/hashicorp/vault/api"
vault "github.com/hashicorp/vault/api"
"github.com/rs/zerolog/log"
"github.com/soerenschneider/acmevault/internal/config"
"github.com/soerenschneider/acmevault/internal/metrics"
"github.com/soerenschneider/acmevault/pkg/certstorage"
)
const (
timeout = 10 * time.Second
backoffRetries = 5
)
type Auth interface {
Login(ctx context.Context, client *api.Client) (*api.Secret, error)
Logout(ctx context.Context, client *api.Client) error
}
type VaultBackend struct {
client *api.Client
conf config.VaultConfig
basePath string
auth Auth
}
func NewVaultBackend(vaultConfig config.VaultConfig, auth Auth) (*VaultBackend, error) {
if auth == nil {
return nil, errors.New("empty auth provided")
}
config := &api.Config{
Timeout: timeout,
MaxRetries: backoffRetries,
Address: vaultConfig.Addr,
}
client, err := api.NewClient(config)
if err != nil {
return nil, fmt.Errorf("couldn't build client: %v", err)
}
vault := &VaultBackend{
auth: auth,
client: client,
conf: vaultConfig,
basePath: fmt.Sprintf("acmevault/%s", vaultConfig.PathPrefix),
//basePath: fmt.Sprintf("%s/data/%s", vaultConfig.Kv2MountPath, vaultConfig.PathPrefix),
}
return vault, nil
}
func (vault *VaultBackend) WriteCertificate(resource *certstorage.AcmeCertificate) error {
// save private key
privateKey := resource.PrivateKey
resource.PrivateKey = nil
data := certstorage.CertToMap(resource)
certPath := vault.getCertDataPath(resource.Domain)
err := vault.writeKv2Secret(certPath, data)
if err != nil {
return fmt.Errorf("could not write certificate data for %s: %v", resource.Domain, err)
}
data = map[string]interface{}{
"private_key": privateKey,
}
secretPath := vault.getSecretDataPath(resource.Domain)
err = vault.writeKv2Secret(secretPath, data)
if err != nil {
return fmt.Errorf("could not write secrete data for domain %s: %v", resource.Domain, err)
}
return nil
}
func (vault *VaultBackend) ReadPublicCertificateData(domain string) (*certstorage.AcmeCertificate, error) {
certPath := vault.getCertDataPath(domain)
data, err := vault.readKv2Secret(certPath)
if err != nil {
return nil, fmt.Errorf("could not readKv2Secret public cert data from vault for domain %s: %v", domain, err)
}
return certstorage.MapToCert(data)
}
func (vault *VaultBackend) ReadFullCertificateData(domain string) (*certstorage.AcmeCertificate, error) {
cert, err := vault.ReadPublicCertificateData(domain)
if err != nil {
return nil, err
}
privateKeyPath := vault.getSecretDataPath(domain)
data, err := vault.readKv2Secret(privateKeyPath)
if err != nil {
return nil, fmt.Errorf("could not readKv2Secret private data from vault for domain %s: %v", domain, err)
}
_, ok := data["private_key"]
if !ok {
return nil, fmt.Errorf("successfully readKv2Secret secret from vault but no private key data avaialble for domain: %s", domain)
}
privRaw := fmt.Sprintf("%s", data["private_key"])
priv, err := base64.StdEncoding.DecodeString(privRaw)
if err != nil {
return nil, fmt.Errorf("can not decode private key: %v", err)
}
cert.PrivateKey = priv
return cert, err
}
func (vault *VaultBackend) WriteAccount(acmeRegistration certstorage.AcmeAccount) error {
jsonBytes, err := json.MarshalIndent(acmeRegistration.Registration.Body, "", "\t")
if err != nil {
return err
}
key, _ := certstorage.ConvertToPem(acmeRegistration.Key)
data := map[string]interface{}{
certstorage.VaultAccountKeyUri: acmeRegistration.Registration.URI,
certstorage.VaultAccountKeyAccount: jsonBytes,
certstorage.VaultAccountKeyKey: key,
certstorage.VaultAccountKeyEmail: acmeRegistration.Email,
}
accountPath := vault.getAccountPath(acmeRegistration.Email)
err = vault.writeKv2Secret(accountPath, data)
return err
}
func (vault *VaultBackend) ReadAccount(hash string) (*certstorage.AcmeAccount, error) {
accountPath := vault.getAccountPath(hash)
data, err := vault.readKv2Secret(accountPath)
if err != nil {
return nil, fmt.Errorf("could not readKv2Secret account from vault: %w", translateError(err))
}
var account acme.Account
accountData := fmt.Sprintf("%v", data[certstorage.VaultAccountKeyAccount])
accountJson, err := base64.StdEncoding.DecodeString(accountData)
if err != nil {
return nil, fmt.Errorf("couldn't decode string: %v", err)
}
if err = json.Unmarshal(accountJson, &account); err != nil {
return nil, fmt.Errorf("couldn't unmarshal json: %v", err)
}
registration := ®istration.Resource{
URI: fmt.Sprintf("%s", data[certstorage.VaultAccountKeyUri]),
Body: account,
}
decodedKey, err := certstorage.FromPem([]byte(fmt.Sprintf("%v", data[certstorage.VaultAccountKeyKey])))
if err != nil {
return nil, fmt.Errorf("can not decode pem private key: %vault", err)
}
conf := certstorage.AcmeAccount{
Email: fmt.Sprintf("%v", data[certstorage.VaultAccountKeyEmail]),
Key: decodedKey,
Registration: registration,
}
return &conf, nil
}
func (vault *VaultBackend) Authenticate() error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
secret, err := vault.client.Auth().Login(ctx, vault.auth)
if err == nil && secret.Auth.LeaseDuration != 0 {
log.Info().Msgf("Login token valid for %d seconds (until %v)", secret.Auth.LeaseDuration, time.Now().Add(time.Second*time.Duration(secret.Auth.LeaseDuration)))
}
return err
}
func (vault *VaultBackend) Logout() error {
return vault.auth.Logout(context.Background(), vault.client)
}
func (vault *VaultBackend) ReadAwsCredentials() (aws.Credentials, error) {
metrics.AwsDynCredentialsRequested.Inc()
path := vault.getAwsCredentialsPath()
secret, err := vault.client.Logical().Read(path)
if err != nil {
metrics.AwsDynCredentialsRequestErrors.Inc()
return aws.Credentials{}, fmt.Errorf("could not gather dynamic credentials: %v", err)
}
return mapVaultAwsCredentialResponse(secret)
}
func (vault *VaultBackend) writeKv2Secret(secretPath string, data map[string]interface{}) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
_, err := vault.client.KVv2(vault.conf.Kv2MountPath).Put(ctx, secretPath, data)
return err
}
func (vault *VaultBackend) readKv2Secret(path string) (map[string]interface{}, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
secret, err := vault.client.KVv2(vault.conf.Kv2MountPath).Get(ctx, path)
if err != nil {
return nil, translateError(err)
}
if secret == nil {
return nil, certstorage.ErrNotFound
}
return secret.Data, nil
}
func translateError(err error) error {
if err == nil {
return nil
}
if errors.Is(err, vault.ErrSecretNotFound) {
return certstorage.ErrNotFound
}
vaultErr, ok := err.(*vault.ResponseError)
if !ok {
return err
}
if vaultErr.StatusCode == 404 {
return certstorage.ErrNotFound
}
if vaultErr.StatusCode == 403 {
return certstorage.ErrPermissionDenied
}
return err
}
func (vault *VaultBackend) formatDomain(domain string) string {
if len(vault.conf.DomainPathFormat) == 0 {
return domain
}
return fmt.Sprintf(vault.conf.DomainPathFormat, domain)
}
func (vault *VaultBackend) getAwsCredentialsPath() string {
return fmt.Sprintf("%s/creds/%s", vault.conf.AwsMountPath, vault.conf.AwsRole)
}
func (vault *VaultBackend) getAccountPath(hash string) string {
return fmt.Sprintf("%s/server/account/%s", vault.basePath, hash)
}
func (vault *VaultBackend) getCertDataPath(domain string) string {
domainFormatted := vault.formatDomain(domain)
return fmt.Sprintf("%s/client/%s/certificate", vault.basePath, domainFormatted)
}
func (vault *VaultBackend) getSecretDataPath(domain string) string {
domainFormatted := vault.formatDomain(domain)
return fmt.Sprintf("%s/client/%s/privatekey", vault.basePath, domainFormatted)
}