-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsecret.go
726 lines (651 loc) · 18 KB
/
secret.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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
// Package secretfetch provides a simple and flexible way to manage secrets from various sources
// including AWS Secrets Manager and environment variables. It supports automatic type conversion,
// validation, and transformation of secret values.
package secretfetch
import (
"context"
"encoding/base64"
"fmt"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/secretsmanager"
)
// SecretsManagerClient defines the interface for AWS Secrets Manager operations
type SecretsManagerClient interface {
GetSecretValue(ctx context.Context, params *secretsmanager.GetSecretValueInput, optFns ...func(*secretsmanager.Options)) (*secretsmanager.GetSecretValueOutput, error)
}
// Options holds configuration options for fetching secrets
type Options struct {
// AWS is the AWS configuration
AWS *aws.Config
// Validators is a map of named validation functions
Validators map[string]ValidationFunc
// Transformers is a map of named transformation functions
Transformers map[string]TransformFunc
// CacheDuration specifies how long to cache values for
CacheDuration time.Duration
// PreloadARNs indicates whether to preload secrets from ARNs
PreloadARNs bool
// SecretsManager is the AWS Secrets Manager client
SecretsManager SecretsManagerClient
// OnSecretAccess is called whenever a secret is accessed
OnSecretAccess func(ctx context.Context, secretID string)
// MetricsCollector collects security metrics
MetricsCollector SecurityMetricsCollector
// SecureCache indicates whether to use secure memory for caching
SecureCache bool
cacheMu sync.RWMutex
cache map[string]*cachedValue
}
// SecurityMetricsCollector defines the interface for collecting security metrics
type SecurityMetricsCollector interface {
// OnSecretAccess is called when a secret is accessed
OnSecretAccess(metric SecretAccessMetric)
}
// SecretAccessMetric contains information about a secret access event
type SecretAccessMetric struct {
// SecretID is the identifier of the secret
SecretID string
// AccessTime is when the secret was accessed
AccessTime time.Time
// Source indicates where the secret came from (AWS, env, etc.)
Source string
// CacheHit indicates if the secret was served from cache
CacheHit bool
}
// secureValue represents a secret value with best-effort secure memory handling
type secureValue struct {
value []byte
mu sync.RWMutex
}
func (s *secureValue) Set(value string) {
s.mu.Lock()
defer s.mu.Unlock()
// First zero any existing value
if s.value != nil {
for i := range s.value {
s.value[i] = 0
}
}
// Create new slice and copy value
s.value = make([]byte, len(value))
copy(s.value, value)
}
func (s *secureValue) Get() string {
s.mu.RLock()
defer s.mu.RUnlock()
// Create a copy to return
// Note: This is necessary in Go as we can't prevent the returned
// string from being copied by the runtime
if s.value == nil {
return ""
}
result := make([]byte, len(s.value))
copy(result, s.value)
return string(result)
}
func (s *secureValue) Clear() {
s.mu.Lock()
defer s.mu.Unlock()
if s.value != nil {
for i := range s.value {
s.value[i] = 0
}
s.value = nil
}
}
// cachedValue represents a cached secret value
type cachedValue struct {
value interface{}
expiration time.Time
secure *secureValue
}
func (cv *cachedValue) String() string {
if cv.secure != nil {
return cv.secure.Get()
}
if str, ok := cv.value.(string); ok {
return str
}
return fmt.Sprintf("%v", cv.value)
}
func (cv *cachedValue) Clear() {
if cv.secure != nil {
cv.secure.Clear()
}
cv.value = nil
}
func newCachedValue(value string, expiration time.Time, secure bool) *cachedValue {
cv := &cachedValue{
expiration: expiration,
}
if secure {
cv.secure = &secureValue{}
cv.secure.Set(value)
} else {
cv.value = value
}
return cv
}
// OptionsKey is the key for storing Options in the context
var optionsKey = "secretfetch-options"
// ValidationFunc is a function type for custom validation
type ValidationFunc func(string) error
// TransformFunc is a function type for custom transformation
type TransformFunc func(string) (string, error)
// ValidationError represents an error that occurred during validation
type ValidationError struct {
Field string
Err error
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("validation failed for field %q: %v", e.Field, e.Err)
}
type secret struct {
pattern *regexp.Regexp
isBase64 bool
isJSON bool
isYAML bool
value string
ttl time.Duration
fetchedAt time.Time
validation func(string) error
transform func(string) (string, error)
field reflect.StructField
envKey string
fallback string
awsKey string
mu sync.RWMutex
cache *cachedValue
required bool
}
var (
secretsCache map[string]string = make(map[string]string)
secretsMu sync.RWMutex
secretsOnce sync.Once
)
func validatePattern(value, pattern string) error {
re, err := regexp.Compile(pattern)
if err != nil {
return fmt.Errorf("invalid pattern %q: %v", pattern, err)
}
if !re.MatchString(value) {
return fmt.Errorf("value %q does not match pattern %q", value, pattern)
}
return nil
}
func parseTag(field reflect.StructField, opts *Options) (*secret, error) {
tag := field.Tag.Get("secret")
if tag == "" {
return nil, fmt.Errorf("no secret tag found for field %s", field.Name)
}
s := &secret{
field: field,
}
// Split by comma but handle special cases for pattern
var parts []string
var current string
var inPattern bool
var depth int
for i := 0; i < len(tag); i++ {
switch tag[i] {
case '{':
depth++
current += string(tag[i])
case '}':
depth--
current += string(tag[i])
case ',':
if depth == 0 && !inPattern {
if current != "" {
parts = append(parts, strings.TrimSpace(current))
}
current = ""
} else {
current += string(tag[i])
}
case '=':
if strings.HasPrefix(tag[i:], "=pattern=") {
inPattern = true
}
current += string(tag[i])
default:
current += string(tag[i])
}
}
if current != "" {
parts = append(parts, strings.TrimSpace(current))
}
for _, part := range parts {
if strings.Contains(part, "=") {
kv := strings.SplitN(part, "=", 2)
key := strings.TrimSpace(kv[0])
value := strings.TrimSpace(kv[1])
switch key {
case "env":
s.envKey = value
case "aws":
s.awsKey = value
case "pattern":
re, err := regexp.Compile(value)
if err != nil {
return nil, fmt.Errorf("invalid pattern %q: %w", value, err)
}
s.pattern = re
case "ttl":
ttl, err := time.ParseDuration(value)
if err != nil {
return nil, fmt.Errorf("invalid ttl %q: %w", value, err)
}
s.ttl = ttl
case "fallback":
s.fallback = value
case "validate":
if opts != nil && opts.Validators != nil {
if validator, ok := opts.Validators[value]; ok {
s.validation = validator
} else {
return nil, fmt.Errorf("unknown validator %q", value)
}
}
case "transform":
if opts != nil && opts.Transformers != nil {
if transformer, ok := opts.Transformers[value]; ok {
s.transform = transformer
} else {
return nil, fmt.Errorf("unknown transformer %q", value)
}
}
case "base64":
if value == "true" {
s.isBase64 = true
}
case "json":
if value == "true" {
s.isJSON = true
}
case "yaml":
if value == "true" {
s.isYAML = true
}
default:
return nil, fmt.Errorf("unknown key %q in secret tag", key)
}
} else {
switch strings.TrimSpace(part) {
case "required":
s.required = true
case "base64":
s.isBase64 = true
case "json":
s.isJSON = true
case "yaml":
s.isYAML = true
default:
return nil, fmt.Errorf("unknown option %q in secret tag", part)
}
}
}
return s, nil
}
func (s *secret) processValue(value string) (string, error) {
// Base64 decode if needed
if s.isBase64 {
decoded, err := base64.StdEncoding.DecodeString(value)
if err != nil {
return "", &ValidationError{
Field: s.field.Name,
Err: fmt.Errorf("failed to decode base64: %w", err),
}
}
value = string(decoded)
}
// Validate pattern if needed
if s.pattern != nil {
if err := validatePattern(value, s.pattern.String()); err != nil {
return "", &ValidationError{
Field: s.field.Name,
Err: err,
}
}
}
// Run custom validation if needed
if s.validation != nil {
if err := s.validation(value); err != nil {
return "", &ValidationError{
Field: s.field.Name,
Err: fmt.Errorf("validation failed: %w", err),
}
}
}
// Transform if needed
if s.transform != nil {
transformed, err := s.transform(value)
if err != nil {
return "", &ValidationError{
Field: s.field.Name,
Err: fmt.Errorf("transformation failed: %w", err),
}
}
value = transformed
}
return value, nil
}
// Fetch retrieves secrets for the given struct
func Fetch(ctx context.Context, v interface{}, opts *Options) error {
if opts == nil {
opts = &Options{
Validators: make(map[string]ValidationFunc),
Transformers: make(map[string]TransformFunc),
cache: make(map[string]*cachedValue),
}
} else if opts.cache == nil {
opts.cache = make(map[string]*cachedValue)
}
// Store options in context
ctx = context.WithValue(ctx, optionsKey, opts)
// Preload secrets from ARNs if enabled
if opts.PreloadARNs {
if err := preloadSecretsFromARNs(ctx, opts); err != nil {
return fmt.Errorf("failed to preload secrets from ARNs: %w", err)
}
}
value := reflect.ValueOf(v)
if value.Kind() != reflect.Ptr {
return fmt.Errorf("v must be a pointer to a struct")
}
value = value.Elem()
if value.Kind() != reflect.Struct {
return fmt.Errorf("v must be a pointer to a struct")
}
typ := value.Type()
for i := 0; i < value.NumField(); i++ {
field := value.Field(i)
if !field.CanSet() {
continue
}
structField := typ.Field(i)
s, err := parseTag(structField, opts)
if err != nil {
return fmt.Errorf("invalid tag for field %s: %w", structField.Name, err)
}
// Get the secret value
val, err := s.Get(ctx, opts)
if err != nil {
return err
}
// Set the value
switch field.Kind() {
case reflect.String:
field.SetString(val)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if i, err := strconv.ParseInt(val, 10, 64); err == nil {
field.SetInt(i)
} else {
return &ValidationError{
Field: structField.Name,
Err: fmt.Errorf("failed to convert %q to integer: %w", val, err),
}
}
case reflect.Bool:
if b, err := strconv.ParseBool(val); err == nil {
field.SetBool(b)
} else {
return &ValidationError{
Field: structField.Name,
Err: fmt.Errorf("failed to convert %q to boolean: %w", val, err),
}
}
default:
return fmt.Errorf("unsupported field type %v", field.Kind())
}
}
return nil
}
// cacheKey generates a unique key for caching based on environment key, AWS key, and field name
func (s *secret) cacheKey() string {
return fmt.Sprintf("env:%s|aws:%s|field:%s", s.envKey, s.awsKey, s.field.Name)
}
// Get retrieves the secret value with the given options. It implements a multi-tiered
// lookup strategy:
// 1. Check cache if available
// 2. Try AWS Secrets Manager if configured
// 3. Check environment variables
// 4. Use fallback value if provided
// The retrieved value is then processed (validated, transformed) and cached if caching is enabled.
func (s *secret) Get(ctx context.Context, opts *Options) (string, error) {
s.mu.RLock()
defer s.mu.RUnlock()
// Generate a unique cache key for this secret
cacheKey := s.cacheKey()
// Check if value exists in cache and is not expired
opts.cacheMu.RLock()
cached, ok := opts.cache[cacheKey]
opts.cacheMu.RUnlock()
if ok && time.Now().Before(cached.expiration) {
if opts.MetricsCollector != nil {
opts.MetricsCollector.OnSecretAccess(SecretAccessMetric{
SecretID: s.awsKey,
AccessTime: time.Now(),
Source: "cache",
CacheHit: true,
})
}
return cached.String(), nil
}
var lastErr error
// Try AWS first if enabled
if opts != nil && opts.AWS != nil && s.awsKey != "" {
awsValue, err := s.getFromAWS(ctx, opts.AWS)
if err != nil {
if s.required {
return "", fmt.Errorf("failed to get value from AWS for required field %s: %w", s.field.Name, err)
}
lastErr = fmt.Errorf("failed to get value from AWS: %w", err)
} else {
// Process and validate the value
processedValue, err := s.processValue(awsValue)
if err != nil {
if s.required {
return "", err
}
lastErr = err
} else {
// Cache the processed value if caching is enabled
if opts.CacheDuration > 0 {
expiration := time.Now().Add(opts.CacheDuration)
cv := newCachedValue(processedValue, expiration, opts.SecureCache)
opts.cacheMu.Lock()
opts.cache[cacheKey] = cv
opts.cacheMu.Unlock()
}
if opts.MetricsCollector != nil {
opts.MetricsCollector.OnSecretAccess(SecretAccessMetric{
SecretID: s.awsKey,
AccessTime: time.Now(),
Source: "aws",
CacheHit: false,
})
}
return processedValue, nil
}
}
}
// Try environment variable if AWS lookup failed or was disabled
if s.envKey != "" {
if value, ok := os.LookupEnv(s.envKey); ok {
// Process and validate the value
processedValue, err := s.processValue(value)
if err != nil {
if s.required {
return "", err
}
lastErr = err
} else {
// Cache the processed value if caching is enabled
if opts.CacheDuration > 0 {
expiration := time.Now().Add(opts.CacheDuration)
cv := newCachedValue(processedValue, expiration, opts.SecureCache)
opts.cacheMu.Lock()
opts.cache[cacheKey] = cv
opts.cacheMu.Unlock()
}
if opts.MetricsCollector != nil {
opts.MetricsCollector.OnSecretAccess(SecretAccessMetric{
SecretID: s.awsKey,
AccessTime: time.Now(),
Source: "env",
CacheHit: false,
})
}
return processedValue, nil
}
}
}
// Use fallback value if no other source provided a value
if s.fallback != "" {
// Process and validate the fallback value
processedValue, err := s.processValue(s.fallback)
if err != nil {
if s.required {
return "", err
}
lastErr = err
} else {
// Cache the processed fallback value if caching is enabled
if opts.CacheDuration > 0 {
expiration := time.Now().Add(opts.CacheDuration)
cv := newCachedValue(processedValue, expiration, opts.SecureCache)
opts.cacheMu.Lock()
opts.cache[cacheKey] = cv
opts.cacheMu.Unlock()
}
if opts.MetricsCollector != nil {
opts.MetricsCollector.OnSecretAccess(SecretAccessMetric{
SecretID: s.awsKey,
AccessTime: time.Now(),
Source: "fallback",
CacheHit: false,
})
}
return processedValue, nil
}
}
// If we reach here, no value was found
if s.required {
if lastErr != nil {
return "", fmt.Errorf("no value found for required secret %s: %w", s.field.Name, lastErr)
}
return "", fmt.Errorf("no value found for required secret %s", s.field.Name)
}
// For non-required fields, return empty string or last error
if lastErr != nil {
return "", lastErr
}
return "", nil
}
func (s *secret) getFromAWS(ctx context.Context, awsConfig *aws.Config) (string, error) {
if s.awsKey == "" {
return "", nil
}
var client SecretsManagerClient
if opts, ok := ctx.Value(optionsKey).(*Options); ok && opts.SecretsManager != nil {
client = opts.SecretsManager
} else {
cfg := awsConfig
if cfg == nil {
defaultCfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
return "", fmt.Errorf("unable to load AWS config: %v", err)
}
cfg = &defaultCfg
}
client = secretsmanager.NewFromConfig(*cfg)
}
input := &secretsmanager.GetSecretValueInput{
SecretId: aws.String(s.awsKey),
}
result, err := client.GetSecretValue(ctx, input)
if err != nil {
return "", fmt.Errorf("error fetching secret %s: %v", s.awsKey, err)
}
if result.SecretString != nil {
return *result.SecretString, nil
}
if result.SecretBinary != nil {
return string(result.SecretBinary), nil
}
return "", fmt.Errorf("no secret value found for %s", s.awsKey)
}
// FetchAndValidate is an alias for Fetch to maintain backward compatibility
func FetchAndValidate(ctx context.Context, v interface{}) error {
return Fetch(ctx, v, nil)
}
// preloadSecretsFromARNs fetches secrets from AWS Secrets Manager and caches them
func preloadSecretsFromARNs(ctx context.Context, opts *Options) error {
arns := getSecretARNs()
if len(arns) == 0 {
return fmt.Errorf("no secret ARNs found in environment variables SECRET_ARNS or SECRET_ARN")
}
var client SecretsManagerClient
if opts.SecretsManager != nil {
client = opts.SecretsManager
} else {
cfg := opts.AWS
if cfg == nil {
defaultCfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
return fmt.Errorf("unable to load AWS config: %v", err)
}
cfg = &defaultCfg
}
client = secretsmanager.NewFromConfig(*cfg)
}
for _, arn := range arns {
input := &secretsmanager.GetSecretValueInput{
SecretId: aws.String(arn),
}
result, err := client.GetSecretValue(ctx, input)
if err != nil {
return fmt.Errorf("error fetching secret %s: %v", arn, err)
}
if result.SecretString == nil && result.SecretBinary == nil {
return fmt.Errorf("no secret value found for %s", arn)
}
// Cache the secret
cacheKey := "aws:" + arn
expiration := time.Now().Add(opts.CacheDuration)
var cv *cachedValue
if result.SecretString != nil {
cv = newCachedValue(*result.SecretString, expiration, opts.SecureCache)
} else {
cv = newCachedValue(string(result.SecretBinary), expiration, opts.SecureCache)
}
opts.cacheMu.Lock()
opts.cache[cacheKey] = cv
opts.cacheMu.Unlock()
}
return nil
}
// getSecretARNs returns a list of secret ARNs from environment variables
func getSecretARNs() []string {
arns := os.Getenv("SECRET_ARNS")
if arns == "" {
arns = os.Getenv("SECRET_ARN")
}
if arns == "" {
return nil
}
arnsList := strings.Split(arns, ",")
for i := range arnsList {
arnsList[i] = strings.TrimSpace(arnsList[i])
}
return arnsList
}