| 1 |
// Copyright 2020 The Go Cloud Development Kit Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
// Package awssecretsmanager provides a runtimevar implementation with variables |
| 16 |
// read from AWS Secrets Manager (https://aws.amazon.com/secrets-manager) |
| 17 |
// Use OpenVariable to construct a *runtimevar.Variable. |
| 18 |
// |
| 19 |
// # URLs |
| 20 |
// |
| 21 |
// For runtimevar.OpenVariable, awssecretsmanager registers for the scheme "awssecretsmanager". |
| 22 |
// The default URL opener will use an AWS session with the default credentials |
| 23 |
// and configuration. |
| 24 |
// |
| 25 |
// To customize the URL opener, or for more details on the URL format, |
| 26 |
// see URLOpener. |
| 27 |
// See https://gocloud.dev/concepts/urls/ for background information. |
| 28 |
// |
| 29 |
// # As |
| 30 |
// |
| 31 |
// awssecretsmanager exposes the following types for As: |
| 32 |
// - Snapshot: *secretsmanager.GetSecretValueOutput, *secretsmanager.DescribeSecretOutput |
| 33 |
// - Error: any error type returned by the service, notably smithy.APIError |
| 34 |
package awssecretsmanager // import "gocloud.dev/runtimevar/awssecretsmanager" |
| 35 |
|
| 36 |
import ( |
| 37 |
"context" |
| 38 |
"errors" |
| 39 |
"fmt" |
| 40 |
"net/url" |
| 41 |
"path" |
| 42 |
"strings" |
| 43 |
"sync" |
| 44 |
"time" |
| 45 |
|
| 46 |
"github.com/aws/aws-sdk-go-v2/aws" |
| 47 |
"github.com/aws/aws-sdk-go-v2/service/secretsmanager" |
| 48 |
"github.com/aws/aws-sdk-go-v2/service/secretsmanager/types" |
| 49 |
"github.com/aws/smithy-go" |
| 50 |
"github.com/google/wire" |
| 51 |
gcaws "gocloud.dev/aws" |
| 52 |
"gocloud.dev/gcerrors" |
| 53 |
"gocloud.dev/runtimevar" |
| 54 |
"gocloud.dev/runtimevar/driver" |
| 55 |
) |
| 56 |
|
| 57 |
func init() { |
| 58 |
runtimevar.DefaultURLMux().RegisterVariable(Scheme, new(lazySessionOpener)) |
| 59 |
} |
| 60 |
|
| 61 |
// Set holds Wire providers for this package. |
| 62 |
var Set = wire.NewSet( |
| 63 |
Dial, |
| 64 |
) |
| 65 |
|
| 66 |
// Dial gets an AWS secretsmanager service client using the AWS SDK V2. |
| 67 |
func Dial(cfg aws.Config) *secretsmanager.Client { |
| 68 |
return secretsmanager.NewFromConfig(cfg) |
| 69 |
} |
| 70 |
|
| 71 |
// URLOpener opens AWS Secrets Manager URLs like "awssecretsmanager://my-secret-var-name". |
| 72 |
// A friendly name of the secret must be specified. You can NOT specify the Amazon Resource Name (ARN). |
| 73 |
// |
| 74 |
// See https://pkg.go.dev/gocloud.dev/aws#V2ConfigFromURLParams. |
| 75 |
// |
| 76 |
// In addition, the following URL parameters are supported: |
| 77 |
// - decoder: The decoder to use. Defaults to URLOpener.Decoder, or |
| 78 |
// runtimevar.BytesDecoder if URLOpener.Decoder is nil. |
| 79 |
// See runtimevar.DecoderByName for supported values. |
| 80 |
// - wait: The poll interval, in time.ParseDuration formats. |
| 81 |
// Defaults to 30s. |
| 82 |
type URLOpener struct { |
| 83 |
// Decoder specifies the decoder to use if one is not specified in the URL. |
| 84 |
// Defaults to runtimevar.BytesDecoder. |
| 85 |
Decoder *runtimevar.Decoder |
| 86 |
|
| 87 |
// Options specifies the options to pass to New. |
| 88 |
Options Options |
| 89 |
} |
| 90 |
|
| 91 |
// lazySessionOpener obtains the AWS session from the environment on the first |
| 92 |
// call to OpenVariableURL. |
| 93 |
type lazySessionOpener struct { |
| 94 |
init sync.Once |
| 95 |
opener *URLOpener |
| 96 |
err error |
| 97 |
} |
| 98 |
|
| 99 |
func (o *lazySessionOpener) OpenVariableURL(ctx context.Context, u *url.URL) (*runtimevar.Variable, error) { |
| 100 |
opener := &URLOpener{} |
| 101 |
return opener.OpenVariableURL(ctx, u) |
| 102 |
} |
| 103 |
|
| 104 |
// Scheme is the URL scheme awssecretsmanager registers its URLOpener under on runtimevar.DefaultMux. |
| 105 |
const Scheme = "awssecretsmanager" |
| 106 |
|
| 107 |
// OpenVariableURL opens the variable at the URL's path. See the package doc |
| 108 |
// for more details. |
| 109 |
func (o *URLOpener) OpenVariableURL(ctx context.Context, u *url.URL) (*runtimevar.Variable, error) { |
| 110 |
q := u.Query() |
| 111 |
|
| 112 |
decoderName := q.Get("decoder") |
| 113 |
q.Del("decoder") |
| 114 |
decoder, err := runtimevar.DecoderByName(ctx, decoderName, o.Decoder) |
| 115 |
if err != nil { |
| 116 |
return nil, fmt.Errorf("open variable %v: invalid decoder: %v", u, err) |
| 117 |
} |
| 118 |
opts := o.Options |
| 119 |
if s := q.Get("wait"); s != "" { |
| 120 |
q.Del("wait") |
| 121 |
d, err := time.ParseDuration(s) |
| 122 |
if err != nil { |
| 123 |
return nil, fmt.Errorf("open variable %v: invalid wait %q: %v", u, s, err) |
| 124 |
} |
| 125 |
opts.WaitDuration = d |
| 126 |
} |
| 127 |
cfg, err := gcaws.V2ConfigFromURLParams(ctx, q) |
| 128 |
if err != nil { |
| 129 |
return nil, fmt.Errorf("open variable %v: %v", u, err) |
| 130 |
} |
| 131 |
return OpenVariable(secretsmanager.NewFromConfig(cfg), path.Join(u.Host, u.Path), decoder, &opts) |
| 132 |
} |
| 133 |
|
| 134 |
// Options sets options. |
| 135 |
type Options struct { |
| 136 |
// WaitDuration controls the rate at which AWS Secrets Manager is polled. |
| 137 |
// Defaults to 30 seconds. |
| 138 |
WaitDuration time.Duration |
| 139 |
} |
| 140 |
|
| 141 |
// OpenVariable constructs a *runtimevar.Variable backed by the variable name in AWS Secrets Manager, |
| 142 |
// using AWS SDK V2. |
| 143 |
// A friendly name of the secret must be specified. You can NOT specify the Amazon Resource Name (ARN). |
| 144 |
// Secrets Manager returns raw bytes; provide a decoder to decode the raw bytes |
| 145 |
// into the appropriate type for runtimevar.Snapshot.Value. |
| 146 |
// See the runtimevar package documentation for examples of decoders. |
| 147 |
func OpenVariable(client *secretsmanager.Client, name string, decoder *runtimevar.Decoder, opts *Options) (*runtimevar.Variable, error) { |
| 148 |
return runtimevar.New(newWatcher(client, name, decoder, opts)), nil |
| 149 |
} |
| 150 |
|
| 151 |
var OpenVariableV2 = OpenVariable |
| 152 |
|
| 153 |
// state implements driver.State. |
| 154 |
type state struct { |
| 155 |
val any |
| 156 |
rawGet *secretsmanager.GetSecretValueOutput |
| 157 |
rawDesc *secretsmanager.DescribeSecretOutput |
| 158 |
updateTime time.Time |
| 159 |
versionID string |
| 160 |
err error |
| 161 |
} |
| 162 |
|
| 163 |
// Value implements driver.State.Value. |
| 164 |
func (s *state) Value() (any, error) { |
| 165 |
return s.val, s.err |
| 166 |
} |
| 167 |
|
| 168 |
// UpdateTime implements driver.State.UpdateTime. |
| 169 |
func (s *state) UpdateTime() time.Time { |
| 170 |
return s.updateTime |
| 171 |
} |
| 172 |
|
| 173 |
// As implements driver.State.As. |
| 174 |
func (s *state) As(i any) bool { |
| 175 |
switch p := i.(type) { |
| 176 |
case **secretsmanager.GetSecretValueOutput: |
| 177 |
*p = s.rawGet |
| 178 |
case **secretsmanager.DescribeSecretOutput: |
| 179 |
*p = s.rawDesc |
| 180 |
default: |
| 181 |
return false |
| 182 |
} |
| 183 |
return true |
| 184 |
} |
| 185 |
|
| 186 |
// errorState returns a new State with err, unless prevS also represents |
| 187 |
// the same error, in which case it returns nil. |
| 188 |
func errorState(err error, prevS driver.State) driver.State { |
| 189 |
// Map to the more standard context package error. |
| 190 |
if strings.Contains(err.Error(), "context deadline exceeded") { |
| 191 |
err = context.DeadlineExceeded |
| 192 |
} else if getErrorCode(err) == "CancelledError" { |
| 193 |
err = context.Canceled |
| 194 |
} |
| 195 |
s := &state{err: err} |
| 196 |
if prevS == nil { |
| 197 |
return s |
| 198 |
} |
| 199 |
prev := prevS.(*state) |
| 200 |
if prev.err == nil { |
| 201 |
// New error. |
| 202 |
return s |
| 203 |
} |
| 204 |
if equivalentError(err, prev.err) { |
| 205 |
// Same error, return nil to indicate no change. |
| 206 |
return nil |
| 207 |
} |
| 208 |
return s |
| 209 |
} |
| 210 |
|
| 211 |
// equivalentError returns true iff err1 and err2 represent an equivalent error; |
| 212 |
// i.e., we don't want to return it to the user as a different error. |
| 213 |
func equivalentError(err1, err2 error) bool { |
| 214 |
if err1 == err2 || err1.Error() == err2.Error() { |
| 215 |
return true |
| 216 |
} |
| 217 |
code1 := getErrorCode(err1) |
| 218 |
code2 := getErrorCode(err2) |
| 219 |
return code1 != "" && code1 == code2 |
| 220 |
} |
| 221 |
|
| 222 |
type watcher struct { |
| 223 |
// client is the client to use. |
| 224 |
client *secretsmanager.Client |
| 225 |
// name is an ID of a secret to retrieve. |
| 226 |
name string |
| 227 |
// wait is the amount of time to wait between querying AWS. |
| 228 |
wait time.Duration |
| 229 |
// decoder is the decoder that unmarshalls the value in the param. |
| 230 |
decoder *runtimevar.Decoder |
| 231 |
} |
| 232 |
|
| 233 |
func newWatcher(client *secretsmanager.Client, name string, decoder *runtimevar.Decoder, opts *Options) *watcher { |
| 234 |
if opts == nil { |
| 235 |
opts = &Options{} |
| 236 |
} |
| 237 |
return &watcher{ |
| 238 |
client: client, |
| 239 |
name: name, |
| 240 |
wait: driver.WaitDuration(opts.WaitDuration), |
| 241 |
decoder: decoder, |
| 242 |
} |
| 243 |
} |
| 244 |
|
| 245 |
func getSecretValue(ctx context.Context, client *secretsmanager.Client, secretID string) (string, []byte, string, *secretsmanager.GetSecretValueOutput, error) { |
| 246 |
getResp, err := client.GetSecretValue(ctx, &secretsmanager.GetSecretValueInput{ |
| 247 |
SecretId: aws.String(secretID), |
| 248 |
}) |
| 249 |
if err != nil { |
| 250 |
return "", nil, "", nil, err |
| 251 |
} |
| 252 |
return aws.ToString(getResp.VersionId), getResp.SecretBinary, aws.ToString(getResp.SecretString), getResp, nil |
| 253 |
} |
| 254 |
|
| 255 |
func describeSecret(ctx context.Context, client *secretsmanager.Client, secretID string) (time.Time, *secretsmanager.DescribeSecretOutput, error) { |
| 256 |
descResp, err := client.DescribeSecret(ctx, &secretsmanager.DescribeSecretInput{ |
| 257 |
SecretId: aws.String(secretID), |
| 258 |
}) |
| 259 |
if err != nil { |
| 260 |
return time.Time{}, nil, err |
| 261 |
} |
| 262 |
return aws.ToTime(descResp.LastChangedDate), descResp, nil |
| 263 |
} |
| 264 |
|
| 265 |
// WatchVariable implements driver.WatchVariable. |
| 266 |
func (w *watcher) WatchVariable(ctx context.Context, prev driver.State) (driver.State, time.Duration) { |
| 267 |
var lastVersionID string |
| 268 |
if prev != nil { |
| 269 |
lastVersionID = prev.(*state).versionID |
| 270 |
} |
| 271 |
|
| 272 |
// GetParameter from S3 to get the current value and version. |
| 273 |
newVersionID, newValBinary, newValString, rawGet, err := getSecretValue(ctx, w.client, w.name) |
| 274 |
if err != nil { |
| 275 |
return errorState(err, prev), w.wait |
| 276 |
} |
| 277 |
if newVersionID == lastVersionID { |
| 278 |
// Version hasn't changed, so no change; return nil. |
| 279 |
return nil, w.wait |
| 280 |
} |
| 281 |
// Both SecretBinary and SecretString fields are not empty |
| 282 |
// which could indicate some internal Secrets Manager issues. |
| 283 |
// Hence, return explicit error instead of choosing one field over another. |
| 284 |
if len(newValBinary) > 0 && newValString != "" { |
| 285 |
err = fmt.Errorf("invalid %q response: both SecretBinary and SecretString are not empty", w.name) |
| 286 |
return errorState(err, prev), w.wait |
| 287 |
} |
| 288 |
|
| 289 |
data := newValBinary |
| 290 |
if len(data) == 0 { |
| 291 |
if newValString == "" { |
| 292 |
err = fmt.Errorf("invalid %q response: both SecretBinary and SecretString are empty", w.name) |
| 293 |
return errorState(err, prev), w.wait |
| 294 |
} |
| 295 |
// SecretBinary is empty so use SecretString |
| 296 |
data = []byte(newValString) |
| 297 |
} |
| 298 |
|
| 299 |
// DescribeParameters from S3 to get the LastModified date. |
| 300 |
newLastModified, rawDesc, err := describeSecret(ctx, w.client, w.name) |
| 301 |
if err != nil { |
| 302 |
return errorState(err, prev), w.wait |
| 303 |
} |
| 304 |
|
| 305 |
// New value (or at least, new version). Decode it. |
| 306 |
val, err := w.decoder.Decode(ctx, data) |
| 307 |
if err != nil { |
| 308 |
return errorState(err, prev), w.wait |
| 309 |
} |
| 310 |
|
| 311 |
return &state{ |
| 312 |
val: val, |
| 313 |
rawGet: rawGet, |
| 314 |
rawDesc: rawDesc, |
| 315 |
updateTime: newLastModified, |
| 316 |
versionID: newVersionID, |
| 317 |
}, w.wait |
| 318 |
} |
| 319 |
|
| 320 |
// Close implements driver.Close. |
| 321 |
func (w *watcher) Close() error { |
| 322 |
return nil |
| 323 |
} |
| 324 |
|
| 325 |
// ErrorAs implements driver.ErrorAs. |
| 326 |
func (w *watcher) ErrorAs(err error, i any) bool { |
| 327 |
return errors.As(err, i) |
| 328 |
} |
| 329 |
|
| 330 |
func getErrorCode(err error) string { |
| 331 |
var ae smithy.APIError |
| 332 |
if errors.As(err, &ae) { |
| 333 |
return ae.ErrorCode() |
| 334 |
} |
| 335 |
return "" |
| 336 |
} |
| 337 |
|
| 338 |
// ErrorCode implements driver.ErrorCode. |
| 339 |
func (w *watcher) ErrorCode(err error) gcerrors.ErrorCode { |
| 340 |
code := getErrorCode(err) |
| 341 |
ec, ok := errorCodeMap[code] |
| 342 |
if !ok { |
| 343 |
return gcerrors.Unknown |
| 344 |
} |
| 345 |
return ec |
| 346 |
} |
| 347 |
|
| 348 |
var errorCodeMap = map[string]gcerrors.ErrorCode{ |
| 349 |
(&types.ResourceNotFoundException{}).ErrorCode(): gcerrors.NotFound, |
| 350 |
(&types.InvalidParameterException{}).ErrorCode(): gcerrors.InvalidArgument, |
| 351 |
(&types.InvalidRequestException{}).ErrorCode(): gcerrors.InvalidArgument, |
| 352 |
(&types.InvalidNextTokenException{}).ErrorCode(): gcerrors.InvalidArgument, |
| 353 |
(&types.EncryptionFailure{}).ErrorCode(): gcerrors.Internal, |
| 354 |
(&types.DecryptionFailure{}).ErrorCode(): gcerrors.Internal, |
| 355 |
(&types.InternalServiceError{}).ErrorCode(): gcerrors.Internal, |
| 356 |
(&types.ResourceExistsException{}).ErrorCode(): gcerrors.AlreadyExists, |
| 357 |
(&types.PreconditionNotMetException{}).ErrorCode(): gcerrors.FailedPrecondition, |
| 358 |
(&types.MalformedPolicyDocumentException{}).ErrorCode(): gcerrors.FailedPrecondition, |
| 359 |
(&types.LimitExceededException{}).ErrorCode(): gcerrors.ResourceExhausted, |
| 360 |
} |