com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder Java Examples

The following examples show how to use com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AWSClientManagerImpl.java    From pacbot with Apache License 2.0 7 votes vote down vote up
/**
 * Gets the temp credentials using cred provider.
 *
 * @param roleArnWithAdequateAccess
 *            the role arn with adequate access
 * @param region
 *            the region
 * @param acp
 *            the acp
 * @param validForSeconds
 *            the valid for seconds
 * @return the temp credentials using cred provider
 */
private BasicSessionCredentials getTempCredentialsUsingCredProvider(String roleArnWithAdequateAccess,
        Regions region, AWSCredentialsProvider acp, Integer validForSeconds) {
    if (null == region) { // cloud trail case
        region = Regions.DEFAULT_REGION;
    }
    AWSSecurityTokenServiceClientBuilder stsBuilder = AWSSecurityTokenServiceClientBuilder.standard()
            .withCredentials(acp).withRegion(region);
    AWSSecurityTokenService sts = stsBuilder.build();
    AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn(roleArnWithAdequateAccess)
            .withDurationSeconds(validForSeconds).withRoleSessionName(PacmanSdkConstants.DEFAULT_SESSION_NAME);
    logger.debug("assume role request " + assumeRequest.toString());
    AssumeRoleResult assumeResult = sts.assumeRole(assumeRequest);
    logger.debug("assume role response " + assumeResult.toString());
    BasicSessionCredentials temporaryCredentials = new BasicSessionCredentials(assumeResult.getCredentials()
            .getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(), assumeResult.getCredentials()
            .getSessionToken());

    return temporaryCredentials;
}
 
Example #2
Source File: CredentialProvider.java    From pacbot with Apache License 2.0 7 votes vote down vote up
/**
 * Gets the credentials.
 *
 * @param account the account
 * @param roleName the role name
 * @return the credentials
 */
public  BasicSessionCredentials getCredentials(String account,String roleName){
	
	BasicSessionCredentials baseAccntCreds = getBaseAccountCredentials(baseAccount,baseRegion,roleName);
	if(baseAccount.equals(account)){
		return baseAccntCreds;
	}
	AWSSecurityTokenServiceClientBuilder stsBuilder = AWSSecurityTokenServiceClientBuilder.standard().withCredentials( new AWSStaticCredentialsProvider(baseAccntCreds)).withRegion(baseRegion);
	AWSSecurityTokenService stsClient = stsBuilder.build();
    AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn(getRoleArn(account,roleName)).withRoleSessionName("pic-ro-"+account);
    AssumeRoleResult assumeResult = stsClient.assumeRole(assumeRequest);
    return  new BasicSessionCredentials(
            assumeResult.getCredentials()
                        .getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(),
            assumeResult.getCredentials().getSessionToken());
}
 
Example #3
Source File: ConvertService.java    From alexa-meets-polly with Apache License 2.0 7 votes vote down vote up
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();
    }
}
 
Example #4
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
private void withFederatedUserId(@Nonnull EnvVars localEnv) {
	if (!StringUtils.isNullOrEmpty(this.step.getFederatedUserId())) {
		AWSSecurityTokenService sts = AWSClientFactory.create(AWSSecurityTokenServiceClientBuilder.standard(), this.envVars);
		GetFederationTokenRequest getFederationTokenRequest = new GetFederationTokenRequest();
		getFederationTokenRequest.setDurationSeconds(this.step.getDuration());
		getFederationTokenRequest.setName(this.step.getFederatedUserId());
		getFederationTokenRequest.setPolicy(ALLOW_ALL_POLICY);

		GetFederationTokenResult federationTokenResult = sts.getFederationToken(getFederationTokenRequest);

		Credentials credentials = federationTokenResult.getCredentials();
		localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, credentials.getAccessKeyId());
		localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, credentials.getSecretAccessKey());
		localEnv.override(AWSClientFactory.AWS_SESSION_TOKEN, credentials.getSessionToken());
		this.envVars.overrideAll(localEnv);
	}

}
 
Example #5
Source File: AWSAuthProvider.java    From graylog-plugin-aws with Apache License 2.0 6 votes vote down vote up
private AWSCredentialsProvider getSTSCredentialsProvider(AWSCredentialsProvider awsCredentials, String region, String assumeRoleArn) {
    AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard()
            .withRegion(region)
            .withCredentials(awsCredentials)
            .build();
    String roleSessionName = String.format("API_KEY_%s@ACCOUNT_%s",
            awsCredentials.getCredentials().getAWSAccessKeyId(),
            stsClient.getCallerIdentity(new GetCallerIdentityRequest()).getAccount());
    LOG.debug("Cross account role session name: " + roleSessionName);
    return new STSAssumeRoleSessionCredentialsProvider.Builder(assumeRoleArn, roleSessionName)
            .withStsClient(stsClient)
            .build();
}
 
Example #6
Source File: AmazonS3Factory.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private AWSCredentialsProvider buildCredentialsProvider(final AWSCredentials credentials, final String region, final String assumeRole) {
  AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
  if (isNullOrEmpty(assumeRole)) {
    return credentialsProvider;
  }
  else {
    // STS requires a region; fall back on the SDK default if not set
    String stsRegion;
    if (isNullOrEmpty(region)) {
      stsRegion = defaultRegion();
    }
    else {
      stsRegion = region;
    }
    AWSSecurityTokenService securityTokenService = AWSSecurityTokenServiceClientBuilder.standard()
        .withRegion(stsRegion)
        .withCredentials(credentialsProvider).build();

    return new STSAssumeRoleSessionCredentialsProvider.Builder(assumeRole, "nexus-s3-session")
        .withStsClient(securityTokenService)
        .build();
  }
}
 
Example #7
Source File: ZTSClient.java    From athenz with Apache License 2.0 6 votes vote down vote up
Credentials assumeAWSRole(String account, String roleName) {
    
    try {
        AssumeRoleRequest req = getAssumeRoleRequest(account, roleName);
        return AWSSecurityTokenServiceClientBuilder.defaultClient().assumeRole(req).getCredentials();
    } catch (Exception ex) {
        LOG.error("assumeAWSRole - unable to assume role: {}", ex.getMessage());
        return null;
    }
}
 
Example #8
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
private void withRole(@Nonnull EnvVars localEnv) throws IOException, InterruptedException {
	if (!StringUtils.isNullOrEmpty(this.step.getRole())) {
		
		AWSSecurityTokenService sts = AWSClientFactory.create(AWSSecurityTokenServiceClientBuilder.standard(), this.envVars);

		AssumeRole assumeRole = IamRoleUtils.validRoleArn(this.step.getRole()) ? new AssumeRole(this.step.getRole()) :
				new AssumeRole(this.step.getRole(), this.createAccountId(sts), IamRoleUtils.selectPartitionName(this.step.getRegion()));
		assumeRole.withDurationSeconds(this.step.getDuration());
		assumeRole.withExternalId(this.step.getExternalId());
		assumeRole.withPolicy(this.step.getPolicy());
		assumeRole.withSamlAssertion(this.step.getSamlAssertion(), this.step.getPrincipalArn());
		assumeRole.withSessionName(this.createRoleSessionName());

		this.getContext().get(TaskListener.class).getLogger().format("Requesting assume role");
		AssumedRole assumedRole = assumeRole.assumedRole(sts);
		this.getContext().get(TaskListener.class).getLogger().format("Assumed role %s with id %s %n ", assumedRole.getAssumedRoleUser().getArn(), assumedRole.getAssumedRoleUser().getAssumedRoleId());

		localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, assumedRole.getCredentials().getAccessKeyId());
		localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, assumedRole.getCredentials().getSecretAccessKey());
		localEnv.override(AWSClientFactory.AWS_SESSION_TOKEN, assumedRole.getCredentials().getSessionToken());
		this.envVars.overrideAll(localEnv);
	}
}
 
Example #9
Source File: STSCredentialProviderV1.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public STSCredentialProviderV1(URI uri, Configuration conf) throws IOException {

    AWSCredentialsProvider awsCredentialsProvider = null;

    //TODO: Leverage S3AUtils createAwsCredentialProvider

    if (S3StoragePlugin.ACCESS_KEY_PROVIDER.equals(conf.get(Constants.ASSUMED_ROLE_CREDENTIALS_PROVIDER))) {
      awsCredentialsProvider = new SimpleAWSCredentialsProvider(uri, conf);
    } else if (S3StoragePlugin.EC2_METADATA_PROVIDER.equals(conf.get(Constants.ASSUMED_ROLE_CREDENTIALS_PROVIDER))) {
      awsCredentialsProvider = InstanceProfileCredentialsProvider.getInstance();
    }

    final String region = S3FileSystem.getAWSRegionFromConfigurationOrDefault(conf).toString();
    final AWSSecurityTokenServiceClientBuilder builder = AWSSecurityTokenServiceClientBuilder.standard()
      .withCredentials(awsCredentialsProvider)
      .withClientConfiguration(S3AUtils.createAwsConf(conf, ""))
      .withRegion(region);
    S3FileSystem.getStsEndpoint(conf).ifPresent(e -> {
      builder.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(e, region));
    });

    this.stsAssumeRoleSessionCredentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(
      conf.get(Constants.ASSUMED_ROLE_ARN), UUID.randomUUID().toString())
      .withStsClient(builder.build())
      .build();
  }
 
Example #10
Source File: STSCredentialsConfigurator.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
protected AWSSecurityTokenService getTokenService(final Host host, final String region, final String accessKey, final String secretKey, final String sessionToken) {
    final ClientConfiguration configuration = new CustomClientConfiguration(host,
        new ThreadLocalHostnameDelegatingTrustManager(trust, host.getHostname()), key);
    return AWSSecurityTokenServiceClientBuilder.standard()
        .withCredentials(new AWSStaticCredentialsProvider(StringUtils.isBlank(sessionToken) ? new AWSCredentials() {
            @Override
            public String getAWSAccessKeyId() {
                return accessKey;
            }

            @Override
            public String getAWSSecretKey() {
                return secretKey;
            }
        } : new AWSSessionCredentials() {
            @Override
            public String getAWSAccessKeyId() {
                return accessKey;
            }

            @Override
            public String getAWSSecretKey() {
                return secretKey;
            }

            @Override
            public String getSessionToken() {
                return sessionToken;
            }
        }))
        .withClientConfiguration(configuration)
        .withRegion(StringUtils.isNotBlank(region) ? Regions.fromName(region) : Regions.DEFAULT_REGION).build();
}
 
Example #11
Source File: CredentialProvider.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the credentials.
 *
 * @param account the account
 * @param roleName the role name
 * @return the credentials
 */
public  BasicSessionCredentials getCredentials(String account,String roleName){
	BasicSessionCredentials baseAccntCreds = getBaseAccountCredentials(roleName);
	if(baseAccount.equals(account)){
		return baseAccntCreds;
	}
	AWSSecurityTokenServiceClientBuilder stsBuilder = AWSSecurityTokenServiceClientBuilder.standard().withCredentials( new AWSStaticCredentialsProvider(baseAccntCreds)).withRegion(baseRegion);
	AWSSecurityTokenService stsClient = stsBuilder.build();
    AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn(getRoleArn(account,roleName)).withRoleSessionName("pic-ro-"+account);
    AssumeRoleResult assumeResult = stsClient.assumeRole(assumeRequest);
    return  new BasicSessionCredentials(
            assumeResult.getCredentials()
                        .getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(),
            assumeResult.getCredentials().getSessionToken());
}
 
Example #12
Source File: AwsSessionCredentialClient.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private AWSSecurityTokenService awsSecurityTokenServiceClient(AwsCredentialView awsCredential) {
    if (!awsEnvironmentVariableChecker.isAwsAccessKeyAvailable(awsCredential)
            || !awsEnvironmentVariableChecker.isAwsSecretAccessKeyAvailable(awsCredential)) {
        LOGGER.debug("AWSSecurityTokenServiceClient will use aws metadata because environment variables are undefined");
        return AWSSecurityTokenServiceClientBuilder.standard()
                .withRegion(awsDefaultZoneProvider.getDefaultZone(awsCredential))
                .withCredentials(new InstanceProfileCredentialsProvider())
                .build();
    } else {
        LOGGER.debug("AWSSecurityTokenServiceClient will use environment variables");
        return AWSSecurityTokenServiceClientBuilder.standard()
                .withRegion(awsDefaultZoneProvider.getDefaultZone(awsCredential))
                .withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
                .build();
    }
}
 
Example #13
Source File: ZipkinKinesisCredentialsConfiguration.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
/** Setup {@link AWSSecurityTokenService} client an IAM role to assume is given. */
@Bean
@ConditionalOnMissingBean
@Conditional(STSSetCondition.class)
AWSSecurityTokenService securityTokenService(ZipkinKinesisCollectorProperties properties) {
  return AWSSecurityTokenServiceClientBuilder.standard()
      .withCredentials(getDefaultCredentialsProvider(properties))
      .withRegion(properties.getAwsStsRegion())
      .build();
}
 
Example #14
Source File: AWSAssumeRoleCredentialsProvider.java    From kafka-connect-lambda with Apache License 2.0 5 votes vote down vote up
@Override
public AWSCredentials getCredentials() {
  AWSSecurityTokenServiceClientBuilder clientBuilder = AWSSecurityTokenServiceClientBuilder.standard();
  AWSCredentialsProvider provider = new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, sessionName)
      .withStsClient(clientBuilder.defaultClient())
      .withExternalId(externalId)
      .build();

  return provider.getCredentials();
}
 
Example #15
Source File: AmazonS3Config.java    From ReCiter with Apache License 2.0 5 votes vote down vote up
private String getAccountIDUsingAccessKey(String accessKey, String secretKey) {
    AWSSecurityTokenService stsService = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(
            new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey))).build();

    GetCallerIdentityResult callerIdentity = stsService.getCallerIdentity(new GetCallerIdentityRequest());
    return callerIdentity.getAccount();
}
 
Example #16
Source File: CachingClientProvider.java    From fullstop with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
    log.debug("Initializing CachingClientProvider");
    final AWSSecurityTokenServiceClientBuilder builder = AWSSecurityTokenServiceClientBuilder.standard();
    if (hasText(stsRegion)) {
        builder.setRegion(stsRegion);
    }
    awsSecurityTokenService = builder.build();
    // TODO this parameters have to be configurable
    cache = CacheBuilder.newBuilder()
            .maximumSize(500)
            .expireAfterAccess(50, TimeUnit.MINUTES)
            .removalListener(this::removalHook)
            .build(createCacheLoader());
}
 
Example #17
Source File: AAWSTest.java    From aws-cf-templates with Apache License 2.0 5 votes vote down vote up
public AAWSTest() {
    super();
    if (Config.has(Config.Key.IAM_ROLE_ARN)) {
        final AWSSecurityTokenService local = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(new DefaultAWSCredentialsProviderChain()).build();
        this.credentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(Config.get(Config.Key.IAM_ROLE_ARN), IAM_SESSION_NAME).withStsClient(local).build();
    } else {
        this.credentialsProvider = new DefaultAWSCredentialsProviderChain();
    }
    this.ec2 = AmazonEC2ClientBuilder.standard().withCredentials(this.credentialsProvider).build();
    this.iam = AmazonIdentityManagementClientBuilder.standard().withCredentials(this.credentialsProvider).build();
    this.s3 = AmazonS3ClientBuilder.standard().withCredentials(this.credentialsProvider).build();
    this.sts = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(this.credentialsProvider).build();
}
 
Example #18
Source File: CloudStore.java    From athenz with Apache License 2.0 5 votes vote down vote up
AWSSecurityTokenService getTokenServiceClient() {

        return AWSSecurityTokenServiceClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(Regions.fromName(awsRegion))
                .build();
    }
 
Example #19
Source File: InstanceAWSProvider.java    From athenz with Apache License 2.0 5 votes vote down vote up
AWSSecurityTokenService getInstanceClient(AWSAttestationData info) {
    
    String access = info.getAccess();
    if (access == null || access.isEmpty()) {
        LOGGER.error("getInstanceClient: No access key id available in instance document");
        return null;
    }
    
    String secret = info.getSecret();
    if (secret == null || secret.isEmpty()) {
        LOGGER.error("getInstanceClient: No secret access key available in instance document");
        return null;
    }
    
    String token = info.getToken();
    if (token == null || token.isEmpty()) {
        LOGGER.error("getInstanceClient: No token available in instance document");
        return null;
    }
    
    BasicSessionCredentials creds = new BasicSessionCredentials(access, secret, token);

    return AWSSecurityTokenServiceClientBuilder.standard()
            .withCredentials(new AWSStaticCredentialsProvider(creds))
            .withRegion(Regions.fromName(awsRegion))
            .build();
}
 
Example #20
Source File: AwsIdentityService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private String getAccountIdUsingAccessKey(String region, String accessKey, String secretKey) {
    AWSSecurityTokenService stsService = AWSSecurityTokenServiceClientBuilder.standard()
            .withRegion(region)
            .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
            .build();

    GetCallerIdentityResult callerIdentity = stsService.getCallerIdentity(new GetCallerIdentityRequest());
    return callerIdentity.getAccount();
}
 
Example #21
Source File: AAWSTest.java    From aws-ec2-ssh with MIT License 5 votes vote down vote up
public AAWSTest() {
    super();
    if (Config.has(Config.Key.IAM_ROLE_ARN)) {
        final AWSSecurityTokenService sts = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(new DefaultAWSCredentialsProviderChain()).build();
        this.credentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(Config.get(Config.Key.IAM_ROLE_ARN), IAM_SESSION_NAME).withStsClient(sts).build();
    } else {
        this.credentialsProvider = new DefaultAWSCredentialsProviderChain();
    }
    this.ec2 = AmazonEC2ClientBuilder.standard().withCredentials(this.credentialsProvider).build();
    this.iam = AmazonIdentityManagementClientBuilder.standard().withCredentials(this.credentialsProvider).build();
}
 
Example #22
Source File: AAWSTest.java    From aws-s3-virusscan with Apache License 2.0 5 votes vote down vote up
public AAWSTest() {
    super();
    if (Config.has(Config.Key.IAM_ROLE_ARN)) {
        final AWSSecurityTokenService local = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(new DefaultAWSCredentialsProviderChain()).build();
        this.credentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(Config.get(Config.Key.IAM_ROLE_ARN), IAM_SESSION_NAME).withStsClient(local).build();
    } else {
        this.credentialsProvider = new DefaultAWSCredentialsProviderChain();
    }
    this.s3 = AmazonS3ClientBuilder.standard().withCredentials(this.credentialsProvider).build();
}
 
Example #23
Source File: IAMPolicyManager.java    From strongbox with Apache License 2.0 5 votes vote down vote up
public static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration) {
    AWSSecurityTokenService client = AWSSecurityTokenServiceClientBuilder.standard()
        .withCredentials(awsCredentialsProvider)
        .withClientConfiguration(transformAndVerifyOrThrow(clientConfiguration))
        .withRegion(RegionResolver.getRegion())
        .build();
    GetCallerIdentityRequest request = new GetCallerIdentityRequest();
    GetCallerIdentityResult result = client.getCallerIdentity(request);

    return result.getAccount();
}
 
Example #24
Source File: ZipkinSQSCredentialsConfiguration.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
/** Setup {@link AWSSecurityTokenService} client an IAM role to assume is given. */
@Bean
@ConditionalOnMissingBean
@Conditional(STSSetCondition.class)
AWSSecurityTokenService securityTokenService(ZipkinSQSCollectorProperties properties) {
  return AWSSecurityTokenServiceClientBuilder.standard()
      .withCredentials(getDefaultCredentialsProvider(properties))
      .withRegion(properties.awsStsRegion)
      .build();
}
 
Example #25
Source File: AWSIdentityStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Override
protected Map<String, String> run() throws Exception {
	AWSSecurityTokenService sts = AWSClientFactory.create(AWSSecurityTokenServiceClientBuilder.standard(), this.getContext());
	GetCallerIdentityResult identity = sts.getCallerIdentity(new GetCallerIdentityRequest());

	this.getContext().get(TaskListener.class).getLogger().format("Current AWS identity: %s - %s - %s %n", identity.getAccount(), identity.getUserId(), identity.getArn());

	Map<String, String> info = new HashMap<>();
	info.put("account", identity.getAccount());
	info.put("user", identity.getUserId());
	info.put("arn", identity.getArn());
	return info;
}
 
Example #26
Source File: AWSAssumeRoleCredentialsProvider.java    From kafka-connect-sqs with Apache License 2.0 5 votes vote down vote up
@Override
public AWSCredentials getCredentials() {
  AWSSecurityTokenServiceClientBuilder clientBuilder = AWSSecurityTokenServiceClientBuilder.standard();
  AWSCredentialsProvider provider = new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, sessionName)
      .withStsClient(clientBuilder.defaultClient())
      .withExternalId(externalId)
      .build();

  return provider.getCredentials();
}
 
Example #27
Source File: KinesisDispatcher.java    From haystack-agent with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
AWSCredentialsProvider buildCredsProvider(final Map<String, String> conf) {
    final Object stsRoleArn = conf.remove(STS_ROLE_ARN);
    final Object awsAccessKey = conf.remove(AWS_ACCESS_KEY);
    final Object awsSecretKey = conf.remove(AWS_SECRET_KEY);

    if (Objects.nonNull(awsAccessKey) && Objects.nonNull(awsSecretKey) && Objects.nonNull(stsRoleArn)) {
        return new STSAssumeRoleSessionCredentialsProvider.Builder(stsRoleArn.toString(), "haystack-agent")
            .withStsClient(
                AWSSecurityTokenServiceClientBuilder.standard()
                    .withCredentials(
                        new AWSStaticCredentialsProvider(new BasicAWSCredentials(awsAccessKey.toString(), awsSecretKey.toString()))
                    )
                    .withRegion(conf.get(AWS_REGION))
                    .build()
            ).build();
    } else if (Objects.nonNull(awsAccessKey) && Objects.nonNull(awsSecretKey)) {
        LOGGER.info("Using static credential provider using aws access and secret keys");
        return new AWSStaticCredentialsProvider(
                new BasicAWSCredentials(awsAccessKey.toString(), awsSecretKey.toString()));
    } else {
        if (Objects.nonNull(stsRoleArn)) {
            LOGGER.info("Using aws sts credential provider with role arn={}", stsRoleArn);
            return new STSProfileCredentialsServiceProvider(
                    new RoleInfo().withRoleArn(stsRoleArn.toString()).withRoleSessionName("haystack-agent"));
        } else {
            return DefaultAWSCredentialsProviderChain.getInstance();
        }
    }
}
 
Example #28
Source File: GroupModel.java    From strongbox with Apache License 2.0 5 votes vote down vote up
private AWSCredentialsProvider assumeRole(AWSCredentialsProvider longLivedAWSCredentials, ClientConfiguration clientConfiguration, String assumeRoleArn) {
    AWSSecurityTokenService client = AWSSecurityTokenServiceClientBuilder.standard()
            .withCredentials(longLivedAWSCredentials)
            .withClientConfiguration(transformAndVerifyOrThrow(clientConfiguration))
            .withRegion(RegionResolver.getRegion())
            .build();

    STSAssumeRoleSessionCredentialsProvider.Builder builder =
            new STSAssumeRoleSessionCredentialsProvider.Builder(assumeRoleArn, "strongbox-cli");
    builder.withStsClient(client);

    return builder.build();
}
 
Example #29
Source File: ProfileCredentialProvider.java    From strongbox with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example #30
Source File: S3ClientFactory.java    From genie with Apache License 2.0 4 votes vote down vote up
/**
 * Constructor.
 *
 * @param awsCredentialsProvider The base AWS credentials provider to use for the generated S3 clients
 * @param regionProvider         How this factory should determine the default {@link Regions}
 * @param environment            The Spring application {@link Environment}
 */
public S3ClientFactory(
    final AWSCredentialsProvider awsCredentialsProvider,
    final AwsRegionProvider regionProvider,
    final Environment environment
) {
    this.awsCredentialsProvider = awsCredentialsProvider;

    /*
     * Use the Spring property binder to dynamically map properties under a common root into a map of key to object.
     *
     * In this case we're trying to get bucketName -> BucketProperties
     *
     * So if there were properties like:
     * genie.aws.s3.buckets.someBucket1.roleARN = blah
     * genie.aws.s3.buckets.someBucket2.region = us-east-1
     * genie.aws.s3.buckets.someBucket2.roleARN = blah
     *
     * The result of this should be two entries in the map "bucket1" and "bucket2" mapping to property binding
     * object instances of BucketProperties with the correct property set or null if option wasn't specified.
     */
    this.bucketProperties = Binder
        .get(environment)
        .bind(
            BUCKET_PROPERTIES_ROOT_KEY,
            Bindable.mapOf(String.class, BucketProperties.class)
        )
        .orElse(Collections.emptyMap());

    // Set the initial size to the number of special cases defined in properties + 1 for the default client
    // NOTE: Should we proactively create all necessary clients or be lazy about it? For now, lazy.
    final int initialCapacity = this.bucketProperties.size() + 1;
    this.clientCache = new ConcurrentHashMap<>(initialCapacity);
    this.transferManagerCache = new ConcurrentHashMap<>(initialCapacity);

    String tmpRegion;
    try {
        tmpRegion = regionProvider.getRegion();
    } catch (final SdkClientException e) {
        tmpRegion = Regions.getCurrentRegion() != null
            ? Regions.getCurrentRegion().getName()
            : Regions.US_EAST_1.getName();
        log.warn(
            "Couldn't determine the AWS region from the provider ({}) supplied. Defaulting to {}",
            regionProvider.toString(),
            tmpRegion
        );
    }
    this.defaultRegion = Regions.fromName(tmpRegion);

    // Create a token service client to use if we ever need to assume a role
    // TODO: Perhaps this should be just set to null if the bucket properties are empty as we'll never need it?
    this.stsClient = AWSSecurityTokenServiceClientBuilder
        .standard()
        .withRegion(this.defaultRegion)
        .withCredentials(this.awsCredentialsProvider)
        .build();

    this.bucketToClientKey = new ConcurrentHashMap<>();
}