com.amazonaws.auth.STSAssumeRoleSessionCredentialsProvider Java Examples

The following examples show how to use com.amazonaws.auth.STSAssumeRoleSessionCredentialsProvider. 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: GlueHiveMetastore.java    From presto with Apache License 2.0 6 votes vote down vote up
private static AWSCredentialsProvider getAwsCredentialsProvider(GlueHiveMetastoreConfig config)
{
    if (config.getAwsAccessKey().isPresent() && config.getAwsSecretKey().isPresent()) {
        return new AWSStaticCredentialsProvider(
                new BasicAWSCredentials(config.getAwsAccessKey().get(), config.getAwsSecretKey().get()));
    }
    if (config.getIamRole().isPresent()) {
        return new STSAssumeRoleSessionCredentialsProvider
                .Builder(config.getIamRole().get(), "presto-session")
                .withExternalId(config.getExternalId().orElse(null))
                .build();
    }
    if (config.getAwsCredentialsProvider().isPresent()) {
        return getCustomAWSCredentialsProvider(config.getAwsCredentialsProvider().get());
    }
    return DefaultAWSCredentialsProviderChain.getInstance();
}
 
Example #2
Source File: S3ClientFactory.java    From genie with Apache License 2.0 6 votes vote down vote up
private AmazonS3 buildS3Client(final S3ClientKey s3ClientKey) {
    // TODO: Do something about allowing ClientConfiguration to be passed in
    return AmazonS3ClientBuilder
        .standard()
        .withRegion(s3ClientKey.getRegion())
        .withForceGlobalBucketAccessEnabled(true)
        .withCredentials(
            s3ClientKey
                .getRoleARN()
                .map(
                    roleARN -> {
                        // TODO: Perhaps rename with more detailed info?
                        final String roleSession = "Genie-Agent-" + UUID.randomUUID().toString();

                        return (AWSCredentialsProvider) new STSAssumeRoleSessionCredentialsProvider
                            .Builder(roleARN, roleSession)
                            .withStsClient(this.stsClient)
                            .build();
                    }
                )
                .orElse(this.awsCredentialsProvider)
        )
        .build();
}
 
Example #3
Source File: AWSCredentialsProviderControllerServiceTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileCredentialsProviderWithRole() throws Throwable {
    final TestRunner runner = TestRunners.newTestRunner(FetchS3Object.class);
    final AWSCredentialsProviderControllerService serviceImpl = new AWSCredentialsProviderControllerService();
    runner.addControllerService("awsCredentialsProvider", serviceImpl);
    runner.setProperty(serviceImpl, AbstractAWSProcessor.CREDENTIALS_FILE,
            "src/test/resources/mock-aws-credentials.properties");
    runner.setProperty(serviceImpl, AWSCredentialsProviderControllerService.ASSUME_ROLE_ARN, "Role");
    runner.setProperty(serviceImpl, AWSCredentialsProviderControllerService.ASSUME_ROLE_NAME, "RoleName");
    runner.enableControllerService(serviceImpl);

    runner.assertValid(serviceImpl);
    final AWSCredentialsProviderService service = (AWSCredentialsProviderService) runner.getProcessContext()
            .getControllerServiceLookup().getControllerService("awsCredentialsProvider");
    Assert.assertNotNull(service);
    final AWSCredentialsProvider credentialsProvider = service.getCredentialsProvider();
    Assert.assertNotNull(credentialsProvider);
    assertEquals("credentials provider should be equal", STSAssumeRoleSessionCredentialsProvider.class,
            credentialsProvider.getClass());
}
 
Example #4
Source File: AWSCredentialsProviderControllerServiceTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testKeysCredentialsProviderWithRoleAndNameAndSessionTimeoutInRange() throws Throwable {
    final TestRunner runner = TestRunners.newTestRunner(FetchS3Object.class);
    final AWSCredentialsProviderControllerService serviceImpl = new AWSCredentialsProviderControllerService();
    runner.addControllerService("awsCredentialsProvider", serviceImpl);
    runner.setProperty(serviceImpl, AbstractAWSProcessor.ACCESS_KEY, "awsAccessKey");
    runner.setProperty(serviceImpl, AbstractAWSProcessor.SECRET_KEY, "awsSecretKey");
    runner.setProperty(serviceImpl, AWSCredentialsProviderControllerService.ASSUME_ROLE_ARN, "Role");
    runner.setProperty(serviceImpl, AWSCredentialsProviderControllerService.ASSUME_ROLE_NAME, "RoleName");
    runner.setProperty(serviceImpl, AWSCredentialsProviderControllerService.MAX_SESSION_TIME, "1000");
    runner.enableControllerService(serviceImpl);

    runner.assertValid(serviceImpl);
    final AWSCredentialsProviderService service = (AWSCredentialsProviderService) runner.getProcessContext()
            .getControllerServiceLookup().getControllerService("awsCredentialsProvider");
    Assert.assertNotNull(service);
    final AWSCredentialsProvider credentialsProvider = service.getCredentialsProvider();
    Assert.assertNotNull(credentialsProvider);
    assertEquals("credentials provider should be equal", STSAssumeRoleSessionCredentialsProvider.class,
            credentialsProvider.getClass());
}
 
Example #5
Source File: AWSCredentialsProviderControllerServiceTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testKeysCredentialsProviderWithRoleAndName() throws Throwable {
    final TestRunner runner = TestRunners.newTestRunner(FetchS3Object.class);
    final AWSCredentialsProviderControllerService serviceImpl = new AWSCredentialsProviderControllerService();
    runner.addControllerService("awsCredentialsProvider", serviceImpl);
    runner.setProperty(serviceImpl, AbstractAWSProcessor.ACCESS_KEY, "awsAccessKey");
    runner.setProperty(serviceImpl, AbstractAWSProcessor.SECRET_KEY, "awsSecretKey");
    runner.setProperty(serviceImpl, AWSCredentialsProviderControllerService.ASSUME_ROLE_ARN, "Role");
    runner.setProperty(serviceImpl, AWSCredentialsProviderControllerService.ASSUME_ROLE_NAME, "RoleName");
    runner.enableControllerService(serviceImpl);

    runner.assertValid(serviceImpl);
    final AWSCredentialsProviderService service = (AWSCredentialsProviderService) runner.getProcessContext()
            .getControllerServiceLookup().getControllerService("awsCredentialsProvider");
    Assert.assertNotNull(service);
    final AWSCredentialsProvider credentialsProvider = service.getCredentialsProvider();
    Assert.assertNotNull(credentialsProvider);
    assertEquals("credentials provider should be equal", STSAssumeRoleSessionCredentialsProvider.class,
            credentialsProvider.getClass());
}
 
Example #6
Source File: TestCredentialsProviderFactory.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testAssumeRoleCredentialsWithProxy() throws Throwable {
    final TestRunner runner = TestRunners.newTestRunner(MockAWSProcessor.class);
    runner.setProperty(CredentialPropertyDescriptors.CREDENTIALS_FILE, "src/test/resources/mock-aws-credentials.properties");
    runner.setProperty(CredentialPropertyDescriptors.ASSUME_ROLE_ARN, "BogusArn");
    runner.setProperty(CredentialPropertyDescriptors.ASSUME_ROLE_NAME, "BogusSession");
    runner.setProperty(CredentialPropertyDescriptors.ASSUME_ROLE_PROXY_HOST, "proxy.company.com");
    runner.setProperty(CredentialPropertyDescriptors.ASSUME_ROLE_PROXY_PORT, "8080");
    runner.assertValid();

    Map<PropertyDescriptor, String> properties = runner.getProcessContext().getProperties();
    final CredentialsProviderFactory factory = new CredentialsProviderFactory();
    final AWSCredentialsProvider credentialsProvider = factory.getCredentialsProvider(properties);
    Assert.assertNotNull(credentialsProvider);
    assertEquals("credentials provider should be equal", STSAssumeRoleSessionCredentialsProvider.class,
            credentialsProvider.getClass());
}
 
Example #7
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 #8
Source File: AWSClusterSecurityManager.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
public AWSCredentialsProvider getCredentialsProvider() {
  AWSCredentialsProvider credentialsProviderChain = new DefaultAWSCredentialsProviderChain(this.config);
  if (config.hasPath(GobblinAWSConfigurationKeys.CLIENT_ASSUME_ROLE_KEY) &&
          config.getBoolean(GobblinAWSConfigurationKeys.CLIENT_ASSUME_ROLE_KEY)) {
    String roleArn = config.getString(GobblinAWSConfigurationKeys.CLIENT_ROLE_ARN_KEY);
    String sessionId = config.getString(GobblinAWSConfigurationKeys.CLIENT_SESSION_ID_KEY);
    STSAssumeRoleSessionCredentialsProvider.Builder builder =
            new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, sessionId)
                    .withLongLivedCredentialsProvider(credentialsProviderChain);
    if (config.hasPath(GobblinAWSConfigurationKeys.CLIENT_EXTERNAL_ID_KEY)) {
      builder.withExternalId(config.getString(GobblinAWSConfigurationKeys.CLIENT_EXTERNAL_ID_KEY));
    }
    if (config.hasPath(GobblinAWSConfigurationKeys.CREDENTIALS_REFRESH_INTERVAL)) {
      builder.withRoleSessionDurationSeconds(
              (int) TimeUnit.MINUTES.toSeconds(config.getLong(GobblinAWSConfigurationKeys.CREDENTIALS_REFRESH_INTERVAL)));
    }
    credentialsProviderChain = builder.build();
  }
  return credentialsProviderChain;
}
 
Example #9
Source File: CachingClientProvider.java    From fullstop with Apache License 2.0 6 votes vote down vote up
private CacheLoader<Key<?>, CacheValue> createCacheLoader() {
    return new CacheLoader<Key<?>, CacheValue>() {
        @Override
        public CacheValue load(@Nonnull final Key<?> key) {
            log.debug("Creating a new AmazonWebServiceClient client for {}", key);
            final STSAssumeRoleSessionCredentialsProvider tempCredentials = new STSAssumeRoleSessionCredentialsProvider
                    .Builder(buildRoleArn(key.accountId), ROLE_SESSION_NAME).withStsClient(awsSecurityTokenService)
                    .build();

            final String builderName = key.type.getName() + "Builder";
            final Class<?> className = ClassUtils.resolveClassName(builderName, ClassUtils.getDefaultClassLoader());
            final Method method = ClassUtils.getStaticMethod(className, "standard");
            Assert.notNull(method, "Could not find standard() method in class:'" + className.getName() + "'");

            final AwsClientBuilder<?, ?> builder = (AwsClientBuilder<?, ?>) ReflectionUtils.invokeMethod(method, null);
            builder.withCredentials(tempCredentials);
            builder.withRegion(key.region.getName());
            builder.withClientConfiguration(new ClientConfiguration().withMaxErrorRetry(MAX_ERROR_RETRY));
            final AmazonWebServiceClient client = (AmazonWebServiceClient) builder.build();
            return new CacheValue(client, tempCredentials);
        }
    };
}
 
Example #10
Source File: DeviceFarmClientFactory.java    From aws-device-farm-gradle-plugin with Apache License 2.0 6 votes vote down vote up
public AWSDeviceFarmClient initializeApiClient(final DeviceFarmExtension extension) {

        final String roleArn = extension.getAuthentication().getRoleArn();

        AWSCredentials credentials = extension.getAuthentication();

        if (roleArn != null) {
            final STSAssumeRoleSessionCredentialsProvider sts = new STSAssumeRoleSessionCredentialsProvider
                    .Builder(roleArn, RandomStringUtils.randomAlphanumeric(8))
                    .build();
            credentials = sts.getCredentials();
        }

        final ClientConfiguration clientConfiguration = new ClientConfiguration()
                .withUserAgent(String.format(extension.getUserAgent(), pluginVersion));

        AWSDeviceFarmClient apiClient = new AWSDeviceFarmClient(credentials, clientConfiguration);
        apiClient.setServiceNameIntern("devicefarm");
        if (extension.getEndpointOverride() != null) {
            apiClient.setEndpoint(extension.getEndpointOverride());
        }

        return apiClient;

    }
 
Example #11
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 #12
Source File: ZipkinKinesisCollectorModuleTest.java    From zipkin-aws with Apache License 2.0 6 votes vote down vote up
@Test
public void kinesisCollectorConfiguredForAWSWithGivenCredentials() {
  TestPropertyValues.of(
      "zipkin.collector.kinesis.stream-name: zipkin-test",
      "zipkin.collector.kinesis.app-name: zipkin",
      "zipkin.collector.kinesis.aws-sts-region: us-east-1",
      "zipkin.collector.kinesis.aws-access-key-id: x",
      "zipkin.collector.kinesis.aws-secret-access-key: x",
      "zipkin.collector.kinesis.aws-sts-role-arn: test")
      .applyTo(context);
  context.register(
      PropertyPlaceholderAutoConfiguration.class,
      ZipkinKinesisCollectorModule.class,
      ZipkinKinesisCredentialsConfiguration.class,
      InMemoryConfiguration.class);
  context.refresh();

  assertThat(context.getBean(KinesisCollector.class)).isNotNull();
  assertThat(context.getBean(AWSSecurityTokenService.class)).isNotNull();
  assertThat(context.getBean(AWSCredentialsProvider.class))
      .isInstanceOf(STSAssumeRoleSessionCredentialsProvider.class);
}
 
Example #13
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 #14
Source File: AmazonClientProvider.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private AWSCredentialsProvider getAwsCredentialsProvider(String accountId) {
    AWSCredentialsProvider credentialsProvider = awsCredentialsByAccountId.get(accountId);
    if (credentialsProvider == null) {
        synchronized (this) {
            credentialsProvider = awsCredentialsByAccountId.get(accountId);
            if (credentialsProvider == null) {
                String roleSessionName = configuration.getControlPlaneRoleSessionName();
                int roleSessionDurationSeconds = configuration.getControlPlaneRoleSessionDurationSeconds();
                Arn roleArn = getControlPlaneRoleArnForAccount(accountId);

                credentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn.toString(), roleSessionName)
                        .withStsClient(stsClient)
                        .withRoleSessionDurationSeconds(roleSessionDurationSeconds)
                        .build();
                awsCredentialsByAccountId.put(accountId, credentialsProvider);
            }
        }
    }
    return credentialsProvider;
}
 
Example #15
Source File: AWSCredentialsProviderControllerServiceTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileCredentialsProviderWithRole() throws Throwable {
    final TestRunner runner = TestRunners.newTestRunner(FetchS3Object.class);
    final AWSCredentialsProviderControllerService serviceImpl = new AWSCredentialsProviderControllerService();
    runner.addControllerService("awsCredentialsProvider", serviceImpl);
    runner.setProperty(serviceImpl, AbstractAWSProcessor.CREDENTIALS_FILE,
            "src/test/resources/mock-aws-credentials.properties");
    runner.setProperty(serviceImpl, AWSCredentialsProviderControllerService.ASSUME_ROLE_ARN, "Role");
    runner.setProperty(serviceImpl, AWSCredentialsProviderControllerService.ASSUME_ROLE_NAME, "RoleName");
    runner.enableControllerService(serviceImpl);

    runner.assertValid(serviceImpl);
    final AWSCredentialsProviderService service = (AWSCredentialsProviderService) runner.getProcessContext()
            .getControllerServiceLookup().getControllerService("awsCredentialsProvider");
    Assert.assertNotNull(service);
    final AWSCredentialsProvider credentialsProvider = service.getCredentialsProvider();
    Assert.assertNotNull(credentialsProvider);
    assertEquals("credentials provider should be equal", STSAssumeRoleSessionCredentialsProvider.class,
            credentialsProvider.getClass());
}
 
Example #16
Source File: AWSCredentialsProviderControllerServiceTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testKeysCredentialsProviderWithRoleAndNameAndSessionTimeoutInRange() throws Throwable {
    final TestRunner runner = TestRunners.newTestRunner(FetchS3Object.class);
    final AWSCredentialsProviderControllerService serviceImpl = new AWSCredentialsProviderControllerService();
    runner.addControllerService("awsCredentialsProvider", serviceImpl);
    runner.setProperty(serviceImpl, AbstractAWSProcessor.ACCESS_KEY, "awsAccessKey");
    runner.setProperty(serviceImpl, AbstractAWSProcessor.SECRET_KEY, "awsSecretKey");
    runner.setProperty(serviceImpl, AWSCredentialsProviderControllerService.ASSUME_ROLE_ARN, "Role");
    runner.setProperty(serviceImpl, AWSCredentialsProviderControllerService.ASSUME_ROLE_NAME, "RoleName");
    runner.setProperty(serviceImpl, AWSCredentialsProviderControllerService.MAX_SESSION_TIME, "1000");
    runner.enableControllerService(serviceImpl);

    runner.assertValid(serviceImpl);
    final AWSCredentialsProviderService service = (AWSCredentialsProviderService) runner.getProcessContext()
            .getControllerServiceLookup().getControllerService("awsCredentialsProvider");
    Assert.assertNotNull(service);
    final AWSCredentialsProvider credentialsProvider = service.getCredentialsProvider();
    Assert.assertNotNull(credentialsProvider);
    assertEquals("credentials provider should be equal", STSAssumeRoleSessionCredentialsProvider.class,
            credentialsProvider.getClass());
}
 
Example #17
Source File: TestPrestoS3FileSystem.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void testAssumeRoleCredentialsWithExternalId()
        throws Exception
{
    Configuration config = new Configuration(false);
    config.set(S3_IAM_ROLE, "role");
    config.set(S3_EXTERNAL_ID, "externalId");

    try (PrestoS3FileSystem fs = new PrestoS3FileSystem()) {
        fs.initialize(new URI("s3n://test-bucket/"), config);
        AWSCredentialsProvider awsCredentialsProvider = getAwsCredentialsProvider(fs);
        assertInstanceOf(awsCredentialsProvider, STSAssumeRoleSessionCredentialsProvider.class);
        assertEquals(getFieldValue(awsCredentialsProvider, "roleArn", String.class), "role");
        assertEquals(getFieldValue(awsCredentialsProvider, "roleExternalId", String.class), "externalId");
    }
}
 
Example #18
Source File: AWSCredentialsProviderControllerServiceTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testKeysCredentialsProviderWithRoleAndName() throws Throwable {
    final TestRunner runner = TestRunners.newTestRunner(FetchS3Object.class);
    final AWSCredentialsProviderControllerService serviceImpl = new AWSCredentialsProviderControllerService();
    runner.addControllerService("awsCredentialsProvider", serviceImpl);
    runner.setProperty(serviceImpl, AbstractAWSProcessor.ACCESS_KEY, "awsAccessKey");
    runner.setProperty(serviceImpl, AbstractAWSProcessor.SECRET_KEY, "awsSecretKey");
    runner.setProperty(serviceImpl, AWSCredentialsProviderControllerService.ASSUME_ROLE_ARN, "Role");
    runner.setProperty(serviceImpl, AWSCredentialsProviderControllerService.ASSUME_ROLE_NAME, "RoleName");
    runner.enableControllerService(serviceImpl);

    runner.assertValid(serviceImpl);
    final AWSCredentialsProviderService service = (AWSCredentialsProviderService) runner.getProcessContext()
            .getControllerServiceLookup().getControllerService("awsCredentialsProvider");
    Assert.assertNotNull(service);
    final AWSCredentialsProvider credentialsProvider = service.getCredentialsProvider();
    Assert.assertNotNull(credentialsProvider);
    assertEquals("credentials provider should be equal", STSAssumeRoleSessionCredentialsProvider.class,
            credentialsProvider.getClass());
}
 
Example #19
Source File: TestCredentialsProviderFactory.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testAssumeRoleCredentialsWithProxy() throws Throwable {
    final TestRunner runner = TestRunners.newTestRunner(MockAWSProcessor.class);
    runner.setProperty(CredentialPropertyDescriptors.CREDENTIALS_FILE, "src/test/resources/mock-aws-credentials.properties");
    runner.setProperty(CredentialPropertyDescriptors.ASSUME_ROLE_ARN, "BogusArn");
    runner.setProperty(CredentialPropertyDescriptors.ASSUME_ROLE_NAME, "BogusSession");
    runner.setProperty(CredentialPropertyDescriptors.ASSUME_ROLE_PROXY_HOST, "proxy.company.com");
    runner.setProperty(CredentialPropertyDescriptors.ASSUME_ROLE_PROXY_PORT, "8080");
    runner.assertValid();

    Map<PropertyDescriptor, String> properties = runner.getProcessContext().getProperties();
    final CredentialsProviderFactory factory = new CredentialsProviderFactory();
    final AWSCredentialsProvider credentialsProvider = factory.getCredentialsProvider(properties);
    Assert.assertNotNull(credentialsProvider);
    assertEquals("credentials provider should be equal", STSAssumeRoleSessionCredentialsProvider.class,
            credentialsProvider.getClass());
}
 
Example #20
Source File: AssumeRoleCredentialProvider.java    From circus-train with Apache License 2.0 5 votes vote down vote up
private void initializeCredentialProvider() {
  String roleArn = conf.get(ASSUME_ROLE_PROPERTY_NAME);
  checkArgument(StringUtils.isNotEmpty(roleArn),
      "Role ARN must not be empty, please set: " + ASSUME_ROLE_PROPERTY_NAME);

  int roleSessionDuration = conf.getInt(ASSUME_ROLE_SESSION_DURATION_SECONDS_PROPERTY_NAME, DEFAULT_CREDENTIALS_DURATION);

  // STSAssumeRoleSessionCredentialsProvider should auto refresh its credentials in the background.
  this.credentialsProvider = new STSAssumeRoleSessionCredentialsProvider
      .Builder(roleArn, "ct-assume-role-session")
      .withRoleSessionDurationSeconds(roleSessionDuration)
      .build();
}
 
Example #21
Source File: PrestoS3FileSystem.java    From presto with Apache License 2.0 5 votes vote down vote up
private AWSCredentialsProvider createAwsCredentialsProvider(URI uri, Configuration conf)
{
    // credentials embedded in the URI take precedence and are used alone
    Optional<AWSCredentials> credentials = getEmbeddedAwsCredentials(uri);
    if (credentials.isPresent()) {
        return new AWSStaticCredentialsProvider(credentials.get());
    }

    // a custom credential provider is also used alone
    String providerClass = conf.get(S3_CREDENTIALS_PROVIDER);
    if (!isNullOrEmpty(providerClass)) {
        return getCustomAWSCredentialsProvider(uri, conf, providerClass);
    }

    // use configured credentials or default chain with optional role
    AWSCredentialsProvider provider = getAwsCredentials(conf)
            .map(value -> (AWSCredentialsProvider) new AWSStaticCredentialsProvider(value))
            .orElseGet(DefaultAWSCredentialsProviderChain::getInstance);

    if (iamRole != null) {
        provider = new STSAssumeRoleSessionCredentialsProvider.Builder(iamRole, "presto-session")
                .withExternalId(externalId)
                .withLongLivedCredentialsProvider(provider)
                .build();
    }

    return provider;
}
 
Example #22
Source File: TestPrestoS3FileSystem.java    From presto with Apache License 2.0 5 votes vote down vote up
private static AWSCredentialsProvider getStsCredentialsProvider(PrestoS3FileSystem fs, String expectedRole)
{
    AWSCredentialsProvider awsCredentialsProvider = getAwsCredentialsProvider(fs);
    assertInstanceOf(awsCredentialsProvider, STSAssumeRoleSessionCredentialsProvider.class);

    assertEquals(getFieldValue(awsCredentialsProvider, "roleArn", String.class), expectedRole);

    AWSSecurityTokenService tokenService = getFieldValue(awsCredentialsProvider, "securityTokenService", AWSSecurityTokenService.class);
    assertInstanceOf(tokenService, AWSSecurityTokenServiceClient.class);
    return getFieldValue(tokenService, "awsCredentialsProvider", AWSCredentialsProvider.class);
}
 
Example #23
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 #24
Source File: TestCredentialsProviderFactory.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testAssumeRoleCredentials() throws Throwable {
    final TestRunner runner = TestRunners.newTestRunner(MockAWSProcessor.class);
    runner.setProperty(CredentialPropertyDescriptors.CREDENTIALS_FILE, "src/test/resources/mock-aws-credentials.properties");
    runner.setProperty(CredentialPropertyDescriptors.ASSUME_ROLE_ARN, "BogusArn");
    runner.setProperty(CredentialPropertyDescriptors.ASSUME_ROLE_NAME, "BogusSession");
    runner.assertValid();

    Map<PropertyDescriptor, String> properties = runner.getProcessContext().getProperties();
    final CredentialsProviderFactory factory = new CredentialsProviderFactory();
    final AWSCredentialsProvider credentialsProvider = factory.getCredentialsProvider(properties);
    Assert.assertNotNull(credentialsProvider);
    assertEquals("credentials provider should be equal", STSAssumeRoleSessionCredentialsProvider.class,
            credentialsProvider.getClass());
}
 
Example #25
Source File: AssumeRoleCredentialsStrategy.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public AWSCredentialsProvider getDerivedCredentialsProvider(Map<PropertyDescriptor, String> properties,
                                                            AWSCredentialsProvider primaryCredentialsProvider) {
    final String assumeRoleArn = properties.get(ASSUME_ROLE_ARN);
    final String assumeRoleName = properties.get(ASSUME_ROLE_NAME);
    String rawMaxSessionTime = properties.get(MAX_SESSION_TIME);
    rawMaxSessionTime = (rawMaxSessionTime != null) ? rawMaxSessionTime : MAX_SESSION_TIME.getDefaultValue();
    final Integer maxSessionTime = Integer.parseInt(rawMaxSessionTime.trim());
    final String assumeRoleExternalId = properties.get(ASSUME_ROLE_EXTERNAL_ID);
    STSAssumeRoleSessionCredentialsProvider.Builder builder;
    ClientConfiguration config = new ClientConfiguration();

    // If proxy variables are set, then create Client Configuration with those values
    if (proxyVariablesValidForAssumeRole(properties)) {
        final String assumeRoleProxyHost = properties.get(ASSUME_ROLE_PROXY_HOST);
        final Integer assumeRoleProxyPort = Integer.parseInt(properties.get(ASSUME_ROLE_PROXY_PORT));
        config.withProxyHost(assumeRoleProxyHost);
        config.withProxyPort(assumeRoleProxyPort);
    }

    AWSSecurityTokenService securityTokenService = new AWSSecurityTokenServiceClient(primaryCredentialsProvider, config);
    builder = new STSAssumeRoleSessionCredentialsProvider
            .Builder(assumeRoleArn, assumeRoleName)
            .withStsClient(securityTokenService)
            .withRoleSessionDurationSeconds(maxSessionTime);

    if (assumeRoleExternalId != null && !assumeRoleExternalId.isEmpty()) {
        builder = builder.withExternalId(assumeRoleExternalId);
    }

    final AWSCredentialsProvider credsProvider = builder.build();

    return credsProvider;
}
 
Example #26
Source File: AWSDeviceFarm.java    From aws-device-farm-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Private AWSDeviceFarm constructor. Uses the roleArn to generate STS creds if the roleArn isn't null; otherwise
 * just uses the AWSCredentials creds.
 *
 * @param creds   AWSCredentials creds to use for authentication.
 * @param roleArn Role ARN to use for authentication.
 */
private AWSDeviceFarm(AWSCredentials creds, String roleArn) {
    if (roleArn != null) {
        STSAssumeRoleSessionCredentialsProvider sts = new STSAssumeRoleSessionCredentialsProvider
                .Builder(roleArn, RandomStringUtils.randomAlphanumeric(8))
                .withRoleSessionDurationSeconds(MAX_ROLE_SESSION_TIMEOUT)
                .build();
        creds = sts.getCredentials();
    }

    ClientConfiguration clientConfiguration = new ClientConfiguration().withUserAgent("AWS Device Farm - Jenkins v1.0");
    api = new AWSDeviceFarmClient(creds, clientConfiguration);
    api.setServiceNameIntern("devicefarm");
}
 
Example #27
Source File: ExamplePlugin.java    From fullstop with Apache License 2.0 5 votes vote down vote up
private AmazonEC2 getClientForAccount(final String accountId, final Region region) {
    final AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClient.builder()
            .withCredentials(new ProfileCredentialsProvider()).build();
    final String roleArn = String.format("arn:aws:iam::%s:role/fullstop-role", accountId);
    final String sessionName = "fullstop-role";
    final AWSCredentialsProvider tempCredentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, sessionName)
            .withStsClient(stsClient)
            .withRoleSessionDurationSeconds(3600)
            .build();
    return AmazonEC2Client.builder().withCredentials(tempCredentialsProvider).withRegion(region.getName()).build();
}
 
Example #28
Source File: ClientTest.java    From fullstop with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
@Test
public void createClient() {
    final AWSCredentialsProvider tempCredentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder("", "").build();
    final AmazonEC2 client = AmazonEC2ClientBuilder.standard()
            .withRegion(Regions.EU_CENTRAL_1)
            .withCredentials(tempCredentialsProvider)
            .build();
}
 
Example #29
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 #30
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();
}