-
Notifications
You must be signed in to change notification settings - Fork 8
/
path_creds.go
288 lines (254 loc) · 9.48 KB
/
path_creds.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
281
282
283
284
285
286
287
288
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package alicloud
import (
"context"
"errors"
"fmt"
"github.com/hashicorp/vault/sdk/helper/jsonutil"
"math/rand"
"time"
"github.com/hashicorp/vault-plugin-secrets-alicloud/clients"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
)
func (b *backend) pathCreds() *framework.Path {
return &framework.Path{
Pattern: "creds/" + framework.GenericNameRegex("name"),
DisplayAttrs: &framework.DisplayAttributes{
OperationPrefix: operationPrefixAliCloud,
OperationVerb: "generate",
OperationSuffix: "credentials",
},
Fields: map[string]*framework.FieldSchema{
"name": {
Type: framework.TypeLowerCaseString,
Description: "The name of the role.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ReadOperation: b.operationCredsRead,
},
HelpSynopsis: pathCredsHelpSyn,
HelpDescription: pathCredsHelpDesc,
}
}
func (b *backend) operationCredsRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("name").(string)
if roleName == "" {
return nil, errors.New("name is required")
}
role, err := readRole(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
if role == nil {
// Attempting to read a role that doesn't exist.
return nil, nil
}
creds, err := readCredentials(ctx, req.Storage)
if err != nil {
return nil, err
}
if creds == nil {
return nil, errors.New("unable to create secret because no credentials are configured")
}
switch role.Type() {
case roleTypeSTS:
client, err := clients.NewSTSClient(b.sdkConfig, creds.AccessKey, creds.SecretKey)
if err != nil {
return nil, err
}
assumeRoleResp, err := client.AssumeRole(generateRoleSessionName(req.DisplayName, roleName), role.RoleARN)
if err != nil {
return nil, err
}
// Parse the expiration into a time, so that when we return it from our API it's formatted
// the same way as how _we_ format times, which could differ from this over time.
expiration, err := time.Parse("2006-01-02T15:04:05Z", assumeRoleResp.Credentials.Expiration)
if err != nil {
return nil, err
}
resp := b.Secret(secretType).Response(map[string]interface{}{
"access_key": assumeRoleResp.Credentials.AccessKeyId,
"secret_key": assumeRoleResp.Credentials.AccessKeySecret,
"security_token": assumeRoleResp.Credentials.SecurityToken,
"expiration": expiration,
}, map[string]interface{}{
"role_type": roleTypeSTS.String(),
})
// Set the secret TTL to appropriately match the expiration of the token.
ttl := expiration.Sub(time.Now())
resp.Secret.TTL = ttl
resp.Secret.MaxTTL = ttl
// STS credentials are purposefully short-lived and aren't renewable.
resp.Secret.Renewable = false
return resp, nil
case roleTypeRAM:
client, err := clients.NewRAMClient(b.sdkConfig, creds.AccessKey, creds.SecretKey)
if err != nil {
return nil, err
}
/*
Now we're embarking upon a multi-step process that could fail at any time.
If it does, let's do our best to clean up after ourselves. Success will be
our flag at the end indicating whether we should leave things be, or clean
things up, based on how we exit this method. Since defer statements are
last-in-first-out, it will perfectly reverse the order of everything just
like we need.
*/
success := false
createUserResp, err := client.CreateUser(generateUsername(req.DisplayName, roleName))
if err != nil {
return nil, err
}
defer func() {
if success {
return
}
if err := client.DeleteUser(createUserResp.User.UserName); err != nil {
if b.Logger().IsError() {
b.Logger().Error(fmt.Sprintf("unable to delete user %s", createUserResp.User.UserName), err)
}
}
}()
// We need to gather up all the names and types of the remote policies we're
// about to create so we can detach and delete them later.
inlinePolicies := make([]*remotePolicy, len(role.InlinePolicies))
for i, inlinePolicy := range role.InlinePolicies {
// By combining the userName with the particular policy's UUID,
// it'll be possible to figure out who this policy is for and which one
// it is using the policy name alone. The max length of a policy name is
// 128, but given the max lengths of our username and inline policy UUID,
// we will always remain well under that here.
policyName := createUserResp.User.UserName + "-" + inlinePolicy.UUID
policyDoc, err := jsonutil.EncodeJSON(inlinePolicy.PolicyDocument)
if err != nil {
return nil, err
}
createPolicyResp, err := client.CreatePolicy(policyName, string(policyDoc))
if err != nil {
return nil, err
}
inlinePolicies[i] = &remotePolicy{
Name: createPolicyResp.Policy.PolicyName,
Type: createPolicyResp.Policy.PolicyType,
}
// This defer is in this loop on purpose.
defer func() {
if success {
return
}
if err := client.DeletePolicy(createPolicyResp.Policy.PolicyName); err != nil {
if b.Logger().IsError() {
b.Logger().Error(fmt.Sprintf("unable to delete policy %s", createPolicyResp.Policy.PolicyName), err)
}
}
}()
if err := client.AttachPolicy(createUserResp.User.UserName, createPolicyResp.Policy.PolicyName, createPolicyResp.Policy.PolicyType); err != nil {
return nil, err
}
// This defer is also in this loop on purpose.
defer func() {
if success {
return
}
if err := client.DetachPolicy(createUserResp.User.UserName, createPolicyResp.Policy.PolicyName, createPolicyResp.Policy.PolicyType); err != nil {
if b.Logger().IsError() {
b.Logger().Error(fmt.Sprintf(
"unable to detach policy name:%s, type:%s from user:%s", createPolicyResp.Policy.PolicyName, createPolicyResp.Policy.PolicyType, createUserResp.User.UserName))
}
}
}()
}
for _, remotePol := range role.RemotePolicies {
if err := client.AttachPolicy(createUserResp.User.UserName, remotePol.Name, remotePol.Type); err != nil {
return nil, err
}
// This defer is also in this loop on purpose.
// Separate these strings from the remotePol pointer so the defer statement will retain the correct values
// due to pointer reuse for the remotePol var on each iteration of the loop.
remotePolName := remotePol.Name
remotePolType := remotePol.Type
defer func() {
if success {
return
}
if err := client.DetachPolicy(createUserResp.User.UserName, remotePolName, remotePolType); err != nil {
if b.Logger().IsError() {
b.Logger().Error(fmt.Sprintf("unable to detach policy name:%s, type:%s from user:%s", remotePolName, remotePolType, createUserResp.User.UserName))
}
}
}()
}
accessKeyResp, err := client.CreateAccessKey(createUserResp.User.UserName)
if err != nil {
return nil, err
}
// It's unlikely we wouldn't have success at this point because there are no further errors returned below, but
// there could be a panic if somehow one of the objects below were missing a pointer, so let's play it safe and
// add a defer rolling back the access key if that happens.
defer func() {
if success {
return
}
if err := client.DeleteAccessKey(createUserResp.User.UserName, accessKeyResp.AccessKey.AccessKeyId); err != nil {
if b.Logger().IsError() {
b.Logger().Error(fmt.Sprintf("unable to delete access key for username:%s", createUserResp.User.UserName))
}
}
}()
resp := b.Secret(secretType).Response(map[string]interface{}{
"access_key": accessKeyResp.AccessKey.AccessKeyId,
"secret_key": accessKeyResp.AccessKey.AccessKeySecret,
}, map[string]interface{}{
"role_type": roleTypeRAM.String(),
"role_name": roleName,
"username": createUserResp.User.UserName,
"access_key_id": accessKeyResp.AccessKey.AccessKeyId,
"inline_policies": inlinePolicies,
"remote_policies": role.RemotePolicies,
})
if role.TTL != 0 {
resp.Secret.TTL = role.TTL
}
if role.MaxTTL != 0 {
resp.Secret.MaxTTL = role.MaxTTL
}
success = true
return resp, nil
default:
return nil, fmt.Errorf("unsupported role type: %s", role.Type())
}
}
// The max length of a username per AliCloud is 64.
func generateUsername(displayName, roleName string) string {
return generateName(displayName, roleName, 64)
}
// The max length of a role session name per AliCloud is 32.
func generateRoleSessionName(displayName, roleName string) string {
return generateName(displayName, roleName, 32)
}
func generateName(displayName, roleName string, maxLength int) string {
name := fmt.Sprintf("%s-%s-", displayName, roleName)
// The time and random number take up to 15 more in length, so if the name
// is too long we need to trim it.
if len(name) > maxLength-15 {
name = name[:maxLength-15]
}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
return fmt.Sprintf("%s%d-%d", name, time.Now().Unix(), r.Intn(10000))
}
const pathCredsHelpSyn = `
Generate an API key or STS credential using the given role's configuration.'
`
const pathCredsHelpDesc = `
This path will generate a new API key or STS credential for
accessing AliCloud. The RAM policies used to back this key pair will be
configured on the role. For example, if this backend is mounted at "alicloud",
then "alicloud/creds/deploy" would generate access keys for the "deploy" role.
The API key or STS credential will have a ttl associated with it. API keys can
be renewed or revoked as described here:
https://www.vaultproject.io/docs/concepts/lease.html,
but STS credentials do not support renewal or revocation.
`