forked from datastax/vault-plugin-secrets-datastax-astra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath_credentials.go
411 lines (389 loc) · 12 KB
/
path_credentials.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package datastax_astra
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
)
const (
credsPath = "org/token"
credsListPath = "org/tokens/?"
pluginversion = "Vault-Plugin v1.0.0"
)
// pathCredentials extends the Vault API with a `/token` endpoint for a role.
func pathCredentials(b *datastaxAstraBackend) *framework.Path {
return &framework.Path{
Pattern: credsPath,
Fields: map[string]*framework.FieldSchema{
"org_id": {
Type: framework.TypeString,
Description: "name of the org for which token is being requested",
Required: true,
DisplayAttrs: &framework.DisplayAttributes{
Sensitive: false,
},
},
"role_name": {
Type: framework.TypeLowerCaseString,
Description: "name of the role for which token is being requested",
Required: true,
DisplayAttrs: &framework.DisplayAttributes{
Sensitive: false,
},
},
"logical_name": {
Type: framework.TypeLowerCaseString,
Description: "Logical name to reference this token by",
Required: true,
DisplayAttrs: &framework.DisplayAttributes{
Sensitive: false,
},
},
"metadata": {
Type: framework.TypeKVPairs,
Description: "Arbitrary key=value",
Required: false,
DisplayAttrs: &framework.DisplayAttributes{Sensitive: false},
},
"client_id": {
Type: framework.TypeString,
Description: "ClientId for the token",
Required: false,
DisplayAttrs: &framework.DisplayAttributes{
Sensitive: false,
},
},
"lease_time": {
Type: framework.TypeString,
Description: "leaseTime in seconds, minutes or hours for the token. Use the duration intials after the number. for e.g. 5s, 5m, 5h",
Required: false,
},
},
Operations: map[logical.Operation]framework.OperationHandler{
logical.ReadOperation: &framework.PathOperation{
Callback: b.pathCredentialsRead,
},
logical.CreateOperation: &framework.PathOperation{Callback: b.pathCredentialsWrite},
logical.UpdateOperation: &framework.PathOperation{Callback: b.pathCredentialsWrite},
logical.DeleteOperation: &framework.PathOperation{Callback: b.pathTokenDelete},
},
HelpSynopsis: pathCredentialsHelpSyn,
HelpDescription: pathCredentialsHelpDesc,
}
}
// pathCredentialsRead reads a token from vault.
func (b *datastaxAstraBackend) pathCredentialsRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
clientId, ok := d.GetOk("client_id")
if !ok {
roleName, ok := d.GetOk("role_name")
if !ok {
return nil, errors.New("role_name not provided")
}
orgId, ok := d.GetOk("org_id")
if !ok {
return nil, errors.New("org_id not provided")
}
logicalName, ok := d.GetOk("logical_name")
if !ok {
return nil, errors.New("logical_name not provided")
}
tokens, err := listCreds(ctx, req.Storage)
if err != nil {
return nil, errors.New("no tokens found")
}
if len(tokens) == 0 {
return nil, errors.New("no token found in vault")
}
for i := 0; i < len(tokens); i++ {
token, err := readToken(ctx, req.Storage, tokens[i])
if err != nil {
return nil, errors.New("no tokens found")
}
if doesTokenMatch(token, orgId.(string), roleName.(string), logicalName.(string)) {
return &logical.Response{Data: token.toResponseData()}, nil
}
}
return nil, errors.New("no token found that matches criteria")
}
tokens, err := listCreds(ctx, req.Storage)
if err != nil {
return nil, errors.New("no tokens found")
}
if len(tokens) == 0 {
return nil, errors.New("no token found in vault")
}
for i := 0; i < len(tokens); i++ {
token, err := readToken(ctx, req.Storage, tokens[i])
if err != nil {
return nil, errors.New("no tokens found")
}
if doesTokenMatchClientId(token, clientId.(string)) {
return &logical.Response{Data: token.toResponseData()}, nil
}
}
return nil, errors.New("no token found that matches criteria client")
}
func doesTokenMatchClientId(token *astraToken, clientId string) bool {
return token.ClientID == clientId
}
func doesTokenMatch(token *astraToken, orgId, role, logicalName string) bool {
return token.LogicalName == logicalName && token.OrgID == orgId && token.RoleNickname == role
}
func readToken(ctx context.Context, s logical.Storage, uuid string) (*astraToken, error) {
token, err := s.Get(ctx, "token/"+uuid)
if err != nil {
return nil, err
}
if token == nil {
return nil, nil
}
result := &astraToken{}
if err := token.DecodeJSON(result); err != nil {
return nil, err
}
return result, nil
}
func (b *datastaxAstraBackend) pathCredentialsWrite(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
roleName, ok := d.GetOk("role_name")
if !ok {
return nil, errors.New("role_name not provided")
}
orgId, ok := d.GetOk("org_id")
if !ok {
return nil, errors.New("org_id not provided")
}
logicalName, ok := d.GetOk("logical_name")
if !ok {
return nil, errors.New("logical_name not provided")
}
tok, err := readToken(ctx, req.Storage, logicalName.(string))
if tok != nil {
return nil, errors.New("token already exists for role")
}
entry, err := readRole(ctx, req.Storage, roleName.(string), orgId.(string))
if err != nil {
return nil, err
}
if entry == nil {
return nil, errors.New("role does not exist. add role first")
}
payload := strings.NewReader(`{
"roles": [` + `"` + entry.RoleId + `"]}`)
conf, err := getConfig(ctx, req.Storage, orgId.(string))
if err != nil {
return nil, err
}
client := &http.Client{}
url := conf.URL + "/v2/clientIdSecrets"
httpReq, err := http.NewRequest(http.MethodPost, url, payload)
if err != nil {
msg := "error creating httpReq " + err.Error()
return nil, errors.New(msg)
}
httpReq.Header.Add("Content-Type", "application/json")
httpReq.Header.Add("Authorization", "Bearer "+conf.AstraToken)
httpReq.Header.Add("User-Agent", pluginversion)
res, err := client.Do(httpReq)
if err != nil {
msg := "error sending request " + err.Error()
return nil, errors.New(msg)
}
defer res.Body.Close()
var token *astraToken
body, err := ioutil.ReadAll(res.Body)
if err != nil {
msg := "error reading ioutil " + err.Error()
return nil, errors.New(msg)
}
err = json.Unmarshal(body, &token)
if err != nil {
msg := " Unmarshal failed " + err.Error()
return nil, errors.New(msg)
}
metadata, ok, err := d.GetOkErr("metadata")
if err != nil {
return logical.ErrorResponse(fmt.Sprintf("failed to parse metadata: %v", err)), nil
}
if ok {
token.Metadata = metadata.(map[string]string)
}
token.LogicalName = logicalName.(string)
token.RoleNickname = roleName.(string)
internalData := map[string]interface{}{
"token": token.Token,
"metadata": token.Metadata,
"orgId": token.OrgID,
}
err = saveToken(ctx, token, req.Storage)
if err != nil {
return nil, err
}
resp := b.Secret(astraTokenType).Response(token.toResponseData(), internalData)
leaseTime, ok := d.GetOk("lease_time")
if !ok {
return resp, nil
}
parseLeaseTime, _ := time.ParseDuration(leaseTime.(string))
resp.Secret.TTL = parseLeaseTime
resp.Secret.Renewable = true
return resp, nil
}
func (b *datastaxAstraBackend) pathTokenDelete(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
roleName, ok := d.GetOk("role_name")
if !ok {
return nil, errors.New("role_name not provided")
}
orgId, ok := d.GetOk("org_id")
if !ok {
return nil, errors.New("org_id not provided")
}
logicalName, ok := d.GetOk("logical_name")
if !ok {
return nil, errors.New("logical_name not provided")
}
tokens, err := listCreds(ctx, req.Storage)
if err != nil {
return nil, errors.New("no tokens found")
}
if len(tokens) == 0 {
return nil, errors.New("no token found in vault")
}
for i := 0; i < len(tokens); i++ {
token, err := readToken(ctx, req.Storage, tokens[i])
if err != nil {
return nil, errors.New("no tokens found")
}
if doesTokenMatch(token, orgId.(string), roleName.(string), logicalName.(string)) {
err = req.Storage.Delete(ctx, "token/"+tokens[i])
if err != nil {
return nil, err
}
conf, err := getConfig(ctx, req.Storage, orgId.(string))
if err != nil {
return nil, err
}
if conf.URL != "" {
client := &http.Client{}
url := conf.URL + "/v2/clientIdSecrets/" + token.ClientID
httpReq, err := http.NewRequest(http.MethodDelete, url, nil)
if err != nil {
msg := "error creating httpReq " + err.Error()
return nil, errors.New(msg)
}
httpReq.Header.Add("Content-Type", "application/json")
httpReq.Header.Add("Authorization", "Bearer "+conf.AstraToken)
httpReq.Header.Add("User-Agent", pluginversion)
res, err := client.Do(httpReq)
if err != nil {
msg := "error sending request " + err.Error()
return nil, errors.New(msg)
}
defer res.Body.Close()
if res.StatusCode != http.StatusNoContent {
return nil, errors.New("could not delete token in astra")
}
} else {
return nil, errors.New("config not found")
}
}
}
b.reset()
return nil, nil
}
func saveToken(ctx context.Context, token *astraToken, s logical.Storage) error {
entry, err := logical.StorageEntryJSON("token/"+token.ClientID, token)
if err != nil {
return err
}
if err = s.Put(ctx, entry); err != nil {
return err
}
return nil
}
func doTokensMatch(token *astraToken, tokentoRevoke string) bool {
return token.Token == tokentoRevoke
}
func (b *datastaxAstraBackend) tokenRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
tokenRaw, ok := req.Secret.InternalData["token"]
if !ok {
return nil, errors.New("token not retrived")
}
tokens, err := listCreds(ctx, req.Storage)
if err != nil {
return nil, errors.New("no tokens found")
}
for i := 0; i < len(tokens); i++ {
token, err := readToken(ctx, req.Storage, tokens[i])
if err != nil {
return nil, errors.New("no tokens found")
}
if doTokensMatch(token, tokenRaw.(string)) {
err = req.Storage.Delete(ctx, "token/"+tokens[i])
if err != nil {
return nil, err
}
conf, err := getConfig(ctx, req.Storage, token.OrgID)
if err != nil {
return nil, err
}
if conf.URL != "" {
client := &http.Client{}
url := conf.URL + "/v2/clientIdSecrets/" + token.ClientID
httpReq, err := http.NewRequest(http.MethodDelete, url, nil)
if err != nil {
msg := "error creating httpReq " + err.Error()
return nil, errors.New(msg)
}
httpReq.Header.Add("Content-Type", "application/json")
httpReq.Header.Add("Authorization", "Bearer "+conf.AstraToken)
httpReq.Header.Add("User-Agent", pluginversion)
res, err := client.Do(httpReq)
if err != nil {
msg := "error sending request " + err.Error()
return nil, errors.New(msg)
}
defer res.Body.Close()
if res.StatusCode != http.StatusNoContent {
return nil, errors.New("could not delete token in astra")
}
} else {
return nil, errors.New("config not found")
}
}
}
b.reset()
return nil, nil
}
func (b *datastaxAstraBackend) tokenRenew(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
resp := &logical.Response{Secret: req.Secret}
uuid := req.Secret.InternalData["orgId"]
configData, err := getConfig(ctx, req.Storage, uuid.(string))
if err != nil {
resp.Secret.TTL = 24 * time.Hour
return resp, errors.New("error getting config data. lease time set to 24h")
}
renewal_time := configData.DefaultLeaseRenewTime
if renewal_time == "" {
resp.Secret.TTL = 24 * time.Hour
return resp, nil
}
parsedRenewalTime, err := time.ParseDuration(renewal_time)
if err != nil {
resp.Secret.TTL = 24 * time.Hour
return resp, errors.New("error parsing default lease time. lease time set to 24h")
}
resp.Secret.TTL = parsedRenewalTime
return resp, nil
}
const pathCredentialsHelpSyn = `
Generate a AstraCS token from a specific Vault role.
`
const pathCredentialsHelpDesc = `
This path generates a Astra CS token based on a particular role.
`