コード例 #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);
        }
コード例 #2
0
        public async void TestAssumeRoleWithWebIdentityCredentialsUsesAnonymousAWSCredentialsToFetch()
        {
            var user = await Client.GetUserAsync().ConfigureAwait(false);

            var createRoleRequest = new CreateRoleRequest()
            {
                RoleName = "DummyAccountRole",
                AssumeRolePolicyDocument = "{\"Version\": \"2012-10-17\", \"Statement\": [{ \"Effect\": \"Allow\",\"Principal\": {\"AWS\": \"" + user.User.Arn + "\"},\"Action\": \"sts:AssumeRole\",\"Condition\": {}}]}"
            };
            var role = await Client.CreateRoleAsync(createRoleRequest).ConfigureAwait(false);

            var dummyToken               = "dummyToken";
            var dummyRoleArn             = role.Role.Arn;
            var dummyRoleSessionName     = "dummyRoleSessionName";
            var dummyOptions             = new AssumeRoleWithWebIdentityCredentialsOptions();
            var currentDirectory         = Directory.GetCurrentDirectory();
            var webIdentityTokenFilePath = Path.Combine(currentDirectory, "my-token.jwt");

            File.WriteAllText(webIdentityTokenFilePath, dummyToken);

            var webIdentityCredentials = new AssumeRoleWithWebIdentityCredentials(webIdentityTokenFilePath, dummyRoleArn, dummyRoleSessionName, dummyOptions);

            try
            {
                var fetchedCredentials = webIdentityCredentials.GetCredentials();
            }
            catch (AmazonClientException e)
            {
                Assert.Equal("InvalidIdentityToken", ((AmazonServiceException)e.InnerException).ErrorCode);
            }
            finally
            {
                var deleteRoleRequest = new DeleteRoleRequest()
                {
                    RoleName = role.Role.RoleName
                };
                await Client.DeleteRoleAsync(deleteRoleRequest);
            }
        }
コード例 #3
0
 public AssumeRoleWithWebIdentityTestCredentials(AssumeRoleWithWebIdentityCredentials baseCreds, AssumeRoleWithWebIdentityCredentialsOptions options)
     : base(baseCreds.WebIdentityTokenFile, baseCreds.RoleArn, baseCreds.RoleSessionName, options)
 {
     Client = base.CreateClient();
 }
コード例 #4
0
 public AssumeRoleWithWebIdentityTestCredentials(string webIdentityTokenFile, string roleArn, string roleSessionName, AssumeRoleWithWebIdentityCredentialsOptions options)
     : base(webIdentityTokenFile, roleArn, roleSessionName, options)
 {
     Client = base.CreateClient();
 }
コード例 #5
0
        private AssumeRoleWithWebIdentityRequest SetupAssumeRoleWithWebIdentityRequest(string webIdentityToken, string roleArn,
                                                                                       string roleSessionName, AssumeRoleWithWebIdentityCredentialsOptions options)
        {
            var request = new AssumeRoleWithWebIdentityRequest
            {
                WebIdentityToken = webIdentityToken,
                RoleArn          = roleArn,
                RoleSessionName  = roleSessionName
            };

            if (options != null)
            {
                request.ProviderId = options.ProviderId;
                request.PolicyArns = options.PolicyArns?.Select((arn) => new PolicyDescriptorType {
                    Arn = arn
                }).ToList();
                request.Policy = options.Policy;
                if (options.DurationSeconds.HasValue)
                {
                    request.DurationSeconds = options.DurationSeconds.Value;
                }
            }

            return(request);
        }
コード例 #6
0
        /// <summary>
        /// <see cref="ICoreAmazonSTS_WebIdentity"/>
        /// </summary>
        /// <param name="webIdentityToken">The OAuth 2.0 access token or OpenID Connect ID token that is provided by the identity provider.</param>
        /// <param name="roleArn">The Amazon Resource Name (ARN) of the role to assume.</param>
        /// <param name="roleSessionName">An identifier for the assumed role session.</param>
        /// <param name="options">Options to be used in the call to AssumeRole.</param>
        /// <returns>Immutable AssumeRoleCredentials</returns>
        async Task <AssumeRoleImmutableCredentials> ICoreAmazonSTS_WebIdentity.CredentialsFromAssumeRoleWithWebIdentityAuthenticationAsync(string webIdentityToken, string roleArn,
                                                                                                                                           string roleSessionName, AssumeRoleWithWebIdentityCredentialsOptions options)
        {
            var request = SetupAssumeRoleWithWebIdentityRequest(webIdentityToken, roleArn, roleSessionName, options);

            try
            {
                var response = await AssumeRoleWithWebIdentityAsync(request).ConfigureAwait(false);

                return(new AssumeRoleImmutableCredentials(response.Credentials.AccessKeyId, response.Credentials.SecretAccessKey,
                                                          response.Credentials.SessionToken, response.Credentials.Expiration));
            }
            catch (Exception e)
            {
                var msg       = "Error calling AssumeRole for role " + roleArn;
                var exception = new AmazonClientException(msg, e);
                Logger.GetLogger(typeof(AmazonSecurityTokenServiceClient)).Error(exception, exception.Message);
                throw exception;
            }
        }