Ejemplo n.º 1
0
        public async Task TestAssumeRoleWithWebIdentityCredentialsPropertiesUsedInAsyncSTSCallAsync()
        {
            #region Setup
            // Set up request variables
            var dummyToken               = "dummyToken";
            var dummyRoleArn             = "dummyRoleArn";
            var dummyRoleSessionName     = "dummyRoleSessionName";
            var dummyOptions             = new AssumeRoleWithWebIdentityCredentialsOptions();
            var currentDirectory         = Directory.GetCurrentDirectory();
            var webIdentityTokenFilePath = Path.Combine(currentDirectory, "my-token.jwt");
            File.WriteAllText(webIdentityTokenFilePath, dummyToken);
            var equalityCheck = new Func <AssumeRoleWithWebIdentityRequest, bool>(req =>
            {
                return(req.DurationSeconds.Equals(dummyOptions.DurationSeconds ?? 0) &&
                       string.Equals(req.Policy, dummyOptions.Policy) &&
                       Equals(req.PolicyArns, dummyOptions.PolicyArns) &&
                       Equals(req.ProviderId, dummyOptions.ProviderId) &&
                       req.RoleArn.Equals(dummyRoleArn) &&
                       req.RoleSessionName.Equals(dummyRoleSessionName) &&
                       req.WebIdentityToken.Equals(dummyToken));
            });
            var envVariables = new Dictionary <string, string>()
            {
                { AssumeRoleWithWebIdentityCredentials.WebIdentityTokenFileEnvVariable, webIdentityTokenFilePath },
                { AssumeRoleWithWebIdentityCredentials.RoleArnEnvVariable, dummyRoleArn },
                { AssumeRoleWithWebIdentityCredentials.RoleSessionNameEnvVariable, dummyRoleSessionName },
            };
            // Set up response
            var dummyAccessKeyId     = "dummyAccessKeyId";
            var dummySecretAccessKey = "dummySecretAccessKey";
            var dummySessionToken    = "dummySessionToken";
            var dummyExpiration      = DateTime.UtcNow.AddDays(1);
            var forcedResponse       = new AssumeRoleWithWebIdentityResponse()
            {
                Credentials = new Credentials(dummyAccessKeyId, dummySecretAccessKey, dummySessionToken, dummyExpiration)
            };
            // Setup service client mock
            var mock = new Mock <AmazonSecurityTokenServiceClient>();
            Expression <Func <AmazonSecurityTokenServiceClient, Task <AssumeRoleWithWebIdentityResponse> > > stsCall = c => c.AssumeRoleWithWebIdentityAsync(It.Is <AssumeRoleWithWebIdentityRequest>(req => equalityCheck(req)), new System.Threading.CancellationToken());
            mock.Setup(stsCall).Returns(Task.FromResult(forcedResponse));
            // Setup credentials
            using (var testCredentials = new AssumeRoleWithWebIdentityTestCredentials(webIdentityTokenFilePath, dummyRoleArn, dummyRoleSessionName, dummyOptions)
            {
                Client = mock.Object
            })
            {
                using (new FallbackFactoryTestFixture(ProfileText, "default", envVariables))
                {
                    #endregion Setup

                    #region Act
                    await testCredentials.GetCredentialsAsync().ConfigureAwait(false);

                    #endregion Act
                }
            }

            // Verify that the credential properties were used for the STS call
            mock.Verify(stsCall, Times.Once);
        }
        public async Task TestRetriesOnExceptionAsync <T>(T excpetion) where T : AmazonServiceException
        {
            var webIdentityToken = "Dummy.OIDC.Token";
            var roleArn          = "someRoleArn";
            var roleSessionName  = "someRoleSessionName";

            var currentDirectory         = Directory.GetCurrentDirectory();
            var webIdentityTokenFilePath = Path.Combine(currentDirectory, "my-token.jwt");

            File.WriteAllText(webIdentityTokenFilePath, webIdentityToken);

            var envVariables = new Dictionary <string, string>()
            {
                { AssumeRoleWithWebIdentityCredentials.WebIdentityTokenFileEnvVariable, webIdentityTokenFilePath },
                { AssumeRoleWithWebIdentityCredentials.RoleArnEnvVariable, roleArn },
                { AssumeRoleWithWebIdentityCredentials.RoleSessionNameEnvVariable, roleSessionName },
            };

            AWSCredentials awsCredentials;

            using (new FallbackFactoryTestFixture(envVariables))
            {
                awsCredentials = FallbackCredentialsFactory.GetCredentials();
            }

            var webIdentityCredentials = new AssumeRoleWithWebIdentityTestCredentials((AssumeRoleWithWebIdentityCredentials)awsCredentials, null);
            var retries  = 0;
            var client   = webIdentityCredentials.Client as AmazonSecurityTokenServiceClient;
            var pipeline = client
                           .GetType()
                           .GetProperty("RuntimePipeline", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
                           .GetValue(client, null)
                           as RuntimePipeline;
            // Setup STS failures
            var credentialsRetriever = new Mock <CredentialsRetriever>(awsCredentials);

            credentialsRetriever.Setup(cr => cr.InvokeAsync <AssumeRoleWithWebIdentityResponse>(It.IsAny <IExecutionContext>())).ThrowsAsync(excpetion); // Setting up the exception here
            pipeline.ReplaceHandler <CredentialsRetriever>(credentialsRetriever.Object);
            // Setup retry count notifications
            var retryHandler          = pipeline.Handlers.Find(h => h is RetryHandler) as RetryHandler;
            var notifyingRetryHandler = new NotifyingRetryHandler(client.Config);

            notifyingRetryHandler.AddHandler((object sender, RetryEventArgs e) => { retries++; });
            pipeline.ReplaceHandler <RetryHandler>(notifyingRetryHandler);
            var defaultRetryPolicy = new DefaultRetryPolicy(client.Config);

            using (new FallbackFactoryTestFixture(envVariables))
            {
                // Act and Assert
                await Assert.ThrowsExceptionAsync <AmazonClientException>(async() => await webIdentityCredentials.GetCredentialsAsync());
            }

            Assert.AreEqual(defaultRetryPolicy.MaxRetries, retries);

            webIdentityCredentials.Dispose();
        }