-
Notifications
You must be signed in to change notification settings - Fork 169
/
ssmstore.go
599 lines (513 loc) · 14.8 KB
/
ssmstore.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
package store
import (
"context"
"errors"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ssm"
"github.com/aws/aws-sdk-go-v2/service/ssm/types"
)
const (
// DefaultKeyID is the default alias for the KMS key used to encrypt/decrypt secrets
DefaultKeyID = "alias/parameter_store_key"
// DefaultRetryMode is the default retry mode for AWS SDK configurations.
DefaultRetryMode = aws.RetryModeStandard
)
// validPathKeyFormat is the format that is expected for key names inside parameter store
// when using paths
var validPathKeyFormat = regexp.MustCompile(`^(\/[\w\-\.]+)+$`)
// ensure SSMStore confirms to Store interface
var _ Store = &SSMStore{}
// label check regexp
var labelMatchRegex = regexp.MustCompile(`^(\/[\w\-\.]+)+:(.+)$`)
// SSMStore implements the Store interface for storing secrets in SSM Parameter
// Store
type SSMStore struct {
svc apiSSM
config aws.Config
}
// NewSSMStore creates a new SSMStore
func NewSSMStore(ctx context.Context, numRetries int) (*SSMStore, error) {
return ssmStoreUsingRetryer(ctx, numRetries, DefaultRetryMode)
}
// NewSSMStoreWithMinThrottleDelay creates a new SSMStore with the aws sdk max retries and min throttle delay are configured.
//
// Deprecated: The AWS SDK no longer supports specifying a minimum throttle delay. Instead, use
// NewSSMStoreWithRetryMode.
func NewSSMStoreWithMinThrottleDelay(ctx context.Context, numRetries int, minThrottleDelay time.Duration) (*SSMStore, error) {
return ssmStoreUsingRetryer(ctx, numRetries, DefaultRetryMode)
}
// NewSSMStoreWithRetryMode creates a new SSMStore, configuring the underlying AWS SDK with the
// given maximum number of retries and retry mode.
func NewSSMStoreWithRetryMode(ctx context.Context, numRetries int, retryMode aws.RetryMode) (*SSMStore, error) {
return ssmStoreUsingRetryer(ctx, numRetries, retryMode)
}
func ssmStoreUsingRetryer(ctx context.Context, numRetries int, retryMode aws.RetryMode) (*SSMStore, error) {
cfg, _, err := getConfig(ctx, numRetries, retryMode)
if err != nil {
return nil, err
}
svc := ssm.NewFromConfig(cfg)
return &SSMStore{
svc: svc,
config: cfg,
}, nil
}
func (s *SSMStore) KMSKey() string {
fromEnv, ok := os.LookupEnv("CHAMBER_KMS_KEY_ALIAS")
if !ok {
return DefaultKeyID
}
if !strings.HasPrefix(fromEnv, "alias/") {
return fmt.Sprintf("alias/%s", fromEnv)
}
return fromEnv
}
// Write writes a given value to a secret identified by id. If the secret
// already exists, then write a new version.
func (s *SSMStore) Write(ctx context.Context, id SecretId, value string) error {
version := 1
// first read to get the current version
current, err := s.Read(ctx, id, -1)
if err != nil && err != ErrSecretNotFound {
return err
}
if err == nil {
version = current.Meta.Version + 1
}
putParameterInput := &ssm.PutParameterInput{
KeyId: aws.String(s.KMSKey()),
Name: aws.String(s.idToName(id)),
Type: types.ParameterTypeSecureString,
Value: aws.String(value),
Overwrite: aws.Bool(true),
Description: aws.String(strconv.Itoa(version)),
}
// This API call returns an empty struct
_, err = s.svc.PutParameter(ctx, putParameterInput)
if err != nil {
return err
}
return nil
}
// Read reads a secret from the parameter store at a specific version.
// To grab the latest version, use -1 as the version number.
func (s *SSMStore) Read(ctx context.Context, id SecretId, version int) (Secret, error) {
if version == -1 {
return s.readLatest(ctx, id)
}
return s.readVersion(ctx, id, version)
}
func (s *SSMStore) WriteTags(ctx context.Context, id SecretId, tags map[string]string, deleteOtherTags bool) error {
if deleteOtherTags {
// list the current tags
currentTags, err := s.ReadTags(ctx, id)
if err != nil {
return err
}
var tagKeysToRemove []string
for k := range currentTags {
if _, ok := tags[k]; !ok {
tagKeysToRemove = append(tagKeysToRemove, k)
}
}
if len(tagKeysToRemove) > 0 {
if err := s.DeleteTags(ctx, id, tagKeysToRemove); err != nil {
return err
}
}
}
addTags := make([]types.Tag, len(tags))
i := 0
for k, v := range tags {
addTags[i] = types.Tag{
Key: aws.String(k),
Value: aws.String(v),
}
i++
}
addTagsInput := &ssm.AddTagsToResourceInput{
ResourceType: types.ResourceTypeForTaggingParameter,
ResourceId: aws.String(s.idToName(id)),
Tags: addTags,
}
_, err := s.svc.AddTagsToResource(ctx, addTagsInput)
if err != nil {
return err
}
return nil
}
func (s *SSMStore) ReadTags(ctx context.Context, id SecretId) (map[string]string, error) {
input := &ssm.ListTagsForResourceInput{
ResourceType: types.ResourceTypeForTaggingParameter,
ResourceId: aws.String(s.idToName(id)),
}
resp, err := s.svc.ListTagsForResource(ctx, input)
if err != nil {
var iri *types.InvalidResourceId
if errors.As(err, &iri) {
return nil, ErrSecretNotFound
}
return nil, err
}
tags := make(map[string]string, len(resp.TagList))
for _, tag := range resp.TagList {
tags[*tag.Key] = *tag.Value
}
return tags, nil
}
// Delete removes a secret from the parameter store. Note this removes all
// versions of the secret.
func (s *SSMStore) Delete(ctx context.Context, id SecretId) error {
// first read to ensure parameter present
_, err := s.Read(ctx, id, -1)
if err != nil {
return err
}
deleteParameterInput := &ssm.DeleteParameterInput{
Name: aws.String(s.idToName(id)),
}
_, err = s.svc.DeleteParameter(ctx, deleteParameterInput)
if err != nil {
return err
}
return nil
}
func (s *SSMStore) DeleteTags(ctx context.Context, id SecretId, tagKeys []string) error {
removeTagsInput := &ssm.RemoveTagsFromResourceInput{
ResourceType: types.ResourceTypeForTaggingParameter,
ResourceId: aws.String(s.idToName(id)),
TagKeys: tagKeys,
}
_, err := s.svc.RemoveTagsFromResource(ctx, removeTagsInput)
if err != nil {
return err
}
return nil
}
func (s *SSMStore) readVersion(ctx context.Context, id SecretId, version int) (Secret, error) {
getParameterHistoryInput := &ssm.GetParameterHistoryInput{
Name: aws.String(s.idToName(id)),
WithDecryption: aws.Bool(true),
}
var result Secret
paginator := ssm.NewGetParameterHistoryPaginator(s.svc, getParameterHistoryInput)
for paginator.HasMorePages() {
o, err := paginator.NextPage(ctx)
if err != nil {
return Secret{}, ErrSecretNotFound
}
for _, history := range o.Parameters {
thisVersion := 0
if history.Description != nil {
thisVersion, _ = strconv.Atoi(*history.Description)
}
if thisVersion == version {
result = Secret{
Value: history.Value,
Meta: SecretMetadata{
Created: *history.LastModifiedDate,
CreatedBy: *history.LastModifiedUser,
Version: thisVersion,
Key: *history.Name,
},
}
break
}
}
}
if result.Value != nil {
return result, nil
}
return Secret{}, ErrSecretNotFound
}
func (s *SSMStore) readLatest(ctx context.Context, id SecretId) (Secret, error) {
getParametersInput := &ssm.GetParametersInput{
Names: []string{s.idToName(id)},
WithDecryption: aws.Bool(true),
}
resp, err := s.svc.GetParameters(ctx, getParametersInput)
if err != nil {
return Secret{}, err
}
if len(resp.Parameters) == 0 {
return Secret{}, ErrSecretNotFound
}
param := resp.Parameters[0]
var parameter *types.ParameterMetadata
// To get metadata, we need to use describe parameters
// There is no way to use describe parameters to get a single key
// if that key uses paths, so instead get all the keys for a path,
// then find the one you are looking for :(
describeParametersInput := &ssm.DescribeParametersInput{
ParameterFilters: []types.ParameterStringFilter{
{
Key: aws.String("Path"),
Option: aws.String("OneLevel"),
Values: []string{basePath(s.idToName(id))},
},
},
}
paginator := ssm.NewDescribeParametersPaginator(s.svc, describeParametersInput)
for paginator.HasMorePages() {
o, err := paginator.NextPage(ctx)
if err != nil {
return Secret{}, err
}
for _, param := range o.Parameters {
if *param.Name == s.idToName(id) {
parameter = ¶m
break
}
}
}
if parameter == nil {
return Secret{}, ErrSecretNotFound
}
secretMeta := parameterMetaToSecretMeta(*parameter)
return Secret{
Value: param.Value,
Meta: secretMeta,
}, nil
}
func (s *SSMStore) ListServices(ctx context.Context, service string, includeSecretName bool) ([]string, error) {
secrets := map[string]Secret{}
describeParametersInput := &ssm.DescribeParametersInput{
MaxResults: aws.Int32(50),
ParameterFilters: []types.ParameterStringFilter{
{
Key: aws.String("Name"),
Option: aws.String("BeginsWith"),
Values: []string{"/" + service},
},
},
}
paginator := ssm.NewDescribeParametersPaginator(s.svc, describeParametersInput)
for paginator.HasMorePages() {
resp, err := paginator.NextPage(ctx)
if err != nil {
return nil, err
}
for _, meta := range resp.Parameters {
if !s.validateName(*meta.Name) {
continue
}
secretMeta := parameterMetaToSecretMeta(meta)
secrets[secretMeta.Key] = Secret{
Value: nil,
Meta: secretMeta,
}
}
}
if includeSecretName {
return keys(secrets), nil
}
var services []string
for key := range secrets {
services = append(services, serviceName(key))
}
return uniqueStringSlice(services), nil
}
// List lists all secrets for a given service. If includeValues is true,
// then those secrets are decrypted and returned, otherwise only the metadata
// about a secret is returned.
func (s *SSMStore) List(ctx context.Context, serviceName string, includeValues bool) ([]Secret, error) {
secrets := map[string]Secret{}
var describeParametersInput *ssm.DescribeParametersInput
service, _ := parseServiceLabel(serviceName)
describeParametersInput = &ssm.DescribeParametersInput{
ParameterFilters: []types.ParameterStringFilter{
{
Key: aws.String("Path"),
Option: aws.String("OneLevel"),
Values: []string{"/" + service},
},
},
}
paginator := ssm.NewDescribeParametersPaginator(s.svc, describeParametersInput)
for paginator.HasMorePages() {
resp, err := paginator.NextPage(ctx)
if err != nil {
return nil, err
}
for _, meta := range resp.Parameters {
if !s.validateName(*meta.Name) {
continue
}
secretMeta := parameterMetaToSecretMeta(meta)
secrets[secretMeta.Key] = Secret{
Value: nil,
Meta: secretMeta,
}
}
}
if includeValues {
secretKeys := keys(secrets)
for i := 0; i < len(secretKeys); i += 10 {
batchEnd := i + 10
if i+10 > len(secretKeys) {
batchEnd = len(secretKeys)
}
batch := secretKeys[i:batchEnd]
getParametersInput := &ssm.GetParametersInput{
Names: batch,
WithDecryption: aws.Bool(true),
}
resp, err := s.svc.GetParameters(ctx, getParametersInput)
if err != nil {
return nil, err
}
for _, param := range resp.Parameters {
secret := secrets[*param.Name]
secret.Value = param.Value
secrets[*param.Name] = secret
}
}
}
return values(secrets), nil
}
// ListRaw lists all secrets keys and values for a given service. Does not include any
// other meta-data. Uses faster AWS APIs with much higher rate-limits. Suitable for
// use in production environments.
func (s *SSMStore) ListRaw(ctx context.Context, serviceName string) ([]RawSecret, error) {
service, label := parseServiceLabel(serviceName)
secrets := map[string]RawSecret{}
getParametersByPathInput := &ssm.GetParametersByPathInput{
Path: aws.String("/" + service + "/"),
WithDecryption: aws.Bool(true),
}
if label != "" {
getParametersByPathInput.ParameterFilters = []types.ParameterStringFilter{
{
Key: aws.String("Label"),
Option: aws.String("Equals"),
Values: []string{label},
},
}
}
paginator := ssm.NewGetParametersByPathPaginator(s.svc, getParametersByPathInput)
for paginator.HasMorePages() {
resp, err := paginator.NextPage(ctx)
if err != nil {
return nil, err
}
for _, param := range resp.Parameters {
if !s.validateName(*param.Name) {
continue
}
secrets[*param.Name] = RawSecret{
Value: *param.Value,
Key: *param.Name,
}
}
}
rawSecrets := make([]RawSecret, len(secrets))
i := 0
for _, rawSecret := range secrets {
rawSecrets[i] = rawSecret
i += 1
}
return rawSecrets, nil
}
// History returns a list of events that have occurred regarding the given
// secret.
func (s *SSMStore) History(ctx context.Context, id SecretId) ([]ChangeEvent, error) {
events := []ChangeEvent{}
getParameterHistoryInput := &ssm.GetParameterHistoryInput{
Name: aws.String(s.idToName(id)),
WithDecryption: aws.Bool(false),
}
paginator := ssm.NewGetParameterHistoryPaginator(s.svc, getParameterHistoryInput)
for paginator.HasMorePages() {
o, err := paginator.NextPage(ctx)
if err != nil {
return events, ErrSecretNotFound
}
for _, history := range o.Parameters {
// Disregard error here, if Atoi fails (secret created outside of
// Chamber), then we use version 0
version := 0
if history.Description != nil {
version, _ = strconv.Atoi(*history.Description)
}
events = append(events, ChangeEvent{
Type: getChangeType(version),
Time: *history.LastModifiedDate,
User: *history.LastModifiedUser,
Version: version,
})
}
}
return events, nil
}
func (s *SSMStore) idToName(id SecretId) string {
return fmt.Sprintf("/%s/%s", id.Service, id.Key)
}
func (s *SSMStore) validateName(name string) bool {
return validPathKeyFormat.MatchString(name)
}
func basePath(key string) string {
pathParts := strings.Split(key, "/")
if len(pathParts) == 1 {
return pathParts[0]
}
end := len(pathParts) - 1
return strings.Join(pathParts[0:end], "/")
}
func serviceName(key string) string {
pathParts := strings.Split(key, "/")
if len(pathParts) == 1 {
return pathParts[0]
}
end := len(pathParts) - 1
return strings.Join(pathParts[1:end], "/")
}
func parameterMetaToSecretMeta(p types.ParameterMetadata) SecretMetadata {
version := 0
if p.Description != nil {
version, _ = strconv.Atoi(*p.Description)
}
return SecretMetadata{
Created: *p.LastModifiedDate,
CreatedBy: *p.LastModifiedUser,
Version: version,
Key: *p.Name,
}
}
func keys(m map[string]Secret) []string {
keys := []string{}
for k := range m {
keys = append(keys, k)
}
return keys
}
func values(m map[string]Secret) []Secret {
values := []Secret{}
for _, v := range m {
values = append(values, v)
}
return values
}
func getChangeType(version int) ChangeEventType {
if version == 1 {
return Created
}
return Updated
}
func parseServiceLabel(serviceAndLabel string) (string, string) {
if labelMatchRegex.MatchString(serviceAndLabel) {
i := strings.Index(serviceAndLabel, ":")
if i > -1 {
service := serviceAndLabel[:i]
label := serviceAndLabel[i+1:]
return service, label
}
return serviceAndLabel, ""
}
return serviceAndLabel, ""
}