public static AWSCredentialsProvider buildCredentials(Logger logger, DeprecationLogger deprecationLogger, Settings settings, Settings repositorySettings, String clientName) { try (SecureString key = getConfigValue(repositorySettings, settings, clientName, S3Repository.ACCESS_KEY_SETTING, S3Repository.Repository.KEY_SETTING, S3Repository.Repositories.KEY_SETTING); SecureString secret = getConfigValue(repositorySettings, settings, clientName, S3Repository.SECRET_KEY_SETTING, S3Repository.Repository.SECRET_SETTING, S3Repository.Repositories.SECRET_SETTING)) { if (key.length() == 0 && secret.length() == 0) { logger.debug("Using instance profile credentials"); return new PrivilegedInstanceProfileCredentialsProvider(); } else { logger.debug("Using basic key/secret credentials"); return new StaticCredentialsProvider(new BasicAWSCredentials(key.toString(), secret.toString())); } } }
@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()); }
@Test public void testProvide() { Env env = new Env().register("DYNAMODB_ENDPOINT", "fakeendpoint"); ClientConfiguration config = new ClientConfiguration(); config.setRetryPolicy(PredefinedRetryPolicies.NO_RETRY_POLICY); AWSCredentialsProvider credentialsProvider = new StaticCredentialsProvider( new BasicAWSCredentials("fake_access_key_id", "fake_secret_access_key")); AmazonDynamoDBFactory factory = new AmazonDynamoDBFactory(env, credentialsProvider, config); AmazonDynamoDB dynamoDB = factory.provide(); String message = ""; try { dynamoDB.listTables(); } catch (AmazonClientException e) { message = e.getMessage(); } assertTrue(message.startsWith("Unable to execute HTTP request: fakeendpoint")); factory.dispose(dynamoDB); }
/** * <p> Gets the {@link AWSCredentialsProvider} based on the credentials in the given parameters. </p> <p> Returns {@link DefaultAWSCredentialsProviderChain} * if either access or secret key is {@code null}. Otherwise returns a {@link StaticCredentialsProvider} with the credentials. </p> * * @param params - Access parameters * * @return AWS credentials provider implementation */ private AWSCredentialsProvider getAWSCredentialsProvider(S3FileTransferRequestParamsDto params) { List<AWSCredentialsProvider> providers = new ArrayList<>(); String accessKey = params.getAwsAccessKeyId(); String secretKey = params.getAwsSecretKey(); if (accessKey != null && secretKey != null) { providers.add(new StaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey))); } for (HerdAWSCredentialsProvider herdAWSCredentialsProvider : params.getAdditionalAwsCredentialsProviders()) { providers.add(new HerdAwsCredentialsProviderWrapper(herdAWSCredentialsProvider)); } providers.add(new DefaultAWSCredentialsProviderChain()); return new AWSCredentialsProviderChain(providers.toArray(new AWSCredentialsProvider[providers.size()])); }
private AmazonDynamoDBClient getDynamoClient(String tableName) { AWSCredentialsProvider credentials = new AWSCredentialsProviderChain(new StaticCredentialsProvider(new BasicAWSCredentials("test", "test"))); AmazonDynamoDBClient amazonDynamoDBClient = new AmazonDynamoDBClient(credentials); amazonDynamoDBClient.setEndpoint("http://localhost:8000"); ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput() .withReadCapacityUnits(5L) .withWriteCapacityUnits(10L); CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName).withProvisionedThroughput(provisionedThroughput); ArrayList<AttributeDefinition> attributeDefinitions= new ArrayList<AttributeDefinition>(); attributeDefinitions.add(new AttributeDefinition().withAttributeName("id").withAttributeType("S")); createTableRequest.setAttributeDefinitions(attributeDefinitions); ArrayList<KeySchemaElement> tableKeySchema = new ArrayList<KeySchemaElement>(); tableKeySchema.add(new KeySchemaElement().withAttributeName("id").withKeyType(KeyType.HASH)); createTableRequest.setKeySchema(tableKeySchema); amazonDynamoDBClient.createTable(createTableRequest); return amazonDynamoDBClient; }
static <T extends AmazonWebServiceClient> T createClient( Class<T> clientType, Identity identity ) { Regions r = Regions.US_EAST_1; if ( StringUtils.isNotBlank( identity.getAwsRegionName() ) ) { r = Regions.fromName( identity.getAwsRegionName() ); } AWSCredentialsProvider creds = new StaticCredentialsProvider( new BasicAWSCredentials( identity.getAwsAccessKeyId(), identity.getAwsSecretKey() ) ); return Region.getRegion( r ).createClient( clientType, creds, null ); }
@Deprecated public Map<String, Profile> getAllProfiles() { Map<String, Profile> legacyProfiles = new HashMap<String, Profile>(); for (Map.Entry<String, BasicProfile> entry : getAllBasicProfiles().entrySet()) { final String profileName = entry.getKey(); legacyProfiles.put(profileName, new Profile(profileName, entry.getValue().getProperties(), new StaticCredentialsProvider( getCredentials(profileName)))); } return legacyProfiles; }
public Profile(String profileName, AWSCredentials awsCredentials) { Map<String, String> properties = new LinkedHashMap<String, String>(); properties.put(ProfileKeyConstants.AWS_ACCESS_KEY_ID, awsCredentials.getAWSAccessKeyId()); properties.put(ProfileKeyConstants.AWS_SECRET_ACCESS_KEY, awsCredentials.getAWSSecretKey()); if (awsCredentials instanceof AWSSessionCredentials) { AWSSessionCredentials sessionCred = (AWSSessionCredentials)awsCredentials; properties.put(ProfileKeyConstants.AWS_SESSION_TOKEN, sessionCred.getSessionToken()); } this.profileName = profileName; this.properties = properties; this.awsCredentials = new StaticCredentialsProvider(awsCredentials); }
@Test public void credentialsExplicitlySet_UsesExplicitCredentials() throws Exception { AWSCredentialsProvider provider = new StaticCredentialsProvider( new BasicAWSCredentials("akid", "skid")); AwsAsyncClientParams params = builderWithRegion().withCredentials(provider).build() .getAsyncParams(); assertEquals(provider, params.getCredentialsProvider()); }
@Test public void base_credentials_returned_when_no_request_credentials_is_present() { final String awsAccessKeyId = "foo"; final String awsSecretAccessKey = "bar"; final StaticCredentialsProvider base = new StaticCredentialsProvider (new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey)); AWSCredentialsProvider actual = CredentialUtils .getCredentialsProvider((AmazonWebServiceRequest) null, base); Assert.assertThat(actual, Matchers.instanceOf(StaticCredentialsProvider .class)); assertEquals(awsAccessKeyId, actual.getCredentials().getAWSAccessKeyId()); assertEquals(awsSecretAccessKey, actual.getCredentials().getAWSSecretKey()); }
/** * @deprecated use {@link AmazonS3EncryptionClientBuilder#withEncryptionMaterials(EncryptionMaterialsProvider)} and * {@link AmazonS3EncryptionClientBuilder#withCredentials(AWSCredentialsProvider)} and * {@link AmazonS3EncryptionClientBuilder#withCryptoConfiguration(CryptoConfiguration)} and * {@link AmazonS3EncryptionClientBuilder#withClientConfiguration(ClientConfiguration)} */ @Deprecated public AmazonS3EncryptionClient(AWSCredentials credentials, EncryptionMaterialsProvider encryptionMaterialsProvider, ClientConfiguration clientConfig, CryptoConfiguration cryptoConfig) { this(new StaticCredentialsProvider(credentials), encryptionMaterialsProvider, clientConfig, cryptoConfig); }
@Override public Connection createConnection() throws JMSException { Builder builder = SQSConnectionFactory.builder().withAWSCredentialsProvider(new StaticCredentialsProvider(new BasicAWSCredentials(this.accessKey,this.secretKey))); if (this.regionName != null && ! this.regionName.isEmpty()) { builder = builder.withRegionName(regionName); } this.factory = builder.build(); return factory.createConnection(); }
/** * * @return */ private AWSCredentialsProvider getCredentials() { return new AWSCredentialsProviderChain(new StaticCredentialsProvider( new AppenderCredentials()), new SystemPropertiesCredentialsProvider(), new EnvironmentVariableCredentialsProvider(), new ProfileCredentialsProvider(), new InstanceProfileCredentialsProvider()); }
private AWSCredentialsProvider getAwsCredentialsProvider(URI uri, Configuration conf) { Optional<AWSCredentials> credentials = getAwsCredentials(uri, conf); if (credentials.isPresent()) { return new StaticCredentialsProvider(credentials.get()); } if (useInstanceCredentials) { return new InstanceProfileCredentialsProvider(); } throw new RuntimeException("S3 credentials not configured"); }
@Test public void testStaticCredentials() throws Exception { Configuration config = new Configuration(); config.set(PrestoS3FileSystem.S3_ACCESS_KEY, "test_secret_access_key"); config.set(PrestoS3FileSystem.S3_SECRET_KEY, "test_access_key_id"); // the static credentials should be preferred try (PrestoS3FileSystem fs = new PrestoS3FileSystem()) { fs.initialize(new URI("s3n://test-bucket/"), config); assertInstanceOf(getAwsCredentialsProvider(fs), StaticCredentialsProvider.class); } }
public static AWSCredentialsProvider createCredentialsProvider( final boolean useInstanceProfileForCredentials, final String accessId, final Secret secretKey) { if (useInstanceProfileForCredentials) { return new InstanceProfileCredentialsProvider(); } BasicAWSCredentials credentials = new BasicAWSCredentials(accessId, Secret.toString(secretKey)); return new StaticCredentialsProvider(credentials); }
@Before public final void before() throws URISyntaxException { Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); calendar.set(2011, 8, 9, 23, 36, 00); currentDate = calendar.getTime(); uri = new URI(TEST_ENDPOINT); AWSCredentialsProviderChain awsCredentialsProvider = new AWSCredentialsProviderChain( new StaticCredentialsProvider(new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_KEY))); testObject = new V4RequestSigner(awsCredentialsProvider, REGION_NAME, SERVICE_NAME, currentDate); }
@Test public final void addsSessionTokenHeaderWhenSessionCredentialsAreProvided() { String sessionToken = "sessionToken"; StaticCredentialsProvider credentialsProvider = new StaticCredentialsProvider(new BasicSessionCredentials("accessKey", "secretKey", sessionToken)); testObject = new V4RequestSigner(credentialsProvider, REGION_NAME, SERVICE_NAME, currentDate); HttpPost request = createTestRequest(); testObject.signRequest(request); Header[] tokenHeaders = request.getHeaders(SESSION_TOKEN_HEADER); assertEquals(1, tokenHeaders.length); assertEquals(SESSION_TOKEN_HEADER, tokenHeaders[0].getName()); assertEquals(sessionToken, tokenHeaders[0].getValue()); }
private static AmazonS3ClientBuilder configureTokenAuthentication(Environment environment, AmazonS3ClientBuilder builder) { LOGGER.info("Using Token authentication"); final String key = environment.getProperty("content-service.store.s3.accessKey"); final String secret = environment.getProperty("content-service.store.s3.secretKey"); AWSCredentials awsCredentials = new BasicAWSCredentials(key, secret); return builder.withCredentials(new StaticCredentialsProvider(awsCredentials)); }
private AWSCredentialsProvider getCredentialsProvider() { if (StringUtils.isNullOrEmpty(awsAccessKey) || StringUtils.isNullOrEmpty(awsSecretKey)) { return new InstanceProfileCredentialsProvider(); } return new StaticCredentialsProvider(new BasicAWSCredentials(awsAccessKey, awsSecretKey)); }
@Test public void testCoverage() { AWSCredentials creds = new BasicAWSCredentials("key", "secret"); CloudWatchMetricsPersister persister = new CloudWatchMetricsPersister(creds, "app", true); StaticCredentialsProvider credProv = new StaticCredentialsProvider(creds); persister = new CloudWatchMetricsPersister(new AWSCredentialsProviderChain(credProv), "app", true); persister = new CloudWatchMetricsPersister(); persister.setAwsCredentials(creds); persister.setAwsCredentialsProvider(credProv); }
public AWSCredentialsProvider getCredentials() { // TODO: add an extra option the allow these values to be NULL. if (accessKey == null || secretAccessKey == null) { return new DefaultAWSCredentialsProviderChain(); } return new StaticCredentialsProvider(new BasicAWSCredentials(getAccessKey(), getSecretAccessKey())); }
public AWSCredentialsProvider getCredentials(AWSCredentials credentials) { return new AWSCredentialsProviderChain( new EnvironmentVariableCredentialsProvider(), new SystemPropertiesCredentialsProvider(), new StaticCredentialsProvider(credentials == null ? new NullCredentials() : credentials), new ProfileCredentialsProvider(), new InstanceProfileCredentialsProvider() ); }
@Test public void testStartTwoServers() throws Exception { S3Server instanceA = null; S3Server instanceB = null; AmazonS3Client client = null; try { instanceA = S3Server.createHttpServer(); instanceB = S3Server.createHttpServer(); instanceA.start(); instanceB.start(); client = new AmazonS3Client(new StaticCredentialsProvider(new AnonymousAWSCredentials())); client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true)); client.setEndpoint(instanceA.getAddress()); BasicTestSuperclass.createDefaultBucket(client); S3Object response = client.getObject("bucketname", "asdf.txt"); String content = inputStreamToString(response.getObjectContent()); assertEquals("asdf",content); assertFalse(instanceA.getAddress().equals(instanceB.getAddress())); } finally { if (client!=null) client.shutdown(); if (instanceA!=null) instanceA.stop(); if (instanceB!=null) instanceB.stop(); } }
@Test public void testStartTwoHttpsServers() throws Exception { S3Server instanceA = null; S3Server instanceB = null; AmazonS3Client client = null; try { instanceA = S3Server.createHttpsServer( MultipleRequestTest.class.getResourceAsStream("/keystore.jks"), "password".toCharArray() ); instanceB = S3Server.createHttpsServer( MultipleRequestTest.class.getResourceAsStream("/keystore.jks"), "password".toCharArray() ); instanceA.start(); instanceB.start(); client = new AmazonS3Client(new StaticCredentialsProvider(new AnonymousAWSCredentials())); client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true)); client.setEndpoint(instanceA.getAddress()); BasicTestSuperclass.createDefaultBucket(client); S3Object response = client.getObject("bucketname", "asdf.txt"); String content = inputStreamToString(response.getObjectContent()); assertEquals("asdf",content); assertFalse(instanceA.getAddress().equals(instanceB.getAddress())); } finally { if (client!=null) client.shutdown(); if (instanceA!=null) instanceA.stop(); if (instanceB!=null) instanceB.stop(); } }
@Test public void testStartBothHttpsAndHttpServers() throws Exception { S3Server instanceA = null; S3Server instanceB = null; AmazonS3Client client = null; try { instanceA = S3Server.createHttpsServer( MultipleRequestTest.class.getResourceAsStream("/keystore.jks"), "password".toCharArray() ); instanceB = S3Server.createHttpServer(); instanceA.start(); instanceB.start(); client = new AmazonS3Client(new StaticCredentialsProvider(new AnonymousAWSCredentials())); client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true)); client.setEndpoint(instanceA.getAddress()); BasicTestSuperclass.createDefaultBucket(client); S3Object response = client.getObject("bucketname", "asdf.txt"); String content = inputStreamToString(response.getObjectContent()); assertEquals("asdf",content); assertFalse(instanceA.getAddress().equals(instanceB.getAddress())); } finally { if (client!=null) client.shutdown(); if (instanceA!=null) instanceA.stop(); if (instanceB!=null) instanceB.stop(); } }
@Before public void setUp() throws Exception { instance = S3Server.createHttpServer(); instance.start(); client = new AmazonS3Client(new StaticCredentialsProvider(new AnonymousAWSCredentials())); client.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true)); client.setEndpoint(instance.getAddress()); createDefaultBucket(client); }
public static AWSCredentialsProvider getAwsCredentials() { try { return new StaticCredentialsProvider(new PropertiesCredentials(new File(System.getProperty("user.home"), ".ec2/credentials.properties"))); } catch (IOException e) { return new DefaultAWSCredentialsProviderChain(); } }
private AWSCredentialsProvider initCredentials() { // Attempt to use any credentials specified in context.xml first if (credentialsExistInContextConfig()) { // Fail fast if credentials aren't valid as user has likely made a configuration mistake if (credentialsInContextConfigAreValid()) { throw new AmazonClientException("Incomplete AWS security credentials specified in context.xml."); } logger.debug("Using AWS access key ID and secret key from context.xml"); return new StaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)); } // Use any explicitly specified credentials properties file next if (credentialsFile != null) { try { logger.debug("Reading security credentials from properties file: " + credentialsFile); PropertiesCredentials credentials = new PropertiesCredentials(credentialsFile); logger.debug("Using AWS credentials from file: " + credentialsFile); return new StaticCredentialsProvider(credentials); } catch (Exception e) { throw new AmazonClientException( "Unable to read AWS security credentials from file specified in context.xml: " + credentialsFile, e); } } // Fall back to the default credentials chain provider if credentials weren't explicitly set AWSCredentialsProvider defaultChainProvider = new DefaultAWSCredentialsProviderChain(); if (defaultChainProvider.getCredentials() == null) { logger.debug("Loading security credentials from default credentials provider chain."); throw new AmazonClientException("Unable to find AWS security credentials. " + "Searched JVM system properties, OS env vars, and EC2 instance roles. " + "Specify credentials in Tomcat's context.xml file or put them in one of the places mentioned above."); } logger.debug("Using default AWS credentials provider chain to load credentials"); return defaultChainProvider; }
public UrlShortnerService(@Value("${AWS_ACCESS_KEY}") String awsAccessKey, @Value("${AWS_SECRET_KEY}") String awsSecretKey, @Value("${AWS_REGION}") String region) { AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey); AWSCredentialsProvider provider = new StaticCredentialsProvider(credentials); this.s3Client = AmazonS3ClientBuilder.standard().withRegion(region).withCredentials(provider).build(); }
public ProfileStaticCredentialsProvider(BasicProfile profile) { this.profile = profile; this.credentialsProvider = new StaticCredentialsProvider(fromStaticCredentials()); }
public static FixedStashReader getInstance(URI stashRoot, String accessKey, String secretKey) { return getInstance(stashRoot, new StaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey))); }
public static StandardStashReader getInstance(URI stashRoot, String accessKey, String secretKey) { return getInstance(stashRoot, new StaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)), null); }
public static StandardStashReader getInstance(URI stashRoot, String accessKey, String secretKey, ClientConfiguration s3Config) { return getInstance(stashRoot, new StaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)), s3Config); }
/** * AWSIoTサーバにログインします. * * @param accessKey アクセスキー * @param secretKey シークレットキー * @param region リージョン */ public void login(final String accessKey, final String secretKey, final Regions region, final LoginCallback callback) { if (accessKey == null || secretKey == null || region == null) { if (callback != null) { callback.onLogin(new RuntimeException("Arguments is null.")); } return; } BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); mCredentialsProvider = new StaticCredentialsProvider(credentials); mIotClient = new AWSIotClient(mCredentialsProvider); mIotClient.setRegion(Region.getRegion(region)); mIotDataClient = new AWSIotDataClient(mCredentialsProvider); new DescribeEndpointTask() { @Override protected void onPostExecute(final AsyncTaskResult<String> result) { Exception exception = null; if (result.getError() == null) { JSONObject json; try { json = new JSONObject(result.getResult()); if (json.has(END_POINT_ADDRESS)) { String endpoint = json.getString(END_POINT_ADDRESS); mAWSIotEndPoint = endpoint; mIotDataClient.setEndpoint(endpoint); for (OnAWSIotEventListener l : mOnAWSIotEventListeners) { l.onLogin(); } connectMQTT(); } else { exception = new Exception("Not found endpointAddress."); } } catch (JSONException e) { exception = e; } } else { exception = result.getError(); } callback.onLogin(exception); } }.execute(); }
/** * Test case given in AWS Signing Test Suite (http://docs.aws.amazon.com/general/latest/gr/signature-v4-test-suite.html) * (get-vanilla.*) * <p> * GET / http/1.1 * Date:Mon, 09 Sep 2011 23:36:00 GMT * Host:host.foo.com * * @throws Exception */ @Test public void testGetVanilla() throws Exception { // GIVEN // Credentials String awsAccessKey = "AKIDEXAMPLE"; String awsSecretKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"; AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey); AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider(credentials); String region = "us-east-1"; String service = "host"; // Date Supplier<LocalDateTime> clock = () -> LocalDateTime.of(2011, 9, 9, 23, 36, 0); // weird date : 09 Sep 2011 is a friday, not a monday String date = "Mon, 09 Sep 2011 23:36:00 GMT"; // HTTP request String host = "host.foo.com"; String uri = "/"; String method = "GET"; Multimap<String, String> queryParams = ImmutableListMultimap.<String, String>builder() .build(); Map<String, Object> headers = ImmutableMap.<String, Object>builder() .put("Date", date) .put("Host", host + ":80") .build(); Optional<byte[]> payload = Optional.absent(); // WHEN // The request is signed AWSSigner signer = new AWSSigner(awsCredentialsProvider, region, service, clock); Map<String, Object> signedHeaders = signer.getSignedHeaders(uri, method, queryParams, headers, payload); // THEN // The signature must match the expected signature String expectedSignature = "b27ccfbfa7df52a200ff74193ca6e32d4b48b8856fab7ebf1c595d0670a7e470"; String expectedAuthorizationHeader = format( "AWS4-HMAC-SHA256 Credential=%s/20110909/%s/%s/aws4_request, SignedHeaders=date;host, Signature=%s", awsAccessKey, region, service, expectedSignature ); TreeMap<String, Object> caseInsensitiveSignedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); caseInsensitiveSignedHeaders.putAll(signedHeaders); assertThat(caseInsensitiveSignedHeaders).containsKey("Authorization"); assertThat(caseInsensitiveSignedHeaders.get("Authorization")).isEqualTo(expectedAuthorizationHeader); assertThat(caseInsensitiveSignedHeaders).containsKey("Host"); assertThat(caseInsensitiveSignedHeaders.get("Host")).isEqualTo(host); assertThat(caseInsensitiveSignedHeaders).containsKey("Date"); assertThat(caseInsensitiveSignedHeaders.get("Date")).isEqualTo(date); assertThat(caseInsensitiveSignedHeaders).doesNotContainKey("X-Amz-Date"); }
/** * Test case given in AWS Signing Test Suite (http://docs.aws.amazon.com/general/latest/gr/signature-v4-test-suite.html) * (post-vanilla-query.*) * <p> * POST /?foo=bar http/1.1 * Date:Mon, 09 Sep 2011 23:36:00 GMT * Host:host.foo.com * * @throws Exception */ @Test public void testPostVanillaQuery() throws Exception { // GIVEN // Credentials String awsAccessKey = "AKIDEXAMPLE"; String awsSecretKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"; AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey); AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider(credentials); String region = "us-east-1"; String service = "host"; // Date Supplier<LocalDateTime> clock = () -> LocalDateTime.of(2011, 9, 9, 23, 36, 0); // weird date : 09 Sep 2011 is a friday, not a monday String date = "Mon, 09 Sep 2011 23:36:00 GMT"; // HTTP request String host = "host.foo.com"; String uri = "/"; String method = "POST"; Multimap<String, String> queryParams = ImmutableListMultimap.<String, String>builder() .put("foo", "bar") .build(); Map<String, Object> headers = ImmutableMap.<String, Object>builder() .put("Date", date) .put("Host", host) .build(); Optional<byte[]> payload = Optional.absent(); // WHEN // The request is signed AWSSigner signer = new AWSSigner(awsCredentialsProvider, region, service, clock); Map<String, Object> signedHeaders = signer.getSignedHeaders(uri, method, queryParams, headers, payload); // THEN // The signature must match the expected signature String expectedSignature = "b6e3b79003ce0743a491606ba1035a804593b0efb1e20a11cba83f8c25a57a92"; String expectedAuthorizationHeader = format( "AWS4-HMAC-SHA256 Credential=%s/20110909/%s/%s/aws4_request, SignedHeaders=date;host, Signature=%s", awsAccessKey, region, service, expectedSignature ); TreeMap<String, Object> caseInsensitiveSignedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); caseInsensitiveSignedHeaders.putAll(signedHeaders); assertThat(caseInsensitiveSignedHeaders).containsKey("Authorization"); assertThat(caseInsensitiveSignedHeaders.get("Authorization")).isEqualTo(expectedAuthorizationHeader); assertThat(caseInsensitiveSignedHeaders).containsKey("Host"); assertThat(caseInsensitiveSignedHeaders.get("Host")).isEqualTo(host); assertThat(caseInsensitiveSignedHeaders).containsKey("Date"); assertThat(caseInsensitiveSignedHeaders.get("Date")).isEqualTo(date); assertThat(caseInsensitiveSignedHeaders).doesNotContainKey("X-Amz-Date"); }
/** * Test case for signing an index request with an encodable id * * @throws Exception */ @Test public void testPostEncodedId() throws Exception { // GIVEN // Credentials String awsAccessKey = "AKIDEXAMPLE"; String awsSecretKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"; AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey); AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider(credentials); String region = "us-east-1"; String service = "service"; // Date Supplier<LocalDateTime> clock = () -> LocalDateTime.of(2015, 8, 30, 12, 36, 0); String date = "20150830T123600Z"; // HTTP request String host = "example.amazonaws.com"; String uri = "/index_name/type_name/joe%40example.com"; String method = "PUT"; Multimap<String, String> queryParams = ImmutableListMultimap.<String, String>builder() .build(); Map<String, Object> headers = ImmutableMap.<String, Object>builder() .put("X-Amz-Date", date) .put("Host", host) .build(); String body = "{\n" + " \"user\" : \"kimchy\",\n" + " \"post_date\" : \"2009-11-15T14:12:12\",\n" + " \"message\" : \"trying out Elasticsearch\"\n" + "}"; Optional<byte[]> payload = Optional.of(body.getBytes("utf-8")); String expectedAuthorizationHeader = SkdSignerUtil.getExpectedAuthorizationHeader( new SkdSignerUtil.Request() .setServiceName(service) .setRegion(region) .setDate( new SimpleDateFormat("yyyyMMdd'T'HHmmssXXX").parse(date)) .setHost(host) .setUri(uri) .setHttpMethod(method) .setHeaders(headers) .setQueryParams(queryParams) .setCredentialsProvider(awsCredentialsProvider) .setBody(body) ); // WHEN // The request is signed AWSSigner signer = new AWSSigner(awsCredentialsProvider, region, service, clock); Map<String, Object> signedHeaders = signer.getSignedHeaders(uri, method, queryParams, headers, payload); // THEN // The signature must match the expected signature TreeMap<String, Object> caseInsensitiveSignedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); caseInsensitiveSignedHeaders.putAll(signedHeaders); assertThat(caseInsensitiveSignedHeaders).containsKey("Authorization"); assertThat(caseInsensitiveSignedHeaders.get("Authorization")).isEqualTo(expectedAuthorizationHeader); }
@Test public void testGetVanillaWithoutDateHeader() throws Exception { // GIVEN // Credentials String awsAccessKey = "AKIDEXAMPLE"; String awsSecretKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"; AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey); AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider(credentials); String region = "us-east-1"; String service = "host"; // Date Supplier<LocalDateTime> clock = () -> LocalDateTime.of(2011, 9, 9, 23, 36, 0); // weird date : 09 Sep 2011 is a friday, not a monday String date = "20110909T233600Z"; // HTTP request String host = "host.foo.com"; String uri = "/"; String method = "GET"; Multimap<String, String> queryParams = ImmutableListMultimap.<String, String>builder() .build(); Map<String, Object> headers = ImmutableMap.<String, Object>builder() .put("Host", host) .build(); Optional<byte[]> payload = Optional.absent(); // WHEN // The request is signed AWSSigner signer = new AWSSigner(awsCredentialsProvider, region, service, clock); Map<String, Object> signedHeaders = signer.getSignedHeaders(uri, method, queryParams, headers, payload); // THEN // The signature must match the expected signature String expectedSignature = "904f8c568bca8bd2618b9241a7f2a8d90f279e717fd0f6727af189668b040151"; String expectedAuthorizationHeader = format( "AWS4-HMAC-SHA256 Credential=%s/20110909/%s/%s/aws4_request, SignedHeaders=host;x-amz-date, Signature=%s", awsAccessKey, region, service, expectedSignature ); TreeMap<String, Object> caseInsensitiveSignedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); caseInsensitiveSignedHeaders.putAll(signedHeaders); assertThat(caseInsensitiveSignedHeaders).containsKey("Authorization"); assertThat(caseInsensitiveSignedHeaders.get("Authorization")).isEqualTo(expectedAuthorizationHeader); assertThat(caseInsensitiveSignedHeaders).containsKey("Host"); assertThat(caseInsensitiveSignedHeaders.get("Host")).isEqualTo(host); assertThat(caseInsensitiveSignedHeaders).containsKey("X-Amz-Date"); assertThat(caseInsensitiveSignedHeaders.get("X-Amz-Date")).isEqualTo(date); assertThat(caseInsensitiveSignedHeaders).doesNotContainKey("Date"); }