@Override public AssumeRoleResult assumeRole(AWSSecurityTokenServiceClient awsSecurityTokenServiceClient, AssumeRoleRequest assumeRoleRequest) { assertNotNull(assumeRoleRequest); if (assumeRoleRequest.getPolicy() != null && assumeRoleRequest.getPolicy().equals(MockAwsOperationsHelper.AMAZON_THROTTLING_EXCEPTION)) { AmazonServiceException throttlingException = new AmazonServiceException("test throttling exception"); throttlingException.setErrorCode("ThrottlingException"); throw throttlingException; } AssumeRoleResult assumeRoleResult = new AssumeRoleResult(); assumeRoleResult.setCredentials(new Credentials(MOCK_AWS_ASSUMED_ROLE_ACCESS_KEY, MOCK_AWS_ASSUMED_ROLE_SECRET_KEY, MOCK_AWS_ASSUMED_ROLE_SESSION_TOKEN, new Date(System.currentTimeMillis() + 1000 * assumeRoleRequest.getDurationSeconds()))); return assumeRoleResult; }
public static AmazonS3 getS3Client(final String region, final String roleArn) { final Regions awsRegion = StringUtils.isNullOrEmpty(region) ? Regions.US_EAST_1 : Regions.fromName(region); if (StringUtils.isNullOrEmpty(roleArn)) { return AmazonS3ClientBuilder.standard().withRegion(awsRegion).build(); } else { final AssumeRoleRequest assumeRole = new AssumeRoleRequest().withRoleArn(roleArn).withRoleSessionName("io-klerch-mp3-converter"); final AWSSecurityTokenService sts = AWSSecurityTokenServiceClientBuilder.standard().withRegion(awsRegion).build(); final Credentials credentials = sts.assumeRole(assumeRole).getCredentials(); final BasicSessionCredentials sessionCredentials = new BasicSessionCredentials( credentials.getAccessKeyId(), credentials.getSecretAccessKey(), credentials.getSessionToken()); return AmazonS3ClientBuilder.standard().withRegion(awsRegion).withCredentials(new AWSStaticCredentialsProvider(sessionCredentials)).build(); } }
@Override public AWSCredentials getCredentials() { AWSCredentialsProvider credentialsProvider = AWSClientFactory.getBasicCredentialsOrDefaultChain(accessKey, secretKey); AWSCredentials initialCredentials = credentialsProvider.getCredentials(); if (iamRoleArn.isEmpty()) { return initialCredentials; } else { AssumeRoleRequest assumeRequest = new AssumeRoleRequest() .withRoleArn(iamRoleArn) .withExternalId(externalId) .withDurationSeconds(3600) .withRoleSessionName("CodeBuild-Jenkins-Plugin"); AssumeRoleResult assumeResult = new AWSSecurityTokenServiceClient(initialCredentials).assumeRole(assumeRequest); return new BasicSessionCredentials( assumeResult.getCredentials().getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(), assumeResult.getCredentials().getSessionToken()); } }
private AmazonEC2Client getClientForAccount(final String accountId, final Region region) { final AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(new ProfileCredentialsProvider()); final AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn( "arn:aws:iam::ACCOUNT_ID:role/fullstop-role") .withDurationSeconds(3600).withRoleSessionName( "fullstop-role"); final AssumeRoleResult assumeResult = stsClient.assumeRole(assumeRequest); final BasicSessionCredentials temporaryCredentials = new BasicSessionCredentials( assumeResult.getCredentials() .getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(), assumeResult.getCredentials().getSessionToken()); final AmazonEC2Client amazonEC2Client = new AmazonEC2Client(temporaryCredentials); amazonEC2Client.setRegion(region); return amazonEC2Client; }
public AWSCredentials getCredentials() { AWSCredentials initialCredentials = new BasicAWSCredentials(accessKey, secretKey.getPlainText()); if (StringUtils.isBlank(iamRoleArn)) { return initialCredentials; } else { // Handle the case of delegation to instance profile if (StringUtils.isBlank(accessKey) && StringUtils.isBlank(secretKey.getPlainText()) ) { initialCredentials = (new InstanceProfileCredentialsProvider()).getCredentials(); } AssumeRoleRequest assumeRequest = createAssumeRoleRequest(iamRoleArn); AssumeRoleResult assumeResult = new AWSSecurityTokenServiceClient(initialCredentials).assumeRole(assumeRequest); return new BasicSessionCredentials( assumeResult.getCredentials().getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(), assumeResult.getCredentials().getSessionToken()); } }
private void assumeRoleAndGetCredentials() { int defaultRequestedExpiryTimeInMinutes = jets3tProperties.getIntProperty("aws.session-credentials.expiry-time.to-be-requested", 60); com.amazonaws.auth.AWSCredentials awsCredentials = new BasicAWSCredentials(iamAccessKey, iamSecretKey); AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(awsCredentials); AssumeRoleRequest assumeRequest = new AssumeRoleRequest() .withRoleArn(roleToBeAssumed) .withDurationSeconds(defaultRequestedExpiryTimeInMinutes * 60) .withRoleSessionName(DEFAULT_SESSION_NAME); if(externalId != null) { assumeRequest = assumeRequest.withExternalId(externalId); } AssumeRoleResult assumeResult = stsClient.assumeRole(assumeRequest); this.accessKey = assumeResult.getCredentials().getAccessKeyId(); this.secretKey = assumeResult.getCredentials().getSecretAccessKey(); this.sessionToken = assumeResult.getCredentials().getSessionToken(); this.expirationDate = assumeResult.getCredentials().getExpiration(); }
private void create() { AssumeRoleResult result = sts.assumeRole( new AssumeRoleRequest().withRoleArn( assumedRoleArn ).withExternalId( AgentConfig.ROLE_EXTERNAL_ID ).withRoleSessionName( "rs-" + RandomStringUtils.randomAlphabetic( 8 ) ) ); synchronized ( this ) { expirationDate = result.getCredentials().getExpiration().getTime(); creds = new BasicSessionCredentials( result.getCredentials().getAccessKeyId(), result.getCredentials().getSecretAccessKey(), result.getCredentials().getSessionToken() ); } }
public FormValidation doCheckIamRoleArn(@QueryParameter("proxyHost") final String proxyHost, @QueryParameter("proxyPort") final String proxyPort, @QueryParameter("accessKey") final String accessKey, @QueryParameter("secretKey") final String secretKey, @QueryParameter("iamRoleArn") final String iamRoleArn, @QueryParameter("externalId") final String externalId) { if (accessKey.isEmpty() || secretKey.isEmpty()) { return FormValidation.error("AWS access and secret keys are required to use an IAM role for authorization"); } if(iamRoleArn.isEmpty()) { return FormValidation.ok(); } try { AWSCredentials initialCredentials = new BasicAWSCredentials(accessKey, secretKey); AssumeRoleRequest assumeRequest = new AssumeRoleRequest() .withRoleArn(iamRoleArn) .withExternalId(externalId) .withDurationSeconds(3600) .withRoleSessionName("jenkins-codebuild-plugin"); new AWSSecurityTokenServiceClient(initialCredentials, getClientConfiguration(proxyHost, proxyPort)).assumeRole(assumeRequest); } catch (Exception e) { String errorMessage = e.getMessage(); if(errorMessage.length() >= ERROR_MESSAGE_MAX_LENGTH) { errorMessage = errorMessage.substring(ERROR_MESSAGE_MAX_LENGTH); } return FormValidation.error("Authorization failed: " + errorMessage); } return FormValidation.ok("IAM role authorization successful."); }
public AWSTemporaryCredentials assumeAWSRole(String account, String roleName, String principal) { if (!awsEnabled) { throw new ResourceException(ResourceException.INTERNAL_SERVER_ERROR, "AWS Support not enabled"); } AssumeRoleRequest req = getAssumeRoleRequest(account, roleName, principal); AWSTemporaryCredentials tempCreds = null; try { AWSSecurityTokenServiceClient client = getTokenServiceClient(); AssumeRoleResult res = client.assumeRole(req); Credentials awsCreds = res.getCredentials(); tempCreds = new AWSTemporaryCredentials() .setAccessKeyId(awsCreds.getAccessKeyId()) .setSecretAccessKey(awsCreds.getSecretAccessKey()) .setSessionToken(awsCreds.getSessionToken()) .setExpiration(Timestamp.fromMillis(awsCreds.getExpiration().getTime())); } catch (Exception ex) { LOGGER.error("CloudStore: assumeAWSRole - unable to assume role: " + ex.getMessage()); return null; } return tempCreds; }
@Override AWSSecurityTokenServiceClient getTokenServiceClient() { AWSSecurityTokenServiceClient client = Mockito.mock(AWSSecurityTokenServiceClient.class); Mockito.when(client.assumeRole(Mockito.any(AssumeRoleRequest.class))).thenReturn(assumeRoleResult); Mockito.when(client.getCallerIdentity(Mockito.any(GetCallerIdentityRequest.class))).thenReturn(callerIdentityResult); return client; }
@Test public void testGetAssumeRoleRequest() { CloudStore store = new CloudStore(null); AssumeRoleRequest req = store.getAssumeRoleRequest("1234", "admin", "sys.auth.zts"); assertEquals("arn:aws:iam::1234:role/admin", req.getRoleArn()); assertEquals("sys.auth.zts", req.getRoleSessionName()); store.close(); }
/** * Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) that can be used to access * the specified AWS resource. * * @param sessionName the session name that will be associated with the temporary credentials. The session name must be the same for an initial set of * credentials and an extended set of credentials if credentials are to be refreshed. The session name also is used to identify the user in AWS logs so it * should be something unique and useful to identify the caller/use. * @param awsRoleArn the AWS ARN for the role required to provide access to the specified AWS resource * @param awsRoleDurationSeconds the duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) to 3600 seconds (1 hour). * @param policy the temporary policy to apply to this request * * @return the assumed session credentials */ @Override public Credentials getTemporarySecurityCredentials(AwsParamsDto awsParamsDto, String sessionName, String awsRoleArn, int awsRoleDurationSeconds, Policy policy) { // Construct a new AWS security token service client using the specified client configuration to access Amazon S3. // A credentials provider chain will be used that searches for credentials in this order: // - Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY // - Java System Properties - aws.accessKeyId and aws.secretKey // - Instance Profile Credentials - delivered through the Amazon EC2 metadata service ClientConfiguration clientConfiguration = new ClientConfiguration().withRetryPolicy(retryPolicyFactory.getRetryPolicy()); // Only set the proxy hostname and/or port if they're configured. if (StringUtils.isNotBlank(awsParamsDto.getHttpProxyHost())) { clientConfiguration.setProxyHost(awsParamsDto.getHttpProxyHost()); } if (awsParamsDto.getHttpProxyPort() != null) { clientConfiguration.setProxyPort(awsParamsDto.getHttpProxyPort()); } AWSSecurityTokenServiceClient awsSecurityTokenServiceClient = new AWSSecurityTokenServiceClient(clientConfiguration); // Create the request. AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest(); assumeRoleRequest.setRoleSessionName(sessionName); assumeRoleRequest.setRoleArn(awsRoleArn); assumeRoleRequest.setDurationSeconds(awsRoleDurationSeconds); if (policy != null) { assumeRoleRequest.setPolicy(policy.toJson()); } // Get the temporary security credentials. AssumeRoleResult assumeRoleResult = stsOperations.assumeRole(awsSecurityTokenServiceClient, assumeRoleRequest); return assumeRoleResult.getCredentials(); }
public AWSCredentials getCredentials(String mfaToken) { AWSCredentials initialCredentials = new BasicAWSCredentials(accessKey, secretKey.getPlainText()); AssumeRoleRequest assumeRequest = createAssumeRoleRequest(iamRoleArn) .withSerialNumber(iamMfaSerialNumber) .withTokenCode(mfaToken); AssumeRoleResult assumeResult = new AWSSecurityTokenServiceClient(initialCredentials).assumeRole(assumeRequest); return new BasicSessionCredentials( assumeResult.getCredentials().getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(), assumeResult.getCredentials().getSessionToken()); }
private static AWSCredentials getCredentials(String iamRole, String externalId) { if (isEmpty(iamRole)) return null; AWSSecurityTokenServiceClient sts = new AWSSecurityTokenServiceClient(); int credsDuration = (int) (AWSCodeDeployPublisher.DEFAULT_TIMEOUT_SECONDS * AWSCodeDeployPublisher.DEFAULT_POLLING_FREQUENCY_SECONDS); if (credsDuration > 3600) { credsDuration = 3600; } AssumeRoleResult assumeRoleResult = sts.assumeRole(new AssumeRoleRequest() .withRoleArn(iamRole) .withExternalId(externalId) .withDurationSeconds(credsDuration) .withRoleSessionName(AWSCodeDeployPublisher.ROLE_SESSION_NAME) ); Credentials stsCredentials = assumeRoleResult.getCredentials(); BasicSessionCredentials credentials = new BasicSessionCredentials( stsCredentials.getAccessKeyId(), stsCredentials.getSecretAccessKey(), stsCredentials.getSessionToken() ); return credentials; }
public BasicSessionCredentials retrieveSessionCredentials(AwsCredentialView awsCredential) { LOGGER.debug("retrieving session credential"); AWSSecurityTokenServiceClient client = awsSecurityTokenServiceClient(); AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest() .withDurationSeconds(DEFAULT_SESSION_CREDENTIALS_DURATION) .withExternalId(externalId) .withRoleArn(awsCredential.getRoleArn()) .withRoleSessionName("hadoop-provisioning"); AssumeRoleResult result = client.assumeRole(assumeRoleRequest); return new BasicSessionCredentials( result.getCredentials().getAccessKeyId(), result.getCredentials().getSecretAccessKey(), result.getCredentials().getSessionToken()); }
/** * Resolve AWS credentials based on MFA/Assume role * * We will assume that if mfa_serial is defined, then role_arn and source_profile also has to be specified. * * Please note that Strongbox differ from the AWS CLI in the following: * AWS CLI: 'Note that configuration variables for using IAM roles can only be in the AWS CLI config file.' * Strongbox: '--assume-role' can be specified explicitly * * https://docs.aws.amazon.com/cli/latest/topic/config-vars.html#using-aws-iam-roles */ private AWSCredentials assumeRole(ClientConfiguration clientConfiguration, ConfigProviderChain configProvider, ProfileIdentifier profile, RoleARN roleToAssume) { Optional<ProfileIdentifier> sourceProfile = configProvider.getSourceProfile(profile); if (!sourceProfile.isPresent()) { throw new IllegalStateException(String.format("'%s' must be specified when using '%s' for profile '%s'", AWSConfigPropertyKey.SOURCE_PROFILE, AWSConfigPropertyKey.ROLE_ARN, profile.name)); } SessionCache sessionCache = new SessionCache(profile, roleToAssume); Optional<BasicSessionCredentials> cachedCredentials = sessionCache.load(); if (cachedCredentials.isPresent()) { return cachedCredentials.get(); } else { AWSCredentialsProvider staticCredentialsProvider = new AWSStaticCredentialsProvider(getStaticCredentials(configProvider, sourceProfile.get())); AWSSecurityTokenService client = AWSSecurityTokenServiceClientBuilder.standard() .withCredentials(staticCredentialsProvider) .withClientConfiguration(transformAndVerifyOrThrow(clientConfiguration)) .withRegion(RegionResolver.getRegion()) .build(); String sessionId = String.format("strongbox-cli-session-%s", ZonedDateTime.now().toEpochSecond()); AssumeRoleRequest request = new AssumeRoleRequest(); request.withRoleArn(roleToAssume.toArn()) .withRoleSessionName(sessionId); Optional<String> mfaSerial = configProvider.getMFASerial(profile); if (mfaSerial.isPresent()) { MFAToken mfaToken = mfaTokenSupplier.get(); request.withSerialNumber(mfaSerial.get()) .withTokenCode(mfaToken.value); } AssumeRoleResult result = client.assumeRole(request); Credentials credentials = result.getCredentials(); BasicSessionCredentials basicSessionCredentials = new BasicSessionCredentials(credentials.getAccessKeyId(), credentials.getSecretAccessKey(), credentials.getSessionToken()); sessionCache.save(result.getAssumedRoleUser(), basicSessionCredentials, ZonedDateTime.ofInstant(credentials.getExpiration().toInstant(), ZoneId.of("UTC"))); return basicSessionCredentials; } }
@Override public AssumeRoleResult assumeRole(AWSSecurityTokenServiceClient awsSecurityTokenServiceClient, AssumeRoleRequest assumeRoleRequest) { return awsSecurityTokenServiceClient.assumeRole(assumeRoleRequest); }
@Test public void testGetTemporarySecurityCredentials() { // Create an AWS parameters DTO with proxy settings. AwsParamsDto awsParamsDto = new AwsParamsDto(); awsParamsDto.setHttpProxyHost(HTTP_PROXY_HOST); awsParamsDto.setHttpProxyPort(HTTP_PROXY_PORT); // Specify the duration, in seconds, of the role session. int awsRoleDurationSeconds = INTEGER_VALUE; // Create an IAM policy. Policy policy = new Policy(STRING_VALUE); // Create a retry policy. RetryPolicy retryPolicy = new RetryPolicy(PredefinedRetryPolicies.DEFAULT_RETRY_CONDITION, PredefinedRetryPolicies.DEFAULT_BACKOFF_STRATEGY, INTEGER_VALUE, true); // Create the expected assume role request. AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest().withRoleArn(AWS_ROLE_ARN).withRoleSessionName(SESSION_NAME).withPolicy(policy.toJson()) .withDurationSeconds(awsRoleDurationSeconds); // Create AWS credentials for API authentication. Credentials credentials = new Credentials(); credentials.setAccessKeyId(AWS_ASSUMED_ROLE_ACCESS_KEY); credentials.setSecretAccessKey(AWS_ASSUMED_ROLE_SECRET_KEY); credentials.setSessionToken(AWS_ASSUMED_ROLE_SESSION_TOKEN); // Create an assume role result. AssumeRoleResult assumeRoleResult = new AssumeRoleResult(); assumeRoleResult.setCredentials(credentials); // Mock the external calls. when(retryPolicyFactory.getRetryPolicy()).thenReturn(retryPolicy); when(stsOperations.assumeRole(any(AWSSecurityTokenServiceClient.class), eq(assumeRoleRequest))).thenReturn(assumeRoleResult); // Call the method under test. Credentials result = stsDaoImpl.getTemporarySecurityCredentials(awsParamsDto, SESSION_NAME, AWS_ROLE_ARN, awsRoleDurationSeconds, policy); // Verify the external calls. verify(retryPolicyFactory).getRetryPolicy(); verify(stsOperations).assumeRole(any(AWSSecurityTokenServiceClient.class), eq(assumeRoleRequest)); verifyNoMoreInteractionsHelper(); // Validate the returned object. assertEquals(credentials, result); }
@Test public void testGetTemporarySecurityCredentialsMissingOptionalParameters() { // Create an AWS parameters DTO without proxy settings. AwsParamsDto awsParamsDto = new AwsParamsDto(); // Specify the duration, in seconds, of the role session. int awsRoleDurationSeconds = INTEGER_VALUE; // Create a retry policy. RetryPolicy retryPolicy = new RetryPolicy(PredefinedRetryPolicies.DEFAULT_RETRY_CONDITION, PredefinedRetryPolicies.DEFAULT_BACKOFF_STRATEGY, INTEGER_VALUE, true); // Create the expected assume role request. AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest().withRoleArn(AWS_ROLE_ARN).withRoleSessionName(SESSION_NAME).withDurationSeconds(awsRoleDurationSeconds); // Create AWS credentials for API authentication. Credentials credentials = new Credentials(); credentials.setAccessKeyId(AWS_ASSUMED_ROLE_ACCESS_KEY); credentials.setSecretAccessKey(AWS_ASSUMED_ROLE_SECRET_KEY); credentials.setSessionToken(AWS_ASSUMED_ROLE_SESSION_TOKEN); // Create an assume role result. AssumeRoleResult assumeRoleResult = new AssumeRoleResult(); assumeRoleResult.setCredentials(credentials); // Mock the external calls. when(retryPolicyFactory.getRetryPolicy()).thenReturn(retryPolicy); when(stsOperations.assumeRole(any(AWSSecurityTokenServiceClient.class), eq(assumeRoleRequest))).thenReturn(assumeRoleResult); // Call the method under test. Please note that we do not specify an IAM policy. Credentials result = stsDaoImpl.getTemporarySecurityCredentials(awsParamsDto, SESSION_NAME, AWS_ROLE_ARN, awsRoleDurationSeconds, null); // Verify the external calls. verify(retryPolicyFactory).getRetryPolicy(); verify(stsOperations).assumeRole(any(AWSSecurityTokenServiceClient.class), eq(assumeRoleRequest)); verifyNoMoreInteractionsHelper(); // Validate the returned object. assertEquals(credentials, result); }
private static AssumeRoleRequest createAssumeRoleRequest(@QueryParameter("iamRoleArn") String iamRoleArn) { return new AssumeRoleRequest() .withRoleArn(iamRoleArn) .withDurationSeconds(STS_CREDENTIALS_DURATION_SECONDS) .withRoleSessionName(Jenkins.getActiveInstance().getDisplayName()); }
AssumeRoleRequest getAssumeRoleRequest(String account, String roleName, String principal) { // assume the target role to get the credentials for the client // aws format is arn:aws:iam::<account-id>:role/<role-name> String arn = "arn:aws:iam::" + account + ":role/" + roleName; AssumeRoleRequest req = new AssumeRoleRequest(); req.setRoleArn(arn); req.setRoleSessionName(principal); return req; }
/** * Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) that can be used to access * the specified AWS resource. * * @param awsSecurityTokenServiceClient the client for accessing the AWS Security Token Service * @param assumeRoleRequest the assume role request * * @return the response from the AssumeRole service method, as returned by AWS Security Token Service */ public AssumeRoleResult assumeRole(AWSSecurityTokenServiceClient awsSecurityTokenServiceClient, AssumeRoleRequest assumeRoleRequest);