Ejemplo n.º 1
0
        public static string GetSecret()
        {
            string secretName = "prod/AWSServerless/DBString";
            string region     = "us-west-2";
            string secret     = "";

            MemoryStream memoryStream = new MemoryStream();

            IAmazonSecretsManager client = new AmazonSecretsManagerClient(RegionEndpoint.GetBySystemName(region));

            GetSecretValueRequest request = new GetSecretValueRequest();

            request.SecretId     = secretName;
            request.VersionStage = "AWSCURRENT"; // VersionStage defaults to AWSCURRENT if unspecified.

            GetSecretValueResponse response = null;

            // In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
            // See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
            // We rethrow the exception by default.

            try
            {
                response = client.GetSecretValueAsync(request).Result;
            }
            catch (DecryptionFailureException e)
            {
                // Secrets Manager can't decrypt the protected secret text using the provided KMS key.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }
            catch (InternalServiceErrorException e)
            {
                // An error occurred on the server side.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }
            catch (InvalidParameterException e)
            {
                // You provided an invalid value for a parameter.
                // Deal with the exception here, and/or rethrow at your discretion
                throw;
            }
            catch (InvalidRequestException e)
            {
                // You provided a parameter value that is not valid for the current state of the resource.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }
            catch (ResourceNotFoundException e)
            {
                // We can't find the resource that you asked for.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }
            catch (System.AggregateException ae)
            {
                // More than one of the above exceptions were triggered.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }

            // Decrypts secret using the associated KMS CMK.
            // Depending on whether the secret is a string or binary, one of these fields will be populated.
            if (response.SecretString != null)
            {
                secret = response.SecretString;
            }
            else
            {
                memoryStream = response.SecretBinary;
                StreamReader reader = new StreamReader(memoryStream);
                string       decodedBinarySecret = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(reader.ReadToEnd()));
            }

            return(secret);
        }
Ejemplo n.º 2
0
        public string GetSecret(string secretName)
        {
            _logger.Info($"Getting secret of {secretName}");

            if (_dictionary.ContainsKey(secretName))
            {
                return(_dictionary[secretName]);
            }

            string secret = "";

            MemoryStream          memoryStream = new MemoryStream();
            GetSecretValueRequest request      = new GetSecretValueRequest();

            request.SecretId     = secretName;
            request.VersionStage = "AWSCURRENT"; // VersionStage defaults to AWSCURRENT if unspecified.

            GetSecretValueResponse response = null;

            try
            {
                response = _secretsManagerClient.GetSecretValueAsync(request).Result;
            }
            catch (DecryptionFailureException e)
            {
                // Secrets Manager can't decrypt the protected secret text using the provided KMS key.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }
            catch (InternalServiceErrorException e)
            {
                // An error occurred on the server side.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }
            catch (InvalidParameterException e)
            {
                // You provided an invalid value for a parameter.
                // Deal with the exception here, and/or rethrow at your discretion
                throw;
            }
            catch (InvalidRequestException e)
            {
                // You provided a parameter value that is not valid for the current state of the resource.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }
            catch (ResourceNotFoundException e)
            {
                // We can't find the resource that you asked for.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }
            catch (System.AggregateException ae)
            {
                // More than one of the above exceptions were triggered.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw;
            }

            // Decrypts secret using the associated KMS CMK.
            // Depending on whether the secret is a string or binary, one of these fields will be populated.
            if (response.SecretString != null)
            {
                secret = response.SecretString;

                _dictionary.Add(secretName, secret);
            }
            else
            {
                memoryStream = response.SecretBinary;
                StreamReader reader = new StreamReader(memoryStream);
                string       decodedBinarySecret = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(reader.ReadToEnd()));
            }

            _logger.Info($"Secret is {secret}");

            return(secret);
        }
        public void Should_poll_and_reload_when_secrets_changed([Frozen] SecretListEntry testEntry, ListSecretsResponse listSecretsResponse, GetSecretValueResponse getSecretValueInitialResponse, GetSecretValueResponse getSecretValueUpdatedResponse, [Frozen] IAmazonSecretsManager secretsManager, [Frozen] SecretsManagerConfigurationProviderOptions options, SecretsManagerConfigurationProvider sut, IFixture fixture, Action <object> changeCallback, object changeCallbackState)
        {
            Mock.Get(secretsManager).Setup(p => p.ListSecretsAsync(It.IsAny <ListSecretsRequest>(), It.IsAny <CancellationToken>())).ReturnsAsync(listSecretsResponse);

            Mock.Get(secretsManager).SetupSequence(p => p.GetSecretValueAsync(It.IsAny <GetSecretValueRequest>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(getSecretValueInitialResponse)
            .ReturnsAsync(getSecretValueUpdatedResponse);

            options.PollingInterval = TimeSpan.FromMilliseconds(100);

            sut.GetReloadToken().RegisterChangeCallback(changeCallback, changeCallbackState);

            sut.Load();
            Assert.That(sut.Get(testEntry.Name), Is.EqualTo(getSecretValueInitialResponse.SecretString));

            Thread.Sleep(200);

            Mock.Get(changeCallback).Verify(c => c(changeCallbackState));
            Assert.That(sut.Get(testEntry.Name), Is.EqualTo(getSecretValueUpdatedResponse.SecretString));
        }
        public async Task Should_reload_when_forceReload_called([Frozen] SecretListEntry testEntry, ListSecretsResponse listSecretsResponse, GetSecretValueResponse getSecretValueInitialResponse, GetSecretValueResponse getSecretValueUpdatedResponse, [Frozen] IAmazonSecretsManager secretsManager, [Frozen] SecretsManagerConfigurationProviderOptions options, SecretsManagerConfigurationProvider sut, IFixture fixture, Action <object> changeCallback, object changeCallbackState)
        {
            Mock.Get(secretsManager).Setup(p => p.ListSecretsAsync(It.IsAny <ListSecretsRequest>(), It.IsAny <CancellationToken>())).ReturnsAsync(listSecretsResponse);

            Mock.Get(secretsManager).SetupSequence(p => p.GetSecretValueAsync(It.IsAny <GetSecretValueRequest>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(getSecretValueInitialResponse)
            .ReturnsAsync(getSecretValueUpdatedResponse);

            sut.GetReloadToken().RegisterChangeCallback(changeCallback, changeCallbackState);

            sut.Load();
            Assert.That(sut.Get(testEntry.Name), Is.EqualTo(getSecretValueInitialResponse.SecretString));


            await sut.ForceReloadAsync(CancellationToken.None);

            Mock.Get(changeCallback).Verify(c => c(changeCallbackState));
            Assert.That(sut.Get(testEntry.Name), Is.EqualTo(getSecretValueUpdatedResponse.SecretString));
        }
        public void Simple_values_in_string_can_be_handled([Frozen] SecretListEntry testEntry, ListSecretsResponse listSecretsResponse, GetSecretValueResponse getSecretValueResponse, [Frozen] IAmazonSecretsManager secretsManager, SecretsManagerConfigurationProvider sut, IFixture fixture)
        {
            Mock.Get(secretsManager).Setup(p => p.ListSecretsAsync(It.IsAny <ListSecretsRequest>(), It.IsAny <CancellationToken>())).ReturnsAsync(listSecretsResponse);

            Mock.Get(secretsManager).Setup(p => p.GetSecretValueAsync(It.IsAny <GetSecretValueRequest>(), It.IsAny <CancellationToken>())).ReturnsAsync(getSecretValueResponse);

            sut.Load();

            Assert.That(sut.Get(testEntry.Name), Is.EqualTo(getSecretValueResponse.SecretString));
        }
        public void Keys_should_be_case_insensitive([Frozen] SecretListEntry testEntry, ListSecretsResponse listSecretsResponse, GetSecretValueResponse getSecretValueResponse, [Frozen] IAmazonSecretsManager secretsManager, SecretsManagerConfigurationProvider sut, IFixture fixture)
        {
            Mock.Get(secretsManager).Setup(p => p.ListSecretsAsync(It.IsAny <ListSecretsRequest>(), It.IsAny <CancellationToken>())).ReturnsAsync(listSecretsResponse);

            Mock.Get(secretsManager).Setup(p => p.GetSecretValueAsync(It.IsAny <GetSecretValueRequest>(), It.IsAny <CancellationToken>())).ReturnsAsync(getSecretValueResponse);

            sut.Load();

            Assert.That(sut.Get(testEntry.Name.ToLower()), Is.EqualTo(getSecretValueResponse.SecretString));
            Assert.That(sut.Get(testEntry.Name.ToUpper()), Is.EqualTo(getSecretValueResponse.SecretString));
        }
        public void Keys_can_be_customized_via_options([Frozen] SecretListEntry testEntry, ListSecretsResponse listSecretsResponse, GetSecretValueResponse getSecretValueResponse, string newKey, [Frozen] IAmazonSecretsManager secretsManager, [Frozen] SecretsManagerConfigurationProviderOptions options, SecretsManagerConfigurationProvider sut, IFixture fixture)
        {
            Mock.Get(secretsManager).Setup(p => p.ListSecretsAsync(It.IsAny <ListSecretsRequest>(), It.IsAny <CancellationToken>())).ReturnsAsync(listSecretsResponse);

            Mock.Get(secretsManager).Setup(p => p.GetSecretValueAsync(It.IsAny <GetSecretValueRequest>(), It.IsAny <CancellationToken>())).ReturnsAsync(getSecretValueResponse);

            options.KeyGenerator = (entry, key) => newKey;

            sut.Load();

            Assert.That(sut.Get(testEntry.Name), Is.Null);
            Assert.That(sut.Get(newKey), Is.EqualTo(getSecretValueResponse.SecretString));
        }
        public void Secrets_can_be_filtered_out_via_options_on_fetching([Frozen] SecretListEntry testEntry, ListSecretsResponse listSecretsResponse, GetSecretValueResponse getSecretValueResponse, [Frozen] IAmazonSecretsManager secretsManager, [Frozen] SecretsManagerConfigurationProviderOptions options, SecretsManagerConfigurationProvider sut, IFixture fixture)
        {
            options.ListSecretsFilters = new List <Filter> {
                new Filter {
                    Key = FilterNameStringType.Name, Values = new List <string> {
                        testEntry.Name
                    }
                }
            };

            Mock.Get(secretsManager).Setup(p => p.ListSecretsAsync(It.Is <ListSecretsRequest>(request => request.Filters == options.ListSecretsFilters), It.IsAny <CancellationToken>())).ReturnsAsync(listSecretsResponse);

            sut.Load();

            Mock.Get(secretsManager).Verify(p => p.ListSecretsAsync(It.Is <ListSecretsRequest>(request => request.Filters == options.ListSecretsFilters), It.IsAny <CancellationToken>()));

            Assert.That(sut.Get(testEntry.Name), Is.Null);
        }
        public void Secrets_can_be_listed_explicitly_and_not_searched([Frozen] SecretListEntry testEntry, ListSecretsResponse listSecretsResponse, GetSecretValueResponse getSecretValueResponse, [Frozen] IAmazonSecretsManager secretsManager, [Frozen] SecretsManagerConfigurationProviderOptions options, SecretsManagerConfigurationProvider sut, IFixture fixture)
        {
            const string secretKey      = "KEY";
            var          firstSecretArn = listSecretsResponse.SecretList.Select(x => x.ARN).First();

            Mock.Get(secretsManager).Setup(p => p.GetSecretValueAsync(It.Is <GetSecretValueRequest>(x => x.SecretId.Equals(firstSecretArn)), It.IsAny <CancellationToken>())).ReturnsAsync(getSecretValueResponse);

            options.SecretFilter       = entry => true;
            options.AcceptedSecretArns = new List <string> {
                firstSecretArn
            };
            options.KeyGenerator = (entry, key) => secretKey;

            sut.Load();

            Mock.Get(secretsManager).Verify(p => p.GetSecretValueAsync(It.Is <GetSecretValueRequest>(x => !x.SecretId.Equals(firstSecretArn)), It.IsAny <CancellationToken>()), Times.Never);
            Mock.Get(secretsManager).Verify(p => p.ListSecretsAsync(It.IsAny <ListSecretsRequest>(), It.IsAny <CancellationToken>()), Times.Never);

            Assert.That(sut.Get(testEntry.Name), Is.Null);
            Assert.That(sut.Get(secretKey), Is.EqualTo(getSecretValueResponse.SecretString));
        }