| 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 |
| 16 |
|
| 17 |
import ( |
| 18 |
"bytes" |
| 19 |
"context" |
| 20 |
"crypto/sha1" |
| 21 |
"errors" |
| 22 |
"fmt" |
| 23 |
"testing" |
| 24 |
"time" |
| 25 |
|
| 26 |
"github.com/aws/aws-sdk-go-v2/aws" |
| 27 |
"github.com/aws/aws-sdk-go-v2/service/secretsmanager" |
| 28 |
"github.com/aws/smithy-go" |
| 29 |
"github.com/googleapis/gax-go/v2" |
| 30 |
"gocloud.dev/gcerrors" |
| 31 |
"gocloud.dev/internal/gcerr" |
| 32 |
"gocloud.dev/internal/retry" |
| 33 |
"gocloud.dev/internal/testing/setup" |
| 34 |
"gocloud.dev/runtimevar" |
| 35 |
"gocloud.dev/runtimevar/driver" |
| 36 |
"gocloud.dev/runtimevar/drivertest" |
| 37 |
) |
| 38 |
|
| 39 |
// This constant records the region used for the last --record. |
| 40 |
// If you want to use --record mode, |
| 41 |
// 1. Update this constant to your AWS region. |
| 42 |
// TODO(issue #300): Use Terraform to get this. |
| 43 |
const region = "us-east-2" |
| 44 |
|
| 45 |
type harness struct { |
| 46 |
client *secretsmanager.Client |
| 47 |
closer func() |
| 48 |
} |
| 49 |
|
| 50 |
// waitForMutation uses check to wait until a mutation has taken effect. |
| 51 |
// The check function should return nil to indicate success (the mutation has |
| 52 |
// taken effect), an error with gcerrors.ErrorCode == NotFound to trigger |
| 53 |
// a retry, or any other error to signal permanent failure. |
| 54 |
func waitForMutation(ctx context.Context, check func() error) error { |
| 55 |
backoff := gax.Backoff{Multiplier: 1.0} |
| 56 |
var initial time.Duration |
| 57 |
if *setup.Record { |
| 58 |
// When recording, wait 3 seconds and then poll every 2s. |
| 59 |
initial = 3 * time.Second |
| 60 |
backoff.Initial = 2 * time.Second |
| 61 |
} else { |
| 62 |
// During replay, we don't wait at all. |
| 63 |
// The recorded file may have retries, but we don't need to actually wait between them. |
| 64 |
backoff.Initial = 1 * time.Millisecond |
| 65 |
} |
| 66 |
backoff.Max = backoff.Initial |
| 67 |
|
| 68 |
// Sleep before the check, since we know it doesn't take effect right away. |
| 69 |
time.Sleep(initial) |
| 70 |
|
| 71 |
// retryIfNotFound returns true if err is NotFound. |
| 72 |
retryIfNotFound := func(err error) bool { return gcerrors.Code(err) == gcerrors.NotFound } |
| 73 |
|
| 74 |
// Poll until the mtuation is seen. |
| 75 |
return retry.Call(ctx, backoff, retryIfNotFound, check) |
| 76 |
} |
| 77 |
|
| 78 |
// AWS Secrets Manager requires unique token for Create and Update requests to ensure idempotency. |
| 79 |
// From the other side, request data must be deterministic in order to make tests reproducible. |
| 80 |
// generateClientRequestToken generates token which is unique per test session but deterministic. |
| 81 |
func generateClientRequestToken(name string, data []byte) string { |
| 82 |
const maxClientRequestTokenLen = 64 |
| 83 |
h := sha1.New() |
| 84 |
_, _ = h.Write(data) |
| 85 |
|
| 86 |
token := fmt.Sprintf("%s-%x", name, h.Sum(nil)) |
| 87 |
|
| 88 |
// Token must have length less than or equal to 64 |
| 89 |
if len(token) > maxClientRequestTokenLen { |
| 90 |
token = token[:maxClientRequestTokenLen] |
| 91 |
} |
| 92 |
|
| 93 |
return token |
| 94 |
} |
| 95 |
|
| 96 |
func newHarness(t *testing.T) (drivertest.Harness, error) { |
| 97 |
t.Helper() |
| 98 |
|
| 99 |
cfg, _, done, _ := setup.NewAWSv2Config(context.Background(), t, region, false) |
| 100 |
return &harness{ |
| 101 |
client: secretsmanager.NewFromConfig(cfg), |
| 102 |
closer: done, |
| 103 |
}, nil |
| 104 |
} |
| 105 |
|
| 106 |
func (h *harness) MakeWatcher(_ context.Context, name string, decoder *runtimevar.Decoder) (driver.Watcher, error) { |
| 107 |
return newWatcher(h.client, name, decoder, nil), nil |
| 108 |
} |
| 109 |
|
| 110 |
func (h *harness) CreateVariable(ctx context.Context, name string, val []byte) error { |
| 111 |
if _, err := h.client.CreateSecret(ctx, &secretsmanager.CreateSecretInput{ |
| 112 |
Name: aws.String(name), |
| 113 |
ClientRequestToken: aws.String(generateClientRequestToken(name, val)), |
| 114 |
SecretBinary: val, |
| 115 |
}); err != nil { |
| 116 |
return err |
| 117 |
} |
| 118 |
// Secret Manager is only eventually consistent, so we retry until we've |
| 119 |
// verified that the mutation was applied. This is still not a guarantee |
| 120 |
// but in practice seems to work well enough to make tests repeatable. |
| 121 |
return waitForMutation(ctx, func() error { |
| 122 |
_, err := h.client.GetSecretValue(ctx, &secretsmanager.GetSecretValueInput{SecretId: aws.String(name)}) |
| 123 |
if err == nil { |
| 124 |
// Create was seen. |
| 125 |
return nil |
| 126 |
} |
| 127 |
// Failure; we'll retry if it's a NotFound. |
| 128 |
w := &watcher{} |
| 129 |
return gcerr.New(w.ErrorCode(err), err, 1, "runtimevar") |
| 130 |
}) |
| 131 |
} |
| 132 |
|
| 133 |
func (h *harness) UpdateVariable(ctx context.Context, name string, val []byte) error { |
| 134 |
if _, err := h.client.PutSecretValue(ctx, &secretsmanager.PutSecretValueInput{ |
| 135 |
ClientRequestToken: aws.String(generateClientRequestToken(name, val)), |
| 136 |
SecretBinary: val, |
| 137 |
SecretId: aws.String(name), |
| 138 |
}); err != nil { |
| 139 |
return err |
| 140 |
} |
| 141 |
// Secret Manager is only eventually consistent, so we retry until we've |
| 142 |
// verified that the mutation was applied. This is still not a guarantee |
| 143 |
// but in practice seems to work well enough to make tests repeatable. |
| 144 |
return waitForMutation(ctx, func() error { |
| 145 |
var err error |
| 146 |
var bb []byte |
| 147 |
var getResp *secretsmanager.GetSecretValueOutput |
| 148 |
getResp, err = h.client.GetSecretValue(ctx, &secretsmanager.GetSecretValueInput{SecretId: aws.String(name)}) |
| 149 |
if err == nil { |
| 150 |
bb = getResp.SecretBinary |
| 151 |
} |
| 152 |
if err != nil { |
| 153 |
// Failure; we'll retry if it's a NotFound, but that's not |
| 154 |
// really expected for an Update. |
| 155 |
w := &watcher{} |
| 156 |
return gcerr.New(w.ErrorCode(err), err, 1, "runtimevar") |
| 157 |
} |
| 158 |
if !bytes.Equal(bb, val) { |
| 159 |
// Value hasn't been updated yet, return a NotFound to |
| 160 |
// trigger retry. |
| 161 |
return gcerr.Newf(gcerr.NotFound, nil, "updated value not seen yet") |
| 162 |
} |
| 163 |
// Update was seen. |
| 164 |
return nil |
| 165 |
}) |
| 166 |
} |
| 167 |
|
| 168 |
func (h *harness) DeleteVariable(ctx context.Context, name string) error { |
| 169 |
if _, err := h.client.DeleteSecret(ctx, &secretsmanager.DeleteSecretInput{ |
| 170 |
ForceDeleteWithoutRecovery: aws.Bool(true), |
| 171 |
SecretId: aws.String(name), |
| 172 |
}); err != nil { |
| 173 |
return err |
| 174 |
} |
| 175 |
// Secret Manager is only eventually consistent, so we retry until we've |
| 176 |
// verified that the mutation was applied. This is still not a guarantee |
| 177 |
// but in practice seems to work well enough to make tests repeatable. |
| 178 |
// Note that "success" after a delete is a NotFound error, so we massage |
| 179 |
// the err returned from DescribeSecret to reflect that. |
| 180 |
return waitForMutation(ctx, func() error { |
| 181 |
_, err := h.client.DescribeSecret(ctx, &secretsmanager.DescribeSecretInput{SecretId: aws.String(name)}) |
| 182 |
if err == nil { |
| 183 |
// Secret still exists, return a NotFound to trigger a retry. |
| 184 |
return gcerr.Newf(gcerr.NotFound, nil, "delete not seen yet") |
| 185 |
} |
| 186 |
w := &watcher{} |
| 187 |
if w.ErrorCode(err) == gcerrors.NotFound { |
| 188 |
// Delete was seen. |
| 189 |
return nil |
| 190 |
} |
| 191 |
// Other errors are not retryable. |
| 192 |
return gcerr.New(w.ErrorCode(err), err, 1, "runtimevar") |
| 193 |
}) |
| 194 |
} |
| 195 |
|
| 196 |
func (h *harness) Close() { |
| 197 |
h.closer() |
| 198 |
} |
| 199 |
|
| 200 |
func (h *harness) Mutable() bool { return true } |
| 201 |
|
| 202 |
func TestConformance(t *testing.T) { |
| 203 |
drivertest.RunConformanceTests(t, newHarness, []drivertest.AsTest{verifyAs{}}) |
| 204 |
} |
| 205 |
|
| 206 |
type verifyAs struct { |
| 207 |
} |
| 208 |
|
| 209 |
func (verifyAs) Name() string { |
| 210 |
return "verify As" |
| 211 |
} |
| 212 |
|
| 213 |
func (v verifyAs) SnapshotCheck(s *runtimevar.Snapshot) error { |
| 214 |
var getParam *secretsmanager.GetSecretValueOutput |
| 215 |
if !s.As(&getParam) { |
| 216 |
return errors.New("Snapshot.As failed for GetSecretValueOutput") |
| 217 |
} |
| 218 |
var descParam *secretsmanager.DescribeSecretOutput |
| 219 |
if !s.As(&descParam) { |
| 220 |
return errors.New("Snapshot.As failed for DescribeSecretOutput") |
| 221 |
} |
| 222 |
return nil |
| 223 |
} |
| 224 |
|
| 225 |
func (va verifyAs) ErrorCheck(v *runtimevar.Variable, err error) error { |
| 226 |
var e smithy.APIError |
| 227 |
if !v.ErrorAs(err, &e) { |
| 228 |
return errors.New("Keeper.ErrorAs failed") |
| 229 |
} |
| 230 |
return nil |
| 231 |
} |
| 232 |
|
| 233 |
// Secrets Manager-specific tests. |
| 234 |
|
| 235 |
func TestOpenVariable(t *testing.T) { |
| 236 |
tests := []struct { |
| 237 |
URL string |
| 238 |
WantErr bool |
| 239 |
}{ |
| 240 |
// OK. |
| 241 |
{"awssecretsmanager://myvar", false}, |
| 242 |
// OK, setting region. |
| 243 |
{"awssecretsmanager://myvar?region=us-west-1", false}, |
| 244 |
// OK, setting decoder. |
| 245 |
{"awssecretsmanager://myvar?decoder=string", false}, |
| 246 |
// Invalid decoder. |
| 247 |
{"awssecretsmanager://myvar?decoder=notadecoder", true}, |
| 248 |
// OK, setting wait. |
| 249 |
{"awssecretsmanager://myvar?wait=5m", false}, |
| 250 |
// Invalid wait. |
| 251 |
{"awssecretsmanager://myvar?wait=xx", true}, |
| 252 |
// Invalid parameter. |
| 253 |
{"awssecretsmanager://myvar?param=value", true}, |
| 254 |
} |
| 255 |
|
| 256 |
ctx := context.Background() |
| 257 |
for _, test := range tests { |
| 258 |
v, err := runtimevar.OpenVariable(ctx, test.URL) |
| 259 |
if (err != nil) != test.WantErr { |
| 260 |
t.Errorf("%s: got error %v, want error %v", test.URL, err, test.WantErr) |
| 261 |
} |
| 262 |
if err == nil { |
| 263 |
v.Close() |
| 264 |
} |
| 265 |
} |
| 266 |
} |