forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
252 lines (221 loc) · 8.16 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
package awsauth
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/hashicorp/go-cleanhttp"
"github.com/hashicorp/vault/helper/awsutil"
"github.com/hashicorp/vault/logical"
)
// getRawClientConfig creates a aws-sdk-go config, which is used to create client
// that can interact with AWS API. This builds credentials in the following
// order of preference:
//
// * Static credentials from 'config/client'
// * Environment variables
// * Instance metadata role
func (b *backend) getRawClientConfig(s logical.Storage, region, clientType string) (*aws.Config, error) {
credsConfig := &awsutil.CredentialsConfig{
Region: region,
}
// Read the configured secret key and access key
config, err := b.nonLockedClientConfigEntry(s)
if err != nil {
return nil, err
}
endpoint := aws.String("")
if config != nil {
// Override the default endpoint with the configured endpoint.
switch {
case clientType == "ec2" && config.Endpoint != "":
endpoint = aws.String(config.Endpoint)
case clientType == "iam" && config.IAMEndpoint != "":
endpoint = aws.String(config.IAMEndpoint)
case clientType == "sts" && config.STSEndpoint != "":
endpoint = aws.String(config.STSEndpoint)
}
credsConfig.AccessKey = config.AccessKey
credsConfig.SecretKey = config.SecretKey
}
credsConfig.HTTPClient = cleanhttp.DefaultClient()
creds, err := credsConfig.GenerateCredentialChain()
if err != nil {
return nil, err
}
if creds == nil {
return nil, fmt.Errorf("could not compile valid credential providers from static config, environment, shared, or instance metadata")
}
// Create a config that can be used to make the API calls.
return &aws.Config{
Credentials: creds,
Region: aws.String(region),
HTTPClient: cleanhttp.DefaultClient(),
Endpoint: endpoint,
}, nil
}
// getClientConfig returns an aws-sdk-go config, with optionally assumed credentials
// It uses getRawClientConfig to obtain config for the runtime environemnt, and if
// stsRole is a non-empty string, it will use AssumeRole to obtain a set of assumed
// credentials. The credentials will expire after 15 minutes but will auto-refresh.
func (b *backend) getClientConfig(s logical.Storage, region, stsRole, accountID, clientType string) (*aws.Config, error) {
config, err := b.getRawClientConfig(s, region, clientType)
if err != nil {
return nil, err
}
if config == nil {
return nil, fmt.Errorf("could not compile valid credentials through the default provider chain")
}
stsConfig, err := b.getRawClientConfig(s, region, "sts")
if stsConfig == nil {
return nil, fmt.Errorf("could not configure STS client")
}
if err != nil {
return nil, err
}
if stsRole != "" {
assumedCredentials := stscreds.NewCredentials(session.New(stsConfig), stsRole)
// Test that we actually have permissions to assume the role
if _, err = assumedCredentials.Get(); err != nil {
return nil, err
}
config.Credentials = assumedCredentials
} else {
if b.defaultAWSAccountID == "" {
client := sts.New(session.New(stsConfig))
if client == nil {
return nil, fmt.Errorf("could not obtain sts client: %v", err)
}
inputParams := &sts.GetCallerIdentityInput{}
identity, err := client.GetCallerIdentity(inputParams)
if err != nil {
return nil, fmt.Errorf("unable to fetch current caller: %v", err)
}
if identity == nil {
return nil, fmt.Errorf("got nil result from GetCallerIdentity")
}
b.defaultAWSAccountID = *identity.Account
}
if b.defaultAWSAccountID != accountID {
return nil, fmt.Errorf("unable to fetch client for account ID %s -- default client is for account %s", accountID, b.defaultAWSAccountID)
}
}
return config, nil
}
// flushCachedEC2Clients deletes all the cached ec2 client objects from the backend.
// If the client credentials configuration is deleted or updated in the backend, all
// the cached EC2 client objects will be flushed. Config mutex lock should be
// acquired for write operation before calling this method.
func (b *backend) flushCachedEC2Clients() {
// deleting items in map during iteration is safe
for region, _ := range b.EC2ClientsMap {
delete(b.EC2ClientsMap, region)
}
}
// flushCachedIAMClients deletes all the cached iam client objects from the
// backend. If the client credentials configuration is deleted or updated in
// the backend, all the cached IAM client objects will be flushed. Config mutex
// lock should be acquired for write operation before calling this method.
func (b *backend) flushCachedIAMClients() {
// deleting items in map during iteration is safe
for region, _ := range b.IAMClientsMap {
delete(b.IAMClientsMap, region)
}
}
func (b *backend) stsRoleForAccount(s logical.Storage, accountID string) (string, error) {
// Check if an STS configuration exists for the AWS account
sts, err := b.lockedAwsStsEntry(s, accountID)
if err != nil {
return "", fmt.Errorf("error fetching STS config for account ID %q: %q\n", accountID, err)
}
// An empty STS role signifies the master account
if sts != nil {
return sts.StsRole, nil
}
return "", nil
}
// clientEC2 creates a client to interact with AWS EC2 API
func (b *backend) clientEC2(s logical.Storage, region, accountID string) (*ec2.EC2, error) {
stsRole, err := b.stsRoleForAccount(s, accountID)
if err != nil {
return nil, err
}
b.configMutex.RLock()
if b.EC2ClientsMap[region] != nil && b.EC2ClientsMap[region][stsRole] != nil {
defer b.configMutex.RUnlock()
// If the client object was already created, return it
return b.EC2ClientsMap[region][stsRole], nil
}
// Release the read lock and acquire the write lock
b.configMutex.RUnlock()
b.configMutex.Lock()
defer b.configMutex.Unlock()
// If the client gets created while switching the locks, return it
if b.EC2ClientsMap[region] != nil && b.EC2ClientsMap[region][stsRole] != nil {
return b.EC2ClientsMap[region][stsRole], nil
}
// Create an AWS config object using a chain of providers
var awsConfig *aws.Config
awsConfig, err = b.getClientConfig(s, region, stsRole, accountID, "ec2")
if err != nil {
return nil, err
}
if awsConfig == nil {
return nil, fmt.Errorf("could not retrieve valid assumed credentials")
}
// Create a new EC2 client object, cache it and return the same
client := ec2.New(session.New(awsConfig))
if client == nil {
return nil, fmt.Errorf("could not obtain ec2 client")
}
if _, ok := b.EC2ClientsMap[region]; !ok {
b.EC2ClientsMap[region] = map[string]*ec2.EC2{stsRole: client}
} else {
b.EC2ClientsMap[region][stsRole] = client
}
return b.EC2ClientsMap[region][stsRole], nil
}
// clientIAM creates a client to interact with AWS IAM API
func (b *backend) clientIAM(s logical.Storage, region, accountID string) (*iam.IAM, error) {
stsRole, err := b.stsRoleForAccount(s, accountID)
if err != nil {
return nil, err
}
b.configMutex.RLock()
if b.IAMClientsMap[region] != nil && b.IAMClientsMap[region][stsRole] != nil {
defer b.configMutex.RUnlock()
// If the client object was already created, return it
return b.IAMClientsMap[region][stsRole], nil
}
// Release the read lock and acquire the write lock
b.configMutex.RUnlock()
b.configMutex.Lock()
defer b.configMutex.Unlock()
// If the client gets created while switching the locks, return it
if b.IAMClientsMap[region] != nil && b.IAMClientsMap[region][stsRole] != nil {
return b.IAMClientsMap[region][stsRole], nil
}
// Create an AWS config object using a chain of providers
var awsConfig *aws.Config
awsConfig, err = b.getClientConfig(s, region, stsRole, accountID, "iam")
if err != nil {
return nil, err
}
if awsConfig == nil {
return nil, fmt.Errorf("could not retrieve valid assumed credentials")
}
// Create a new IAM client object, cache it and return the same
client := iam.New(session.New(awsConfig))
if client == nil {
return nil, fmt.Errorf("could not obtain iam client")
}
if _, ok := b.IAMClientsMap[region]; !ok {
b.IAMClientsMap[region] = map[string]*iam.IAM{stsRole: client}
} else {
b.IAMClientsMap[region][stsRole] = client
}
return b.IAMClientsMap[region][stsRole], nil
}