forked from Lucretius/vault_raft_snapshot_agent
/
agent.go
189 lines (168 loc) · 5 KB
/
agent.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
package snapshot_agent
import (
"context"
"errors"
"fmt"
"net/url"
"os"
"path"
"time"
"cloud.google.com/go/storage"
"github.com/Azure/azure-storage-blob-go/azblob"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
vaultApi "github.com/hashicorp/vault/api"
"github.com/wasilak/vault_raft_snapshot_agent/config"
"golang.org/x/exp/slog"
)
type Snapshotter struct {
API *vaultApi.Client
Uploader *s3manager.Uploader
S3Client *s3.S3
GCPBucket *storage.BucketHandle
AzureUploader azblob.ContainerURL
TokenExpiration time.Time
}
func NewSnapshotter(config *config.Configuration) (*Snapshotter, error) {
snapshotter := &Snapshotter{}
err := snapshotter.ConfigureVaultClient(config)
if err != nil {
return nil, err
}
if config.AWS.Bucket != "" {
err = snapshotter.ConfigureS3(config)
if err != nil {
return nil, err
}
}
if config.GCP.Bucket != "" {
err = snapshotter.ConfigureGCP(config)
if err != nil {
return nil, err
}
}
if config.Azure.ContainerName != "" {
err = snapshotter.ConfigureAzure(config)
if err != nil {
return nil, err
}
}
return snapshotter, nil
}
func (s *Snapshotter) ConfigureVaultClient(config *config.Configuration) error {
vaultConfig := vaultApi.DefaultConfig()
if config.Address != "" {
vaultConfig.Address = config.Address
}
tlsConfig := &vaultApi.TLSConfig{
Insecure: true,
}
vaultConfig.ConfigureTLS(tlsConfig)
api, err := vaultApi.NewClient(vaultConfig)
if err != nil {
return err
}
s.API = api
if config.VaultAuthMethod == "k8s" {
return s.SetClientTokenFromK8sAuth(config)
}
return s.SetClientTokenFromAppRole(config)
}
func (s *Snapshotter) SetClientTokenFromAppRole(config *config.Configuration) error {
data := map[string]interface{}{
"role_id": config.RoleID,
"secret_id": config.SecretID,
}
approle := "approle"
if config.Approle != "" {
approle = config.Approle
}
resp, err := s.API.Logical().Write("auth/"+approle+"/login", data)
if err != nil {
return fmt.Errorf("error logging into AppRole auth backend: %s", err)
}
s.API.SetToken(resp.Auth.ClientToken)
s.TokenExpiration = time.Now().Add(time.Duration((time.Second * time.Duration(resp.Auth.LeaseDuration)) / 2))
return nil
}
func (s *Snapshotter) SetClientTokenFromK8sAuth(config *config.Configuration) error {
if config.K8sAuthPath == "" || config.K8sAuthRole == "" {
return errors.New("missing k8s auth definitions")
}
jwt, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/token")
if err != nil {
return err
}
data := map[string]string{
"role": config.K8sAuthRole,
"jwt": string(jwt),
}
login := path.Clean("/v1/auth/" + config.K8sAuthPath + "/login")
req := s.API.NewRequest("POST", login)
req.SetJSONBody(data)
resp, err := s.API.RawRequest(req)
if err != nil {
return err
}
if respErr := resp.Error(); respErr != nil {
return respErr
}
var result vaultApi.Secret
if err := resp.DecodeJSON(&result); err != nil {
return err
}
s.API.SetToken(result.Auth.ClientToken)
s.TokenExpiration = time.Now().Add(time.Duration((time.Second * time.Duration(result.Auth.LeaseDuration)) / 2))
return nil
}
func (s *Snapshotter) ConfigureS3(config *config.Configuration) error {
awsConfig := &aws.Config{Region: aws.String(config.AWS.Region)}
if config.AWS.AccessKeyID != "" && config.AWS.SecretAccessKey != "" {
awsConfig.Credentials = credentials.NewStaticCredentials(config.AWS.AccessKeyID, config.AWS.SecretAccessKey, "")
}
if config.AWS.Endpoint != "" {
awsConfig.Endpoint = aws.String(config.AWS.Endpoint)
}
if !config.AWS.S3ForcePathStyle {
awsConfig.S3ForcePathStyle = aws.Bool(config.AWS.S3ForcePathStyle)
}
sess := session.Must(session.NewSession(awsConfig))
s.S3Client = s3.New(sess)
s.Uploader = s3manager.NewUploader(sess)
return nil
}
func (s *Snapshotter) ConfigureGCP(config *config.Configuration) error {
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
return err
}
s.GCPBucket = client.Bucket(config.GCP.Bucket)
return nil
}
func (s *Snapshotter) ConfigureAzure(config *config.Configuration) error {
accountName := config.Azure.AccountName
if os.Getenv("AZURE_STORAGE_ACCOUNT") != "" {
accountName = os.Getenv("AZURE_STORAGE_ACCOUNT")
}
accountKey := config.Azure.AccountKey
if os.Getenv("AZURE_STORAGE_ACCESS_KEY") != "" {
accountKey = os.Getenv("AZURE_STORAGE_ACCESS_KEY")
}
if len(accountName) == 0 || len(accountKey) == 0 {
return errors.New("invalid Azure configuration")
}
credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
slog.Error("Invalid credentials with error: " + err.Error())
panic(err)
}
p := azblob.NewPipeline(credential, azblob.PipelineOptions{})
URL, _ := url.Parse(
fmt.Sprintf("https://%s.blob.core.windows.net/%s", accountName, config.Azure.ContainerName))
s.AzureUploader = azblob.NewContainerURL(*URL, p)
return nil
}