-
Notifications
You must be signed in to change notification settings - Fork 27
/
client.go
253 lines (206 loc) · 7.17 KB
/
client.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package vault
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault-lambda-extension/internal/config"
)
const (
tokenExpiryGracePeriodEnv = "VAULT_TOKEN_EXPIRY_GRACE_PERIOD"
defaultTokenExpiryGracePeriod = 10 * time.Second
)
// Client holds api.Client and handles state required to renew tokens and re-auth as required.
type Client struct {
Name string
Version string
mtx sync.Mutex
VaultClient *api.Client
VaultConfig *api.Config
logger hclog.Logger
stsSvc *sts.STS
authConfig config.AuthConfig
// Token refresh/renew data.
tokenExpiryGracePeriod time.Duration
tokenExpiry time.Time
tokenTTL time.Duration
tokenRenewable bool
}
// NewClient uses the AWS IAM auth method configured in a Vault cluster to
// authenticate the execution role and create a Vault API client.
func NewClient(name, version string, logger hclog.Logger, vaultConfig *api.Config, authConfig config.AuthConfig, awsSes *session.Session) (*Client, error) {
vaultClient, err := api.NewClient(vaultConfig)
if err != nil {
return nil, fmt.Errorf("error making extension: %w", err)
}
expiryGracePeriod, err := parseTokenExpiryGracePeriod()
if err != nil {
return nil, err
}
client := &Client{
VaultClient: vaultClient,
VaultConfig: vaultConfig,
Name: name,
Version: version,
logger: logger,
stsSvc: sts.New(awsSes),
authConfig: authConfig,
tokenExpiryGracePeriod: expiryGracePeriod,
}
return client, nil
}
// Token synchronously renews/re-auths as required and returns a Vault token.
func (c *Client) Token(ctx context.Context) (string, error) {
start := time.Now()
c.logger.Debug("fetching token")
c.mtx.Lock()
defer c.mtx.Unlock()
if c.expired() {
c.logger.Debug("authenticating to Vault")
err := c.login(ctx)
if err != nil {
return "", err
}
} else if c.shouldRenew() {
// Renew but don't retry or bail on errors, just best effort.
c.logger.Debug("renewing Vault token")
err := c.renew()
if err != nil {
c.logger.Error("failed to renew token but attempting to continue", "error", err)
}
}
c.logger.Debug(fmt.Sprintf("fetched token in %v", time.Since(start)))
return c.VaultClient.Token(), nil
}
// login authenticates to Vault using IAM auth, and sets the client's token.
func (c *Client) login(ctx context.Context) error {
authConfig := config.AuthConfigFromEnv()
roleToAssumeArn := authConfig.AssumedRoleArn
stsSvc := c.stsSvc
/* If passing in a role (through VAULT_ASSUMED_ROLE_ARN enviornment variable)
to be assumed for Vault authentication, use it instead of the function execution role */
if roleToAssumeArn != "" {
c.logger.Debug(fmt.Sprintf("Trying to assume role with arn of %s to authenticate with Vault", roleToAssumeArn))
sessionName := "vault_auth"
result, err := c.stsSvc.AssumeRole(&sts.AssumeRoleInput{
RoleArn: &roleToAssumeArn,
RoleSessionName: &sessionName,
})
if err != nil {
return fmt.Errorf("failed to assume role with arn of %s %w", roleToAssumeArn, err)
}
c.logger.Debug(fmt.Sprintf("Assumed role successfully with token expiration time: %s ", result.Credentials.Expiration.String()))
var ses *session.Session
if authConfig.STSEndpointRegion != "" {
ses = session.Must(session.NewSession(&aws.Config{
Region: aws.String(authConfig.STSEndpointRegion),
STSRegionalEndpoint: endpoints.RegionalSTSEndpoint,
Credentials: credentials.NewStaticCredentials(*result.Credentials.AccessKeyId, *result.Credentials.SecretAccessKey, *result.Credentials.SessionToken),
}))
} else {
ses = session.Must(session.NewSession(&aws.Config{
Credentials: credentials.NewStaticCredentials(*result.Credentials.AccessKeyId, *result.Credentials.SecretAccessKey, *result.Credentials.SessionToken),
}))
}
stsSvc = sts.New(ses)
}
// ignore out
req, _ := stsSvc.GetCallerIdentityRequest(&sts.GetCallerIdentityInput{})
req.SetContext(ctx)
if c.authConfig.IAMServerID != "" {
req.HTTPRequest.Header.Add("X-Vault-AWS-IAM-Server-ID", c.authConfig.IAMServerID)
}
if signErr := req.Sign(); signErr != nil {
return signErr
}
headers, err := json.Marshal(req.HTTPRequest.Header)
if err != nil {
return err
}
body, err := io.ReadAll(req.HTTPRequest.Body)
if err != nil {
return err
}
d := make(map[string]interface{})
d["iam_http_request_method"] = req.HTTPRequest.Method
d["iam_request_url"] = base64.StdEncoding.EncodeToString([]byte(req.HTTPRequest.URL.String()))
d["iam_request_headers"] = base64.StdEncoding.EncodeToString(headers)
d["iam_request_body"] = base64.StdEncoding.EncodeToString(body)
d["role"] = c.authConfig.Role
secret, err := c.VaultClient.Logical().Write(fmt.Sprintf("auth/%s/login", c.authConfig.Provider), d)
if err != nil {
return err
}
if secret == nil {
return fmt.Errorf("got no response from the %s authentication provider", c.authConfig.Provider)
}
token, err := secret.TokenID()
if err != nil {
return fmt.Errorf("error reading token: %s", err)
}
c.VaultClient.SetToken(token)
return c.updateTokenMetadata(secret)
}
func (c *Client) renew() error {
secret, err := c.VaultClient.Auth().Token().RenewSelf(int(c.tokenTTL.Seconds()))
if err != nil {
return err
}
return c.updateTokenMetadata(secret)
}
// Stores metadata about token lease that informs when to re-auth or renew.
func (c *Client) updateTokenMetadata(secret *api.Secret) error {
var err error
c.tokenTTL, err = secret.TokenTTL()
if err != nil {
return err
}
c.tokenExpiry = time.Now().Add(c.tokenTTL)
c.tokenRenewable, err = secret.TokenIsRenewable()
if err != nil {
return err
}
return nil
}
// Returns true if current time is after tokenExpiry, or within 10s.
func (c *Client) expired() bool {
return time.Now().Add(c.tokenExpiryGracePeriod).After(c.tokenExpiry)
}
// Returns true if tokenExpiry time is in less than 20% of tokenTTL.
func (c *Client) shouldRenew() bool {
remaining := time.Until(c.tokenExpiry)
return c.tokenRenewable && remaining.Nanoseconds() < c.tokenTTL.Nanoseconds()/5
}
func parseTokenExpiryGracePeriod() (time.Duration, error) {
var err error
expiryGracePeriod := defaultTokenExpiryGracePeriod
expiryGracePeriodString := strings.TrimSpace(os.Getenv(tokenExpiryGracePeriodEnv))
if expiryGracePeriodString != "" {
expiryGracePeriod, err = time.ParseDuration(expiryGracePeriodString)
if err != nil {
return 0, fmt.Errorf("unable to parse %q environment variable as a valid duration: %w", tokenExpiryGracePeriodEnv, err)
}
}
return expiryGracePeriod, nil
}
// UserAgentRequestCallback takes a function that returns a user agent string and will invoke that function to set
// the user agent string on the request.
func UserAgentRequestCallback(agentFunc func(request *api.Request) string) api.RequestCallback {
return func(req *api.Request) {
req.Headers.Set("User-Agent", agentFunc(req))
}
}