private AmazonIdentityManagement client() { return AmazonIdentityManagementClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(new AWSCredentials() { @Override public String getAWSAccessKeyId() { return bookmark.getCredentials().getUsername(); } @Override public String getAWSSecretKey() { return bookmark.getCredentials().getPassword(); } })) .withClientConfiguration(configuration) .withRegion(Regions.DEFAULT_REGION).build(); }
@Override public Credentials get() { if (getIdentity() == null || getIdentity().trim().isEmpty() || getCredential() == null || getCredential().trim().isEmpty()) { DefaultAWSCredentialsProviderChain chain = new DefaultAWSCredentialsProviderChain(); AWSCredentials cred = chain.getCredentials(); if (cred instanceof BasicSessionCredentials) { BasicSessionCredentials sesCred = (BasicSessionCredentials)cred; return new SessionCredentials.Builder() .identity(sesCred.getAWSAccessKeyId()) .credential(sesCred.getAWSSecretKey()) .sessionToken(sesCred.getSessionToken()) .build(); } else { return new Credentials.Builder<>() .identity(cred.getAWSAccessKeyId()) .credential(cred.getAWSSecretKey()) .build(); } } return super.get(); }
@Test public void testAWSCredentials() throws Exception { // Ask for connection AmazonEC2 client = ec2comm.getEC2(); assertNotNull(client); assertNotNull(credProvider); AWSCredentials credentials = credProvider.getCredentials(); assertEquals("access_key", credentials.getAWSAccessKeyId()); assertEquals("secret_key", credentials.getAWSSecretKey()); credProvider.refresh(); credentials = credProvider.getCredentials(); assertEquals("access_key", credentials.getAWSAccessKeyId()); assertEquals("secret_key", credentials.getAWSSecretKey()); }
@Override public Credentials configure(final Host host) { final Credentials credentials = host.getCredentials(); // Only for AWS if(host.getHostname().endsWith(PreferencesFactory.get().getProperty("s3.hostname.default"))) { if(!credentials.validate(host.getProtocol(), new LoginOptions(host.getProtocol()).password(false))) { // Lookup from default profile if no access key is set in bookmark for(AWSCredentialsProvider provider : providers) { try { final AWSCredentials c = provider.getCredentials(); credentials.setUsername(c.getAWSAccessKeyId()); credentials.setPassword(c.getAWSSecretKey()); break; } catch(SdkClientException e) { log.debug(String.format("Ignore failure loading credentials from provider %s", provider)); // Continue searching with next provider } } } } return credentials; }
@Test public void shouldHaveAwsCredentialsIntanceWhenEndpointUrlIsNotProvidedAndProfileIsProvided() { ReflectionTestUtils.setField(config, "ENDPOINT_URL", ""); ReflectionTestUtils.setField(config, "PROFILE", "default"); Assert.isInstanceOf(AWSCredentials.class, config.awsCredentials(new StubProfileCredentialsProvider())); }
private void start() throws IOException { //this.port = findFreeLocalPort(); @see https://github.com/findify/sqsmock/pull/7 this.api = new SQSService(this.port, 1); this.api.start(); AWSCredentials credentials = new AnonymousAWSCredentials(); this.sqsClient = new MockSQSClient(credentials); this.endpoint = String.format("http://localhost:%s", this.port); this.sqsClient.setEndpoint(endpoint); this.sqsUrl = this.sqsClient.createQueue(this.getClass().getSimpleName()).getQueueUrl(); ((MockSQSClient)this.sqsClient).setQueueUrl(this.sqsUrl); this.started = true; }
@Test public void testEnvironmentVariable() throws Exception { Map<String, String> immutableEnv = System.getenv(); Class<?> unMap = Class.forName("java.util.Collections$UnmodifiableMap"); Field m = unMap.getDeclaredField("m"); m.setAccessible(true); @SuppressWarnings("unchecked") Map<String, String> env = (Map<String, String>) m.get(immutableEnv); try { env.put(AwsProfileNameLoader.AWS_PROFILE_ENVIRONMENT_VARIABLE, "test"); ProfileCredentialsProvider provider = newProvider(); AWSCredentials credentials = provider.getCredentials(); Assert.assertEquals("test", credentials.getAWSAccessKeyId()); Assert.assertEquals("test key", credentials.getAWSSecretKey()); } finally { env.remove(AwsProfileNameLoader.AWS_PROFILE_ENVIRONMENT_VARIABLE); } }
private static void assertEqualCredentials(AWSCredentials expected, AWSCredentials actual) { assertEquals(expected.getAWSAccessKeyId(), actual.getAWSAccessKeyId()); assertEquals(expected.getAWSAccessKeyId(), actual.getAWSAccessKeyId()); if (expected instanceof AWSSessionCredentials) { assertTrue(actual instanceof AWSSessionCredentials); AWSSessionCredentials expectedSession = (AWSSessionCredentials)expected; AWSSessionCredentials actualSession = (AWSSessionCredentials)actual; assertEquals(expectedSession.getSessionToken(), actualSession.getSessionToken()); } else { assertFalse(actual instanceof AWSSessionCredentials); } }
/** * Tests two profiles having same name. The second profile overrides the first profile. Also * checks if the AWS Access Key ID and AWS Secret Access Key are mapped properly under the * profile. */ @Test public void testTwoProfileWithSameName() throws URISyntaxException { ProfilesConfigFile profile = new ProfilesConfigFile( ProfileResourceLoader.profilesWithSameProfileName().asFile()); AWSCredentials defaultCred = profile.getCredentials(DEFAULT_PROFILE_NAME); assertNotNull(defaultCred); assertTrue(defaultCred instanceof BasicAWSCredentials); AWSCredentials testCred = profile.getCredentials(PROFILE_NAME_TEST); assertNotNull(testCred); assertTrue(testCred instanceof AWSSessionCredentials); AWSSessionCredentials testSessionCred = (AWSSessionCredentials) testCred; assertEquals(testSessionCred.getAWSAccessKeyId(), "testProfile2"); assertEquals(testSessionCred.getAWSSecretKey(), "testProfile2"); assertEquals(testSessionCred.getSessionToken(), "testProfile2"); }
private static void verifyBaseAfterCopy(final ProgressListener listener, final AWSCredentials credentials, final RequestMetricCollector collector, final AmazonWebServiceRequest from, final AmazonWebServiceRequest to) { RequestClientOptions toOptions; Map<String, String> headers = to.getCustomRequestHeaders(); assertTrue(2 == headers.size()); assertEquals("v1", headers.get("k1")); assertEquals("v2", headers.get("k2")); Map<String, List<String>> parmas = to.getCustomQueryParameters(); assertTrue(2 == parmas.size()); assertEquals(Arrays.asList("v1"), parmas.get("k1")); assertEquals(Arrays.asList("v2a", "v2b"), parmas.get("k2")); assertSame(listener, to.getGeneralProgressListener()); assertSame(credentials, to.getRequestCredentials()); assertSame(collector, to.getRequestMetricCollector()); assertTrue(1234 == to.getReadLimit()); toOptions = to.getRequestClientOptions(); assertEquals( from.getRequestClientOptions().getClientMarker( Marker.USER_AGENT), toOptions.getClientMarker(Marker.USER_AGENT)); assertTrue(1234 == toOptions.getReadLimit()); }
@Test public void request_credentials_takes_precendence_over_client_credentials() { final String awsAccessKeyId = "foo"; final String awsSecretAccessKey = "bar"; final AWSCredentials reqCredentials = new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey); EmptyAmazonWebServiceRequest req = new EmptyAmazonWebServiceRequest(); req.setRequestCredentials(reqCredentials); AWSCredentialsProvider actual = CredentialUtils.getCredentialsProvider(req, null); Assert.assertThat(actual, Matchers.instanceOf(StaticCredentialsProvider .class)); assertEquals(awsAccessKeyId, actual.getCredentials().getAWSAccessKeyId()); assertEquals(awsSecretAccessKey, actual.getCredentials().getAWSSecretKey()); }
public void sign(SignableRequest<?> request, AWSCredentials credentials) throws SdkClientException { AWSCredentials sanitizedCredentials = sanitizeCredentials(credentials); if ( sanitizedCredentials instanceof AWSSessionCredentials ) { addSessionCredentials(request, (AWSSessionCredentials) sanitizedCredentials); } String expirationInSeconds = Long.toString(expiration.getTime() / 1000L); String canonicalString = RestUtils.makeS3CanonicalString( httpVerb, resourcePath, request, expirationInSeconds); String signature = super.signAndBase64Encode(canonicalString, sanitizedCredentials.getAWSSecretKey(), SigningAlgorithm.HmacSHA1); request.addParameter("AWSAccessKeyId", sanitizedCredentials.getAWSAccessKeyId()); request.addParameter("Expires", expirationInSeconds); request.addParameter("Signature", signature); }
protected void launchAWSCredentialsWithElasticsearchSettingsTest(Settings singleRepositorySettings, Settings settings, String expectedKey, String expectedSecret) { String configName = InternalAwsS3Service.CLIENT_NAME.get(singleRepositorySettings); AWSCredentials credentials = InternalAwsS3Service.buildCredentials(logger, deprecationLogger, settings, singleRepositorySettings, configName).getCredentials(); assertThat(credentials.getAWSAccessKeyId(), is(expectedKey)); assertThat(credentials.getAWSSecretKey(), is(expectedSecret)); }
public AmazonEC2HostProvider(final AWSCredentials credentials, final ClientConfiguration configuration, String endpoint, Function<Instance, Host> instance_converter) { this.instance_converter = instance_converter; ec2_client = new AmazonEC2Client(credentials, configuration); ec2_client.setEndpoint(endpoint); next_host_index = new AtomicInteger(); }
public S3Utils() { accountsDirectory = AccountsDirectory.getInstance(); final Account s3Account = accountsDirectory.getAccount("s3").get(); final AWSCredentials credentials = new BasicAWSCredentials( s3Account.getProperty("accessKey"), s3Account.getProperty("secretKey") ); s3client = AmazonS3ClientBuilder .standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .withRegion(Regions.US_WEST_1) .build(); }
protected static AmazonS3 createS3(String accessKey, String secretKey) { AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); ClientConfiguration clientConfig = new ClientConfiguration(); clientConfig.setProtocol(Protocol.HTTP); clientConfig.withSignerOverride("S3SignerType"); //noinspection deprecation AmazonS3 s3 = new AmazonS3Client(credentials, clientConfig); s3.setEndpoint(s3Endpoint); return s3; }
/** * Constructor * * @param ph */ public EC2Communication(PropertyHandler ph) { this.ph = ph; final String secretKey = ph.getSecretKey(); final String accessKeyId = ph.getAccessKeyId(); credentialsProvider = new AWSCredentialsProvider() { @Override public void refresh() { } @Override public AWSCredentials getCredentials() { return new AWSCredentials() { @Override public String getAWSSecretKey() { return secretKey; } @Override public String getAWSAccessKeyId() { return accessKeyId; } }; } }; }
@Test public void credentials() throws IOException { when(conf.getPassword("access.key")).thenReturn("accessKey".toCharArray()); when(conf.getPassword("secret.key")).thenReturn("secretKey".toCharArray()); AWSCredentialsProvider credentialsProvider = configuration.awsCredentialsProvider(conf); AWSCredentials awsCredentials = credentialsProvider.getCredentials(); assertThat(awsCredentials.getAWSAccessKeyId(), is("accessKey")); assertThat(awsCredentials.getAWSSecretKey(), is("secretKey")); }
@Override public AWSCredentials getCredentials() { if (credentials == null) { refresh(); } return credentials; }
@Test public void credentialsFromFile() throws IOException { String jceksPath = "jceks://file" + dataFolder.getFile("aws.jceks").getAbsolutePath(); JceksAWSCredentialProvider provider = new JceksAWSCredentialProvider(jceksPath); AWSCredentials credentials = provider.getCredentials(); assertThat(credentials.getAWSAccessKeyId(), is("access")); assertThat(credentials.getAWSSecretKey(), is("secret")); }
@Test public void credentialsFromConf() throws IOException { when(conf.getPassword(AWSConstants.ACCESS_KEY)).thenReturn("accessKey".toCharArray()); when(conf.getPassword(AWSConstants.SECRET_KEY)).thenReturn("secretKey".toCharArray()); JceksAWSCredentialProvider provider = new JceksAWSCredentialProvider(conf); AWSCredentials credentials = provider.getCredentials(); assertThat(credentials.getAWSAccessKeyId(), is("accessKey")); assertThat(credentials.getAWSSecretKey(), is("secretKey")); }
public static AmazonSQS createSqsClient(AWSCredentials credentials, ClientConfiguration cc, Regions region) { return AmazonSQSClientBuilder // .standard() // .withCredentials(new AWSStaticCredentialsProvider(credentials)) // .withRegion(region) // .build(); }
public static AmazonS3 createS3Client(AWSCredentials credentials, ClientConfiguration cc, Regions region) { return AmazonS3ClientBuilder // .standard() // .withCredentials(new AWSStaticCredentialsProvider(credentials)) // .withRegion(region) // .build(); }
@Test public void tests3() { AwsClients.createS3Client(new AWSCredentials() { @Override public String getAWSSecretKey() { return "a"; } @Override public String getAWSAccessKeyId() { return "b"; } }, new ClientConfiguration(), Regions.AP_SOUTHEAST_2); }
@Test public void testSqs() { AwsClients.createSqsClient(new AWSCredentials() { @Override public String getAWSSecretKey() { return "a"; } @Override public String getAWSAccessKeyId() { return "b"; } }, new ClientConfiguration(), Regions.AP_SOUTHEAST_2); }
@Override public Request toHttpRequest(AWSCredentials credentials) { URI fullUri = URI.create(requestUrl); URI endpoint = URI.create(fullUri.getScheme() + SCHEME_SEPERATOR + fullUri.getHost()); awsHttpRequest = marshaller.marshall(request); awsHttpRequest.setEndpoint(endpoint); awsHttpRequest.setResourcePath(fullUri.getPath()); requestSigner.setServiceName(SHORT_SERVICE_NAME); requestSigner.sign(awsHttpRequest, credentials); return requestConverter.apply(awsHttpRequest); }
@Before public void setup() { EndpointConfiguration endpoint = new EndpointConfiguration(UNIT_STACK_URL + ":" + SNS_PORT, Region.EU_Frankfurt.name()); AWSCredentials credentials = new BasicAWSCredentials("key", "secret"); AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials); sns = AmazonSNSAsyncClientBuilder.standard().withEndpointConfiguration(endpoint) .withCredentials(credentialsProvider).build(); }
@Before public void setup() { MockParameters params = new MockParameters(); params.setMockRegion("EU"); mockS3(params); EndpointConfiguration endpoint = new EndpointConfiguration(UNIT_STACK_URL + ":" + S3_PORT, Region.EU_Frankfurt.name()); AWSCredentials credentials = new BasicAWSCredentials("key", "secret"); AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials); s3 = AmazonS3ClientBuilder.standard().withEndpointConfiguration(endpoint) .withCredentials(credentialsProvider).build(); }
@Before public void setup() { mockSqs(null); EndpointConfiguration endpoint = new EndpointConfiguration(UNIT_STACK_URL + ":" + SQS_PORT, "eu-central-1"); AWSCredentials credentials = new BasicAWSCredentials("key", "secret"); AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials); sqs = AmazonSQSAsyncClientBuilder.standard().withEndpointConfiguration(endpoint) .withCredentials(credentialsProvider).build(); }
@Bean @DependsOn("awsCredentials") public AmazonDynamoDB amazonDynamoDBClient(AWSCredentials awsCredentials) { AmazonDynamoDBClient awsClient = new AmazonDynamoDBClient(awsCredentials); if (!ENDPOINT_URL.isEmpty()) { LOGGER.info("END POINT " + ENDPOINT_URL); awsClient.setEndpoint(ENDPOINT_URL); awsClient.setSignerRegionOverride("local"); } return awsClient; }
@Test public void shouldHaveAwsCredentialsIntanceWhenEndpointUrlIsNotProvided() { ReflectionTestUtils.setField(config, "ENDPOINT_URL", ""); ReflectionTestUtils.setField(config, "PROFILE", ""); Assert.isInstanceOf(AWSCredentials.class, config.awsCredentials(new StubProfileCredentialsProvider())); }
public static String getOwnIP() { AWSCredentials credentials = null; try { credentials = new ProfileCredentialsProvider().getCredentials(); } catch(Exception e){} AmazonEC2 ec2 = new AmazonEC2Client(credentials); ec2.setEndpoint("ec2.eu-west-1.amazonaws.com"); DescribeInstancesResult describeInstancesResult = ec2.describeInstances(); List<Reservation> reservations = describeInstancesResult.getReservations(); ArrayList<Instance> listOfInstances = new ArrayList<Instance>(); for(Reservation reservation : reservations) listOfInstances.addAll(reservation.getInstances()); String ownIP = null; String ownInstanceID = checkInstanceId(); for(Instance instance: listOfInstances) { if(instance.getInstanceId().equals(ownInstanceID)) ownIP = instance.getPublicIpAddress(); } return ownIP; }
public S3Publisher(AWSCredentials credentials, String bucketName, String blobNamespace) { this.s3 = new AmazonS3Client(credentials); this.s3TransferManager = new TransferManager(s3); this.bucketName = bucketName; this.blobNamespace = blobNamespace; this.snapshotIndex = initializeSnapshotIndex(); }
/** * Constructs an AmazonRDSClient and sets the region. */ public AmazonRDSClient makeRegionalRdsClient() { AWSCredentials credentials = new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey); AmazonRDSClient rds = new AmazonRDSClient(credentials); rds.setRegion(awsRegion); return rds; }
public S3AnnouncementWatcher(AWSCredentials credentials, String bucketName, String blobNamespace) { this.s3 = new AmazonS3Client(credentials); this.bucketName = bucketName; this.blobNamespace = blobNamespace; this.subscribedConsumers = Collections.synchronizedList(new ArrayList<HollowConsumer>()); this.latestVersion = readLatestVersion(); setupPollingThread(); }
S3LoggerBase(AWSCredentials credentials, String bucketName) { _logger.debug("entering"); if(bucketName == null) throw new NullPointerException("bucketName may not be null"); if(bucketName.trim().length() == 0) throw new IllegalArgumentException("bucketName must have at least one non-whitespace character"); _credentials = credentials; _bucketName = bucketName; _logger.debug("exiting"); }
public AWSCredentials getCredentials() { if (!StringUtils.isEmpty(accessKey) && !StringUtils.isEmpty(secretKey)) { return new BasicAWSCredentials(accessKey, secretKey); } throw new AmazonClientException( "Access key or secret key is null"); }
private AWSCredentials getCredentialsFromProfile(final ProfileIdentifier profile) { ConfigProviderChain configProvider = new ConfigProviderChain(); if (!configProvider.hasConfig()) { throw new IllegalStateException("When using '--profile', an AWS credentials or config file must be present"); } Optional<RoleARN> roleToAssume = configProvider.getRoleArn(profile); if (roleToAssume.isPresent()) { return assumeRole(clientConfiguration, configProvider, profile, roleToAssume.get()); } else { return getStaticCredentials(configProvider, profile); } }
private void runBeforeRequestHandlers() { AWSCredentials credentials = getCredentialsFromContext(); request.addHandlerContext(HandlerContextKey.AWS_CREDENTIALS, credentials); // Apply any additional service specific request handlers that need to be run for (RequestHandler2 requestHandler2 : requestHandler2s) { // If the request handler is a type of CredentialsRequestHandler, then set the credentials in the request handler. if (requestHandler2 instanceof CredentialsRequestHandler) { ((CredentialsRequestHandler) requestHandler2).setCredentials(credentials); } requestHandler2.beforeRequest(request); } }
/** * Returns the credentials from the execution if exists. Else returns null. */ private AWSCredentials getCredentialsFromContext() { final AWSCredentialsProvider credentialsProvider = executionContext.getCredentialsProvider(); AWSCredentials credentials = null; if (credentialsProvider != null) { awsRequestMetrics.startEvent(Field.CredentialsRequestTime); try { credentials = credentialsProvider.getCredentials(); } finally { awsRequestMetrics.endEvent(Field.CredentialsRequestTime); } } return credentials; }