-
Notifications
You must be signed in to change notification settings - Fork 48
/
credentials.go
99 lines (77 loc) · 2.57 KB
/
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
package credentials
import (
"context"
"encoding/json"
"fmt"
"os"
"github.com/newrelic/newrelic-lambda-extension/util"
"github.com/newrelic/newrelic-lambda-extension/config"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/secretsmanager"
"github.com/aws/aws-sdk-go/service/secretsmanager/secretsmanageriface"
)
type licenseKeySecret struct {
LicenseKey string
}
var (
sess = session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
secrets secretsmanageriface.SecretsManagerAPI
)
const defaultSecretId = "NEW_RELIC_LICENSE_KEY"
func init() {
secrets = secretsmanager.New(sess)
}
func getLicenseKeySecretId(conf *config.Configuration) string {
if conf.LicenseKeySecretId != "" {
util.Logln("Fetching license key from secret id " + conf.LicenseKeySecretId)
return conf.LicenseKeySecretId
}
return defaultSecretId
}
func decodeLicenseKey(rawJson *string) (string, error) {
var secrets licenseKeySecret
err := json.Unmarshal([]byte(*rawJson), &secrets)
if err != nil {
return "", err
}
if secrets.LicenseKey == "" {
return "", fmt.Errorf("malformed license key secret; missing \"LicenseKey\" attribute")
}
return secrets.LicenseKey, nil
}
// IsSecretConfigured returns true if the Secrets Maanger secret is configured, false
// otherwise
func IsSecretConfigured(ctx context.Context, conf *config.Configuration) bool {
secretId := getLicenseKeySecretId(conf)
secretValueInput := secretsmanager.GetSecretValueInput{SecretId: &secretId}
_, err := secrets.GetSecretValueWithContext(ctx, &secretValueInput)
if err != nil {
return false
}
return true
}
// GetNewRelicLicenseKey fetches the license key from AWS Secrets Manager, falling back
// to the NEW_RELIC_LICENSE_KEY environment variable if set.
func GetNewRelicLicenseKey(ctx context.Context, conf *config.Configuration) (string, error) {
if conf.LicenseKey != "" {
util.Logln("Using license key from environment variable")
return conf.LicenseKey, nil
}
secretId := getLicenseKeySecretId(conf)
secretValueInput := secretsmanager.GetSecretValueInput{SecretId: &secretId}
secretValueOutput, err := secrets.GetSecretValueWithContext(ctx, &secretValueInput)
if err != nil {
envLicenseKey, found := os.LookupEnv(defaultSecretId)
if found {
return envLicenseKey, nil
}
return "", err
}
return decodeLicenseKey(secretValueOutput.SecretString)
}
// OverrideSecretsManager overrides the default Secrets Manager implementation
func OverrideSecretsManager(override secretsmanageriface.SecretsManagerAPI) {
secrets = override
}