com.amazonaws.auth.AWSCredentialsProvider Java Examples

The following examples show how to use com.amazonaws.auth.AWSCredentialsProvider. 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: CredentialsProviderFactoryBeanTest.java    From spring-cloud-aws with Apache License 2.0 7 votes vote down vote up
@Test
void getObject_withZeroConfiguredProviders_returnsDefaultAwsCredentialsProviderChain()
		throws Exception {
	// Arrange
	CredentialsProviderFactoryBean credentialsProviderFactoryBean = new CredentialsProviderFactoryBean();
	credentialsProviderFactoryBean.afterPropertiesSet();

	// Act
	AWSCredentialsProvider credentialsProvider = credentialsProviderFactoryBean
			.getObject();

	// Assert
	assertThat(credentialsProvider).isNotNull();
	assertThat(
			DefaultAWSCredentialsProviderChain.class.isInstance(credentialsProvider))
					.isTrue();
}
 
Example #3
Source File: AWSClientFactory.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
private AWSCredentialsProvider getStepCreds(EnvVars stepEnvVars) {
    String stepAccessKey = stepEnvVars.get(AWS_ACCESS_KEY_ID);
    String stepSecretKey = stepEnvVars.get(AWS_SECRET_ACCESS_KEY);
    String stepSessionToken = stepEnvVars.get(AWS_SESSION_TOKEN);

    if(stepAccessKey != null && !stepAccessKey.isEmpty() && stepSecretKey != null && !stepSecretKey.isEmpty()) {
        this.credentialsDescriptor = stepCredentials;
        if(stepSessionToken != null && !stepSessionToken.isEmpty()) {
            return new AWSStaticCredentialsProvider(new BasicSessionCredentials(stepAccessKey, stepSecretKey, stepSessionToken));
        } else {
            return new AWSStaticCredentialsProvider(new BasicAWSCredentials(stepAccessKey, stepSecretKey));
        }
    }

    return null;
}
 
Example #4
Source File: ContextCredentialsAutoConfigurationTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void credentialsProvider_profileNameConfigured_configuresProfileCredentialsProvider() {
	this.contextRunner.withPropertyValues(
			"cloud.aws.credentials.use-default-aws-credentials-chain:false",
			"cloud.aws.credentials.profile-name:test").run((context) -> {
				AWSCredentialsProvider awsCredentialsProvider = context.getBean(
						AmazonWebserviceClientConfigurationUtils.CREDENTIALS_PROVIDER_BEAN_NAME,
						AWSCredentialsProvider.class);
				assertThat(awsCredentialsProvider).isNotNull();

				@SuppressWarnings("unchecked")
				List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils
						.getField(awsCredentialsProvider, "credentialsProviders");
				assertThat(credentialsProviders).hasSize(1)
						.hasOnlyElementsOfType(ProfileCredentialsProvider.class);
				assertThat(ReflectionTestUtils.getField(credentialsProviders.get(0),
						"profileName")).isEqualTo("test");
			});
}
 
Example #5
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 #6
Source File: Main.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private static AwsInstanceCloudConnector createConnector() {
    AWSCredentialsProvider baseCredentials = new ProfileCredentialsProvider("default");
    AWSSecurityTokenServiceAsync stsClient = new AmazonStsAsyncProvider(CONFIGURATION, baseCredentials).get();
    AWSCredentialsProvider credentialsProvider = new DataPlaneControllerCredentialsProvider(CONFIGURATION, stsClient, baseCredentials).get();

    Region currentRegion = Regions.getCurrentRegion();
    if (currentRegion == null) {
        currentRegion = Region.getRegion(Regions.US_EAST_1);
    }
    return new AwsInstanceCloudConnector(
            CONFIGURATION,
            AmazonEC2AsyncClientBuilder.standard()
                    .withRegion(currentRegion.getName())
                    .withCredentials(credentialsProvider)
                    .build(),
            AmazonAutoScalingAsyncClientBuilder.standard()
                    .withRegion(currentRegion.getName())
                    .withCredentials(credentialsProvider)
                    .build()
    );
}
 
Example #7
Source File: CodeBuildBaseCredentials.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public void refresh() {
    if (!iamRoleArn.isEmpty()) {
        if (!haveCredentialsExpired()) {
            return;
        }

        AWSCredentialsProvider credentialsProvider = getBasicCredentialsOrDefaultChain(accessKey, secretKey);
        AWSCredentials credentials = credentialsProvider.getCredentials();

        AssumeRoleRequest assumeRequest = new AssumeRoleRequest()
                .withRoleArn(iamRoleArn)
                .withExternalId(externalId)
                .withDurationSeconds(3600)
                .withRoleSessionName(ROLE_SESSION_NAME);

        AssumeRoleResult assumeResult = new AWSSecurityTokenServiceClient(credentials).assumeRole(assumeRequest);

        roleCredentials = assumeResult.getCredentials();
    }
}
 
Example #8
Source File: S3Accessor.java    From datacollector with Apache License 2.0 6 votes vote down vote up
AWSCredentialsProvider createCredentialsProvider() throws StageException {
  AWSCredentialsProvider awsCredentialsProvider = null;
  CredentialValue accessKey = credentialConfigs.getAccessKey();
  CredentialValue secretKey = credentialConfigs.getSecretKey();

  if (accessKey != null && secretKey != null) {
    String accessKeyString = accessKey.get();
    String secretKeyString = secretKey.get();

    if (accessKeyString != null &&
        !accessKeyString.isEmpty() &&
        secretKeyString != null &&
        !secretKeyString.isEmpty()) {
      awsCredentialsProvider = new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKeyString,
          secretKeyString
      ));
    }
  }

  return awsCredentialsProvider;
}
 
Example #9
Source File: ZipkinSQSCollectorModule.java    From zipkin-aws with Apache License 2.0 6 votes vote down vote up
@Bean
SQSCollector sqsCollector(
    ZipkinSQSCollectorProperties properties,
    AWSCredentialsProvider credentialsProvider,
    CollectorSampler sampler,
    CollectorMetrics metrics,
    StorageComponent storage) {
  return properties
      .toBuilder()
      .queueUrl(properties.getQueueUrl())
      .waitTimeSeconds(properties.getWaitTimeSeconds())
      .parallelism(properties.getParallelism())
      .endpointConfiguration(endpointConfiguration)
      .credentialsProvider(credentialsProvider)
      .sampler(sampler)
      .metrics(metrics)
      .storage(storage)
      .build()
      .start();
}
 
Example #10
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 #11
Source File: KMSEncryptor.java    From strongbox with Apache License 2.0 6 votes vote down vote up
public KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, AwsCrypto awsCrypto, EncryptionStrength encryptionStrength) {
    this.awsCredentials = awsCredentials;
    this.clientConfiguration = clientConfiguration;
    this.groupIdentifier = groupIdentifier;
    this.kmsManager = kmsManager;

    if (encryptionStrength.equals(EncryptionStrength.AES_128)) {
        awsCrypto.setEncryptionAlgorithm(CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256);
    } else if (encryptionStrength.equals(EncryptionStrength.AES_256)) {
        awsCrypto.setEncryptionAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384);
    } else {
        throw new IllegalArgumentException(String.format("Unrecognized encryption strength %s", encryptionStrength.toString()));
    }

    this.crypto = awsCrypto;
}
 
Example #12
Source File: CredentialsProviderFactoryBeanTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void testCreateWithMultiple() throws Exception {
	AWSCredentialsProvider first = mock(AWSCredentialsProvider.class);
	AWSCredentialsProvider second = mock(AWSCredentialsProvider.class);

	CredentialsProviderFactoryBean credentialsProviderFactoryBean = new CredentialsProviderFactoryBean(
			Arrays.asList(first, second));
	credentialsProviderFactoryBean.afterPropertiesSet();

	AWSCredentialsProvider provider = credentialsProviderFactoryBean.getObject();

	BasicAWSCredentials foo = new BasicAWSCredentials("foo", "foo");
	BasicAWSCredentials bar = new BasicAWSCredentials("bar", "bar");

	when(first.getCredentials()).thenReturn(null, foo);
	when(second.getCredentials()).thenReturn(bar);

	assertThat(provider.getCredentials()).isEqualTo(bar);
	assertThat(provider.getCredentials()).isEqualTo(foo);
}
 
Example #13
Source File: KMSProviderBuilderIntegrationTests.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void whenCustomCredentialsSet_theyAreUsed() throws Exception {
    AWSCredentialsProvider customProvider = spy(new DefaultAWSCredentialsProviderChain());

    KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder()
                                                   .withCredentials(customProvider)
                                                   .withKeysForEncryption(KMSTestFixtures.TEST_KEY_IDS[0])
                                                   .build();

    new AwsCrypto().encryptData(mkp, new byte[1]);

    verify(customProvider, atLeastOnce()).getCredentials();

    AWSCredentials customCredentials = spy(customProvider.getCredentials());

    mkp = KmsMasterKeyProvider.builder()
                                                   .withCredentials(customCredentials)
                                                   .withKeysForEncryption(KMSTestFixtures.TEST_KEY_IDS[0])
                                                   .build();

    new AwsCrypto().encryptData(mkp, new byte[1]);

    verify(customCredentials, atLeastOnce()).getAWSSecretKey();
}
 
Example #14
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 #15
Source File: AWSCredentialsProviderControllerServiceTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileCredentialsProvider() 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.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", PropertiesFileCredentialsProvider.class,
            credentialsProvider.getClass());
}
 
Example #16
Source File: ZipkinKinesisCollectorModule.java    From zipkin-aws with Apache License 2.0 6 votes vote down vote up
@Bean
KinesisCollector kinesisCollector(
    ZipkinKinesisCollectorProperties properties,
    AWSCredentialsProvider credentialsProvider,
    CollectorSampler sampler,
    CollectorMetrics metrics,
    StorageComponent storage) {
  return KinesisCollector.newBuilder()
      .credentialsProvider(credentialsProvider)
      .sampler(sampler)
      .metrics(metrics)
      .storage(storage)
      .streamName(properties.getStreamName())
      .appName(properties.getAppName())
      .regionName(properties.getAwsKinesisRegion())
      .build()
      .start();
}
 
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: KinesisVideoGStreamerPiperExample.java    From amazon-kinesis-video-streams-parser-library with Apache License 2.0 6 votes vote down vote up
@Builder
private KinesisVideoGStreamerPiperExample(Regions region,
        String streamName,
        AWSCredentialsProvider credentialsProvider,
        InputStream inputVideoStream,
        String gStreamerPipelineArgument) {
    super(region, credentialsProvider, streamName);
    final AmazonKinesisVideoClientBuilder builder = AmazonKinesisVideoClientBuilder.standard();
    configureClient(builder);
    this.amazonKinesisVideo = builder.build();
    this.inputStream = inputVideoStream;
    this.streamOps = new StreamOps(region,  streamName, credentialsProvider);
    this.executorService = Executors.newFixedThreadPool(2);
    this.gStreamerPipelineArguments = new ArrayList<>();
    addGStreamerPipelineArguments(gStreamerPipelineArgument);
}
 
Example #19
Source File: AWSSNSMetaDataExtension.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<MetaData> meta(Map<String, Object> parameters) {
    final String accessKey = ConnectorOptions.extractOption(parameters, "accessKey");
    final String secretKey = ConnectorOptions.extractOption(parameters, "secretKey");
    final String region = ConnectorOptions.extractOption(parameters, "region");
    AmazonSNSClientBuilder clientBuilder;
    AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
    clientBuilder = AmazonSNSClientBuilder.standard().withCredentials(credentialsProvider);
    clientBuilder = clientBuilder.withRegion(Regions.valueOf(region));
    AmazonSNS sqsClient = clientBuilder.build();
    try {
        ListTopicsResult result = sqsClient.listTopics();
        Set<String> setTopic = new HashSet<String>();
        if (result.getTopics() != null) {
            for (Topic entry : result.getTopics()) {
            	setTopic.add(entry.getTopicArn());
            }
        }
        return Optional.of(MetaDataBuilder.on(getCamelContext()).withAttribute(MetaData.CONTENT_TYPE, "text/plain").withAttribute(MetaData.JAVA_TYPE, String.class)
            .withPayload(setTopic).build());
    } catch (Exception e) {
        throw new IllegalStateException("Get information about existing topics with has failed.", e);
    }
}
 
Example #20
Source File: InvocationClientConfig.java    From kafka-connect-lambda with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
AWSCredentialsProvider loadAwsCredentialsProvider() {
    try {
        AWSCredentialsProvider credentialsProvider = ((Class<? extends AWSCredentialsProvider>)
            getClass(CREDENTIALS_PROVIDER_CLASS_KEY)).getDeclaredConstructor().newInstance();

        if (credentialsProvider instanceof Configurable) {
            Map<String, Object> configs = originalsWithPrefix(
                CREDENTIALS_PROVIDER_CONFIG_PREFIX);

            ((Configurable)credentialsProvider).configure(configs);
        }

        return credentialsProvider;

    } catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) {
        throw new ConnectException("Unable to create " + CREDENTIALS_PROVIDER_CLASS_KEY, e);
    }
}
 
Example #21
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 #22
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 #23
Source File: DynamoDBStreamsProxy.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an AmazonDynamoDBStreamsAdapterClient.
 * Uses it as the internal client interacting with the DynamoDB streams.
 *
 * @param configProps configuration properties
 * @return an AWS DynamoDB streams adapter client
 */
@Override
protected AmazonKinesis createKinesisClient(Properties configProps) {
	ClientConfiguration awsClientConfig = new ClientConfigurationFactory().getConfig();
	setAwsClientConfigProperties(awsClientConfig, configProps);

	AWSCredentialsProvider credentials = getCredentialsProvider(configProps);
	awsClientConfig.setUserAgentPrefix(
			String.format(
					USER_AGENT_FORMAT,
					EnvironmentInformation.getVersion(),
					EnvironmentInformation.getRevisionInformation().commitId));

	AmazonDynamoDBStreamsAdapterClient adapterClient =
			new AmazonDynamoDBStreamsAdapterClient(credentials, awsClientConfig);

	if (configProps.containsKey(AWS_ENDPOINT)) {
		adapterClient.setEndpoint(configProps.getProperty(AWS_ENDPOINT));
	} else {
		adapterClient.setRegion(Region.getRegion(
				Regions.fromName(configProps.getProperty(AWS_REGION))));
	}

	return adapterClient;
}
 
Example #24
Source File: ContextCredentialsConfigurationRegistrarTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void credentialsProvider_configWithAccessAndSecretKeyAndInstanceProfile_staticAwsCredentialsProviderConfiguredWithInstanceProfile()
		throws Exception {
	// @checkstyle:on
	// Arrange
	this.context = new AnnotationConfigApplicationContext(
			ApplicationConfigurationWithAccessKeyAndSecretKeyAndInstanceProfile.class);

	// Act
	AWSCredentialsProvider awsCredentialsProvider = this.context
			.getBean(AWSCredentialsProvider.class);

	// Assert
	assertThat(awsCredentialsProvider).isNotNull();

	@SuppressWarnings("unchecked")
	List<CredentialsProvider> credentialsProviders = (List<CredentialsProvider>) ReflectionTestUtils
			.getField(awsCredentialsProvider, "credentialsProviders");
	assertThat(credentialsProviders.size()).isEqualTo(2);
	assertThat(AWSStaticCredentialsProvider.class
			.isInstance(credentialsProviders.get(0))).isTrue();
	assertThat(EC2ContainerCredentialsProviderWrapper.class
			.isInstance(credentialsProviders.get(1))).isTrue();
}
 
Example #25
Source File: KinesisMessageChannelBinder.java    From spring-cloud-stream-binder-aws-kinesis with Apache License 2.0 6 votes vote down vote up
public KinesisMessageChannelBinder(KinesisBinderConfigurationProperties configurationProperties,
		KinesisStreamProvisioner provisioningProvider, AmazonKinesisAsync amazonKinesis,
		AWSCredentialsProvider awsCredentialsProvider,
		@Nullable AmazonDynamoDB dynamoDBClient,
		@Nullable AmazonDynamoDBStreams dynamoDBStreams,
		@Nullable AmazonCloudWatch cloudWatchClient) {

	super(headersToMap(configurationProperties), provisioningProvider);
	Assert.notNull(amazonKinesis, "'amazonKinesis' must not be null");
	Assert.notNull(awsCredentialsProvider, "'awsCredentialsProvider' must not be null");
	this.configurationProperties = configurationProperties;
	this.amazonKinesis = amazonKinesis;
	this.cloudWatchClient = cloudWatchClient;
	this.dynamoDBClient = dynamoDBClient;
	this.awsCredentialsProvider = awsCredentialsProvider;

	if (dynamoDBStreams != null) {
		this.dynamoDBStreamsAdapter = new AmazonDynamoDBStreamsAdapterClient(dynamoDBStreams);
	}
	else {
		this.dynamoDBStreamsAdapter = null;
	}
}
 
Example #26
Source File: StashReader.java    From emodb with Apache License 2.0 6 votes vote down vote up
protected static AmazonS3 getS3Client(URI stashRoot, final AWSCredentialsProvider credentialsProvider,
                                      final @Nullable ClientConfiguration s3Config) {
    final String bucket = stashRoot.getHost();

    // If the bucket is a well-known Stash bucket then the region for the bucket is known in advance.
    // Otherwise return a proxy which lazily looks up the bucket on the first call.

    return StashUtil.getRegionForBucket(bucket)
            .map(region -> createS3ClientForRegion(region, credentialsProvider, s3Config))
            .orElseGet(() -> Reflection.newProxy(AmazonS3.class, new AbstractInvocationHandler() {
                private AmazonS3 _resolvedClient = null;

                @Override
                protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
                    return method.invoke(resolvedClient(), args);
                }

                private AmazonS3 resolvedClient() {
                    if (_resolvedClient == null) {
                        String endPoint = determineEndpointForBucket(bucket, credentialsProvider, s3Config, stashRoot.getPath());
                        _resolvedClient = createS3ClientForEndpoint(endPoint, credentialsProvider, s3Config);
                    }
                    return _resolvedClient;
                }
            }));
}
 
Example #27
Source File: DemoAppCachedInfo.java    From amazon-kinesis-video-streams-producer-sdk-java with Apache License 2.0 6 votes vote down vote up
private static void addCachedStreamInfoWithCredentialsProvider(CachedInfoMultiAuthServiceCallbacksImpl serviceCallbacks,
                                                               String streamName,
                                                               AWSCredentialsProvider credentialsProvider,
                                                               String region) {
    // Set up credentials provider for the stream name
    serviceCallbacks.addCredentialsProviderToCache(streamName, credentialsProvider);

    // Set up stream info for the stream name
    AmazonKinesisVideo kvsClient = AmazonKinesisVideoClientBuilder.standard()
            .withRegion(region)
            .withCredentials(credentialsProvider)
            .build();
    DescribeStreamResult streamInfo = kvsClient.describeStream(new DescribeStreamRequest().withStreamName(streamName));
    serviceCallbacks.addStreamInfoToCache(streamName, streamInfo);

    // Set up endpoint for the stream name
    GetDataEndpointResult dataEndpoint =
            kvsClient.getDataEndpoint(new GetDataEndpointRequest().withAPIName(APIName.PUT_MEDIA).withStreamName(streamName));
    serviceCallbacks.addStreamingEndpointToCache(streamName, dataEndpoint.getDataEndpoint());
}
 
Example #28
Source File: SQSFactoryImpl.java    From aws-codecommit-trigger-plugin with Apache License 2.0 6 votes vote down vote up
private AmazonSQSAsyncClientBuilder createStandardAsyncClientBuilder(SQSQueue queue, AWSCredentialsProvider credentials) {
    ClientConfiguration clientConfiguration = this.getClientConfiguration(queue);
    AmazonSQSAsyncClientBuilder builder = AmazonSQSAsyncClientBuilder.standard()
        .withClientConfiguration(clientConfiguration)
        .withCredentials(credentials)
        .withExecutorFactory(this.SQSExecutorFactory);

    if (queue != null) {
        Regions region = queue.getRegion();
        if (region != null) {
            builder.withRegion(region);
        }
    }

    return builder;
}
 
Example #29
Source File: GroupModel.java    From strongbox with Apache License 2.0 6 votes vote down vote up
public GroupModel(String rawProfileIdentifier, String explicitAssumeRole, String region, boolean useAES256, String outputFormat, String fieldName, String saveToFilePath) {
    this.outputFormat = extractOutput(outputFormat);
    this.fieldName = extractFieldName(this.outputFormat, fieldName);
    this.saveToFilePath = extractSaveToFilePath(saveToFilePath);

    ProfileIdentifier profileIdentifier = ProfileResolver.resolveProfile(Optional.ofNullable(rawProfileIdentifier));
    this.region = resolveRegion(region, profileIdentifier);
    RegionResolver.setRegion(this.region);

    ClientConfiguration clientConfiguration = getClientConfiguration();
    AWSCredentialsProvider baseCredentials = resolveBaseCredentials(clientConfiguration, profileIdentifier);
    AWSCredentialsProvider credentials = resolveExplicitAssumeRole(baseCredentials, clientConfiguration, explicitAssumeRole);

    UserConfig userConfig = getUserConfig();
    EncryptionStrength encryptionStrength = useAES256 ? EncryptionStrength.AES_256 : EncryptionStrength.AES_128;

    this.randomGenerator = new KMSRandomGenerator(credentials, clientConfiguration);
    this.principalAutoSuggestion = PrincipalAutoSuggestion.fromCredentials(credentials, clientConfiguration);

    this.secretsGroupManager = new DefaultSecretsGroupManager(credentials, userConfig, encryptionStrength, clientConfiguration);
}
 
Example #30
Source File: AbstractAWSGatewayApiProcessor.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
protected GenericApiGatewayClient createClient(ProcessContext context,
                                               AWSCredentialsProvider awsCredentialsProvider,
                                               ClientConfiguration clientConfiguration) {

    GenericApiGatewayClientBuilder builder = new GenericApiGatewayClientBuilder()
        .withCredentials(awsCredentialsProvider).withClientConfiguration(clientConfiguration)
        .withEndpoint(context.getProperty(PROP_AWS_GATEWAY_API_ENDPOINT).getValue()).withRegion(
            Region.getRegion(
                Regions.fromName(context.getProperty(PROP_AWS_GATEWAY_API_REGION).getValue())));
    if (context.getProperty(PROP_AWS_API_KEY).isSet()) {
        builder = builder.withApiKey(context.getProperty(PROP_AWS_API_KEY).evaluateAttributeExpressions().getValue());
    }
    if (providedClient != null) {
        builder = builder.withHttpClient(providedClient);
    }
    return builder.build();
}