index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/providers/LazyAwsRegionProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; public class LazyAwsRegionProviderTest { @SuppressWarnings("unchecked") private Supplier<AwsRegionProvider> regionProviderConstructor = Mockito.mock(Supplier.class); private AwsRegionProvider regionProvider = Mockito.mock(AwsRegionProvider.class); @BeforeEach public void reset() { Mockito.reset(regionProvider, regionProviderConstructor); Mockito.when(regionProviderConstructor.get()).thenReturn(regionProvider); } @Test public void creationDoesntInvokeSupplier() { new LazyAwsRegionProvider(regionProviderConstructor); Mockito.verifyNoMoreInteractions(regionProviderConstructor); } @Test public void getRegionInvokesSupplierExactlyOnce() { LazyAwsRegionProvider lazyRegionProvider = new LazyAwsRegionProvider(regionProviderConstructor); lazyRegionProvider.getRegion(); lazyRegionProvider.getRegion(); Mockito.verify(regionProviderConstructor, Mockito.times(1)).get(); Mockito.verify(regionProvider, Mockito.times(2)).getRegion(); } }
1,300
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/providers/InstanceProfileRegionProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.internal.util.EC2MetadataUtilsServer; /** * Tests broken up by fixture. */ @RunWith(Enclosed.class) public class InstanceProfileRegionProviderTest { /** * If the EC2 metadata service is running it should return the region the server is mocked * with. */ public static class MetadataServiceRunningTest { private static EC2MetadataUtilsServer server; private AwsRegionProvider regionProvider; @BeforeClass public static void setupFixture() throws IOException { server = new EC2MetadataUtilsServer(0); server.start(); System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), "http://localhost:" + server.getLocalPort()); } @AfterClass public static void tearDownFixture() throws IOException { server.stop(); System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property()); } @Before public void setup() { regionProvider = new InstanceProfileRegionProvider(); } @Test public void metadataServiceRunning_ProvidesCorrectRegion() { assertEquals(Region.US_EAST_1, regionProvider.getRegion()); } @Test(expected = SdkClientException.class) public void ec2MetadataDisabled_shouldReturnNull() { try { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property(), "true"); regionProvider.getRegion(); } finally { System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property()); } } } /** * If the EC2 metadata service is not present then the provider will throw an exception. If the provider is used * in a {@link AwsRegionProviderChain}, the chain will catch the exception and go on to the next region provider. */ public static class MetadataServiceNotRunning { private AwsRegionProvider regionProvider; @Before public void setup() { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), "http://localhost:54123"); regionProvider = new InstanceProfileRegionProvider(); } @Test (expected = SdkClientException.class) public void metadataServiceNotRunning_ThrowsException() { regionProvider.getRegion(); } } }
1,301
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/providers/AwsProfileRegionProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.URISyntaxException; import java.nio.file.Paths; import org.junit.Rule; import org.junit.Test; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; public class AwsProfileRegionProviderTest { @Rule public EnvironmentVariableHelper settingsHelper = new EnvironmentVariableHelper(); @Test public void nonExistentDefaultConfigFile_ThrowsException() { settingsHelper.set(ProfileFileSystemSetting.AWS_CONFIG_FILE, "/var/tmp/this/is/invalid.txt"); settingsHelper.set(ProfileFileSystemSetting.AWS_SHARED_CREDENTIALS_FILE, "/var/tmp/this/is/also.invalid.txt"); assertThatThrownBy(() -> new AwsProfileRegionProvider().getRegion()) .isInstanceOf(SdkClientException.class) .hasMessageContaining("No region provided in profile: default"); } @Test public void profilePresentAndRegionIsSet_ProvidesCorrectRegion() throws URISyntaxException { String testFile = "/profileconfig/test-profiles.tst"; settingsHelper.set(ProfileFileSystemSetting.AWS_PROFILE, "test"); settingsHelper.set(ProfileFileSystemSetting.AWS_CONFIG_FILE, Paths.get(getClass().getResource(testFile).toURI()).toString()); assertThat(new AwsProfileRegionProvider().getRegion()).isEqualTo(Region.of("saa")); } }
1,302
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal/RegionScopeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.regions.RegionScope; @RunWith(Parameterized.class) public class RegionScopeTest { private final TestCase testCase; public RegionScopeTest(TestCase testCase) { this.testCase = testCase; } @Test public void validateRegionScope() { try { RegionScope regionScope = RegionScope.create(testCase.regionScope); assertThat(regionScope.id()).isEqualTo(testCase.regionScope); } catch (RuntimeException e) { if (testCase.expectedException == null) { throw e; } assertThat(e).isInstanceOf(testCase.expectedException); } } @Parameterized.Parameters(name = "{0}") public static Collection<TestCase> testCases() { List<TestCase> cases = new ArrayList<>(); cases.add(new TestCase().setCaseName("Standard Region accepted").setRegionScope("eu-north-1")); cases.add(new TestCase().setCaseName("Wildcard last segment accepted").setRegionScope("eu-north-*")); cases.add(new TestCase().setCaseName("Wildcard middle segment accepted").setRegionScope("eu-*")); cases.add(new TestCase().setCaseName("Global Wildcard accepted").setRegionScope("*")); cases.add(new TestCase().setCaseName("Null string fails").setRegionScope(null).setExpectedException(NullPointerException.class)); cases.add(new TestCase().setCaseName("Empty string fails") .setRegionScope("") .setExpectedException(IllegalArgumentException.class)); cases.add(new TestCase().setCaseName("Blank string fails") .setRegionScope(" ") .setExpectedException(IllegalArgumentException.class)); cases.add(new TestCase().setCaseName("Wildcard mixed last segment fails") .setRegionScope("eu-north-45*") .setExpectedException(IllegalArgumentException.class)); cases.add(new TestCase().setCaseName("Wildcard mixed middle segment fails") .setRegionScope("eu-north*") .setExpectedException(IllegalArgumentException.class)); cases.add(new TestCase().setCaseName("Wildcard mixed global fails") .setRegionScope("eu*") .setExpectedException(IllegalArgumentException.class)); cases.add(new TestCase().setCaseName("Wildcard not at end fails") .setRegionScope("*-north-1") .setExpectedException(IllegalArgumentException.class)); cases.add(new TestCase().setCaseName("Double wildcard fails") .setRegionScope("**") .setExpectedException(IllegalArgumentException.class)); return cases; } private static class TestCase { private String caseName; private String regionScope; private Class<? extends RuntimeException> expectedException; public TestCase setCaseName(String caseName) { this.caseName = caseName; return this; } public TestCase setRegionScope(String regionScope) { this.regionScope = regionScope; return this; } public TestCase setExpectedException(Class<? extends RuntimeException> expectedException) { this.expectedException = expectedException; return this; } @Override public String toString() { return this.caseName + (regionScope == null ? "" : ": " + regionScope); } } }
1,303
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal/util/EC2MetadataUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal.util; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.http.Fault; import com.github.tomakehurst.wiremock.junit.WireMockRule; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; public class EC2MetadataUtilsTest { private static final String TOKEN_RESOURCE_PATH = "/latest/api/token"; private static final String TOKEN_HEADER = "x-aws-ec2-metadata-token"; private static final String EC2_METADATA_TOKEN_TTL_HEADER = "x-aws-ec2-metadata-token-ttl-seconds"; private static final String EC2_METADATA_ROOT = "/latest/meta-data"; private static final String AMI_ID_RESOURCE = EC2_METADATA_ROOT + "/ami-id"; @Rule public ExpectedException thrown = ExpectedException.none(); @Rule public WireMockRule mockMetadataEndpoint = new WireMockRule(); @Before public void methodSetup() { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), "http://localhost:" + mockMetadataEndpoint.port()); EC2MetadataUtils.clearCache(); } @Test public void getToken_queriesCorrectPath() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token"))); String token = EC2MetadataUtils.getToken(); assertThat(token).isEqualTo("some-token"); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); } @Test public void getAmiId_queriesAndIncludesToken() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); EC2MetadataUtils.getAmiId(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withHeader(TOKEN_HEADER, equalTo("some-token"))); } @Test public void getAmiId_tokenQueryTimeout_fallsBackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withFixedDelay(Integer.MAX_VALUE))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); EC2MetadataUtils.getAmiId(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withoutHeader(TOKEN_HEADER)); } @Test public void getAmiId_queriesTokenResource_403Error_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(403).withBody("oops"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); EC2MetadataUtils.getAmiId(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withoutHeader(TOKEN_HEADER)); } @Test public void getAmiId_queriesTokenResource_404Error_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(404).withBody("oops"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); EC2MetadataUtils.getAmiId(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withoutHeader(TOKEN_HEADER)); } @Test public void getAmiId_queriesTokenResource_405Error_fallbackToInsecure() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(405).withBody("oops"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); EC2MetadataUtils.getAmiId(); WireMock.verify(putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); WireMock.verify(getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)).withoutHeader(TOKEN_HEADER)); } @Test public void getAmiId_queriesTokenResource_400Error_throws() { thrown.expect(SdkClientException.class); thrown.expectMessage("token"); stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(400).withBody("oops"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); EC2MetadataUtils.getAmiId(); } @Test public void fetchDataWithAttemptNumber_ioError_shouldHonor() { int attempts = 1; thrown.expect(SdkClientException.class); thrown.expectMessage("Unable to contact EC2 metadata service"); stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token")));; stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER))); EC2MetadataUtils.fetchData(AMI_ID_RESOURCE, false, attempts); WireMock.verify(attempts, getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE))); } }
1,304
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal/util/EC2MetadataUtilsServer.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; /** * Starts a new EC2 Metadata server instance with given address and port number. */ public class EC2MetadataUtilsServer { private ServerSocket server; public EC2MetadataUtilsServer(int port) throws UnknownHostException, IOException { server = new ServerSocket(port, 1, InetAddress.getLoopbackAddress()); } public void start() throws UnknownHostException, IOException { Thread thread = new Thread() { @Override public void run() { try { startServer(); } catch (IOException exception) { if ((exception instanceof SocketException) && (exception.getMessage().equals("Socket closed"))) { return; } throw new RuntimeException("BOOM", exception); } } }; thread.setDaemon(true); thread.start(); } public void stop() throws IOException { if (server != null) { server.close(); } } public int getLocalPort() { return server.getLocalPort(); } private void startServer() throws IOException { while (true) { try (Socket sock = server.accept(); BufferedReader reader = new BufferedReader(new InputStreamReader( sock.getInputStream())); PrintWriter writer = new PrintWriter(sock.getOutputStream());) { handleConnection(reader, writer); } } } private void handleConnection(BufferedReader input, PrintWriter output) throws IOException { String line = input.readLine(); if (line == null) { return; } String[] parts = line.split(" "); if (parts.length != 3) { throw new RuntimeException("Bogus request: " + line); } if (!"GET".equals(parts[0]) && !"PUT".equals(parts[0])) { throw new RuntimeException("Bogus verb: " + line); } ignoreRequest(input); String path = parts[1]; if (path.equals("/latest/meta-data/iam/info")) { outputIamInfo(output); } else if (path.equals("/latest/meta-data/iam/security-credentials")) { outputIamCredList(output); } else if (path .startsWith("/latest/meta-data/iam/security-credentials/")) { outputIamCred(output); } else if (path.equals("/latest/dynamic/instance-identity/document")) { outputInstanceInfo(output); } else if (path.equals("/latest/dynamic/instance-identity/signature")) { outputInstanceSignature(output); } else if (path.equals("/latest/api/token")) { outputToken(output); } else { throw new RuntimeException("Unknown path: " + path); } } private void ignoreRequest(BufferedReader input) throws IOException { while (true) { String line = input.readLine(); if (line == null) { throw new RuntimeException("Unexpected end of input"); } if (line.length() == 0) { return; } } } private void outputToken(PrintWriter output) { String payload = "test-token"; output.println("HTTP/1.1 200 OK"); output.println("Connection: close"); output.println("Content-Length: " + payload.length()); output.println(); output.print(payload); output.flush(); } private void outputIamInfo(PrintWriter output) throws IOException { String payload = "{" + "\"Code\":\"Success\"," + "\"LastUpdated\":\"2014-04-07T08:18:41Z\"," + "\"InstanceProfileArn\":\"foobar\"," + "\"InstanceProfileId\":\"moobily\"," + "\"NewFeature\":12345" + "}"; output.println("HTTP/1.1 200 OK"); output.println("Connection: close"); output.println("Content-Length: " + payload.length()); output.println(); output.print(payload); output.flush(); } private void outputIamCredList(PrintWriter output) throws IOException { String payload = "test1\ntest2"; output.println("HTTP/1.1 200 OK"); output.println("Connection: close"); output.println("Content-Length: " + payload.length()); output.println(); output.print(payload); output.flush(); } private void outputIamCred(PrintWriter output) throws IOException { String payload = "{" + "\"Code\":\"Success\"," + "\"LastUpdated\":\"2014-04-07T08:18:41Z\"," + "\"Type\":\"AWS-HMAC\"," + "\"AccessKeyId\":\"foobar\"," + "\"SecretAccessKey\":\"moobily\"," + "\"Token\":\"beebop\"," + "\"Expiration\":\"2014-04-08T23:16:53Z\"" + "}"; output.println("HTTP/1.1 200 OK"); output.println("Connection: close"); output.println("Content-Length: " + payload.length()); output.println(); output.print(payload); output.flush(); } private void outputInstanceInfo(PrintWriter output) throws IOException { String payload = constructInstanceInfo(); output.println("HTTP/1.1 200 OK"); output.println("Connection: close"); output.println("Content-Length: " + payload.length()); output.println(); output.print(payload); output.flush(); } protected String constructInstanceInfo() { return "{" + "\"pendingTime\":\"2014-08-07T22:07:46Z\"," + "\"instanceType\":\"m1.small\"," + "\"imageId\":\"ami-a49665cc\"," + "\"instanceId\":\"i-6b2de041\"," + "\"billingProducts\":[\"foo\"]," + "\"architecture\":\"x86_64\"," + "\"accountId\":\"599169622985\"," + "\"kernelId\":\"aki-919dcaf8\"," + "\"ramdiskId\":\"baz\"," + "\"region\":\"us-east-1\"," + "\"version\":\"2010-08-31\"," + "\"availabilityZone\":\"us-east-1b\"," + "\"privateIp\":\"10.201.215.38\"," + "\"devpayProductCodes\":[\"bar\"]," + "\"marketplaceProductCodes\":[\"qaz\"]" + "}"; } private void outputInstanceSignature(PrintWriter output) { String payload = "foobar"; output.println("HTTP/1.1 200 OK"); output.println("Connection: close"); output.println("Content-Length: " + payload.length()); output.println(); output.print(payload); output.flush(); } }
1,305
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal/util/ConnectionUtilsComponentTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal.util; import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assume.assumeTrue; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.IOException; import java.net.HttpURLConnection; import java.net.Inet4Address; import java.net.URI; import java.util.Collections; import org.junit.After; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; public class ConnectionUtilsComponentTest { @ClassRule public static WireMockRule mockProxyServer = new WireMockRule(WireMockConfiguration.wireMockConfig().port(0), false); @Rule public WireMockRule mockServer = new WireMockRule(WireMockConfiguration.wireMockConfig().port(0), false); private final ConnectionUtils sut = ConnectionUtils.create(); @After public void cleanup() { System.getProperties().remove("http.proxyHost"); System.getProperties().remove("http.proxyPort"); } @Test public void proxiesAreNotUsedEvenIfPropertyIsSet() throws IOException { assumeTrue(Inet4Address.getLocalHost().isReachable(100)); System.getProperties().put("http.proxyHost", "localhost"); System.getProperties().put("http.proxyPort", String.valueOf(mockProxyServer.port())); HttpURLConnection connection = sut.connectToEndpoint(URI.create("http://" + Inet4Address.getLocalHost().getHostAddress() + ":" + mockServer.port()), emptyMap()); assertThat(connection.usingProxy()).isFalse(); } @Test public void headersArePassedAsPartOfRequest() throws IOException { HttpURLConnection connection = sut.connectToEndpoint(URI.create("http://localhost:" + mockServer.port()), Collections.singletonMap("HeaderA", "ValueA")); connection.getResponseCode(); mockServer.verify(WireMock.getRequestedFor(WireMock.urlMatching("/")).withHeader("HeaderA", WireMock.equalTo("ValueA"))); } @Test public void shouldNotFollowRedirects() throws IOException { mockServer.stubFor(WireMock.get(WireMock.urlMatching("/")).willReturn(WireMock.aResponse().withStatus(301).withHeader("Location", "http://localhost:" + mockServer.port() + "/hello"))); HttpURLConnection connection = sut.connectToEndpoint(URI.create("http://localhost:" + mockServer.port()), Collections.emptyMap()); assertThat(connection.getResponseCode()).isEqualTo(301); } }
1,306
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal/util/Ec2MetadataUtilsTt0049160280Test.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal.util; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class Ec2MetadataUtilsTt0049160280Test { private static final String JSON = "{" + " \"privateIp\" : \"172.31.56.174\"," + " \"devpayProductCodes\" : null," + " \"availabilityZone\" : \"us-east-1b\"," + " \"version\" : \"2010-08-31\"," + " \"accountId\" : \"123456789012\"," + " \"instanceId\" : \"i-b32c0064\"," + " \"billingProducts\" : [\"bp-6ba54002\" ]," + " \"imageId\" : \"ami-ac3a1cc4\"," + " \"instanceType\" : \"t2.small\"," + " \"kernelId\" : null," + " \"ramdiskId\" : null," + " \"pendingTime\" : \"2015-04-13T19:57:24Z\"," + " \"architecture\" : \"x86_64\"," + " \"region\" : \"us-east-1\"" + "}"; @Test public void getRegionIntern() throws Exception { String region = EC2MetadataUtils.doGetEC2InstanceRegion(JSON); assertEquals("us-east-1", region); } @Test public void tt0049160280() { EC2MetadataUtils.InstanceInfo info = EC2MetadataUtils.doGetInstanceInfo(JSON); String[] billingProducts = info.getBillingProducts(); assertTrue(billingProducts.length == 1); assertEquals(billingProducts[0], "bp-6ba54002"); } @Test public void devProductCodes() { final String JSON = "{" + " \"privateIp\" : \"172.31.56.174\"," + " \"devpayProductCodes\" : [\"foo\", \"bar\"]," + " \"availabilityZone\" : \"us-east-1b\"," + " \"version\" : \"2010-08-31\"," + " \"accountId\" : \"123456789012\"," + " \"instanceId\" : \"i-b32c0064\"," + " \"billingProducts\" : [\"bp-6ba54002\" ]," + " \"imageId\" : \"ami-ac3a1cc4\"," + " \"instanceType\" : \"t2.small\"," + " \"kernelId\" : null," + " \"ramdiskId\" : null," + " \"pendingTime\" : \"2015-04-13T19:57:24Z\"," + " \"architecture\" : \"x86_64\"," + " \"region\" : \"us-east-1\"" + "}"; EC2MetadataUtils.InstanceInfo info = EC2MetadataUtils.doGetInstanceInfo(JSON); String[] devpayProductCodes = info.getDevpayProductCodes(); assertTrue(devpayProductCodes.length == 2); assertEquals(devpayProductCodes[0], "foo"); assertEquals(devpayProductCodes[1], "bar"); } }
1,307
0
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal
Create_ds/aws-sdk-java-v2/core/regions/src/test/java/software/amazon/awssdk/regions/internal/util/SocketUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal.util; import java.io.IOException; import java.net.ServerSocket; public class SocketUtils { /** * Returns an unused port in the localhost. */ public static int getUnusedPort() throws IOException { try (ServerSocket socket = new ServerSocket(0)) { socket.setReuseAddress(true); return socket.getLocalPort(); } } }
1,308
0
Create_ds/aws-sdk-java-v2/core/regions/src/it/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/it/java/software/amazon/awssdk/regions/util/EC2MetadataUtilsIntegrationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.util; import java.io.IOException; import java.util.Map; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.internal.util.EC2MetadataUtils; import software.amazon.awssdk.regions.internal.util.EC2MetadataUtilsServer; public class EC2MetadataUtilsIntegrationTest { private static EC2MetadataUtilsServer SERVER = null; @BeforeClass public static void setUp() throws IOException { SERVER = new EC2MetadataUtilsServer( 0); SERVER.start(); System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), "http://localhost:" + SERVER.getLocalPort()); } @AfterClass public static void cleanUp() throws IOException { if (SERVER != null) { SERVER.stop(); } System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property()); } @Test(expected = SdkClientException.class) public void ec2MetadataDisabled_shouldThrowException() { try { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property(), "true"); EC2MetadataUtils.getInstanceId(); } finally { System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_DISABLED.property()); } } @Test public void testInstanceSignature() { String signature = EC2MetadataUtils.getInstanceSignature(); Assert.assertEquals("foobar", signature); } @Test public void testInstanceInfo() { EC2MetadataUtils.InstanceInfo info = EC2MetadataUtils.getInstanceInfo(); Assert.assertEquals("2014-08-07T22:07:46Z", info.getPendingTime()); Assert.assertEquals("m1.small", info.getInstanceType()); Assert.assertEquals("ami-a49665cc", info.getImageId()); Assert.assertEquals("i-6b2de041", info.getInstanceId()); Assert.assertEquals("foo", info.getBillingProducts()[0]); Assert.assertEquals("x86_64", info.getArchitecture()); Assert.assertEquals("599169622985", info.getAccountId()); Assert.assertEquals("aki-919dcaf8", info.getKernelId()); Assert.assertEquals("baz", info.getRamdiskId()); Assert.assertEquals("us-east-1", info.getRegion()); Assert.assertEquals("2010-08-31", info.getVersion()); Assert.assertEquals("us-east-1b", info.getAvailabilityZone()); Assert.assertEquals("10.201.215.38", info.getPrivateIp()); Assert.assertEquals("bar", info.getDevpayProductCodes()[0]); Assert.assertEquals("qaz", info.getMarketplaceProductCodes()[0]); } }
1,309
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/ServiceMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import java.net.URI; import java.util.List; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.regions.internal.MetadataLoader; /** * Metadata about a service, like S3, DynamoDB, etc. * * <p>This is useful for building meta-functionality around AWS services. For example, UIs that list the available regions for a * service would use the {@link #regions()} method for a service.</p> * * <p>This is usually created by calling the {@code serviceMetadata} method on the service client's interface, but can also be * created by calling the {@link #of(String)} method and providing the service's unique endpoint prefix.</p> */ @SdkPublicApi public interface ServiceMetadata { /** * Retrieve the AWS endpoint that should be used for this service in the provided region, if no {@link EndpointTag}s are * desired. * * @param region The region that should be used to load the service endpoint. * @return The region-specific endpoint for this service. * @throws RuntimeException if an endpoint cannot be determined. */ default URI endpointFor(Region region) { return endpointFor(ServiceEndpointKey.builder().region(region).build()); } /** * Retrieve the AWS endpoint that should be used for this service associated with the provided {@link ServiceEndpointKey}. * * @param key The service endpoint key with which an endpoint should be retrieved. * @return The region-specific endpoint for this service. * @throws RuntimeException if an endpoint cannot be determined. */ default URI endpointFor(ServiceEndpointKey key) { throw new UnsupportedOperationException(); } /** * Retrieve the region that should be used for message signing when communicating with this service in the provided region. * For most services, this will match the provided region, but it may differ for unusual services or when using a region that * does not correspond to a physical location, like {@link Region#AWS_GLOBAL}. * * @param region The region from which the signing region should be derived. * @return The region that should be used for signing messages when communicating with this service in the requested region. */ default Region signingRegion(Region region) { return signingRegion(ServiceEndpointKey.builder().region(region).build()); } /** * Retrieve the region that should be used for message signing when communicating with this service in the provided region * and with the provided endpoint tags. For most services, this will match the provided region, but it may differ for * unusual services or when using a region that does not correspond to a physical location, like {@link Region#AWS_GLOBAL}. * * @param key The service endpoint key with which an endpoint should be retrieved. * @return The region that should be used for signing messages when communicating with this service in the requested region. */ default Region signingRegion(ServiceEndpointKey key) { throw new UnsupportedOperationException(); } /** * Retrieve the list of regions this service is currently available in. * * @return The list of regions this service is currently available in. */ List<Region> regions(); /** * Retrieve the service-specific partition configuration of each partition in which this service is currently available. * * @return The list of service-specific service metadata for each partition in which this service is available. */ List<ServicePartitionMetadata> servicePartitions(); /** * Load the service metadata for the provided service endpoint prefix. This should only be used when you do not wish to have * a dependency on the service for which you are retrieving the metadata. When you have a dependency on the service client, * the metadata should instead be loaded using the service client's {@code serviceMetadata()} method. * * @param serviceEndpointPrefix The service-specific endpoint prefix of the service about which you wish to load metadata. * @return The service metadata for the requested service. */ static ServiceMetadata of(String serviceEndpointPrefix) { ServiceMetadata metadata = MetadataLoader.serviceMetadata(serviceEndpointPrefix); return metadata == null ? new DefaultServiceMetadata(serviceEndpointPrefix) : metadata; } /** * Reconfigure this service metadata using the provided {@link ServiceMetadataConfiguration}. This is useful, because some * service metadata instances refer to external configuration that might wish to be modified, like a {@link ProfileFile}. */ default ServiceMetadata reconfigure(ServiceMetadataConfiguration configuration) { return this; } /** * Reconfigure this service metadata using the provided {@link ServiceMetadataConfiguration}. This is useful, because some * service metadata instances refer to external configuration that might wish to be modified, like a {@link ProfileFile}. * * This is a shorthand form of {@link #reconfigure(ServiceMetadataConfiguration)}, without the need to call * {@code builder()} or {@code build()}. */ default ServiceMetadata reconfigure(Consumer<ServiceMetadataConfiguration.Builder> consumer) { ServiceMetadataConfiguration.Builder configuration = ServiceMetadataConfiguration.builder(); consumer.accept(configuration); return reconfigure(configuration.build()); } }
1,310
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/ServiceMetadataAdvancedOption.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.client.config.ClientOption; import software.amazon.awssdk.profiles.ProfileProperty; /** * A collection of advanced options that can be configured on a {@link ServiceMetadata} via * {@link ServiceMetadataConfiguration.Builder#putAdvancedOption(ServiceMetadataAdvancedOption, Object)}. * * @param <T> The type of value associated with the option. */ @SdkPublicApi public class ServiceMetadataAdvancedOption<T> extends ClientOption<T> { /** * The default S3 regional endpoint setting for the {@code us-east-1} region to use. Setting * the value to {@code regional} causes the SDK to use the {@code s3.us-east-1.amazonaws.com} endpoint when using the * {@link Region#US_EAST_1} region instead of the global {@code s3.amazonaws.com} by default if it's not configured otherwise * via {@link SdkSystemSetting#AWS_S3_US_EAST_1_REGIONAL_ENDPOINT} or {@link ProfileProperty#S3_US_EAST_1_REGIONAL_ENDPOINT} */ public static final ServiceMetadataAdvancedOption<String> DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT = new ServiceMetadataAdvancedOption<>(String.class); protected ServiceMetadataAdvancedOption(Class<T> valueClass) { super(valueClass); } }
1,311
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/PartitionEndpointKey.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.Mutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * A key used to look up a specific partition hostname or DNS suffix via * {@link PartitionMetadata#hostname(PartitionEndpointKey)} or {@link PartitionMetadata#dnsSuffix(PartitionEndpointKey)}. */ @SdkPublicApi @Immutable public final class PartitionEndpointKey { private final Set<EndpointTag> tags; private PartitionEndpointKey(DefaultBuilder builder) { this.tags = Collections.unmodifiableSet(new HashSet<>(Validate.paramNotNull(builder.tags, "tags"))); Validate.noNullElements(builder.tags, "tags must not contain null."); } /** * Create a builder for a {@link PartitionEndpointKey}. */ public static Builder builder() { return new DefaultBuilder(); } public Set<EndpointTag> tags() { return tags; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PartitionEndpointKey that = (PartitionEndpointKey) o; return tags.equals(that.tags); } @Override public int hashCode() { return tags.hashCode(); } @Override public String toString() { return ToString.builder("PartitionEndpointKey") .add("tags", tags) .toString(); } @SdkPublicApi @Mutable public interface Builder { /** * Configure the tags associated with the partition endpoint that should be retrieved. */ Builder tags(Collection<EndpointTag> tags); /** * Configure the tags associated with the partition endpoint that should be retrieved. */ Builder tags(EndpointTag... tags); /** * Create a {@link PartitionEndpointKey} from the configuration on this builder. */ PartitionEndpointKey build(); } private static class DefaultBuilder implements Builder { private List<EndpointTag> tags = Collections.emptyList(); @Override public Builder tags(Collection<EndpointTag> tags) { this.tags = new ArrayList<>(tags); return this; } @Override public Builder tags(EndpointTag... tags) { this.tags = Arrays.asList(tags); return this; } public List<EndpointTag> getTags() { return Collections.unmodifiableList(tags); } public void setTags(Collection<EndpointTag> tags) { this.tags = new ArrayList<>(tags); } @Override public PartitionEndpointKey build() { return new PartitionEndpointKey(this); } } }
1,312
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/ServicePartitionMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import java.util.Optional; import software.amazon.awssdk.annotations.SdkPublicApi; /** * The metadata associated with a specific service, in a specific partition. * * This can be loaded via {@link ServiceMetadata#servicePartitions()}. */ @SdkPublicApi public interface ServicePartitionMetadata { /** * Retrieve the partition to which this service is known to exist. */ PartitionMetadata partition(); /** * Retrieve the global region associated with this service, in this {@link #partition()}. This will return empty if the * service is regionalized in the partition. */ Optional<Region> globalRegion(); }
1,313
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/DefaultServiceMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import java.net.URI; import java.util.Collections; import java.util.List; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.internal.util.ServiceMetadataUtils; @SdkPublicApi public class DefaultServiceMetadata implements ServiceMetadata { private final String endpointPrefix; public DefaultServiceMetadata(String endpointPrefix) { this.endpointPrefix = endpointPrefix; } @Override public URI endpointFor(ServiceEndpointKey key) { PartitionMetadata partition = PartitionMetadata.of(key.region()); PartitionEndpointKey endpointKey = PartitionEndpointKey.builder().tags(key.tags()).build(); String hostname = partition.hostname(endpointKey); String dnsName = partition.dnsSuffix(endpointKey); return ServiceMetadataUtils.endpointFor(hostname, endpointPrefix, key.region().id(), dnsName); } @Override public Region signingRegion(ServiceEndpointKey key) { return key.region(); } @Override public List<Region> regions() { return Collections.emptyList(); } @Override public List<ServicePartitionMetadata> servicePartitions() { return Collections.emptyList(); } }
1,314
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/RegionMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.internal.MetadataLoader; /** * A collection of metadata about a region. This can be loaded using the {@link #of(Region)} method. */ @SdkPublicApi public interface RegionMetadata { /** * The unique system ID for this region; ex: &quot;us-east-1&quot;. * * @return The unique system ID for this region. */ String id(); /** * Returns the default domain for this region; ex: &quot;amazonaws.com&quot;, without considering any {@link EndpointTag}s * or environment variables. * * @return The domain for this region. * @deprecated This information does not consider any endpoint variant factors, like {@link EndpointTag}s. If those factors * are important, use {@link ServiceMetadata#endpointFor(ServiceEndpointKey)} or * {@link PartitionMetadata#dnsSuffix(PartitionEndpointKey)}. */ @Deprecated String domain(); /** * Returns the metadata for this region's partition. */ PartitionMetadata partition(); /** * Returns the description of this region; ex: &quot;US East (N. Virginia)&quot;. * * @return The description for this region */ String description(); /** * Returns the region metadata pertaining to the given region. * * @param region The region to get the metadata for. * @return The metadata for that region. */ static RegionMetadata of(Region region) { return MetadataLoader.regionMetadata(region); } }
1,315
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/PartitionMetadataProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import software.amazon.awssdk.annotations.SdkPublicApi; @SdkPublicApi public interface PartitionMetadataProvider { /** * Returns the partition metadata for a given partition. * * @param partition The partition to find partition metadata for. * @return {@link PartitionMetadata} for the given partition */ PartitionMetadata partitionMetadata(String partition); /** * Returns the partition metadata for a given region. * * @param region The region to find partition metadata for. * @return {@link PartitionMetadata} for the given region. */ PartitionMetadata partitionMetadata(Region region); }
1,316
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/ServiceEndpointKey.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.Mutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * A ServiceEndpointKey uniquely identifies a service endpoint, and can be used to look up endpoints via * {@link ServiceMetadata#endpointFor(ServiceEndpointKey)}. * * <p>An endpoint is uniquely identified by the {@link Region} of that service and the {@link EndpointTag}s associated with that * endpoint. For example, the {@link EndpointTag#FIPS} endpoint in {@link Region#US_WEST_2}. * * <p>This can be created via {@link #builder()}. */ @SdkPublicApi @Immutable public final class ServiceEndpointKey { private final Region region; private final Set<EndpointTag> tags; private ServiceEndpointKey(DefaultBuilder builder) { this.region = Validate.paramNotNull(builder.region, "region"); this.tags = Collections.unmodifiableSet(new LinkedHashSet<>(Validate.paramNotNull(builder.tags, "tags"))); Validate.noNullElements(builder.tags, "tags must not contain null."); } /** * Create a builder for {@link ServiceEndpointKey}s. */ public static Builder builder() { return new DefaultBuilder(); } /** * Retrieve the region associated with the endpoint. */ public Region region() { return region; } /** * Retrieve the tags associated with the endpoint (or the empty set, to use the default endpoint). */ public Set<EndpointTag> tags() { return tags; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ServiceEndpointKey that = (ServiceEndpointKey) o; if (!region.equals(that.region)) { return false; } return tags.equals(that.tags); } @Override public int hashCode() { int result = region.hashCode(); result = 31 * result + tags.hashCode(); return result; } @Override public String toString() { return ToString.builder("ServiceEndpointKey") .add("region", region) .add("tags", tags) .toString(); } @SdkPublicApi @Mutable public interface Builder { /** * Configure the region associated with the endpoint that should be loaded. */ Builder region(Region region); /** * Configure the tags associated with the endpoint that should be loaded. */ Builder tags(Collection<EndpointTag> tags); /** * Configure the tags associated with the endpoint that should be loaded. */ Builder tags(EndpointTag... tags); /** * Build a {@link ServiceEndpointKey} using the configuration on this builder. */ ServiceEndpointKey build(); } private static class DefaultBuilder implements Builder { private Region region; private List<EndpointTag> tags = Collections.emptyList(); @Override public Builder region(Region region) { this.region = region; return this; } public Region getRegion() { return region; } public void setRegion(Region region) { this.region = region; } @Override public Builder tags(Collection<EndpointTag> tags) { this.tags = new ArrayList<>(tags); return this; } @Override public Builder tags(EndpointTag... tags) { this.tags = Arrays.asList(tags); return this; } public List<EndpointTag> getTags() { return Collections.unmodifiableList(tags); } public void setTags(Collection<EndpointTag> tags) { this.tags = new ArrayList<>(tags); } @Override public ServiceEndpointKey build() { return new ServiceEndpointKey(this); } } }
1,317
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/ServiceMetadataConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import java.util.Map; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.utils.AttributeMap; /** * Configuration for a {@link ServiceMetadata}. This allows modifying the values used by default when a metadata instance is * generating endpoint data. * * Created using a {@link #builder()}. */ @SdkPublicApi public final class ServiceMetadataConfiguration { private final Supplier<ProfileFile> profileFile; private final String profileName; private final AttributeMap advancedOptions; private ServiceMetadataConfiguration(Builder builder) { this.profileFile = builder.profileFile; this.profileName = builder.profileName; this.advancedOptions = builder.advancedOptions.build(); } /** * Create a {@link Builder} that can be used to create {@link ServiceMetadataConfiguration} instances. */ public static Builder builder() { return new Builder(); } /** * Retrieve the profile file configured via {@link Builder#profileFile(Supplier)}. */ public Supplier<ProfileFile> profileFile() { return profileFile; } /** * Retrieve the profile name configured via {@link Builder#profileName(String)}. */ public String profileName() { return profileName; } /** * Load the optional requested advanced option that was configured on the service metadata builder. * * @see ServiceMetadataConfiguration.Builder#putAdvancedOption(ServiceMetadataAdvancedOption, Object) */ public <T> Optional<T> advancedOption(ServiceMetadataAdvancedOption<T> option) { return Optional.ofNullable(advancedOptions.get(option)); } public static final class Builder { private Supplier<ProfileFile> profileFile; private String profileName; private AttributeMap.Builder advancedOptions = AttributeMap.builder(); private Builder() { } /** * Configure the profile file used by some services to calculate the endpoint from the region. The supplier is only * invoked zero or one time, and only the first time the value is needed. * * If this is null, the {@link ProfileFile#defaultProfileFile()} is used. */ public Builder profileFile(Supplier<ProfileFile> profileFile) { this.profileFile = profileFile; return this; } /** * Configure which profile in the {@link #profileFile(Supplier)} should be usedto calculate the endpoint from the region. * * If this is null, the {@link ProfileFileSystemSetting#AWS_PROFILE} is used. */ public Builder profileName(String profileName) { this.profileName = profileName; return this; } /** * Configure the map of advanced override options. This will override all values currently configured. The values in the * map must match the key type of the map, or a runtime exception will be raised. */ public <T> Builder putAdvancedOption(ServiceMetadataAdvancedOption<T> option, T value) { this.advancedOptions.put(option, value); return this; } /** * Configure an advanced override option. * @see ServiceMetadataAdvancedOption */ public Builder advancedOptions(Map<ServiceMetadataAdvancedOption<?>, ?> advancedOptions) { this.advancedOptions.putAll(advancedOptions); return this; } /** * Build the {@link ServiceMetadata} instance with the updated configuration. */ public ServiceMetadataConfiguration build() { return new ServiceMetadataConfiguration(this); } } }
1,318
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/RegionMetadataProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import software.amazon.awssdk.annotations.SdkPublicApi; @SdkPublicApi public interface RegionMetadataProvider { /** * Returns the region metadata with the name given, if it exists in the metadata * or if it can be derived from the metadata. * * Otherwise, returns null. * * @param region the region to search for * @return the corresponding region metadata, if it exists or derived. */ RegionMetadata regionMetadata(Region region); }
1,319
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/RegionScope.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.Validate; /** * This class represents the concept of a regional scope, in form of a string with possible wildcards. * <p/> * The string can contain a region value such as us-east-1, or add the wildcard '*' at the end of the region * string to represent all possible regional combinations that can match the expression. A wildcard must be * it's own segment and preceeded by a '-' dash, unless the whole expression is the wildcard. * <p/> * Examples of valid combinations: * <ul> * <li>'us-east-1' - Represents the region exactly</li> * <li>'eu-west-*' - Represents all regions that start with 'eu-west-'</li> * <li>'eu-*' - Represents all regions that start with 'eu-'</li> * <li>'*' - Represents all regions, i.e. a global scope</li> * </ul> * <p/> * Examples of invalid combinations: * <ul> * <li>'us-*-1' - The wildcard must appear at the end.</li> * <li>'eu-we*' - The wildcard must be its own segment</li> * </ul> */ @SdkPublicApi public final class RegionScope { public static final RegionScope GLOBAL; private static final Pattern REGION_SCOPE_PATTERN; //Pattern must be compiled when static scope is created static { REGION_SCOPE_PATTERN = Pattern.compile("^([a-z0-9-])*([*]?)$"); GLOBAL = RegionScope.create("*"); } private final String regionScope; private RegionScope(String regionScope) { this.regionScope = Validate.paramNotBlank(regionScope, "regionScope"); validateFormat(regionScope); } /** * Gets the string representation of this region scope. */ public String id() { return this.regionScope; } /** * Creates a RegionScope with the supplied value. * * @param value See class documentation {@link RegionScope} for allowed values. */ public static RegionScope create(String value) { return new RegionScope(value); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RegionScope that = (RegionScope) o; return regionScope.equals(that.regionScope); } @Override public int hashCode() { return 31 * (1 + (regionScope != null ? regionScope.hashCode() : 0)); } private void validateFormat(String regionScope) { Matcher matcher = REGION_SCOPE_PATTERN.matcher(regionScope); if (!matcher.matches()) { if (regionScope.contains(",")) { throw new IllegalArgumentException("Incorrect region scope '" + regionScope + "'. Region scopes with more than " + "one region defined are not supported."); } throw new IllegalArgumentException("Incorrect region scope '" + regionScope + "'. Region scope must be a" + " string that either is a complete region string, such as 'us-east-1'," + " or uses the wildcard '*' to represent any region that starts with" + " the preceding parts. Wildcards must appear as a separate segment after" + " a '-' dash, for example 'us-east-*'. A global scope of '*' is allowed."); } List<String> segments = Arrays.asList(regionScope.split("-")); String lastSegment = segments.get(segments.size() - 1); if (lastSegment.contains("*") && lastSegment.length() != 1) { throw new IllegalArgumentException("Incorrect region scope '" + regionScope + "'. A wildcard must only appear on its own at the end of the expression " + "after a '-' dash. A global scope of '*' is allowed."); } } }
1,320
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/PartitionMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.regions.internal.MetadataLoader; /** * Metadata about a partition such as aws or aws-cn. * * <p>This is useful for building meta-functionality around AWS services. Partition metadata helps to provide * data about regions which may not yet be in the endpoints.json file but have a specific prefix.</p> */ @SdkPublicApi public interface PartitionMetadata { /** * Returns the DNS suffix, such as amazonaws.com for this partition. This is the DNS suffix with no * {@link EndpointTag}s. * * @return The DNS suffix for this partition with no endpoint tags. * @see #dnsSuffix(PartitionEndpointKey) */ default String dnsSuffix() { return dnsSuffix(PartitionEndpointKey.builder().build()); } /** * Returns the DNS suffix, such as amazonaws.com for this partition. This returns the DNS suffix associated with the tags in * the provided {@link PartitionEndpointKey}. * * @return The DNS suffix for this partition with the endpoint tags specified in the endpoint key, or null if one is not * known. */ default String dnsSuffix(PartitionEndpointKey key) { throw new UnsupportedOperationException(); } /** * Returns the hostname pattern, such as {service}.{region}.{dnsSuffix} for this partition. This is the hostname pattern * with no {@link EndpointTag}s. * * @return The hostname pattern for this partition with no endpoint tags. * @see #hostname(PartitionEndpointKey) */ default String hostname() { return hostname(PartitionEndpointKey.builder().build()); } /** * Returns the hostname pattern, such as {service}.{region}.{dnsSuffix} for this partition. This returns the hostname * associated with the tags in the provided {@link PartitionEndpointKey}. * * @return The hostname pattern for this partition with the endpoint tags specified in the endpoint key, or null if one is * not known. */ default String hostname(PartitionEndpointKey key) { throw new UnsupportedOperationException(); } /** * Returns the identifier for this partition, such as aws. * * @return The identifier for this partition. */ String id(); /** * Returns the partition name for this partition, such as AWS Standard * * @return The name of this partition */ String name(); /** * Returns the region regex used for pattern matching for this partition. * * @return The region regex of this partition. */ String regionRegex(); /** * Retrieves the partition metadata for a given partition. * * @param partition The partition to get metadata for. * * @return {@link PartitionMetadata} for the given partition. */ static PartitionMetadata of(String partition) { return MetadataLoader.partitionMetadata(partition); } /** * Retrieves the partition metadata for a given region. * * @param region The region to get the partition metadata for. * * @return {@link PartitionMetadata} for the given region. */ static PartitionMetadata of(Region region) { return MetadataLoader.partitionMetadata(region); } }
1,321
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/ServiceMetadataProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions; import software.amazon.awssdk.annotations.SdkPublicApi; @SdkPublicApi public interface ServiceMetadataProvider { /** * Returns the service metadata with the name given, if it exists in the metadata * or if it can be derived from the metadata. * * Otherwise, returns null. * * @param service the service to search for * @return the corresponding service metadata, if it exists or derived. */ ServiceMetadata serviceMetadata(String service); }
1,322
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/servicemetadata/EnhancedS3ServiceMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.servicemetadata; import java.net.URI; import java.util.List; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServiceEndpointKey; import software.amazon.awssdk.regions.ServiceMetadata; import software.amazon.awssdk.regions.ServiceMetadataAdvancedOption; import software.amazon.awssdk.regions.ServiceMetadataConfiguration; import software.amazon.awssdk.regions.ServicePartitionMetadata; import software.amazon.awssdk.utils.Lazy; import software.amazon.awssdk.utils.Logger; /** * Decorator metadata class for S3 to allow customers to opt in to using the * regional S3 us-east-1 endpoint instead of the legacy * {@code s3.amazonaws.com} when specifying the us-east-1 region. */ @SdkPublicApi public final class EnhancedS3ServiceMetadata implements ServiceMetadata { private static final Logger log = Logger.loggerFor(EnhancedS3ServiceMetadata.class); private static final String REGIONAL_SETTING = "regional"; private final Lazy<Boolean> useUsEast1RegionalEndpoint; private final ServiceMetadata s3ServiceMetadata; public EnhancedS3ServiceMetadata() { this(ServiceMetadataConfiguration.builder().build()); } private EnhancedS3ServiceMetadata(ServiceMetadataConfiguration config) { Supplier<ProfileFile> profileFile = config.profileFile() != null ? config.profileFile() : ProfileFile::defaultProfileFile; Supplier<String> profileName = config.profileName() != null ? () -> config.profileName() : ProfileFileSystemSetting.AWS_PROFILE::getStringValueOrThrow; this.useUsEast1RegionalEndpoint = new Lazy<>(() -> useUsEast1RegionalEndpoint(profileFile, profileName, config)); this.s3ServiceMetadata = new S3ServiceMetadata().reconfigure(config); } @Override public URI endpointFor(ServiceEndpointKey key) { if (Region.US_EAST_1.equals(key.region()) && key.tags().isEmpty() && !useUsEast1RegionalEndpoint.getValue()) { return URI.create("s3.amazonaws.com"); } return s3ServiceMetadata.endpointFor(key); } @Override public Region signingRegion(ServiceEndpointKey key) { return s3ServiceMetadata.signingRegion(key); } @Override public List<Region> regions() { return s3ServiceMetadata.regions(); } @Override public List<ServicePartitionMetadata> servicePartitions() { return s3ServiceMetadata.servicePartitions(); } private boolean useUsEast1RegionalEndpoint(Supplier<ProfileFile> profileFile, Supplier<String> profileName, ServiceMetadataConfiguration config) { String env = envVarSetting(); if (env != null) { return REGIONAL_SETTING.equalsIgnoreCase(env); } String profile = profileFileSetting(profileFile, profileName); if (profile != null) { return REGIONAL_SETTING.equalsIgnoreCase(profile); } return config.advancedOption(ServiceMetadataAdvancedOption.DEFAULT_S3_US_EAST_1_REGIONAL_ENDPOINT) .filter(REGIONAL_SETTING::equalsIgnoreCase).isPresent(); } private static String envVarSetting() { return SdkSystemSetting.AWS_S3_US_EAST_1_REGIONAL_ENDPOINT.getStringValue().orElse(null); } private String profileFileSetting(Supplier<ProfileFile> profileFileSupplier, Supplier<String> profileNameSupplier) { try { ProfileFile profileFile = profileFileSupplier.get(); String profileName = profileNameSupplier.get(); if (profileFile == null || profileName == null) { return null; } return profileFile.profile(profileName) .flatMap(p -> p.property(ProfileProperty.S3_US_EAST_1_REGIONAL_ENDPOINT)) .orElse(null); } catch (Exception t) { log.warn(() -> "Unable to load config file", t); return null; } } @Override public ServiceMetadata reconfigure(ServiceMetadataConfiguration configuration) { return new EnhancedS3ServiceMetadata(configuration); } }
1,323
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/util/ResourcesEndpointProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.util; import java.io.IOException; import java.net.URI; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.util.SdkUserAgent; /** * <p> * Abstract class to return an endpoint URI from which the resources can be loaded. * </p> * <p> * By default, the request won't be retried if the request fails while computing endpoint. * </p> */ @SdkProtectedApi @FunctionalInterface public interface ResourcesEndpointProvider { /** * Returns the URI that contains the credentials. * @return * URI to retrieve the credentials. * * @throws IOException * If any problems are encountered while connecting to the * service to retrieve the endpoint. */ URI endpoint() throws IOException; /** * Allows the extending class to provide a custom retry policy. * The default behavior is not to retry. */ default ResourcesEndpointRetryPolicy retryPolicy() { return ResourcesEndpointRetryPolicy.NO_RETRY; } /** * Allows passing additional headers to the request */ default Map<String, String> headers() { Map<String, String> requestHeaders = new HashMap<>(); requestHeaders.put("User-Agent", SdkUserAgent.create().userAgent()); requestHeaders.put("Accept", "*/*"); requestHeaders.put("Connection", "keep-alive"); return requestHeaders; } }
1,324
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/util/ResourcesEndpointRetryParameters.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.util; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Parameters that are used in {@link ResourcesEndpointRetryPolicy}. */ @SdkProtectedApi public final class ResourcesEndpointRetryParameters { private final Integer statusCode; private final Exception exception; private ResourcesEndpointRetryParameters(Builder builder) { this.statusCode = builder.statusCode; this.exception = builder.exception; } public static Builder builder() { return new Builder(); } public Integer getStatusCode() { return statusCode; } public Exception getException() { return exception; } public static class Builder { private final Integer statusCode; private final Exception exception; private Builder() { this.statusCode = null; this.exception = null; } private Builder(Integer statusCode, Exception exception) { this.statusCode = statusCode; this.exception = exception; } /** * @param statusCode The status code from Http response. * * @return This object for method chaining. */ public Builder withStatusCode(Integer statusCode) { return new Builder(statusCode, this.exception); } /** * * @param exception The exception that was thrown. * @return This object for method chaining. */ public Builder withException(Exception exception) { return new Builder(this.statusCode, exception); } public ResourcesEndpointRetryParameters build() { return new ResourcesEndpointRetryParameters(this); } } }
1,325
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/util/ResourcesEndpointRetryPolicy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.util; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Custom retry policy that retrieve information from a local endpoint in EC2 host. * * Internal use only. */ @SdkProtectedApi public interface ResourcesEndpointRetryPolicy { ResourcesEndpointRetryPolicy NO_RETRY = (retriesAttempted, retryParams) -> false; /** * Returns whether a failed request should be retried. * * @param retriesAttempted * The number of times the current request has been * attempted. * * @return True if the failed request should be retried. */ boolean shouldRetry(int retriesAttempted, ResourcesEndpointRetryParameters retryParams); }
1,326
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/util/HttpResourcesUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.util; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URI; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser; import software.amazon.awssdk.regions.internal.util.ConnectionUtils; import software.amazon.awssdk.utils.IoUtils; @SdkProtectedApi public final class HttpResourcesUtils { private static final Logger log = LoggerFactory.getLogger(HttpResourcesUtils.class); private static final JsonNodeParser JSON_PARSER = JsonNode.parser(); private static volatile HttpResourcesUtils instance; private final ConnectionUtils connectionUtils; private HttpResourcesUtils() { this(ConnectionUtils.create()); } HttpResourcesUtils(ConnectionUtils connectionUtils) { this.connectionUtils = connectionUtils; } public static HttpResourcesUtils instance() { if (instance == null) { synchronized (HttpResourcesUtils.class) { if (instance == null) { instance = new HttpResourcesUtils(); } } } return instance; } /** * Connects to the given endpoint to read the resource * and returns the text contents. * * If the connection fails, the request will not be retried. * * @param endpoint The service endpoint to connect to. * @return The text payload returned from the container metadata endpoint * service for the specified resource path. * @throws IOException If any problems were encountered while connecting to the * service for the requested resource path. * @throws SdkClientException If the requested service is not found. */ public String readResource(URI endpoint) throws IOException { return readResource(() -> endpoint, "GET"); } /** * Connects to the given endpoint to read the resource * and returns the text contents. * * @param endpointProvider The endpoint provider. * @return The text payload returned from the container metadata endpoint * service for the specified resource path. * @throws IOException If any problems were encountered while connecting to the * service for the requested resource path. * @throws SdkClientException If the requested service is not found. */ public String readResource(ResourcesEndpointProvider endpointProvider) throws IOException { return readResource(endpointProvider, "GET"); } /** * Connects to the given endpoint to read the resource * and returns the text contents. * * @param endpointProvider The endpoint provider. * @param method The HTTP request method to use. * @return The text payload returned from the container metadata endpoint * service for the specified resource path. * @throws IOException If any problems were encountered while connecting to the * service for the requested resource path. * @throws SdkClientException If the requested service is not found. */ public String readResource(ResourcesEndpointProvider endpointProvider, String method) throws IOException { int retriesAttempted = 0; InputStream inputStream = null; while (true) { try { HttpURLConnection connection = connectionUtils.connectToEndpoint(endpointProvider.endpoint(), endpointProvider.headers(), method); int statusCode = connection.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_OK) { inputStream = connection.getInputStream(); return IoUtils.toUtf8String(inputStream); } else if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) { // This is to preserve existing behavior of EC2 Instance metadata service. throw SdkClientException.builder() .message("The requested metadata is not found at " + connection.getURL()) .build(); } else { if (!endpointProvider.retryPolicy().shouldRetry(retriesAttempted++, ResourcesEndpointRetryParameters.builder() .withStatusCode(statusCode) .build())) { inputStream = connection.getErrorStream(); handleErrorResponse(inputStream, statusCode, connection.getResponseMessage()); } } } catch (IOException ioException) { if (!endpointProvider.retryPolicy().shouldRetry(retriesAttempted++, ResourcesEndpointRetryParameters.builder() .withException(ioException) .build())) { throw ioException; } log.debug("An IOException occurred when connecting to endpoint: {} \n Retrying to connect again", endpointProvider.endpoint()); } finally { IoUtils.closeQuietly(inputStream, log); } } } private void handleErrorResponse(InputStream errorStream, int statusCode, String responseMessage) throws IOException { // Parse the error stream returned from the service. if (errorStream != null) { String errorResponse = IoUtils.toUtf8String(errorStream); try { Optional<JsonNode> message = JSON_PARSER.parse(errorResponse).field("message"); if (message.isPresent()) { responseMessage = message.get().text(); } } catch (RuntimeException exception) { log.debug("Unable to parse error stream", exception); } } throw SdkServiceException.builder() .message(responseMessage) .statusCode(statusCode) .build(); } }
1,327
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/providers/AwsRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; /** * Interface for providing AWS region information. Implementations are free to use any strategy for * providing region information. */ @SdkProtectedApi @FunctionalInterface public interface AwsRegionProvider { /** * Returns the region name to use. If region information is not available, throws an {@link SdkClientException}. * * @return Region name to use. */ Region getRegion(); }
1,328
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/providers/InstanceProfileRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.internal.util.EC2MetadataUtils; /** * Attempts to load region information from the EC2 Metadata service. If the application is not * running on EC2 this provider will thrown an exception. * * <P> * If {@link SdkSystemSetting#AWS_EC2_METADATA_DISABLED} is set to true, it will not try to load * region from EC2 metadata service and will return null. */ @SdkProtectedApi public final class InstanceProfileRegionProvider implements AwsRegionProvider { /** * Cache region as it will not change during the lifetime of the JVM. */ private volatile String region; @Override public Region getRegion() throws SdkClientException { if (SdkSystemSetting.AWS_EC2_METADATA_DISABLED.getBooleanValueOrThrow()) { throw SdkClientException.builder() .message("EC2 Metadata is disabled. Unable to retrieve region information from " + "EC2 Metadata service.") .build(); } if (region == null) { synchronized (this) { if (region == null) { this.region = tryDetectRegion(); } } } if (region == null) { throw SdkClientException.builder() .message("Unable to retrieve region information from EC2 Metadata service. " + "Please make sure the application is running on EC2.") .build(); } return Region.of(region); } private String tryDetectRegion() { return EC2MetadataUtils.getEC2InstanceRegion(); } }
1,329
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/providers/AwsProfileRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.regions.Region; /** * Loads region information from the {@link ProfileFile#defaultProfileFile()} using the default profile name. */ @SdkProtectedApi public final class AwsProfileRegionProvider implements AwsRegionProvider { private final Supplier<ProfileFile> profileFile; private final String profileName; public AwsProfileRegionProvider() { this(null, null); } public AwsProfileRegionProvider(Supplier<ProfileFile> profileFile, String profileName) { this.profileFile = profileFile != null ? profileFile : ProfileFile::defaultProfileFile; this.profileName = profileName != null ? profileName : ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow(); } @Override public Region getRegion() { return profileFile.get() .profile(profileName) .map(p -> p.properties().get(ProfileProperty.REGION)) .map(Region::of) .orElseThrow(() -> SdkClientException.builder() .message("No region provided in profile: " + profileName) .build()); } }
1,330
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/providers/DefaultAwsRegionProviderChain.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.profiles.ProfileFile; /** * AWS Region provider that looks for the region in this order: * <ol> * <li>Check the 'aws.region' system property for the region.</li> * <li>Check the 'AWS_REGION' environment variable for the region.</li> * <li>Check the {user.home}/.aws/credentials and {user.home}/.aws/config files for the region.</li> * <li>If running in EC2, check the EC2 metadata service for the region.</li> * </ol> */ @SdkProtectedApi public final class DefaultAwsRegionProviderChain extends AwsRegionProviderChain { public DefaultAwsRegionProviderChain() { super(new SystemSettingsRegionProvider(), new AwsProfileRegionProvider(), new InstanceProfileRegionProvider()); } private DefaultAwsRegionProviderChain(Builder builder) { super(new SystemSettingsRegionProvider(), new AwsProfileRegionProvider(builder.profileFile, builder.profileName), new InstanceProfileRegionProvider()); } public static Builder builder() { return new Builder(); } public static final class Builder { private Supplier<ProfileFile> profileFile; private String profileName; private Builder() { } public Builder profileFile(Supplier<ProfileFile> profileFile) { this.profileFile = profileFile; return this; } public Builder profileName(String profileName) { this.profileName = profileName; return this; } public DefaultAwsRegionProviderChain build() { return new DefaultAwsRegionProviderChain(this); } } }
1,331
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/providers/SystemSettingsRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; /** * Loads region information from the 'aws.region' system property or the 'AWS_REGION' environment variable. If both are specified, * the system property will be used. */ @SdkProtectedApi public final class SystemSettingsRegionProvider implements AwsRegionProvider { @Override public Region getRegion() throws SdkClientException { return SdkSystemSetting.AWS_REGION.getStringValue() .map(Region::of) .orElseThrow(this::exception); } private SdkClientException exception() { return SdkClientException.builder().message(String.format("Unable to load region from system settings. Region" + " must be specified either via environment variable (%s) or " + " system property (%s).", SdkSystemSetting.AWS_REGION.environmentVariable(), SdkSystemSetting.AWS_REGION.property())).build(); } }
1,332
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/providers/LazyAwsRegionProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.Lazy; import software.amazon.awssdk.utils.ToString; /** * A wrapper for {@link AwsRegionProvider} that defers creation of the underlying provider until the first time the * {@link AwsRegionProvider#getRegion()} method is invoked. */ @SdkProtectedApi public class LazyAwsRegionProvider implements AwsRegionProvider { private final Lazy<AwsRegionProvider> delegate; public LazyAwsRegionProvider(Supplier<AwsRegionProvider> delegateConstructor) { this.delegate = new Lazy<>(delegateConstructor); } @Override public Region getRegion() { return delegate.getValue().getRegion(); } @Override public String toString() { return ToString.builder("LazyAwsRegionProvider") .add("delegate", delegate) .build(); } }
1,333
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/providers/AwsRegionProviderChain.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.providers; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; /** * Composite {@link AwsRegionProvider} that sequentially delegates to a chain of providers looking * for region information. * * Throws an {@link SdkClientException} if region could not be find in any of the providers. */ @SdkProtectedApi public class AwsRegionProviderChain implements AwsRegionProvider { private static final Logger log = LoggerFactory.getLogger(AwsRegionProviderChain.class); private final List<AwsRegionProvider> providers; public AwsRegionProviderChain(AwsRegionProvider... providers) { this.providers = new ArrayList<>(providers.length); Collections.addAll(this.providers, providers); } @Override public Region getRegion() throws SdkClientException { List<String> exceptionMessages = null; for (AwsRegionProvider provider : providers) { try { Region region = provider.getRegion(); if (region != null) { return region; } } catch (Exception e) { // Ignore any exceptions and move onto the next provider log.debug("Unable to load region from {}:{}", provider.toString(), e.getMessage()); String message = provider.toString() + ": " + e.getMessage(); if (exceptionMessages == null) { exceptionMessages = new ArrayList<>(); } exceptionMessages.add(message); } } throw SdkClientException.builder() .message("Unable to load region from any of the providers in the chain " + this + ": " + exceptionMessages) .build(); } }
1,334
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal/MetadataLoader.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.regions.GeneratedPartitionMetadataProvider; import software.amazon.awssdk.regions.GeneratedRegionMetadataProvider; import software.amazon.awssdk.regions.GeneratedServiceMetadataProvider; import software.amazon.awssdk.regions.PartitionMetadata; import software.amazon.awssdk.regions.PartitionMetadataProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.RegionMetadata; import software.amazon.awssdk.regions.RegionMetadataProvider; import software.amazon.awssdk.regions.ServiceMetadata; import software.amazon.awssdk.regions.ServiceMetadataProvider; /** * Internal class for determining where to load region and service * metadata from. Currently only generated region metadata is supported. */ @SdkInternalApi public final class MetadataLoader { private static final RegionMetadataProvider REGION_METADATA_PROVIDER = new GeneratedRegionMetadataProvider(); private static final ServiceMetadataProvider SERVICE_METADATA_PROVIDER = new GeneratedServiceMetadataProvider(); private static final PartitionMetadataProvider PARTITION_METADATA_PROVIDER = new GeneratedPartitionMetadataProvider(); private MetadataLoader() { } public static PartitionMetadata partitionMetadata(Region region) { return PARTITION_METADATA_PROVIDER.partitionMetadata(region); } public static PartitionMetadata partitionMetadata(String partition) { return PARTITION_METADATA_PROVIDER.partitionMetadata(partition); } public static RegionMetadata regionMetadata(Region region) { return REGION_METADATA_PROVIDER.regionMetadata(region); } public static ServiceMetadata serviceMetadata(String service) { return SERVICE_METADATA_PROVIDER.serviceMetadata(service); } }
1,335
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal/DefaultServicePartitionMetadata.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.regions.PartitionMetadata; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServicePartitionMetadata; @SdkInternalApi public class DefaultServicePartitionMetadata implements ServicePartitionMetadata { private final String partition; private final Region globalRegionForPartition; public DefaultServicePartitionMetadata(String partition, Region globalRegionForPartition) { this.partition = partition; this.globalRegionForPartition = globalRegionForPartition; } @Override public PartitionMetadata partition() { return PartitionMetadata.of(partition); } @Override public Optional<Region> globalRegion() { return Optional.ofNullable(globalRegionForPartition); } }
1,336
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal/util/ConnectionUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal.util; import java.io.IOException; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URI; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; @SdkInternalApi //TODO: Refactor to use SDK HTTP client instead of URL connection, also consider putting EC2MetadataClient in its own module public class ConnectionUtils { public static ConnectionUtils create() { return new ConnectionUtils(); } public HttpURLConnection connectToEndpoint(URI endpoint, Map<String, String> headers) throws IOException { return connectToEndpoint(endpoint, headers, "GET"); } public HttpURLConnection connectToEndpoint(URI endpoint, Map<String, String> headers, String method) throws IOException { HttpURLConnection connection = (HttpURLConnection) endpoint.toURL().openConnection(Proxy.NO_PROXY); connection.setConnectTimeout(1000); connection.setReadTimeout(1000); connection.setRequestMethod(method); connection.setDoOutput(true); headers.forEach(connection::addRequestProperty); connection.setInstanceFollowRedirects(false); connection.connect(); return connection; } }
1,337
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal/util/Ec2MetadataConfigProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal.util; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.profiles.Profile; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.profiles.ProfileProperty; @SdkInternalApi // TODO: Remove or consolidate this class with the one from the auth module. // There's currently no good way for both auth and regions to share the same // class since there's no suitable common dependency between the two where this // can live. Ideally, we can do this when the EC2MetadataUtils is replaced with // the IMDS client. public final class Ec2MetadataConfigProvider { /** Default IPv4 endpoint for the Amazon EC2 Instance Metadata Service. */ private static final String EC2_METADATA_SERVICE_URL_IPV4 = "http://169.254.169.254"; /** Default IPv6 endpoint for the Amazon EC2 Instance Metadata Service. */ private static final String EC2_METADATA_SERVICE_URL_IPV6 = "http://[fd00:ec2::254]"; private final Supplier<ProfileFile> profileFile; private final String profileName; private Ec2MetadataConfigProvider(Builder builder) { this.profileFile = builder.profileFile; this.profileName = builder.profileName; } public enum EndpointMode { IPV4, IPV6, ; public static EndpointMode fromValue(String s) { if (s == null) { return null; } for (EndpointMode value : EndpointMode.values()) { if (value.name().equalsIgnoreCase(s)) { return value; } } throw new IllegalArgumentException("Unrecognized value for endpoint mode: " + s); } } public String getEndpoint() { String endpointOverride = getEndpointOverride(); if (endpointOverride != null) { return endpointOverride; } EndpointMode endpointMode = getEndpointMode(); switch (endpointMode) { case IPV4: return EC2_METADATA_SERVICE_URL_IPV4; case IPV6: return EC2_METADATA_SERVICE_URL_IPV6; default: throw SdkClientException.create("Unknown endpoint mode: " + endpointMode); } } public EndpointMode getEndpointMode() { Optional<String> endpointMode = SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.getNonDefaultStringValue(); if (endpointMode.isPresent()) { return EndpointMode.fromValue(endpointMode.get()); } return configFileEndpointMode().orElseGet(() -> EndpointMode.fromValue(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.defaultValue())); } public String getEndpointOverride() { Optional<String> endpointOverride = SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.getNonDefaultStringValue(); if (endpointOverride.isPresent()) { return endpointOverride.get(); } Optional<String> configFileValue = configFileEndpointOverride(); return configFileValue.orElse(null); } public static Builder builder() { return new Builder(); } private Optional<EndpointMode> configFileEndpointMode() { return resolveProfile().flatMap(p -> p.property(ProfileProperty.EC2_METADATA_SERVICE_ENDPOINT_MODE)) .map(EndpointMode::fromValue); } private Optional<String> configFileEndpointOverride() { return resolveProfile().flatMap(p -> p.property(ProfileProperty.EC2_METADATA_SERVICE_ENDPOINT)); } private Optional<Profile> resolveProfile() { ProfileFile profileFileToUse = resolveProfileFile(); String profileNameToUse = resolveProfileName(); return profileFileToUse.profile(profileNameToUse); } private ProfileFile resolveProfileFile() { if (profileFile != null) { return profileFile.get(); } return ProfileFile.defaultProfileFile(); } private String resolveProfileName() { if (profileName != null) { return profileName; } return ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow(); } public static class Builder { private Supplier<ProfileFile> profileFile; private String profileName; public Builder profileFile(Supplier<ProfileFile> profileFile) { this.profileFile = profileFile; return this; } public Builder profileName(String profileName) { this.profileName = profileName; return this; } public Ec2MetadataConfigProvider build() { return new Ec2MetadataConfigProvider(this); } } }
1,338
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal/util/EC2MetadataUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal.util; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.core.util.SdkUserAgent; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser; import software.amazon.awssdk.regions.util.HttpResourcesUtils; import software.amazon.awssdk.regions.util.ResourcesEndpointProvider; /** * * Utility class for retrieving Amazon EC2 instance metadata. * * <p> * <b>Note</b>: this is an internal API subject to change. Users of the SDK * should not depend on this. * * <p> * You can use the data to build more generic AMIs that can be modified by * configuration files supplied at launch time. For example, if you run web * servers for various small businesses, they can all use the same AMI and * retrieve their content from the Amazon S3 bucket you specify at launch. To * add a new customer at any time, simply create a bucket for the customer, add * their content, and launch your AMI.<br> * * <P> * If {@link SdkSystemSetting#AWS_EC2_METADATA_DISABLED} is set to true, EC2 metadata usage * will be disabled and {@link SdkClientException} will be thrown for any metadata retrieval attempt. * * <p> * More information about Amazon EC2 Metadata * * @see <a * href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html">Amazon * EC2 User Guide: Instance Metadata</a> */ @SdkInternalApi public final class EC2MetadataUtils { private static final JsonNodeParser JSON_PARSER = JsonNode.parser(); /** Default resource path for credentials in the Amazon EC2 Instance Metadata Service. */ private static final String REGION = "region"; private static final String INSTANCE_IDENTITY_DOCUMENT = "instance-identity/document"; private static final String INSTANCE_IDENTITY_SIGNATURE = "instance-identity/signature"; private static final String EC2_METADATA_ROOT = "/latest/meta-data"; private static final String EC2_USERDATA_ROOT = "/latest/user-data/"; private static final String EC2_DYNAMICDATA_ROOT = "/latest/dynamic/"; private static final String EC2_METADATA_TOKEN_HEADER = "x-aws-ec2-metadata-token"; private static final int DEFAULT_QUERY_ATTEMPTS = 3; private static final int MINIMUM_RETRY_WAIT_TIME_MILLISECONDS = 250; private static final Logger log = LoggerFactory.getLogger(EC2MetadataUtils.class); private static final Map<String, String> CACHE = new ConcurrentHashMap<>(); private static final InstanceProviderTokenEndpointProvider TOKEN_ENDPOINT_PROVIDER = new InstanceProviderTokenEndpointProvider(); private static final Ec2MetadataConfigProvider EC2_METADATA_CONFIG_PROVIDER = Ec2MetadataConfigProvider.builder() .build(); private EC2MetadataUtils() { } /** * Get the AMI ID used to launch the instance. */ public static String getAmiId() { return fetchData(EC2_METADATA_ROOT + "/ami-id"); } /** * Get the index of this instance in the reservation. */ public static String getAmiLaunchIndex() { return fetchData(EC2_METADATA_ROOT + "/ami-launch-index"); } /** * Get the manifest path of the AMI with which the instance was launched. */ public static String getAmiManifestPath() { return fetchData(EC2_METADATA_ROOT + "/ami-manifest-path"); } /** * Get the list of AMI IDs of any instances that were rebundled to created * this AMI. Will only exist if the AMI manifest file contained an * ancestor-amis key. */ public static List<String> getAncestorAmiIds() { return getItems(EC2_METADATA_ROOT + "/ancestor-ami-ids"); } /** * Notifies the instance that it should reboot in preparation for bundling. * Valid values: none | shutdown | bundle-pending. */ public static String getInstanceAction() { return fetchData(EC2_METADATA_ROOT + "/instance-action"); } /** * Get the ID of this instance. */ public static String getInstanceId() { return fetchData(EC2_METADATA_ROOT + "/instance-id"); } /** * Get the type of the instance. */ public static String getInstanceType() { return fetchData(EC2_METADATA_ROOT + "/instance-type"); } /** * Get the local hostname of the instance. In cases where multiple network * interfaces are present, this refers to the eth0 device (the device for * which device-number is 0). */ public static String getLocalHostName() { return fetchData(EC2_METADATA_ROOT + "/local-hostname"); } /** * Get the MAC address of the instance. In cases where multiple network * interfaces are present, this refers to the eth0 device (the device for * which device-number is 0). */ public static String getMacAddress() { return fetchData(EC2_METADATA_ROOT + "/mac"); } /** * Get the private IP address of the instance. In cases where multiple * network interfaces are present, this refers to the eth0 device (the * device for which device-number is 0). */ public static String getPrivateIpAddress() { return fetchData(EC2_METADATA_ROOT + "/local-ipv4"); } /** * Get the Availability Zone in which the instance launched. */ public static String getAvailabilityZone() { return fetchData(EC2_METADATA_ROOT + "/placement/availability-zone"); } /** * Get the list of product codes associated with the instance, if any. */ public static List<String> getProductCodes() { return getItems(EC2_METADATA_ROOT + "/product-codes"); } /** * Get the public key. Only available if supplied at instance launch time. */ public static String getPublicKey() { return fetchData(EC2_METADATA_ROOT + "/public-keys/0/openssh-key"); } /** * Get the ID of the RAM disk specified at launch time, if applicable. */ public static String getRamdiskId() { return fetchData(EC2_METADATA_ROOT + "/ramdisk-id"); } /** * Get the ID of the reservation. */ public static String getReservationId() { return fetchData(EC2_METADATA_ROOT + "/reservation-id"); } /** * Get the list of names of the security groups applied to the instance. */ public static List<String> getSecurityGroups() { return getItems(EC2_METADATA_ROOT + "/security-groups"); } /** * Get the signature of the instance. */ public static String getInstanceSignature() { return fetchData(EC2_DYNAMICDATA_ROOT + INSTANCE_IDENTITY_SIGNATURE); } /** * Returns the current region of this running EC2 instance; or null if * it is unable to do so. The method avoids interpreting other parts of the * instance info JSON document to minimize potential failure. * <p> * The instance info is only guaranteed to be a JSON document per * http://docs * .aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html */ public static String getEC2InstanceRegion() { return doGetEC2InstanceRegion(getData( EC2_DYNAMICDATA_ROOT + INSTANCE_IDENTITY_DOCUMENT)); } static String doGetEC2InstanceRegion(final String json) { if (null != json) { try { return JSON_PARSER.parse(json) .field(REGION) .map(JsonNode::text) .orElseThrow(() -> new IllegalStateException("Region not included in metadata.")); } catch (Exception e) { log.warn("Unable to parse EC2 instance info (" + json + ") : " + e.getMessage(), e); } } return null; } /** * Get the virtual devices associated with the ami, root, ebs, and swap. */ public static Map<String, String> getBlockDeviceMapping() { Map<String, String> blockDeviceMapping = new HashMap<>(); List<String> devices = getItems(EC2_METADATA_ROOT + "/block-device-mapping"); for (String device : devices) { blockDeviceMapping.put(device, getData(EC2_METADATA_ROOT + "/block-device-mapping/" + device)); } return blockDeviceMapping; } /** * Get the list of network interfaces on the instance. */ public static List<NetworkInterface> getNetworkInterfaces() { List<NetworkInterface> networkInterfaces = new LinkedList<>(); List<String> macs = getItems(EC2_METADATA_ROOT + "/network/interfaces/macs/"); for (String mac : macs) { String key = mac.trim(); if (key.endsWith("/")) { key = key.substring(0, key.length() - 1); } networkInterfaces.add(new NetworkInterface(key)); } return networkInterfaces; } /** * Get the metadata sent to the instance */ public static String getUserData() { return getData(EC2_USERDATA_ROOT); } /** * Retrieve some of the data from http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html as a typed * object. This entire class will be removed as part of https://github.com/aws/aws-sdk-java-v2/issues/61, so don't rely on * this sticking around. * * This should not be removed until https://github.com/aws/aws-sdk-java-v2/issues/61 is implemented. */ public static InstanceInfo getInstanceInfo() { return doGetInstanceInfo(getData(EC2_DYNAMICDATA_ROOT + INSTANCE_IDENTITY_DOCUMENT)); } static InstanceInfo doGetInstanceInfo(String json) { if (json != null) { try { Map<String, JsonNode> jsonNode = JSON_PARSER.parse(json).asObject(); return new InstanceInfo(stringValue(jsonNode.get("pendingTime")), stringValue(jsonNode.get("instanceType")), stringValue(jsonNode.get("imageId")), stringValue(jsonNode.get("instanceId")), stringArrayValue(jsonNode.get("billingProducts")), stringValue(jsonNode.get("architecture")), stringValue(jsonNode.get("accountId")), stringValue(jsonNode.get("kernelId")), stringValue(jsonNode.get("ramdiskId")), stringValue(jsonNode.get("region")), stringValue(jsonNode.get("version")), stringValue(jsonNode.get("availabilityZone")), stringValue(jsonNode.get("privateIp")), stringArrayValue(jsonNode.get("devpayProductCodes")), stringArrayValue(jsonNode.get("marketplaceProductCodes"))); } catch (Exception e) { log.warn("Unable to parse dynamic EC2 instance info (" + json + ") : " + e.getMessage(), e); } } return null; } private static String stringValue(JsonNode jsonNode) { if (jsonNode == null || !jsonNode.isString()) { return null; } return jsonNode.asString(); } private static String[] stringArrayValue(JsonNode jsonNode) { if (jsonNode == null || !jsonNode.isArray()) { return null; } return jsonNode.asArray() .stream() .filter(JsonNode::isString) .map(JsonNode::asString) .toArray(String[]::new); } public static String getData(String path) { return getData(path, DEFAULT_QUERY_ATTEMPTS); } public static String getData(String path, int tries) { List<String> items = getItems(path, tries, true); if (null != items && items.size() > 0) { return items.get(0); } return null; } public static List<String> getItems(String path) { return getItems(path, DEFAULT_QUERY_ATTEMPTS, false); } public static List<String> getItems(String path, int tries) { return getItems(path, tries, false); } @SdkTestInternalApi public static void clearCache() { CACHE.clear(); } private static List<String> getItems(String path, int tries, boolean slurp) { if (tries == 0) { throw SdkClientException.builder().message("Unable to contact EC2 metadata service.").build(); } if (SdkSystemSetting.AWS_EC2_METADATA_DISABLED.getBooleanValueOrThrow()) { throw SdkClientException.builder().message("EC2 metadata usage is disabled.").build(); } List<String> items; String token = getToken(); try { String hostAddress = EC2_METADATA_CONFIG_PROVIDER.getEndpoint(); String response = doReadResource(new URI(hostAddress + path), token); if (slurp) { items = Collections.singletonList(response); } else { items = Arrays.asList(response.split("\n")); } return items; } catch (SdkClientException ace) { log.warn("Unable to retrieve the requested metadata."); return null; } catch (IOException | URISyntaxException | RuntimeException e) { // If there is no retry available, just throw exception instead of pausing. if (tries - 1 == 0) { throw SdkClientException.builder().message("Unable to contact EC2 metadata service.").cause(e).build(); } // Retry on any other exceptions int pause = (int) (Math.pow(2, DEFAULT_QUERY_ATTEMPTS - tries) * MINIMUM_RETRY_WAIT_TIME_MILLISECONDS); try { Thread.sleep(pause < MINIMUM_RETRY_WAIT_TIME_MILLISECONDS ? MINIMUM_RETRY_WAIT_TIME_MILLISECONDS : pause); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } return getItems(path, tries - 1, slurp); } } private static String doReadResource(URI resource, String token) throws IOException { return HttpResourcesUtils.instance().readResource(new DefaultEndpointProvider(resource, token), "GET"); } public static String getToken() { try { return HttpResourcesUtils.instance().readResource(TOKEN_ENDPOINT_PROVIDER, "PUT"); } catch (Exception e) { boolean is400ServiceException = e instanceof SdkServiceException && ((SdkServiceException) e).statusCode() == 400; // metadata resolution must not continue to the token-less flow for a 400 if (is400ServiceException) { throw SdkClientException.builder() .message("Unable to fetch metadata token") .cause(e) .build(); } return null; } } private static String fetchData(String path) { return fetchData(path, false); } private static String fetchData(String path, boolean force) { return fetchData(path, force, DEFAULT_QUERY_ATTEMPTS); } /** * Fetch data using the given path * * @param path the path * @param force whether to force to override the value in the cache * @param attempts the number of attempts that should be executed. * @return the value retrieved from the path */ public static String fetchData(String path, boolean force, int attempts) { if (SdkSystemSetting.AWS_EC2_METADATA_DISABLED.getBooleanValueOrThrow()) { throw SdkClientException.builder().message("EC2 metadata usage is disabled.").build(); } try { if (force || !CACHE.containsKey(path)) { CACHE.put(path, getData(path, attempts)); } return CACHE.get(path); } catch (SdkClientException e) { throw e; } catch (RuntimeException e) { return null; } } /** * All of the metada associated with a network interface on the instance. */ public static class NetworkInterface { private String path; private String mac; private List<String> availableKeys; private Map<String, String> data = new HashMap<>(); public NetworkInterface(String macAddress) { mac = macAddress; path = "/network/interfaces/macs/" + mac + "/"; } /** * The interface's Media Acess Control (mac) address */ public String getMacAddress() { return mac; } /** * The ID of the owner of the network interface.<br> * In multiple-interface environments, an interface can be attached by a * third party, such as Elastic Load Balancing. Traffic on an interface * is always billed to the interface owner. */ public String getOwnerId() { return getData("owner-id"); } /** * The interface's profile. */ public String getProfile() { return getData("profile"); } /** * The interface's local hostname. */ public String getHostname() { return getData("local-hostname"); } /** * The private IP addresses associated with the interface. */ public List<String> getLocalIPv4s() { return getItems("local-ipv4s"); } /** * The interface's public hostname. */ public String getPublicHostname() { return getData("public-hostname"); } /** * The elastic IP addresses associated with the interface.<br> * There may be multiple IP addresses on an instance. */ public List<String> getPublicIPv4s() { return getItems("public-ipv4s"); } /** * Security groups to which the network interface belongs. */ public List<String> getSecurityGroups() { return getItems("security-groups"); } /** * IDs of the security groups to which the network interface belongs. * Returned only for Amazon EC2 instances launched into a VPC. */ public List<String> getSecurityGroupIds() { return getItems("security-group-ids"); } /** * The CIDR block of the Amazon EC2-VPC subnet in which the interface * resides.<br> * Returned only for Amazon EC2 instances launched into a VPC. */ public String getSubnetIPv4CidrBlock() { return getData("subnet-ipv4-cidr-block"); } /** * ID of the subnet in which the interface resides.<br> * Returned only for Amazon EC2 instances launched into a VPC. */ public String getSubnetId() { return getData("subnet-id"); } /** * The CIDR block of the Amazon EC2-VPC in which the interface * resides.<br> * Returned only for Amazon EC2 instances launched into a VPC. */ public String getVpcIPv4CidrBlock() { return getData("vpc-ipv4-cidr-block"); } /** * ID of the Amazon EC2-VPC in which the interface resides.<br> * Returned only for Amazon EC2 instances launched into a VPC. */ public String getVpcId() { return getData("vpc-id"); } /** * Get the private IPv4 address(es) that are associated with the * public-ip address and assigned to that interface. * * @param publicIp * The public IP address * @return Private IPv4 address(es) associated with the public IP * address. */ public List<String> getIPv4Association(String publicIp) { return getItems(EC2_METADATA_ROOT + path + "ipv4-associations/" + publicIp); } private String getData(String key) { if (data.containsKey(key)) { return data.get(key); } // Since the keys are variable, cache a list of which ones are // available // to prevent unnecessary trips to the service. if (null == availableKeys) { availableKeys = EC2MetadataUtils.getItems(EC2_METADATA_ROOT + path); } if (availableKeys.contains(key)) { data.put(key, EC2MetadataUtils.getData(EC2_METADATA_ROOT + path + key)); return data.get(key); } else { return null; } } private List<String> getItems(String key) { if (null == availableKeys) { availableKeys = EC2MetadataUtils.getItems(EC2_METADATA_ROOT + path); } if (availableKeys.contains(key)) { return EC2MetadataUtils .getItems(EC2_METADATA_ROOT + path + key); } else { return Collections.emptyList(); } } } private static final class DefaultEndpointProvider implements ResourcesEndpointProvider { private final URI endpoint; private final String metadataToken; private DefaultEndpointProvider(URI endpoint, String metadataToken) { this.endpoint = endpoint; this.metadataToken = metadataToken; } @Override public URI endpoint() { return endpoint; } @Override public Map<String, String> headers() { Map<String, String> requestHeaders = new HashMap<>(); requestHeaders.put("User-Agent", SdkUserAgent.create().userAgent()); requestHeaders.put("Accept", "*/*"); requestHeaders.put("Connection", "keep-alive"); if (metadataToken != null) { requestHeaders.put(EC2_METADATA_TOKEN_HEADER, metadataToken); } return requestHeaders; } } public static class InstanceInfo { private final String pendingTime; private final String instanceType; private final String imageId; private final String instanceId; private final String[] billingProducts; private final String architecture; private final String accountId; private final String kernelId; private final String ramdiskId; private final String region; private final String version; private final String availabilityZone; private final String privateIp; private final String[] devpayProductCodes; private final String[] marketplaceProductCodes; public InstanceInfo( String pendingTime, String instanceType, String imageId, String instanceId, String[] billingProducts, String architecture, String accountId, String kernelId, String ramdiskId, String region, String version, String availabilityZone, String privateIp, String[] devpayProductCodes, String[] marketplaceProductCodes) { this.pendingTime = pendingTime; this.instanceType = instanceType; this.imageId = imageId; this.instanceId = instanceId; this.billingProducts = billingProducts == null ? null : billingProducts.clone(); this.architecture = architecture; this.accountId = accountId; this.kernelId = kernelId; this.ramdiskId = ramdiskId; this.region = region; this.version = version; this.availabilityZone = availabilityZone; this.privateIp = privateIp; this.devpayProductCodes = devpayProductCodes == null ? null : devpayProductCodes.clone(); this.marketplaceProductCodes = marketplaceProductCodes == null ? null : marketplaceProductCodes.clone(); } public String getPendingTime() { return pendingTime; } public String getInstanceType() { return instanceType; } public String getImageId() { return imageId; } public String getInstanceId() { return instanceId; } public String[] getBillingProducts() { return billingProducts == null ? null : billingProducts.clone(); } public String getArchitecture() { return architecture; } public String getAccountId() { return accountId; } public String getKernelId() { return kernelId; } public String getRamdiskId() { return ramdiskId; } public String getRegion() { return region; } public String getVersion() { return version; } public String getAvailabilityZone() { return availabilityZone; } public String getPrivateIp() { return privateIp; } public String[] getDevpayProductCodes() { return devpayProductCodes == null ? null : devpayProductCodes.clone(); } public String[] getMarketplaceProductCodes() { return marketplaceProductCodes == null ? null : marketplaceProductCodes.clone(); } } }
1,339
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal/util/ServiceMetadataUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal.util; import java.net.URI; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.regions.PartitionEndpointKey; import software.amazon.awssdk.regions.PartitionMetadata; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.ServiceEndpointKey; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.StringUtils; import software.amazon.awssdk.utils.Validate; @SdkInternalApi public class ServiceMetadataUtils { private static final String[] SEARCH_LIST = {"{service}", "{region}", "{dnsSuffix}" }; private ServiceMetadataUtils() { } public static URI endpointFor(String hostname, String endpointPrefix, String region, String dnsSuffix) { return URI.create(StringUtils.replaceEach(hostname, SEARCH_LIST, new String[] { endpointPrefix, region, dnsSuffix })); } public static Region signingRegion(ServiceEndpointKey key, Map<ServiceEndpointKey, String> signingRegionsByRegion, Map<Pair<String, PartitionEndpointKey>, String> signingRegionsByPartition) { String region = signingRegionsByRegion.get(key); if (region == null) { region = signingRegionsByPartition.get(partitionKey(key)); } return region != null ? Region.of(region) : key.region(); } public static String dnsSuffix(ServiceEndpointKey key, Map<ServiceEndpointKey, String> dnsSuffixesByRegion, Map<Pair<String, PartitionEndpointKey>, String> dnsSuffixesByPartition) { String dnsSuffix = dnsSuffixesByRegion.get(key); if (dnsSuffix == null) { dnsSuffix = dnsSuffixesByPartition.get(partitionKey(key)); } if (dnsSuffix == null) { dnsSuffix = PartitionMetadata.of(key.region()) .dnsSuffix(PartitionEndpointKey.builder().tags(key.tags()).build()); } Validate.notNull(dnsSuffix, "No endpoint known for " + key.tags() + " in " + key.region() + " with this service. " + "A newer SDK version may have an endpoint available, or you could configure the endpoint directly " + "after consulting service documentation."); return dnsSuffix; } public static String hostname(ServiceEndpointKey key, Map<ServiceEndpointKey, String> hostnamesByRegion, Map<Pair<String, PartitionEndpointKey>, String> hostnamesByPartition) { String hostname = hostnamesByRegion.get(key); if (hostname == null) { hostname = hostnamesByPartition.get(partitionKey(key)); } if (hostname == null) { hostname = PartitionMetadata.of(key.region()) .hostname(PartitionEndpointKey.builder().tags(key.tags()).build()); } Validate.notNull(hostname, "No endpoint known for " + key.tags() + " in " + key.region() + " with this service. " + "A newer SDK version may have an endpoint available, or you could configure the endpoint directly " + "after consulting service documentation."); return hostname; } public static Pair<String, PartitionEndpointKey> partitionKey(ServiceEndpointKey key) { return Pair.of(PartitionMetadata.of(key.region()).id(), PartitionEndpointKey.builder().tags(key.tags()).build()); } }
1,340
0
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal
Create_ds/aws-sdk-java-v2/core/regions/src/main/java/software/amazon/awssdk/regions/internal/util/InstanceProviderTokenEndpointProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.regions.internal.util; import java.net.URI; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.util.SdkUserAgent; import software.amazon.awssdk.regions.util.ResourcesEndpointProvider; @SdkInternalApi public final class InstanceProviderTokenEndpointProvider implements ResourcesEndpointProvider { private static final String TOKEN_RESOURCE_PATH = "/latest/api/token"; private static final String EC2_METADATA_TOKEN_TTL_HEADER = "x-aws-ec2-metadata-token-ttl-seconds"; private static final String DEFAULT_TOKEN_TTL = "21600"; private static final Ec2MetadataConfigProvider EC2_METADATA_CONFIG_PROVIDER = Ec2MetadataConfigProvider.builder() .build(); @Override public URI endpoint() { String host = EC2_METADATA_CONFIG_PROVIDER.getEndpoint(); if (host.endsWith("/")) { host = host.substring(0, host.length() - 1); } return URI.create(host + TOKEN_RESOURCE_PATH); } @Override public Map<String, String> headers() { Map<String, String> requestHeaders = new HashMap<>(); requestHeaders.put("User-Agent", SdkUserAgent.create().userAgent()); requestHeaders.put("Accept", "*/*"); requestHeaders.put("Connection", "keep-alive"); requestHeaders.put(EC2_METADATA_TOKEN_TTL_HEADER, DEFAULT_TOKEN_TTL); return requestHeaders; } }
1,341
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/EndpointModeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; /** * Unit Tests to test the EndpointMode enum functionality. */ class EndpointModeTest { @Test void verifyFromValue_when_nullParameterIsPassed(){ assertThat(EndpointMode.fromValue(null)).isEqualTo(null); } @Test void verifyFromValue_when_normalParameterIsPassed(){ assertThat(EndpointMode.fromValue("ipv4")).isEqualTo(EndpointMode.IPV4); } @Test void verifyFromValue_when_wrongParameterIsPassed(){ assertThatThrownBy(() -> { EndpointMode.fromValue("ipv8"); }).hasMessageContaining("Unrecognized value for endpoint mode") .isInstanceOf(IllegalArgumentException.class); } }
1,342
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/Ec2MetadataRetryPolicyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; class Ec2MetadataRetryPolicyTest { @Test void equals_hashCode() { BackoffStrategy backoffStrategy = BackoffStrategy.defaultStrategy(); Ec2MetadataRetryPolicy policy = Ec2MetadataRetryPolicy.builder() .numRetries(3) .backoffStrategy(backoffStrategy) .build(); assertThat(policy).isEqualTo(Ec2MetadataRetryPolicy.builder() .numRetries(3) .backoffStrategy(backoffStrategy) .build()); } @Test void builder_setNumRetriesCorrectly() { Ec2MetadataRetryPolicy policy = Ec2MetadataRetryPolicy.builder() .numRetries(3) .build(); assertThat(policy.numRetries()).isEqualTo(3); } }
1,343
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/TestConstants.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; public class TestConstants { public static final String TOKEN_RESOURCE_PATH = "/latest/api/token"; public static final String TOKEN_HEADER = "x-aws-ec2-metadata-token"; public static final String EC2_METADATA_TOKEN_TTL_HEADER = "x-aws-ec2-metadata-token-ttl-seconds"; public static final String EC2_METADATA_ROOT = "/latest/meta-data"; public static final String AMI_ID_RESOURCE = EC2_METADATA_ROOT + "/ami-id"; }
1,344
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/Ec2MetadataResponseTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.thirdparty.jackson.core.JsonParseException; /** * The class tests the utility methods provided by MetadataResponse Class . */ class Ec2MetadataResponseTest { @Test void check_asString_success() { String response = "foobar"; Ec2MetadataResponse metadataResponse = Ec2MetadataResponse.create(response); String result = metadataResponse.asString(); assertThat(result).isEqualTo(response); } @Test void check_asString_failure() { assertThatThrownBy(() -> Ec2MetadataResponse.create(null)).isInstanceOf(NullPointerException.class); } @Test void check_asList_success_with_delimiter() { String response = "sai\ntest"; Ec2MetadataResponse metadataResponse = Ec2MetadataResponse.create(response); List<String> result = metadataResponse.asList(); assertThat(result).hasSize(2); } @Test void check_asList_success_without_delimiter() { String response = "test1-test2"; Ec2MetadataResponse metadataResponse = Ec2MetadataResponse.create(response); List<String> result = metadataResponse.asList(); assertThat(result).hasSize(1); } @Test void check_asDocument_success() { String jsonResponse = "{" + "\"instanceType\":\"m1.small\"," + "\"devpayProductCodes\":[\"bar\",\"foo\"]" + "}"; Ec2MetadataResponse metadataResponse = Ec2MetadataResponse.create(jsonResponse); Document document = metadataResponse.asDocument(); Map<String, Document> expectedMap = new LinkedHashMap<>(); List<Document> documentList = new ArrayList<>(); documentList.add(Document.fromString("bar")); documentList.add(Document.fromString("foo")); expectedMap.put("instanceType", Document.fromString("m1.small")); expectedMap.put("devpayProductCodes", Document.fromList(documentList)); Document expectedDocumentMap = Document.fromMap(expectedMap); assertThat(document).isEqualTo(expectedDocumentMap); } @Test void toDocument_nonJsonFormat_ExpectIllegalArgument() { String malformed = "this is not json"; Ec2MetadataResponse metadataResponse = Ec2MetadataResponse.create(malformed); assertThatThrownBy(metadataResponse::asDocument).getCause().isInstanceOf(JsonParseException.class); } @Test void equals_hasCode() { Ec2MetadataResponse metadataResponse = Ec2MetadataResponse.create("Line 1"); assertThat(metadataResponse).isEqualTo(Ec2MetadataResponse.create("Line 1")) .hasSameHashCodeAs("Line 1"); assertThat(metadataResponse.equals(null)).isFalse(); } }
1,345
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/EndpointProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.params.provider.Arguments.arguments; import static software.amazon.awssdk.imds.EndpointMode.IPV4; import static software.amazon.awssdk.imds.EndpointMode.IPV6; import java.net.URISyntaxException; import java.nio.file.Paths; import java.util.stream.Stream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.imds.EndpointMode; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.internal.SystemSettingUtilsTestBackdoor; /** * Test Class to test the endpoint resolution functionality. */ class EndpointProviderTest { @AfterEach void reset() { System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.property()); System.clearProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property()); SystemSettingUtilsTestBackdoor.clearEnvironmentVariableOverrides(); } private static Stream<Arguments> provideEndpointAndEndpointModes() { String testIpv4Url = "http://90:90:90:90"; String testIpv6Url = "http://[9876:ec2::123]"; return Stream.of( arguments(null, true, testIpv4Url, true, "testIPv6", testIpv4Url), arguments(null, true, testIpv6Url, true, "testIPv4", testIpv6Url), arguments(null, true, testIpv4Url, false, "testIPv6", testIpv4Url), arguments(null, true, testIpv6Url, false, "testIPv4", testIpv6Url), arguments(null, false, "unused", true, "testIPv6", "[1234:ec2::456]"), arguments(null, false, "unused", true, "testIPv4", "http://42.42.42.42"), arguments(IPV4, false, "unused", false, "unused", "http://169.254.169.254"), arguments(IPV6, false, "unused", false, "unused", "http://[fd00:ec2::254]") ); } @ParameterizedTest @MethodSource("provideEndpointAndEndpointModes") void validateResolveEndpoint(EndpointMode endpointMode, boolean setEnvVariable, String envEndpoint, boolean setConfigFile, String profile, String expectedValue) throws URISyntaxException { if (setEnvVariable) { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.property(), envEndpoint); } if (setConfigFile) { String testFile = "/profile-config/test-profiles.tst"; SystemSettingUtilsTestBackdoor.addEnvironmentVariableOverride( ProfileFileSystemSetting.AWS_PROFILE.environmentVariable(), profile); SystemSettingUtilsTestBackdoor.addEnvironmentVariableOverride( ProfileFileSystemSetting.AWS_CONFIG_FILE.environmentVariable(), Paths.get(getClass().getResource(testFile).toURI()).toString()); } Ec2MetadataEndpointProvider endpointProvider = Ec2MetadataEndpointProvider.builder().build(); String endpoint = endpointProvider.resolveEndpoint(endpointMode); assertThat(endpoint).isEqualTo(expectedValue); } private static Stream<Arguments> provideEndpointModes() { return Stream.of( arguments(false, "unused", false, "unused", IPV4), arguments(true, "IPv4", true, "IPv4", IPV4), arguments(true, "IPv6", true, "IPv6", IPV6), arguments(true, "IPv6", true, "IPv4", IPV6), arguments(true, "IPv4", true, "IPv6", IPV4), arguments(false, "unused", true, "IPv6", IPV6), arguments(false, "unused", true, "IPv4", IPV4), arguments(true, "IPv6", false, "unused", IPV6), arguments(true, "IPv4", false, "unused", IPV4) ); } @ParameterizedTest @MethodSource("provideEndpointModes") void endpointModeCheck(boolean useEnvVariable, String envVarValue, boolean useConfigFile, String configFileValue, EndpointMode expectedValue) throws URISyntaxException { if (useEnvVariable) { System.setProperty(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.property(), envVarValue); } if (useConfigFile) { String testFile = "/profile-config/test-profiles.tst"; SystemSettingUtilsTestBackdoor.addEnvironmentVariableOverride( ProfileFileSystemSetting.AWS_PROFILE.environmentVariable(), "test" + configFileValue); SystemSettingUtilsTestBackdoor.addEnvironmentVariableOverride( ProfileFileSystemSetting.AWS_CONFIG_FILE.environmentVariable(), Paths.get(getClass().getResource(testFile).toURI()).toString()); } Ec2MetadataEndpointProvider endpointProvider = Ec2MetadataEndpointProvider.builder().build(); EndpointMode endpointMode = endpointProvider.resolveEndpointMode(); assertThat(endpointMode).isEqualTo(expectedValue); } @Test void endpointFromBuilder_withIpv4_shouldBesetCorrectly() { ProfileFile.Builder content = ProfileFile.builder() .type(ProfileFile.Type.CONFIGURATION) .content(Paths.get("src/test/resources/profile-config/test-profiles.tst")); Ec2MetadataEndpointProvider provider = Ec2MetadataEndpointProvider.builder() .profileFile(content::build) .profileName("testIPv4") .build(); assertThat(provider.resolveEndpointMode()).isEqualTo(IPV4); assertThat(provider.resolveEndpoint(IPV4)).isEqualTo("http://42.42.42.42"); } @Test void endpointFromBuilder_withIpv6_shouldBesetCorrectly() { ProfileFile.Builder content = ProfileFile.builder() .type(ProfileFile.Type.CONFIGURATION) .content(Paths.get("src/test/resources/profile-config/test-profiles.tst")); Ec2MetadataEndpointProvider provider = Ec2MetadataEndpointProvider.builder() .profileFile(content::build) .profileName("testIPv6") .build(); assertThat(provider.resolveEndpointMode()).isEqualTo(IPV6); assertThat(provider.resolveEndpoint(IPV6)).isEqualTo("[1234:ec2::456]"); } }
1,346
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/LargeAsyncRequestTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.exactly; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.imds.TestConstants.AMI_ID_RESOURCE; import static software.amazon.awssdk.imds.TestConstants.EC2_METADATA_TOKEN_TTL_HEADER; import static software.amazon.awssdk.imds.TestConstants.TOKEN_HEADER; import static software.amazon.awssdk.imds.TestConstants.TOKEN_RESOURCE_PATH; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.imds.Ec2MetadataAsyncClient; import software.amazon.awssdk.imds.Ec2MetadataResponse; @WireMockTest class LargeAsyncRequestTest { private int port; @BeforeEach public void init(WireMockRuntimeInfo wiremock) { this.port = wiremock.getHttpPort(); } @Test void largeRequestTest() throws Exception { int size = 10 * 1024 * 1024; // 10MB byte[] bytes = new byte[size]; for (int i = 0; i < size; i++) { bytes[i] = (byte) (i % 128); } String ec2MetadataContent = new String(bytes, StandardCharsets.US_ASCII); stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody(ec2MetadataContent))); try (Ec2MetadataAsyncClient client = Ec2MetadataAsyncClient.builder() .endpoint(URI.create("http://localhost:" + port)) .httpClient(NettyNioAsyncHttpClient.builder().readTimeout(Duration.ofSeconds(30)).build()) .build()) { CompletableFuture<Ec2MetadataResponse> res = client.get(AMI_ID_RESOURCE); Ec2MetadataResponse response = res.get(); assertThat(response.asString()).hasSize(size); assertThat(response.asString()).isEqualTo(ec2MetadataContent); verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(1), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); } } }
1,347
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/Ec2MetadataAsyncClientTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.catchThrowable; import static org.junit.jupiter.api.Assertions.fail; import static software.amazon.awssdk.imds.TestConstants.AMI_ID_RESOURCE; import static software.amazon.awssdk.imds.TestConstants.EC2_METADATA_TOKEN_TTL_HEADER; import static software.amazon.awssdk.imds.TestConstants.TOKEN_RESOURCE_PATH; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.net.URI; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.internal.http.loader.DefaultSdkAsyncHttpClientBuilder; import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient; import software.amazon.awssdk.imds.Ec2MetadataAsyncClient; import software.amazon.awssdk.imds.Ec2MetadataResponse; @WireMockTest class Ec2MetadataAsyncClientTest extends BaseEc2MetadataClientTest<Ec2MetadataAsyncClient, Ec2MetadataAsyncClient.Builder> { private Ec2MetadataAsyncClient client; private int port; @BeforeEach public void init(WireMockRuntimeInfo wiremock) { this.port = wiremock.getHttpPort(); this.client = Ec2MetadataAsyncClient.builder() .endpoint(URI.create("http://localhost:" + wiremock.getHttpPort())) .build(); } @Override protected int getPort() { return port; } @Override protected BaseEc2MetadataClient overrideClient(Consumer<Ec2MetadataAsyncClient.Builder> builderConsumer) { Ec2MetadataAsyncClient.Builder builder = Ec2MetadataAsyncClient.builder(); builderConsumer.accept(builder); this.client = builder.build(); return (BaseEc2MetadataClient) this.client; } @Override protected void successAssertions(String path, Consumer<Ec2MetadataResponse> assertions) { CompletableFuture<Ec2MetadataResponse> response = client.get(path); try { assertions.accept(response.join()); } catch (Exception e) { fail("unexpected error while exeucting tests", e); } } @Override @SuppressWarnings("unchecked") // safe because of assertion: assertThat(ex).getCause().isInstanceOf(exceptionType); protected <T extends Throwable> void failureAssertions(String path, Class<T> exceptionType, Consumer<T> assertions) { CompletableFuture<Ec2MetadataResponse> future = client.get(path); Throwable ex = catchThrowable(future::join); assertThat(future).isCompletedExceptionally(); assertThat(ex).getCause().isInstanceOf(exceptionType); assertions.accept((T) ex.getCause()); } @Test void get_cancelResponseFuture_shouldCancelHttpRequest() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withFixedDelay(1000))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn( aResponse().withBody("some-content").withFixedDelay(1000))); CompletableFuture<Ec2MetadataResponse> responseFuture = client.get(AMI_ID_RESOURCE); try { responseFuture.cancel(true); responseFuture.join(); } catch (CancellationException e) { // ignore java.util.concurrent.CancellationException } verify(0, getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE))); } @Test void builder_httpClientWithDefaultBuilder_shouldBuildProperly() { Ec2MetadataAsyncClient buildClient = Ec2MetadataAsyncClient.builder() .httpClient(new DefaultSdkAsyncHttpClientBuilder()) .endpoint(URI.create("http://localhost:" + port)) .build(); stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("some-value"))); CompletableFuture<Ec2MetadataResponse> responseFuture = buildClient.get(AMI_ID_RESOURCE); Ec2MetadataResponse response = responseFuture.join(); assertThat(response.asString()).isEqualTo("some-value"); } @Test void builder_httpClientAndHttpBuilder_shouldThrowException() { assertThatThrownBy(() -> Ec2MetadataAsyncClient.builder() .httpClient(new DefaultSdkAsyncHttpClientBuilder()) .httpClient(NettyNioAsyncHttpClient.create()) .build()) .isInstanceOf(IllegalArgumentException.class); } }
1,348
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/BaseEc2MetadataClientTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.exactly; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static com.github.tomakehurst.wiremock.stubbing.Scenario.STARTED; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.params.provider.Arguments.arguments; import static software.amazon.awssdk.imds.EndpointMode.IPV4; import static software.amazon.awssdk.imds.EndpointMode.IPV6; import static software.amazon.awssdk.imds.TestConstants.AMI_ID_RESOURCE; import static software.amazon.awssdk.imds.TestConstants.EC2_METADATA_TOKEN_TTL_HEADER; import static software.amazon.awssdk.imds.TestConstants.TOKEN_HEADER; import static software.amazon.awssdk.imds.TestConstants.TOKEN_RESOURCE_PATH; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.net.URI; import java.time.Duration; import java.util.function.Consumer; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; import software.amazon.awssdk.imds.Ec2MetadataClientBuilder; import software.amazon.awssdk.imds.Ec2MetadataResponse; import software.amazon.awssdk.imds.Ec2MetadataRetryPolicy; import software.amazon.awssdk.imds.EndpointMode; @WireMockTest abstract class BaseEc2MetadataClientTest<T, B extends Ec2MetadataClientBuilder<B, T>> { protected static final int DEFAULT_TOTAL_ATTEMPTS = 4; protected abstract BaseEc2MetadataClient overrideClient(Consumer<B> builderConsumer); protected abstract void successAssertions(String path, Consumer<Ec2MetadataResponse> assertions); protected abstract <T extends Throwable> void failureAssertions(String path, Class<T> exceptionType, Consumer<T> assertions); protected abstract int getPort(); @Test void get_successOnFirstTry_shouldNotRetryAndSucceed() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); successAssertions(AMI_ID_RESOURCE, response -> { assertThat(response.asString()).isEqualTo("{}"); verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(1), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void get_failsEverytime_shouldRetryAndFails() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withStatus(500).withBody("Error 500"))); failureAssertions(AMI_ID_RESOURCE, SdkClientException.class, ex -> { verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(DEFAULT_TOTAL_ATTEMPTS), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void get_returnsStatus4XX_shouldFailsAndNotRetry() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withStatus(400).withBody("error"))); failureAssertions(AMI_ID_RESOURCE, SdkClientException.class, ex -> { verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(1), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void get_failsOnceThenSucceed_withCustomClient_shouldSucceed() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)) .inScenario("Retry Scenario") .whenScenarioStateIs(STARTED) .willReturn(aResponse().withStatus(500).withBody("Error 500")) .willSetStateTo("Cause Success")); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)) .inScenario("Retry Scenario") .whenScenarioStateIs("Cause Success") .willReturn(aResponse().withBody("{}"))); overrideClient(builder -> builder .retryPolicy(Ec2MetadataRetryPolicy.builder() .numRetries(5) .backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofMillis(300))) .build()) .endpoint(URI.create("http://localhost:" + getPort())) .tokenTtl(Duration.ofSeconds(1024))); successAssertions(AMI_ID_RESOURCE, response -> { assertThat(response.asString()).isEqualTo("{}"); verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("1024"))); verify(exactly(2), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void getToken_failsEverytime_shouldRetryAndFailsAndNotCallService() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(500).withBody("Error 500"))); failureAssertions(AMI_ID_RESOURCE, SdkClientException.class, ex -> { verify(exactly(DEFAULT_TOTAL_ATTEMPTS), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(0), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void getToken_returnsStatus4XX_shouldFailsAndNotRetry() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withStatus(400).withBody("ERROR 400"))); failureAssertions(AMI_ID_RESOURCE, SdkClientException.class, ex -> { verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(0), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void getToken_failsOnceThenSucceed_withCustomClient_shouldSucceed() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).inScenario("Retry Scenario") .whenScenarioStateIs(STARTED) .willReturn(aResponse().withStatus(500).withBody("Error 500")) .willSetStateTo("Cause Success")); stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).inScenario("Retry Scenario") .whenScenarioStateIs("Cause Success") .willReturn( aResponse() .withBody("some-token") .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).inScenario("Retry Scenario") .whenScenarioStateIs("Cause Success") .willReturn(aResponse().withBody("Success"))); overrideClient(builder -> builder .retryPolicy(Ec2MetadataRetryPolicy.builder() .numRetries(5) .backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofMillis(300))) .build()) .endpoint(URI.create("http://localhost:" + getPort())) .build()); successAssertions(AMI_ID_RESOURCE, response -> { assertThat(response.asString()).isEqualTo("Success"); verify(exactly(2), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(1), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void get_noRetries_shouldNotRetry() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withStatus(500).withBody("Error 500"))); overrideClient(builder -> builder .endpoint(URI.create("http://localhost:" + getPort())) .retryPolicy(Ec2MetadataRetryPolicy.none()).build()); failureAssertions(AMI_ID_RESOURCE, SdkClientException.class, ex -> { verify(1, putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(1, putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); }); } @Test void builder_endpointAndEndpointModeSpecified_shouldThrowIllegalArgException() { assertThatThrownBy(() -> overrideClient(builder -> builder .endpoint(URI.create("http://localhost:" + getPort())) .endpointMode(IPV6))) .isInstanceOf(IllegalArgumentException.class); } @Test void builder_defaultValue_clientShouldUseIPV4Endpoint() { BaseEc2MetadataClient client = overrideClient(builder -> { }); assertThat(client.endpoint).hasToString("http://169.254.169.254"); } @Test void builder_setEndpoint_shouldUseEndpoint() { BaseEc2MetadataClient client = overrideClient(builder -> builder.endpoint(URI.create("http://localhost:" + 12312))); assertThat(client.endpoint).hasToString("http://localhost:" + 12312); } @ParameterizedTest @MethodSource("endpointArgumentSource") void builder_setEndPointMode_shouldUseEndpointModeValue(EndpointMode endpointMode, String value) { BaseEc2MetadataClient client = overrideClient(builder -> builder.endpointMode(endpointMode)); assertThat(client.endpoint).hasToString(value); } private static Stream<Arguments> endpointArgumentSource() { return Stream.of( arguments(IPV4, "http://169.254.169.254"), arguments(IPV6, "http://[fd00:ec2::254]")); } @Test void get_tokenExpiresWhileRetrying_shouldSucceedWithNewToken() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "2"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).inScenario("Retry Scenario") .whenScenarioStateIs(STARTED) .willReturn(aResponse().withStatus(500) .withBody("Error 500") .withFixedDelay(700)) .willSetStateTo("Retry-1")); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).inScenario("Retry Scenario") .whenScenarioStateIs("Retry-1") .willReturn(aResponse().withStatus(500) .withBody("Error 500") .withFixedDelay(700)) .willSetStateTo("Retry-2")); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).inScenario("Retry Scenario") .whenScenarioStateIs("Retry-2") .willReturn(aResponse().withStatus(500) .withBody("Error 500") .withFixedDelay(700)) .willSetStateTo("Retry-3")); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).inScenario("Retry Scenario") .whenScenarioStateIs("Retry-3") .willReturn(aResponse().withStatus(200) .withBody("Success") .withFixedDelay(700))); overrideClient(builder -> builder .tokenTtl(Duration.ofSeconds(2)) .endpoint(URI.create("http://localhost:" + getPort())) .build()); successAssertions(AMI_ID_RESOURCE, response -> { assertThat(response.asString()).isEqualTo("Success"); verify(exactly(2), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("2"))); verify(exactly(4), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void getToken_responseWithoutTtlHeaders_shouldFailAndNotRetry() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token"))); // no EC2_METADATA_TOKEN_TTL_HEADER header stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withStatus(200).withBody("some-value"))); failureAssertions(AMI_ID_RESOURCE, SdkClientException.class, e -> { verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(0), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } @Test void getToken_responseTtlHeadersNotANumber_shouldFailAndNotRetry() { stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn(aResponse().withBody("some-token"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withStatus(200).withBody("some-value"))); stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "not-a-number"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withStatus(200).withBody("some-value"))); failureAssertions(AMI_ID_RESOURCE, SdkClientException.class, e -> { verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(0), getRequestedFor(urlPathEqualTo(AMI_ID_RESOURCE)) .withHeader(TOKEN_HEADER, equalTo("some-token"))); }); } }
1,349
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/MultipleAsyncRequestsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.exactly; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.imds.TestConstants.AMI_ID_RESOURCE; import static software.amazon.awssdk.imds.TestConstants.EC2_METADATA_TOKEN_TTL_HEADER; import static software.amazon.awssdk.imds.TestConstants.TOKEN_HEADER; import static software.amazon.awssdk.imds.TestConstants.TOKEN_RESOURCE_PATH; import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.net.URI; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.imds.Ec2MetadataAsyncClient; import software.amazon.awssdk.imds.Ec2MetadataResponse; @WireMockTest class MultipleAsyncRequestsTest { private int port; @BeforeEach public void init(WireMockRuntimeInfo wiremock) { this.port = wiremock.getHttpPort(); } @Test void multipleRequests() { int totalRequests = 128; String tokenValue = "some-token"; stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody(tokenValue).withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); for (int i = 0; i < totalRequests; i++) { ResponseDefinitionBuilder responseStub = aResponse().withStatus(200).withBody("response::" + i); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE + "/" + i)).willReturn(responseStub)); } Ec2MetadataAsyncClient client = Ec2MetadataAsyncClient.builder() .endpoint(URI.create("http://localhost:" + this.port)) .build(); List<CompletableFuture<Ec2MetadataResponse>> requests = Stream.iterate(0, x -> x + 1) .map(i -> client.get(AMI_ID_RESOURCE + "/" + i)) .limit(totalRequests) .collect(Collectors.toList()); CompletableFuture<List<Ec2MetadataResponse>> responses = CompletableFuture .allOf(requests.toArray(new CompletableFuture[0])) .thenApply(unusedVoid -> requests.stream() .map(CompletableFuture::join) .collect(Collectors.toList())); List<Ec2MetadataResponse> resolvedResponses = responses.join(); for (int i = 0; i < totalRequests; i++) { Ec2MetadataResponse response = resolvedResponses.get(i); assertThat(response.asString()).isEqualTo("response::" + i); } verify(exactly(1), putRequestedFor(urlPathEqualTo(TOKEN_RESOURCE_PATH)) .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, equalTo("21600"))); verify(exactly(totalRequests), getRequestedFor(urlPathMatching(AMI_ID_RESOURCE + "/" + "\\d+")) .withHeader(TOKEN_HEADER, equalTo(tokenValue))); } }
1,350
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/Ec2MetadataClientTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.catchThrowable; import static software.amazon.awssdk.imds.TestConstants.AMI_ID_RESOURCE; import static software.amazon.awssdk.imds.TestConstants.EC2_METADATA_TOKEN_TTL_HEADER; import static software.amazon.awssdk.imds.TestConstants.TOKEN_RESOURCE_PATH; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.net.URI; import java.util.function.Consumer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.internal.http.loader.DefaultSdkHttpClientBuilder; import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; import software.amazon.awssdk.imds.Ec2MetadataClient; import software.amazon.awssdk.imds.Ec2MetadataResponse; @WireMockTest class Ec2MetadataClientTest extends BaseEc2MetadataClientTest<Ec2MetadataClient, Ec2MetadataClient.Builder> { private Ec2MetadataClient client; private int port; @BeforeEach public void init(WireMockRuntimeInfo wiremock) { this.port = wiremock.getHttpPort(); this.client = Ec2MetadataClient.builder() .endpoint(URI.create("http://localhost:" + wiremock.getHttpPort())) .build(); } @Override protected int getPort() { return port; } @Override protected BaseEc2MetadataClient overrideClient(Consumer<Ec2MetadataClient.Builder> builderConsumer) { Ec2MetadataClient.Builder builder = Ec2MetadataClient.builder(); builderConsumer.accept(builder); this.client = builder.build(); return (BaseEc2MetadataClient) this.client; } @Override protected void successAssertions(String path, Consumer<Ec2MetadataResponse> assertions) { Ec2MetadataResponse response = client.get(path); assertions.accept(response); } @Override @SuppressWarnings("unchecked") // safe because of assertion: assertThat(ex).isInstanceOf(exceptionType); protected <T extends Throwable> void failureAssertions(String path, Class<T> exceptionType, Consumer<T> assertions) { Throwable ex = catchThrowable(() -> client.get(path)); assertThat(ex).isInstanceOf(exceptionType); assertions.accept((T) ex); } @Test void builder_httpClientWithDefaultBuilder_shouldBuildProperly() { Ec2MetadataClient buildClient = Ec2MetadataClient.builder() .httpClient(new DefaultSdkHttpClientBuilder()) .endpoint(URI.create("http://localhost:" + port)) .build(); stubFor(put(urlPathEqualTo(TOKEN_RESOURCE_PATH)).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo(AMI_ID_RESOURCE)).willReturn(aResponse().withBody("{}"))); Ec2MetadataResponse response = buildClient.get(AMI_ID_RESOURCE); assertThat(response.asString()).isEqualTo("{}"); } @Test void builder_httpClientAndHttpBuilder_shouldThrowException() { assertThatThrownBy(() -> Ec2MetadataClient.builder() .httpClient(new DefaultSdkHttpClientBuilder()) .httpClient(UrlConnectionHttpClient.create()) .build()) .isInstanceOf(IllegalArgumentException.class); } }
1,351
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/CachedTokenClientTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.exactly; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static com.github.tomakehurst.wiremock.stubbing.Scenario.STARTED; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static software.amazon.awssdk.imds.TestConstants.EC2_METADATA_TOKEN_TTL_HEADER; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.time.Duration; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.ExecutableHttpRequest; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.http.SdkHttpResponse; import software.amazon.awssdk.imds.Ec2MetadataClient; import software.amazon.awssdk.imds.Ec2MetadataResponse; @WireMockTest class CachedTokenClientTest { private Ec2MetadataClient.Builder clientBuilder; @BeforeEach void init(WireMockRuntimeInfo wmRuntimeInfo) { this.clientBuilder = Ec2MetadataClient.builder() .endpoint(URI.create("http://localhost:" + wmRuntimeInfo.getHttpPort())); } @AfterEach void tearDown(WireMockRuntimeInfo wmRuntimeInfo) { wmRuntimeInfo.getWireMock().resetMappings(); } @Test void get_tokenFailsError4xx_shouldNotRetry() throws IOException { SdkHttpClient mockClient = mock(SdkHttpClient.class); ExecutableHttpRequest mockRequest = mock(ExecutableHttpRequest.class); when(mockClient.prepareRequest(any(HttpExecuteRequest.class))).thenReturn(mockRequest); AbortableInputStream content = AbortableInputStream.create(new ByteArrayInputStream("ERROR 400".getBytes(StandardCharsets.UTF_8))); SdkHttpResponse httpResponse = SdkHttpFullResponse.builder() .statusCode(400) .build(); HttpExecuteResponse executeResponse = HttpExecuteResponse.builder() .response(httpResponse) .responseBody(content) .build(); when(mockRequest.call()).thenReturn(executeResponse); Ec2MetadataClient imdsClient = Ec2MetadataClient.builder().httpClient(mockClient).build(); assertThatThrownBy(() ->imdsClient.get("/latest/meta-data/ami-id")).isInstanceOf(SdkClientException.class); ArgumentCaptor<HttpExecuteRequest> requestCaptor = ArgumentCaptor.forClass(HttpExecuteRequest.class); Mockito.verify(mockClient).prepareRequest(requestCaptor.capture()); SdkHttpRequest httpRequest = requestCaptor.getValue().httpRequest(); assertThat(httpRequest.encodedPath()).isEqualTo("/latest/api/token"); assertThat(httpRequest.firstMatchingHeader("x-aws-ec2-metadata-token-ttl-seconds").get()).isEqualTo("21600"); } @Test void getToken_failsError5xx_shouldRetryUntilMaxRetriesIsReached() { stubFor(put(urlPathEqualTo("/latest/api/token")).willReturn(aResponse().withStatus(500).withBody("ERROR 500"))); stubFor(get(urlPathEqualTo("/latest/meta-data/ami-id")).willReturn(aResponse().withBody("{}"))); assertThatThrownBy(() -> clientBuilder.build().get("/latest/meta-data/ami-id")).isInstanceOf(SdkClientException.class); verify(exactly(4), putRequestedFor(urlPathEqualTo("/latest/api/token")) .withHeader("x-aws-ec2-metadata-token-ttl-seconds", equalTo("21600"))); } @Test void getToken_failsThenSucceeds_doesCacheTokenThatSucceeds() { stubFor(put(urlPathEqualTo("/latest/api/token")).inScenario("Retry Scenario") .whenScenarioStateIs(STARTED) .willReturn(aResponse().withStatus(500).withBody("Error 500")) .willSetStateTo("Cause Success")); stubFor(put(urlPathEqualTo("/latest/api/token")).inScenario("Retry Scenario") .whenScenarioStateIs("Cause Success") .willReturn(aResponse() .withBody("token-ok") .withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo("/latest/meta-data/ami-id")).inScenario("Retry Scenario") .whenScenarioStateIs("Cause Success") .willReturn(aResponse().withBody("Success"))); // 3 requests Ec2MetadataClient client = clientBuilder.build(); Ec2MetadataResponse response = client.get("/latest/meta-data/ami-id"); assertThat(response.asString()).isEqualTo("Success"); response = client.get("/latest/meta-data/ami-id"); assertThat(response.asString()).isEqualTo("Success"); response = client.get("/latest/meta-data/ami-id"); assertThat(response.asString()).isEqualTo("Success"); verify(exactly(2), putRequestedFor(urlPathEqualTo("/latest/api/token")) .withHeader("x-aws-ec2-metadata-token-ttl-seconds", equalTo("21600"))); verify(exactly(3), getRequestedFor(urlPathEqualTo("/latest/meta-data/ami-id")) .withHeader("x-aws-ec2-metadata-token", equalTo("token-ok"))); } @Test void get_multipleCallsSuccess_shouldReuseToken() throws Exception { stubFor(put(urlPathEqualTo("/latest/api/token")).willReturn( aResponse().withBody("some-token").withHeader(EC2_METADATA_TOKEN_TTL_HEADER, "21600"))); stubFor(get(urlPathEqualTo("/latest/meta-data/ami-id")) .willReturn(aResponse().withBody("{}").withFixedDelay(800))); int tokenTTlSeconds = 4; Ec2MetadataClient client = clientBuilder.tokenTtl(Duration.ofSeconds(tokenTTlSeconds)).build(); int totalRequests = 10; for (int i = 0; i < totalRequests; i++) { Ec2MetadataResponse response = client.get("/latest/meta-data/ami-id"); assertThat(response.asString()).isEqualTo("{}"); } verify(exactly(2), putRequestedFor(urlPathEqualTo("/latest/api/token")) .withHeader("x-aws-ec2-metadata-token-ttl-seconds", equalTo(String.valueOf(tokenTTlSeconds)))); verify(exactly(totalRequests), getRequestedFor(urlPathEqualTo("/latest/meta-data/ami-id")) .withHeader("x-aws-ec2-metadata-token", equalTo("some-token"))); } }
1,352
0
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/unmarshall
Create_ds/aws-sdk-java-v2/core/imds/src/test/java/software/amazon/awssdk/imds/internal/unmarshall/document/DocumentUnmarshallerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal.unmarshall.document; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.math.BigDecimal; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkNumber; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.internal.EmbeddedObjectJsonNode; class DocumentUnmarshallerTest { @Test void testDocumentFromNumberNode() { JsonNode node = JsonNode.parser().parse("100"); assertThat(Document.fromNumber(SdkNumber.fromInteger(100)).asNumber().intValue()) .isEqualTo(node.visit(new DocumentUnmarshaller()).asNumber().intValue()); } @Test void testDocumentFromBoolean() { JsonNode node = JsonNode.parser().parse("true"); assertThat(Document.fromBoolean(true)).isEqualTo(node.visit(new DocumentUnmarshaller())); } @Test void testDocumentFromString() { JsonNode node = JsonNode.parser().parse("\"100.00\""); assertThat(Document.fromString("100.00")).isEqualTo(node.visit(new DocumentUnmarshaller())); } @Test void testDocumentFromNull() { JsonNode node = JsonNode.parser().parse("null"); assertThat(Document.fromNull()).isEqualTo(node.visit(new DocumentUnmarshaller())); } @Test void testExceptionIsThrownFromEmbededObjectType() { assertThatExceptionOfType(UnsupportedOperationException.class) .isThrownBy(() -> new EmbeddedObjectJsonNode(new Object()).visit(new DocumentUnmarshaller())); } @Test void testDocumentFromObjectNode(){ JsonNode node = JsonNode.parser().parse("{\"firstKey\": \"firstValue\", \"secondKey\": \"secondValue\"}"); Document documentMap = node.visit(new DocumentUnmarshaller()); Map<String, Document> expectedMap = new LinkedHashMap<>(); expectedMap.put("firstKey", Document.fromString("firstValue")); expectedMap.put("secondKey", Document.fromString("secondValue")); Document expectedDocumentMap = Document.fromMap(expectedMap); assertThat(documentMap).isEqualTo(expectedDocumentMap); } @Test void testDocumentFromArrayNode(){ JsonNode node = JsonNode.parser().parse("[\"One\", 10, true, null]"); List<Document> documentList = new ArrayList<>(); documentList.add(Document.fromString("One")); documentList.add(Document.fromNumber(SdkNumber.fromBigDecimal(BigDecimal.TEN))); documentList.add(Document.fromBoolean(true)); documentList.add(Document.fromNull()); Document document = Document.fromList(documentList); Document actualDocument = node.visit(new DocumentUnmarshaller()); assertThat(actualDocument).isEqualTo(document); } }
1,353
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/Ec2MetadataRetryPolicy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import java.util.Objects; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Interface for specifying a retry policy to use when evaluating whether or not a request should be retried, and the gap * between each retry. The {@link #builder()} can be used to construct a retry policy with numRetries and backoffStrategy. * <p> * When using the {@link #builder()} the SDK will use default values for fields that are not provided.A custom BackoffStrategy * can be used to construct a policy or a default {@link BackoffStrategy} is used. * * @see BackoffStrategy for a list of SDK provided backoff strategies */ @SdkPublicApi public final class Ec2MetadataRetryPolicy implements ToCopyableBuilder<Ec2MetadataRetryPolicy.Builder, Ec2MetadataRetryPolicy> { private static final int DEFAULT_RETRY_ATTEMPTS = 3; private final BackoffStrategy backoffStrategy; private final Integer numRetries; private Ec2MetadataRetryPolicy(BuilderImpl builder) { this.numRetries = Validate.getOrDefault(builder.numRetries, () -> DEFAULT_RETRY_ATTEMPTS); this.backoffStrategy = Validate.getOrDefault(builder.backoffStrategy, () -> BackoffStrategy.defaultStrategy(RetryMode.STANDARD)); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Ec2MetadataRetryPolicy ec2MetadataRetryPolicy = (Ec2MetadataRetryPolicy) obj; if (!Objects.equals(numRetries, ec2MetadataRetryPolicy.numRetries)) { return false; } return Objects.equals(backoffStrategy, ec2MetadataRetryPolicy.backoffStrategy); } @Override public int hashCode() { int result = Math.max(numRetries, 0); result = 31 * result + (backoffStrategy != null ? backoffStrategy.hashCode() : 0); return result; } @Override public String toString() { return "Ec2MetadataRetryPolicy{" + "backoffStrategy=" + backoffStrategy.toString() + ", numRetries=" + numRetries + '}'; } /** * Method to return the number of retries allowed. * @return The number of retries allowed. */ public int numRetries() { return numRetries; } /** * Method to return the BackoffStrategy used. * @return The backoff Strategy used. */ public BackoffStrategy backoffStrategy() { return backoffStrategy; } public static Builder builder() { return new BuilderImpl(); } @Override public Builder toBuilder() { return builder().numRetries(numRetries) .backoffStrategy(backoffStrategy); } public static Ec2MetadataRetryPolicy none() { return builder().numRetries(0).build(); } public interface Builder extends CopyableBuilder<Ec2MetadataRetryPolicy.Builder, Ec2MetadataRetryPolicy> { /** * Configure the backoff strategy that should be used for waiting in between retry attempts. */ Builder backoffStrategy(BackoffStrategy backoffStrategy); /** * Configure the maximum number of times that a single request should be retried, assuming it fails for a retryable error. */ Builder numRetries(Integer numRetries); } private static final class BuilderImpl implements Builder { private Integer numRetries; private BackoffStrategy backoffStrategy; private BuilderImpl() { } @Override public Builder numRetries(Integer numRetries) { this.numRetries = numRetries; return this; } @Override public Builder backoffStrategy(BackoffStrategy backoffStrategy) { this.backoffStrategy = backoffStrategy; return this; } @Override public Ec2MetadataRetryPolicy build() { return new Ec2MetadataRetryPolicy(this); } } }
1,354
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/EndpointMode.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import software.amazon.awssdk.annotations.SdkPublicApi; /** * Enum Class for the Endpoint Mode. */ @SdkPublicApi public enum EndpointMode { IPV4, IPV6; /** * Returns the appropriate EndpointMode Value after parsing the parameter. * @param s EndpointMode in String Format. * @return EndpointMode enumValue (IPV4 or IPV6). * @throws IllegalArgumentException Unrecognized value for endpoint mode. */ public static EndpointMode fromValue(String s) { if (s == null) { return null; } for (EndpointMode value : values()) { if (value.name().equalsIgnoreCase(s)) { return value; } } throw new IllegalArgumentException("Unrecognized value for endpoint mode: " + s); } }
1,355
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/Ec2MetadataResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import java.io.UncheckedIOException; import java.util.Arrays; import java.util.List; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.imds.internal.unmarshall.document.DocumentUnmarshaller; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser; import software.amazon.awssdk.thirdparty.jackson.core.JsonParseException; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * This class is used for response handling and parsing the metadata fetched by the get call in the {@link Ec2MetadataClient} * interface. It provides convenience methods to the users to parse the metadata as a String and List. Also provides * ways to parse the metadata as Document type if it is in the json format. */ @SdkPublicApi public final class Ec2MetadataResponse { private static final JsonNodeParser JSON_NODE_PARSER = JsonNode.parserBuilder().removeErrorLocations(true).build(); private final String body; private Ec2MetadataResponse(String body) { this.body = Validate.notNull(body, "Metadata is null"); } /** * Create a {@link Ec2MetadataResponse} with the given body as its content. * @param body the content of the response * @return a {@link Ec2MetadataResponse} with the given body as its content. */ public static Ec2MetadataResponse create(String body) { return new Ec2MetadataResponse(body); } /** * @return String Representation of the Metadata Response Body. */ public String asString() { return body; } /** * Splits the Metadata response body on new line character and returns it as a list. * @return The Metadata response split on each line. */ public List<String> asList() { return Arrays.asList(body.split("\n")); } /** * Parses the response String into a {@link Document} type. This method can be used for * parsing the metadata in a String Json Format. * @return Document Representation, as json, of the Metadata Response Body. * @throws UncheckedIOException (wrapping a {@link JsonParseException} if the Response body is not of JSON format. */ public Document asDocument() { JsonNode node = JSON_NODE_PARSER.parse(body); return node.visit(new DocumentUnmarshaller()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Ec2MetadataResponse that = (Ec2MetadataResponse) o; return body.equals(that.body); } @Override public int hashCode() { return body.hashCode(); } @Override public String toString() { return ToString.builder("MetadataResponse") .add("body", body) .build(); } }
1,356
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/Ec2MetadataClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.imds.internal.DefaultEc2MetadataClient; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Interface to represent the Ec2Metadata Client Class. Used to access instance metadata from a running EC2 instance. * <h2>Instantiate the Ec2MetadataClient</h2> * <h3>Default configuration</h3> * {@snippet : * Ec2MetadataClient client = Ec2MetadataClient.create(); * } * <h3>Custom configuration</h3> * Example of a client configured for using IPV6 and a fixed delay for retry attempts : * {@snippet : * Ec2MetadataClient client = Ec2MetadataClient.builder() * .retryPolicy(p -> p.backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofMillis(500)))) * .endpointMode(EndpointMode.IPV6) * .build(); * } * <h2>Use the client</h2> * To retrieve EC2 Instance Metadata, call the {@code get} method on the client with a path to an instance metadata: * {@snippet : * Ec2MetadataClient client = Ec2MetadataClient.create(); * Ec2MetadataResponse response = client.get("/latest/meta-data/"); * System.out.println(response.asString()); * } * <h2>Closing the client</h2> * Once all operations are done, you may close the client to free any resources used by it. * {@snippet : * Ec2MetadataClient client = Ec2MetadataClient.create(); * // ... do the things * client.close(); * } * <br/>Note: A single client instance should be reused for multiple requests when possible. */ @SdkPublicApi public interface Ec2MetadataClient extends SdkAutoCloseable { /** * Gets the specified instance metadata value by the given path. For more information about instance metadata, check the * <a href=https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html>Instance metadata documentation</a> * * @param path Input path * @return Instance metadata value as part of MetadataResponse Object */ Ec2MetadataResponse get(String path); /** * Create an {@link Ec2MetadataClient} instance using the default values. * * @return the client instance. */ static Ec2MetadataClient create() { return builder().build(); } /** * Creates a default builder for {@link Ec2MetadataClient}. */ static Builder builder() { return DefaultEc2MetadataClient.builder(); } /** * The builder definition for a {@link Ec2MetadataClient}. */ interface Builder extends Ec2MetadataClientBuilder<Ec2MetadataClient.Builder, Ec2MetadataClient> { /** * Define the http client used by the Ec2 Metadata client. If provided, the Ec2MetadataClient will <em>NOT</em> manage the * lifetime if the httpClient and must therefore be closed explicitly by calling the {@link SdkHttpClient#close()} * method on it. * <p> * If not specified, the IMDS client will look for a SdkHttpClient class included in the classpath of the * application and create a new instance of that class, managed by the IMDS Client, that will be closed when the IMDS * Client is closed. If no such class can be found, will throw a {@link SdkClientException}. * * @param httpClient the http client * @return a reference to this builder */ Builder httpClient(SdkHttpClient httpClient); /** * A http client builder used to retrieve an instance of an {@link SdkHttpClient}. If specified, the Ec2 Metadata Client * will use the instance returned by the builder and manage its lifetime by closing the http client once the Ec2 Client * itself is closed. * * @param builder the builder to used to retrieve an instance. * @return a reference to this builder */ Builder httpClient(SdkHttpClient.Builder<?> builder); } }
1,357
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/Ec2MetadataClientBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import java.net.URI; import java.time.Duration; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.retry.RetryMode; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.imds.internal.Ec2MetadataEndpointProvider; import software.amazon.awssdk.utils.builder.SdkBuilder; /** * Base shared builder interface for Ec2MetadataClients, sync and async. * @param <B> the Builder Type * @param <T> the Ec2MetadataClient Type */ @SdkPublicApi public interface Ec2MetadataClientBuilder<B, T> extends SdkBuilder<Ec2MetadataClientBuilder<B, T>, T> { /** * Define the retry policy which includes the number of retry attempts for any failed request. * <p> * If not specified, defaults to 3 retry attempts and a {@link BackoffStrategy#defaultStrategy()} backoff strategy} that * uses {@link RetryMode#STANDARD}. Can be also specified by using the * {@link Ec2MetadataClientBuilder#retryPolicy(Consumer)} method. if any of the retryPolicy methods are called multiple times, * only the last invocation will be considered. * * @param retryPolicy The retry policy which includes the number of retry attempts for any failed request. * @return a reference to this builder */ B retryPolicy(Ec2MetadataRetryPolicy retryPolicy); /** * Define the retry policy which includes the number of retry attempts for any failed request. Can be used instead of * {@link Ec2MetadataClientBuilder#retryPolicy(Ec2MetadataRetryPolicy)} to use a "fluent consumer" syntax. User * <em>should not</em> manually build the builder in the consumer. * <p> * If not specified, defaults to 3 retry attempts and a {@link BackoffStrategy#defaultStrategy()} backoff strategy} that * uses {@link RetryMode#STANDARD}. Can be also specified by using the * {@link Ec2MetadataClientBuilder#retryPolicy(Ec2MetadataRetryPolicy)} method. if any of the retryPolicy methods are * called multiple times, only the last invocation will be considered. * * @param builderConsumer the consumer * @return a reference to this builder */ B retryPolicy(Consumer<Ec2MetadataRetryPolicy.Builder> builderConsumer); /** * Define the endpoint of IMDS. * <p> * If not specified, the IMDS client will attempt to automatically resolve the endpoint value * based on the logic of {@link Ec2MetadataEndpointProvider}. * * @param endpoint The endpoint of IMDS. * @return a reference to this builder */ B endpoint(URI endpoint); /** * Define the Time to live (TTL) of the token. The token represents a logical session. The TTL specifies the length of time * that the token is valid and, therefore, the duration of the session. Defaults to 21,600 seconds (6 hours) if not specified. * * @param tokenTtl The Time to live (TTL) of the token. * @return a reference to this builder */ B tokenTtl(Duration tokenTtl); /** * Define the endpoint mode of IMDS. Supported values include IPv4 and IPv6. Used to determine the endpoint of the IMDS * Client only if {@link Ec2MetadataClientBuilder#endpoint(URI)} is not specified. Only one of both endpoint or endpoint mode * but not both. If both are specified in the Builder, a {@link IllegalArgumentException} will be thrown. * <p> * If not specified, the IMDS client will attempt to automatically resolve the endpoint mode value * based on the logic of {@link Ec2MetadataEndpointProvider}. * * @param endpointMode The endpoint mode of IMDS. Supported values include IPv4 and IPv6. * @return a reference to this builder */ B endpointMode(EndpointMode endpointMode); }
1,358
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/Ec2MetadataAsyncClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.imds.internal.DefaultEc2MetadataAsyncClient; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Interface to represent the Ec2Metadata Client Class. Used to access instance metadata from a running EC2 instance. * <h2>Instantiate the Ec2MetadataAsyncClient</h2> * <h3>Default configuration</h3> * {@snippet : * Ec2MetadataAsyncClient client = Ec2MetadataAsyncClient.create(); * } * <h3>Custom configuration</h3> * Example of a client configured for using IPV6 and a fixed delay for retry attempts : * {@snippet : * Ec2MetadataAsyncClient client = Ec2MetadataAsyncClient.builder() * .retryPolicy(p -> p.backoffStrategy(FixedDelayBackoffStrategy.create(Duration.ofMillis(500)))) * .endpointMode(EndpointMode.IPV6) * .build(); * } * <h2>Use the client</h2> * Call the {@code get} method on the client with a path to an instance metadata: * {@snippet : * Ec2MetadataAsyncClient client = Ec2MetadataAsyncClient.create(); * CompletableFuture<Ec2MetadataResponse> response = client.get("/latest/meta-data/"); * response.thenAccept(System.out::println); * } * <h2>Closing the client</h2> * Once all operations are done, you may close the client to free any resources used by it. * {@snippet : * Ec2MetadataAsyncClient client = Ec2MetadataAsyncClient.create(); * // ... do the things * client.close(); * } * <br/>Note: A single client instance should be reused for multiple requests when possible. */ @SdkPublicApi public interface Ec2MetadataAsyncClient extends SdkAutoCloseable { /** * Gets the specified instance metadata value by the given path. For more information about instance metadata, check the * <a href=https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html>Instance metadata documentation</a>. * * @param path Input path * @return A CompletableFuture that completes when the MetadataResponse is made available. */ CompletableFuture<Ec2MetadataResponse> get(String path); /** * Create an {@link Ec2MetadataAsyncClient} instance using the default values. * * @return the client instance. */ static Ec2MetadataAsyncClient create() { return builder().build(); } /** * Creates a builder for an async client instance. * @return the newly created builder instance. */ static Ec2MetadataAsyncClient.Builder builder() { return DefaultEc2MetadataAsyncClient.builder(); } /** * The builder definition for a {@link Ec2MetadataClient}. All parameters are optional and have default values if not * specified. Therefore, an instance can be simply created with {@code Ec2MetadataAsyncClient.builder().build()} or * {@code Ec2MetadataAsyncClient.create()}, both having the same result. */ interface Builder extends Ec2MetadataClientBuilder<Ec2MetadataAsyncClient.Builder, Ec2MetadataAsyncClient> { /** * Define the {@link ScheduledExecutorService} used to schedule asynchronous retry attempts. If provided, the * Ec2MetadataClient will <em>NOT</em> manage the lifetime if the httpClient and must therefore be * closed explicitly by calling the {@link SdkAsyncHttpClient#close()} method on it. * <p> * If not specified, defaults to {@link Executors#newScheduledThreadPool} with a default value of 3 thread in the * pool. * * @param scheduledExecutorService the ScheduledExecutorService to use for retry attempt. * @return a reference to this builder */ Builder scheduledExecutorService(ScheduledExecutorService scheduledExecutorService); /** * Define the http client used by the Ec2 Metadata client. If provided, the Ec2MetadataClient will <em>NOT</em> manage the * lifetime if the httpClient and must therefore be closed explicitly by calling the {@link SdkAsyncHttpClient#close()} * method on it. * <p> * If not specified, the IMDS client will look for a SdkAsyncHttpClient class included in the classpath of the * application and creates a new instance of that class, managed by the IMDS Client, that will be closed when the IMDS * Client is closed. If no such class can be found, will throw a {@link SdkClientException}. * * @param httpClient the http client * @return a reference to this builder */ Builder httpClient(SdkAsyncHttpClient httpClient); /** * An http client builder used to retrieve an instance of an {@link SdkAsyncHttpClient}. If specified, the Ec2 * Metadata Client will use the instance returned by the builder and manage its lifetime by closing the http client * once the Ec2 Client itself is closed. * * @param builder the builder to used to retrieve an instance. * @return a reference to this builder */ Builder httpClient(SdkAsyncHttpClient.Builder<?> builder); } }
1,359
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/DefaultEc2MetadataAsyncClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static software.amazon.awssdk.imds.internal.AsyncHttpRequestHelper.sendAsyncTokenRequest; import java.net.URI; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.internal.http.loader.DefaultSdkAsyncHttpClientBuilder; import software.amazon.awssdk.core.retry.RetryPolicyContext; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.imds.Ec2MetadataAsyncClient; import software.amazon.awssdk.imds.Ec2MetadataResponse; import software.amazon.awssdk.imds.Ec2MetadataRetryPolicy; import software.amazon.awssdk.imds.EndpointMode; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.Either; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.ThreadFactoryBuilder; import software.amazon.awssdk.utils.Validate; @SdkInternalApi @Immutable @ThreadSafe public final class DefaultEc2MetadataAsyncClient extends BaseEc2MetadataClient implements Ec2MetadataAsyncClient { private static final Logger log = Logger.loggerFor(DefaultEc2MetadataClient.class); private static final int DEFAULT_RETRY_THREAD_POOL_SIZE = 3; private final SdkAsyncHttpClient httpClient; private final ScheduledExecutorService asyncRetryScheduler; private final boolean httpClientIsInternal; private final boolean retryExecutorIsInternal; private final AsyncTokenCache tokenCache; private DefaultEc2MetadataAsyncClient(Ec2MetadataAsyncBuilder builder) { super(builder); Validate.isTrue(builder.httpClient == null || builder.httpClientBuilder == null, "The httpClient and the httpClientBuilder can't both be configured."); this.httpClient = Either .fromNullable(builder.httpClient, builder.httpClientBuilder) .map(e -> e.map(Function.identity(), SdkAsyncHttpClient.Builder::build)) .orElseGet(() -> new DefaultSdkAsyncHttpClientBuilder().buildWithDefaults(IMDS_HTTP_DEFAULTS)); this.httpClientIsInternal = builder.httpClient == null; this.asyncRetryScheduler = Validate.getOrDefault( builder.scheduledExecutorService, () -> { ThreadFactory threadFactory = new ThreadFactoryBuilder().threadNamePrefix("IMDS-ScheduledExecutor").build(); return Executors.newScheduledThreadPool(DEFAULT_RETRY_THREAD_POOL_SIZE, threadFactory); }); this.retryExecutorIsInternal = builder.scheduledExecutorService == null; Supplier<CompletableFuture<Token>> tokenSupplier = () -> { SdkHttpFullRequest baseTokenRequest = requestMarshaller.createTokenRequest(tokenTtl); return sendAsyncTokenRequest(httpClient, baseTokenRequest); }; this.tokenCache = new AsyncTokenCache(tokenSupplier); } public static Ec2MetadataAsyncClient.Builder builder() { return new DefaultEc2MetadataAsyncClient.Ec2MetadataAsyncBuilder(); } @Override public CompletableFuture<Ec2MetadataResponse> get(String path) { CompletableFuture<Ec2MetadataResponse> returnFuture = new CompletableFuture<>(); get(path, RetryPolicyContext.builder().retriesAttempted(0).build(), returnFuture); return returnFuture; } private void get(String path, RetryPolicyContext retryPolicyContext, CompletableFuture<Ec2MetadataResponse> returnFuture) { CompletableFuture<Token> tokenFuture = tokenCache.get(); CompletableFuture<Ec2MetadataResponse> result = tokenFuture.thenCompose(token -> { SdkHttpFullRequest baseMetadataRequest = requestMarshaller.createDataRequest(path, token.value(), tokenTtl); return AsyncHttpRequestHelper.sendAsyncMetadataRequest(httpClient, baseMetadataRequest, returnFuture); }).thenApply(Ec2MetadataResponse::create); CompletableFutureUtils.forwardExceptionTo(returnFuture, result); result.whenComplete((response, error) -> { if (response != null) { returnFuture.complete(response); return; } if (!shouldRetry(retryPolicyContext, error)) { returnFuture.completeExceptionally(error); return; } int newAttempt = retryPolicyContext.retriesAttempted() + 1; log.debug(() -> "Retrying request: Attempt " + newAttempt); RetryPolicyContext newContext = RetryPolicyContext.builder() .retriesAttempted(newAttempt) .exception(SdkClientException.create(error.getMessage(), error)) .build(); scheduledRetryAttempt(() -> get(path, newContext, returnFuture), newContext); }); } private void scheduledRetryAttempt(Runnable runnable, RetryPolicyContext retryPolicyContext) { Duration retryDelay = retryPolicy.backoffStrategy().computeDelayBeforeNextRetry(retryPolicyContext); Executor retryExecutor = retryAttempt -> asyncRetryScheduler.schedule(retryAttempt, retryDelay.toMillis(), TimeUnit.MILLISECONDS); CompletableFuture.runAsync(runnable, retryExecutor); } @Override public void close() { if (httpClientIsInternal) { httpClient.close(); } if (retryExecutorIsInternal) { asyncRetryScheduler.shutdown(); } } protected static final class Ec2MetadataAsyncBuilder implements Ec2MetadataAsyncClient.Builder { private Ec2MetadataRetryPolicy retryPolicy; private URI endpoint; private Duration tokenTtl; private EndpointMode endpointMode; private SdkAsyncHttpClient httpClient; private SdkAsyncHttpClient.Builder<?> httpClientBuilder; private ScheduledExecutorService scheduledExecutorService; private Ec2MetadataAsyncBuilder() { } @Override public Ec2MetadataAsyncBuilder retryPolicy(Ec2MetadataRetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } @Override public Ec2MetadataAsyncBuilder retryPolicy(Consumer<Ec2MetadataRetryPolicy.Builder> builderConsumer) { Validate.notNull(builderConsumer, "builderConsumer must not be null"); Ec2MetadataRetryPolicy.Builder builder = Ec2MetadataRetryPolicy.builder(); builderConsumer.accept(builder); this.retryPolicy = builder.build(); return this; } @Override public Ec2MetadataAsyncBuilder endpoint(URI endpoint) { this.endpoint = endpoint; return this; } @Override public Ec2MetadataAsyncBuilder tokenTtl(Duration tokenTtl) { this.tokenTtl = tokenTtl; return this; } @Override public Ec2MetadataAsyncBuilder endpointMode(EndpointMode endpointMode) { this.endpointMode = endpointMode; return this; } @Override public Ec2MetadataAsyncBuilder httpClient(SdkAsyncHttpClient httpClient) { this.httpClient = httpClient; return this; } @Override public Builder httpClient(SdkAsyncHttpClient.Builder<?> builder) { this.httpClientBuilder = builder; return this; } @Override public Ec2MetadataAsyncBuilder scheduledExecutorService(ScheduledExecutorService scheduledExecutorService) { this.scheduledExecutorService = scheduledExecutorService; return this; } public Ec2MetadataRetryPolicy getRetryPolicy() { return this.retryPolicy; } public URI getEndpoint() { return this.endpoint; } public Duration getTokenTtl() { return this.tokenTtl; } public EndpointMode getEndpointMode() { return this.endpointMode; } @Override public Ec2MetadataAsyncClient build() { return new DefaultEc2MetadataAsyncClient(this); } } }
1,360
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/DefaultEc2MetadataClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static software.amazon.awssdk.imds.internal.RequestMarshaller.EC2_METADATA_TOKEN_TTL_HEADER; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; import java.time.Duration; import java.time.Instant; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.internal.http.loader.DefaultSdkHttpClientBuilder; import software.amazon.awssdk.core.retry.RetryPolicyContext; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.HttpExecuteRequest; import software.amazon.awssdk.http.HttpExecuteResponse; import software.amazon.awssdk.http.HttpStatusFamily; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.imds.Ec2MetadataClient; import software.amazon.awssdk.imds.Ec2MetadataResponse; import software.amazon.awssdk.imds.Ec2MetadataRetryPolicy; import software.amazon.awssdk.imds.EndpointMode; import software.amazon.awssdk.utils.Either; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.cache.CachedSupplier; import software.amazon.awssdk.utils.cache.RefreshResult; /** * An Implementation of the Ec2Metadata Interface. */ @SdkInternalApi @Immutable @ThreadSafe public final class DefaultEc2MetadataClient extends BaseEc2MetadataClient implements Ec2MetadataClient { private static final Logger log = Logger.loggerFor(DefaultEc2MetadataClient.class); private final SdkHttpClient httpClient; private final Supplier<Token> tokenCache; private final boolean httpClientIsInternal; private DefaultEc2MetadataClient(Ec2MetadataBuilder builder) { super(builder); Validate.isTrue(builder.httpClient == null || builder.httpClientBuilder == null, "The httpClient and the httpClientBuilder can't both be configured."); this.httpClient = Either .fromNullable(builder.httpClient, builder.httpClientBuilder) .map(e -> e.map(Function.identity(), SdkHttpClient.Builder::build)) .orElseGet(() -> new DefaultSdkHttpClientBuilder().buildWithDefaults(IMDS_HTTP_DEFAULTS)); this.httpClientIsInternal = builder.httpClient == null; this.tokenCache = CachedSupplier.builder(() -> RefreshResult.builder(this.getToken()) .staleTime(Instant.now().plus(tokenTtl)) .build()) .cachedValueName(toString()) .build(); } @Override public String toString() { return ToString.create("Ec2MetadataClient"); } @Override public void close() { if (httpClientIsInternal) { httpClient.close(); } } public static Ec2MetadataBuilder builder() { return new DefaultEc2MetadataClient.Ec2MetadataBuilder(); } /** * Gets the specified instance metadata value by the given path. Will retry base on the * {@link Ec2MetadataRetryPolicy retry policy} provided, in the case of an IOException during request. Will not retry on * SdkClientException, like 4XX HTTP error. * * @param path Input path of the resource to get. * @return Instance metadata value as part of MetadataResponse Object * @throws SdkClientException if the request for a token or the request for the Metadata does not have a 2XX SUCCESS response, * if the maximum number of retries is reached, or if another IOException is thrown during the * request. */ @Override public Ec2MetadataResponse get(String path) { Throwable lastCause = null; // 3 retries means 4 total attempts Token token = null; for (int attempt = 0; attempt < retryPolicy.numRetries() + 1; attempt++) { RetryPolicyContext retryPolicyContext = RetryPolicyContext.builder().retriesAttempted(attempt).build(); try { if (token == null || token.isExpired()) { token = tokenCache.get(); } return sendRequest(path, token.value()); } catch (UncheckedIOException | RetryableException e) { lastCause = e; int currentTry = attempt; log.debug(() -> "Error while executing EC2Metadata request, attempting retry. Current attempt: " + currentTry); } catch (SdkClientException sdkClientException) { int totalTries = attempt + 1; log.debug(() -> String.format("Error while executing EC2Metadata request. Total attempts: %d. %s", totalTries, sdkClientException.getMessage())); throw sdkClientException; } catch (IOException ioe) { lastCause = new UncheckedIOException(ioe); int currentTry = attempt; log.debug(() -> "Error while executing EC2Metadata request, attempting retry. Current attempt: " + currentTry); } pauseBeforeRetryIfNeeded(retryPolicyContext); } SdkClientException.Builder sdkClientExceptionBuilder = SdkClientException .builder() .message("Exceeded maximum number of retries. Total retry attempts: " + retryPolicy.numRetries()); if (lastCause != null) { String msg = sdkClientExceptionBuilder.message(); sdkClientExceptionBuilder.cause(lastCause).message(msg); } throw sdkClientExceptionBuilder.build(); } private Ec2MetadataResponse sendRequest(String path, String token) throws IOException { HttpExecuteRequest httpExecuteRequest = HttpExecuteRequest.builder() .request(requestMarshaller.createDataRequest(path, token, tokenTtl)) .build(); HttpExecuteResponse response = httpClient.prepareRequest(httpExecuteRequest).call(); int statusCode = response.httpResponse().statusCode(); Optional<AbortableInputStream> responseBody = response.responseBody(); if (HttpStatusFamily.of(statusCode).isOneOf(HttpStatusFamily.SERVER_ERROR)) { responseBody.map(BaseEc2MetadataClient::uncheckedInputStreamToUtf8) .ifPresent(str -> log.debug(() -> "Metadata request response body: " + str)); throw RetryableException .builder() .message(String.format("The requested metadata at path '%s' returned Http code %s", path, statusCode)) .build(); } if (!HttpStatusFamily.of(statusCode).isOneOf(HttpStatusFamily.SUCCESSFUL)) { responseBody.map(BaseEc2MetadataClient::uncheckedInputStreamToUtf8) .ifPresent(str -> log.debug(() -> "Metadata request response body: " + str)); throw SdkClientException .builder() .message(String.format("The requested metadata at path '%s' returned Http code %s", path, statusCode)) .build(); } AbortableInputStream abortableInputStream = responseBody.orElseThrow( SdkClientException.builder().message("Response body empty with Status Code " + statusCode)::build); String data = uncheckedInputStreamToUtf8(abortableInputStream); return Ec2MetadataResponse.create(data); } private void pauseBeforeRetryIfNeeded(RetryPolicyContext retryPolicyContext) { long backoffTimeMillis = retryPolicy.backoffStrategy() .computeDelayBeforeNextRetry(retryPolicyContext) .toMillis(); if (backoffTimeMillis > 0) { try { TimeUnit.MILLISECONDS.sleep(backoffTimeMillis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw SdkClientException.builder().message("Thread interrupted while trying to sleep").cause(e).build(); } } } private Token getToken() { HttpExecuteRequest httpExecuteRequest = HttpExecuteRequest.builder() .request(requestMarshaller.createTokenRequest(tokenTtl)) .build(); HttpExecuteResponse response = null; try { response = httpClient.prepareRequest(httpExecuteRequest).call(); } catch (IOException e) { throw new UncheckedIOException(e); } int statusCode = response.httpResponse().statusCode(); if (HttpStatusFamily.of(statusCode).isOneOf(HttpStatusFamily.SERVER_ERROR)) { response.responseBody().map(BaseEc2MetadataClient::uncheckedInputStreamToUtf8) .ifPresent(str -> log.debug(() -> "Metadata request response body: " + str)); throw RetryableException.builder() .message("Could not retrieve token, " + statusCode + " error occurred").build(); } if (!HttpStatusFamily.of(statusCode).isOneOf(HttpStatusFamily.SUCCESSFUL)) { response.responseBody().map(BaseEc2MetadataClient::uncheckedInputStreamToUtf8) .ifPresent(body -> log.debug(() -> "Token request response body: " + body)); throw SdkClientException.builder() .message("Could not retrieve token, " + statusCode + " error occurred.") .build(); } String ttl = response.httpResponse() .firstMatchingHeader(EC2_METADATA_TOKEN_TTL_HEADER) .orElseThrow(() -> SdkClientException .builder() .message(EC2_METADATA_TOKEN_TTL_HEADER + " header not found in token response") .build()); Duration ttlDuration; try { ttlDuration = Duration.ofSeconds(Long.parseLong(ttl)); } catch (NumberFormatException nfe) { throw SdkClientException.create("Invalid token format received from IMDS server", nfe); } AbortableInputStream abortableInputStream = response.responseBody().orElseThrow( SdkClientException.builder().message("Empty response body")::build); String value = uncheckedInputStreamToUtf8(abortableInputStream); return new Token(value, ttlDuration); } protected static final class Ec2MetadataBuilder implements Ec2MetadataClient.Builder { private Ec2MetadataRetryPolicy retryPolicy; private URI endpoint; private Duration tokenTtl; private EndpointMode endpointMode; private SdkHttpClient httpClient; private SdkHttpClient.Builder<?> httpClientBuilder; private Ec2MetadataBuilder() { } @Override public Ec2MetadataBuilder retryPolicy(Ec2MetadataRetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } @Override public Builder retryPolicy(Consumer<Ec2MetadataRetryPolicy.Builder> builderConsumer) { Validate.notNull(builderConsumer, "builderConsumer must not be null"); Ec2MetadataRetryPolicy.Builder builder = Ec2MetadataRetryPolicy.builder(); builderConsumer.accept(builder); return retryPolicy(builder.build()); } @Override public Ec2MetadataBuilder endpoint(URI endpoint) { this.endpoint = endpoint; return this; } @Override public Ec2MetadataBuilder tokenTtl(Duration tokenTtl) { this.tokenTtl = tokenTtl; return this; } @Override public Ec2MetadataBuilder endpointMode(EndpointMode endpointMode) { this.endpointMode = endpointMode; return this; } @Override public Ec2MetadataBuilder httpClient(SdkHttpClient httpClient) { this.httpClient = httpClient; return this; } @Override public Builder httpClient(SdkHttpClient.Builder<?> builder) { this.httpClientBuilder = builder; return this; } public Ec2MetadataRetryPolicy getRetryPolicy() { return this.retryPolicy; } public URI getEndpoint() { return this.endpoint; } public Duration getTokenTtl() { return this.tokenTtl; } public EndpointMode getEndpointMode() { return this.endpointMode; } @Override public Ec2MetadataClient build() { return new DefaultEc2MetadataClient(this); } } }
1,361
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/BaseEc2MetadataClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; import java.time.Duration; import java.time.temporal.ChronoUnit; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.retry.RetryPolicyContext; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.imds.Ec2MetadataRetryPolicy; import software.amazon.awssdk.imds.EndpointMode; import software.amazon.awssdk.utils.AttributeMap; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; @SdkInternalApi public abstract class BaseEc2MetadataClient { protected static final Duration DEFAULT_TOKEN_TTL = Duration.of(21_600, ChronoUnit.SECONDS); protected static final AttributeMap IMDS_HTTP_DEFAULTS = AttributeMap.builder() .put(SdkHttpConfigurationOption.CONNECTION_TIMEOUT, Duration.ofSeconds(1)) .put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofSeconds(1)) .build(); private static final Logger log = Logger.loggerFor(BaseEc2MetadataClient.class); protected final Ec2MetadataRetryPolicy retryPolicy; protected final URI endpoint; protected final RequestMarshaller requestMarshaller; protected final Duration tokenTtl; private BaseEc2MetadataClient(Ec2MetadataRetryPolicy retryPolicy, Duration tokenTtl, URI endpoint, EndpointMode endpointMode) { this.retryPolicy = Validate.getOrDefault(retryPolicy, Ec2MetadataRetryPolicy.builder()::build); this.tokenTtl = Validate.getOrDefault(tokenTtl, () -> DEFAULT_TOKEN_TTL); this.endpoint = getEndpoint(endpoint, endpointMode); this.requestMarshaller = new RequestMarshaller(this.endpoint); } protected BaseEc2MetadataClient(DefaultEc2MetadataClient.Ec2MetadataBuilder builder) { this(builder.getRetryPolicy(), builder.getTokenTtl(), builder.getEndpoint(), builder.getEndpointMode()); } protected BaseEc2MetadataClient(DefaultEc2MetadataAsyncClient.Ec2MetadataAsyncBuilder builder) { this(builder.getRetryPolicy(), builder.getTokenTtl(), builder.getEndpoint(), builder.getEndpointMode()); } private URI getEndpoint(URI builderEndpoint, EndpointMode builderEndpointMode) { Validate.mutuallyExclusive("Only one of 'endpoint' or 'endpointMode' must be specified, but not both", builderEndpoint, builderEndpointMode); if (builderEndpoint != null) { return builderEndpoint; } if (builderEndpointMode != null) { return URI.create(Ec2MetadataEndpointProvider.instance().resolveEndpoint(builderEndpointMode)); } EndpointMode resolvedEndpointMode = Ec2MetadataEndpointProvider.instance().resolveEndpointMode(); return URI.create(Ec2MetadataEndpointProvider.instance().resolveEndpoint(resolvedEndpointMode)); } protected static String uncheckedInputStreamToUtf8(AbortableInputStream inputStream) { try { return IoUtils.toUtf8String(inputStream); } catch (IOException ioe) { throw new UncheckedIOException(ioe); } finally { IoUtils.closeQuietly(inputStream, log.logger()); } } protected boolean shouldRetry(RetryPolicyContext retryPolicyContext, Throwable error) { boolean maxAttemptReached = retryPolicyContext.retriesAttempted() >= retryPolicy.numRetries(); if (maxAttemptReached) { return false; } return error instanceof RetryableException || error.getCause() instanceof RetryableException; } }
1,362
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/Ec2MetadataEndpointProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static software.amazon.awssdk.imds.EndpointMode.IPV4; import static software.amazon.awssdk.imds.EndpointMode.IPV6; import java.util.EnumMap; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.imds.EndpointMode; import software.amazon.awssdk.profiles.Profile; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.utils.Validate; /** * Endpoint Provider Class which contains methods for endpoint resolution. */ @SdkInternalApi public final class Ec2MetadataEndpointProvider { private static final Ec2MetadataEndpointProvider DEFAULT_ENDPOINT_PROVIDER = builder().build(); private static final EnumMap<EndpointMode, String> DEFAULT_ENDPOINT_MODE; static { DEFAULT_ENDPOINT_MODE = new EnumMap<>(EndpointMode.class); DEFAULT_ENDPOINT_MODE.put(IPV4, "http://169.254.169.254"); DEFAULT_ENDPOINT_MODE.put(IPV6, "http://[fd00:ec2::254]"); } private final Supplier<ProfileFile> profileFile; private final String profileName; private Ec2MetadataEndpointProvider(Builder builder) { this.profileFile = builder.profileFile; this.profileName = builder.profileName; } public static Ec2MetadataEndpointProvider instance() { return DEFAULT_ENDPOINT_PROVIDER; } /** * Resolve the endpoint to be used for the {@link DefaultEc2MetadataClient} client. Users may manually provide an endpoint * through the {@code AWS_EC2_METADATA_SERVICE_ENDPOINT} environment variable or the {@code ec2_metadata_service_endpoint} * key in their aws config file. * If an endpoint is specified is this manner, use it. If no values are provided, the defaults to: * <ol> * <li>If endpoint mode is set to IPv4: {@code "http://169.254.169.254"}</li> * <li>If endpoint mode is set to IPv6: {@code "http://[fd00:ec2::254]"}</li> * </ol> * (the default endpoint mode is IPV4). * @param endpointMode Used only if an endpoint value is not specified. If so, this method will use the endpointMode to * choose the default value to return. * @return the String representing the endpoint to be used, */ public String resolveEndpoint(EndpointMode endpointMode) { Optional<String> endpointFromSystem = SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.getNonDefaultStringValue(); if (endpointFromSystem.isPresent()) { return stripEndingSlash(endpointFromSystem.get()); } Optional<String> endpointFromConfigProfile = resolveProfile() .flatMap(profile -> profile.property(ProfileProperty.EC2_METADATA_SERVICE_ENDPOINT)); if (endpointFromConfigProfile.isPresent()) { return stripEndingSlash(endpointFromConfigProfile.get()); } Validate.notNull(endpointMode, "endpointMode must not be null."); return endpointFromConfigProfile.orElseGet(() -> DEFAULT_ENDPOINT_MODE.get(endpointMode)); } private static String stripEndingSlash(String uri) { return uri.endsWith("/") ? uri.substring(0, uri.length() - 1) : uri; } public EndpointMode resolveEndpointMode() { Optional<String> systemEndpointMode = SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.getNonDefaultStringValue(); if (systemEndpointMode.isPresent()) { return EndpointMode.fromValue(systemEndpointMode.get()); } Optional<EndpointMode> configFileEndPointMode = resolveProfile() .flatMap(p -> p.property(ProfileProperty.EC2_METADATA_SERVICE_ENDPOINT_MODE)) .map(EndpointMode::fromValue); if (configFileEndPointMode.isPresent()) { return configFileEndPointMode.get(); } String defaultSystemEndpointMode = SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.defaultValue(); return EndpointMode.fromValue(defaultSystemEndpointMode); } public Optional<Profile> resolveProfile() { String profileNameToUse = profileName == null ? ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow() : profileName; ProfileFile profileFileToUse = profileFile.get(); return profileFileToUse.profile(profileNameToUse); } public static Builder builder() { return new Builder(); } public static final class Builder { private Supplier<ProfileFile> profileFile; private String profileName; private Builder() { this.profileFile = ProfileFile::defaultProfileFile; } public Builder profileFile(Supplier<ProfileFile> profileFile) { Validate.notNull(profileFile, "profileFile Supplier must not be null"); this.profileFile = profileFile; return this; } public Builder profileName(String profileName) { this.profileName = profileName; return this; } public Ec2MetadataEndpointProvider build() { return new Ec2MetadataEndpointProvider(this); } } }
1,363
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/AsyncHttpRequestHelper.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import static software.amazon.awssdk.imds.internal.BaseEc2MetadataClient.uncheckedInputStreamToUtf8; import static software.amazon.awssdk.imds.internal.RequestMarshaller.EC2_METADATA_TOKEN_TTL_HEADER; import java.time.Duration; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.exception.RetryableException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.http.HttpResponseHandler; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.internal.http.TransformingAsyncResponseHandler; import software.amazon.awssdk.core.internal.http.async.AsyncResponseHandler; import software.amazon.awssdk.core.internal.http.async.SimpleHttpContentPublisher; import software.amazon.awssdk.http.AbortableInputStream; import software.amazon.awssdk.http.HttpStatusFamily; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpFullResponse; import software.amazon.awssdk.http.async.AsyncExecuteRequest; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.http.async.SdkHttpContentPublisher; import software.amazon.awssdk.utils.CompletableFutureUtils; @SdkInternalApi final class AsyncHttpRequestHelper { private AsyncHttpRequestHelper() { // static utility class } public static CompletableFuture<String> sendAsyncMetadataRequest(SdkAsyncHttpClient httpClient, SdkHttpFullRequest baseRequest, CompletableFuture<?> parentFuture) { return sendAsync(httpClient, baseRequest, AsyncHttpRequestHelper::handleResponse, parentFuture); } public static CompletableFuture<Token> sendAsyncTokenRequest(SdkAsyncHttpClient httpClient, SdkHttpFullRequest baseRequest) { return sendAsync(httpClient, baseRequest, AsyncHttpRequestHelper::handleTokenResponse, null); } private static <T> CompletableFuture<T> sendAsync(SdkAsyncHttpClient client, SdkHttpFullRequest request, HttpResponseHandler<T> handler, CompletableFuture<?> parentFuture) { SdkHttpContentPublisher requestContentPublisher = new SimpleHttpContentPublisher(request); TransformingAsyncResponseHandler<T> responseHandler = new AsyncResponseHandler<>(handler, Function.identity(), new ExecutionAttributes()); CompletableFuture<T> responseHandlerFuture = responseHandler.prepare(); AsyncExecuteRequest metadataRequest = AsyncExecuteRequest.builder() .request(request) .requestContentPublisher(requestContentPublisher) .responseHandler(responseHandler) .build(); CompletableFuture<Void> executeFuture = client.execute(metadataRequest); if (parentFuture != null) { CompletableFutureUtils.forwardExceptionTo(parentFuture, executeFuture); CompletableFutureUtils.forwardExceptionTo(parentFuture, responseHandlerFuture); } return responseHandlerFuture; } private static String handleResponse(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) { HttpStatusFamily statusCode = HttpStatusFamily.of(response.statusCode()); AbortableInputStream inputStream = response.content().orElseThrow(() -> SdkClientException.create("Unexpected error: empty response content")); String responseContent = uncheckedInputStreamToUtf8(inputStream); // non-retryable error if (statusCode.isOneOf(HttpStatusFamily.CLIENT_ERROR)) { throw SdkClientException.builder().message(responseContent).build(); } // retryable error if (statusCode.isOneOf(HttpStatusFamily.SERVER_ERROR)) { throw RetryableException.create(responseContent); } return responseContent; } private static Token handleTokenResponse(SdkHttpFullResponse response, ExecutionAttributes executionAttributes) { String tokenValue = handleResponse(response, executionAttributes); Optional<String> ttl = response.firstMatchingHeader(EC2_METADATA_TOKEN_TTL_HEADER); if (!ttl.isPresent()) { throw SdkClientException.create(EC2_METADATA_TOKEN_TTL_HEADER + " header not found in token response"); } try { Duration ttlDuration = Duration.ofSeconds(Long.parseLong(ttl.get())); return new Token(tokenValue, ttlDuration); } catch (NumberFormatException nfe) { throw SdkClientException.create( "Invalid token format received from IMDS server. Token received: " + tokenValue, nfe); } } }
1,364
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/Token.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import java.time.Duration; import java.time.Instant; import java.util.Objects; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.ToString; @SdkInternalApi @Immutable public final class Token { private final String value; private final Duration ttl; private final Instant createdTime; public Token(String value, Duration ttl) { this.value = value; this.ttl = ttl; this.createdTime = Instant.now(); } public String value() { return value; } public Duration ttl() { return ttl; } public Instant createdTime() { return createdTime; } public boolean isExpired() { return Instant.now().isAfter(createdTime.plus(ttl)); } @Override public String toString() { return ToString.builder("Token") .add("value", value) .add("ttl", ttl) .add("createdTime", createdTime) .build(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Token token = (Token) o; if (!Objects.equals(value, token.value)) { return false; } if (!Objects.equals(ttl, token.ttl)) { return false; } return Objects.equals(createdTime, token.createdTime); } @Override public int hashCode() { int result = value != null ? value.hashCode() : 0; result = 31 * result + (ttl != null ? ttl.hashCode() : 0); result = 31 * result + (createdTime != null ? createdTime.hashCode() : 0); return result; } }
1,365
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/AsyncTokenCache.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.utils.Logger; /** * A cache for the IMDS {@link Token}, which can be refreshed through an asynchronous operation. * A call to the {@link AsyncTokenCache#get()} method returns an already completed future if the cached token is still fresh. * If the cached token was expired, the returned future will be completed once the refresh process has been * completed. * In the case where multiple call to <pre>get</pre> are made while the token is expired, all CompletableFuture returned * will be completed once the single refresh process completes. * */ @SdkInternalApi final class AsyncTokenCache implements Supplier<CompletableFuture<Token>> { private static final Logger log = Logger.loggerFor(AsyncTokenCache.class); /** * The currently cached value. * Only modified through synchronized block, under the refreshLock. */ private volatile Token cachedToken; /** * The asynchronous operation that is used to refresh the token. * The Supplier must not block the current thread and is responsible to start the process that will complete the future. * A call the {@link AsyncTokenCache#get} method does not join or wait for the supplied future to finish, it only refreshes * the token once it finishes. */ private final Supplier<CompletableFuture<Token>> supplier; /** * The collection of future that are waiting for the refresh call to complete. If a call to {@link AsyncTokenCache#get()} * is made while the token request is happening, a future will be added to this collection. All future in this collection * are completed once the token request is done. * Should only be modified while holding the lock on {@link AsyncTokenCache#refreshLock}. */ private Collection<CompletableFuture<Token>> waitingFutures = new ArrayList<>(); /** * Indicates if the token refresh request is currently running or not. */ private final AtomicBoolean refreshRunning = new AtomicBoolean(false); private final Object refreshLock = new Object(); AsyncTokenCache(Supplier<CompletableFuture<Token>> supplier) { this.supplier = supplier; } @Override public CompletableFuture<Token> get() { Token currentValue = cachedToken; if (!needsRefresh(currentValue)) { log.debug(() -> "IMDS Token is not expired"); return CompletableFuture.completedFuture(currentValue); } synchronized (refreshLock) { // Make sure the value wasn't refreshed while we were waiting for the lock. currentValue = cachedToken; if (!needsRefresh(currentValue)) { return CompletableFuture.completedFuture(currentValue); } CompletableFuture<Token> result = new CompletableFuture<>(); waitingFutures.add(result); if (!refreshRunning.get()) { startRefresh(); } return result; } } private void startRefresh() { log.debug(() -> "IMDS token expired or null, starting asynchronous refresh."); CompletableFuture<Token> tokenRequest = supplier.get(); refreshRunning.set(true); // After supplier.get(), in case that throws an exception tokenRequest.whenComplete((token, throwable) -> { Collection<CompletableFuture<Token>> toComplete; synchronized (refreshLock) { // Instead of completing the waiting future while holding the lock, we copy the list reference and // release the lock before completing them. This is just in case someone (naughty) is doing something // blocking on the complete calls. It's not good that they're doing that, but at least // it won't block other threads trying to acquire the lock. toComplete = waitingFutures; waitingFutures = new ArrayList<>(); refreshRunning.set(false); if (token != null) { log.debug(() -> "IMDS token refresh completed. Token value: " + token.value()); cachedToken = token; } else { log.error(() -> "IMDS token refresh completed with error.", throwable); } } toComplete.forEach(future -> { if (throwable == null) { future.complete(token); } else { future.completeExceptionally(throwable); } }); }); } private boolean needsRefresh(Token token) { return token == null || token.isExpired(); } }
1,366
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/RequestMarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal; import java.net.URI; import java.time.Duration; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.util.SdkUserAgent; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; /** * Class to parse the parameters to a SdkHttpRequest, make the call to the endpoint and send the HttpExecuteResponse * to the DefaultEc2Metadata class for further processing. */ @SdkInternalApi public class RequestMarshaller { public static final String TOKEN_RESOURCE_PATH = "/latest/api/token"; public static final String TOKEN_HEADER = "x-aws-ec2-metadata-token"; public static final String EC2_METADATA_TOKEN_TTL_HEADER = "x-aws-ec2-metadata-token-ttl-seconds"; public static final String USER_AGENT = "user_agent"; public static final String ACCEPT = "Accept"; public static final String CONNECTION = "connection"; private final URI basePath; private final URI tokenPath; public RequestMarshaller(URI basePath) { this.basePath = basePath; this.tokenPath = URI.create(basePath + TOKEN_RESOURCE_PATH); } public SdkHttpFullRequest createTokenRequest(Duration tokenTtl) { return defaulttHttpBuilder() .method(SdkHttpMethod.PUT) .uri(tokenPath) .putHeader(EC2_METADATA_TOKEN_TTL_HEADER, String.valueOf(tokenTtl.getSeconds())) .build(); } public SdkHttpFullRequest createDataRequest(String path, String token, Duration tokenTtl) { URI resourcePath = URI.create(basePath + path); return defaulttHttpBuilder() .method(SdkHttpMethod.GET) .uri(resourcePath) .putHeader(EC2_METADATA_TOKEN_TTL_HEADER, String.valueOf(tokenTtl.getSeconds())) .putHeader(TOKEN_HEADER, token) .build(); } private SdkHttpFullRequest.Builder defaulttHttpBuilder() { return SdkHttpFullRequest.builder() .putHeader(USER_AGENT, SdkUserAgent.create().userAgent()) .putHeader(ACCEPT, "*/*") .putHeader(CONNECTION, "keep-alive"); } }
1,367
0
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/unmarshall
Create_ds/aws-sdk-java-v2/core/imds/src/main/java/software/amazon/awssdk/imds/internal/unmarshall/document/DocumentUnmarshaller.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.imds.internal.unmarshall.document; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.document.Document; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor; @SdkInternalApi public final class DocumentUnmarshaller implements JsonNodeVisitor<Document> { @Override public Document visitNull() { return Document.fromNull(); } @Override public Document visitBoolean(boolean bool) { return Document.fromBoolean(bool); } @Override public Document visitNumber(String number) { return Document.fromNumber(number); } @Override public Document visitString(String string) { return Document.fromString(string); } @Override public Document visitArray(List<JsonNode> array) { return Document.fromList(array.stream() .map(node -> node.visit(this)) .collect(Collectors.toList())); } @Override public Document visitObject(Map<String, JsonNode> object) { return Document.fromMap(object.entrySet() .stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().visit(this), (left, right) -> left, LinkedHashMap::new))); } @Override public Document visitEmbeddedObject(Object embeddedObject) { throw new UnsupportedOperationException("Embedded objects are not supported within Document types."); } }
1,368
0
Create_ds/aws-sdk-java-v2/core/crt-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/crt-core/src/test/java/software/amazon/awssdk/crtcore/CrtProxyConfigurationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.crtcore; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class CrtProxyConfigurationTest { @Test void equalsHashCodeTest() { EqualsVerifier.forClass(CrtProxyConfiguration.class) .usingGetClass() .verify(); } }
1,369
0
Create_ds/aws-sdk-java-v2/core/crt-core/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/crt-core/src/test/java/software/amazon/awssdk/crtcore/CrtConnectionUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.crtcore; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import java.time.Duration; import java.util.Optional; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.crt.http.HttpMonitoringOptions; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.crt.io.TlsContext; class CrtConnectionUtilsTest { @Test void resolveProxy_basicAuthorization() { CrtProxyConfiguration configuration = new TestProxy.Builder().host("1.2.3.4") .port(123) .scheme("https") .password("bar") .username("foo") .build(); TlsContext tlsContext = Mockito.mock(TlsContext.class); Optional<HttpProxyOptions> httpProxyOptions = CrtConfigurationUtils.resolveProxy(configuration, tlsContext); assertThat(httpProxyOptions).hasValueSatisfying(proxy -> { assertThat(proxy.getTlsContext()).isEqualTo(tlsContext); assertThat(proxy.getAuthorizationPassword()).isEqualTo("bar"); assertThat(proxy.getAuthorizationUsername()).isEqualTo("foo"); assertThat(proxy.getAuthorizationType()).isEqualTo(HttpProxyOptions.HttpProxyAuthorizationType.Basic); }); } @Test void resolveProxy_emptyProxy_shouldReturnEmpty() { TlsContext tlsContext = Mockito.mock(TlsContext.class); assertThat(CrtConfigurationUtils.resolveProxy(null, tlsContext)).isEmpty(); } @Test void resolveProxy_noneAuthorization() { CrtProxyConfiguration configuration = new TestProxy.Builder().host("1.2.3.4") .port(123) .build(); TlsContext tlsContext = Mockito.mock(TlsContext.class); Optional<HttpProxyOptions> httpProxyOptions = CrtConfigurationUtils.resolveProxy(configuration, tlsContext); assertThat(httpProxyOptions).hasValueSatisfying(proxy -> { assertThat(proxy.getTlsContext()).isNull(); assertThat(proxy.getAuthorizationPassword()).isNull(); assertThat(proxy.getAuthorizationUsername()).isNull(); assertThat(proxy.getAuthorizationType()).isEqualTo(HttpProxyOptions.HttpProxyAuthorizationType.None); }); } @Test void resolveHttpMonitoringOptions_shouldMap() { CrtConnectionHealthConfiguration configuration = new TestConnectionHealthConfiguration.Builder() .minimumThroughputInBps(123L) .minimumThroughputTimeout(Duration.ofSeconds(5)) .build(); Optional<HttpMonitoringOptions> options = CrtConfigurationUtils.resolveHttpMonitoringOptions(configuration); assertThat(options).hasValueSatisfying(proxy -> { assertThat(proxy.getAllowableThroughputFailureIntervalSeconds()).isEqualTo(5); assertThat(proxy.getMinThroughputBytesPerSecond()).isEqualTo(123L); }); } @Test void resolveHttpMonitoringOptions_nullConfig_shouldReturnEmpty() { assertThat(CrtConfigurationUtils.resolveHttpMonitoringOptions(null)).isEmpty(); } private static final class TestProxy extends CrtProxyConfiguration { private TestProxy(DefaultBuilder<?> builder) { super(builder); } private static final class Builder extends CrtProxyConfiguration.DefaultBuilder<Builder> { @Override public TestProxy build() { return new TestProxy(this); } } } private static final class TestConnectionHealthConfiguration extends CrtConnectionHealthConfiguration { private TestConnectionHealthConfiguration(DefaultBuilder<?> builder) { super(builder); } private static final class Builder extends CrtConnectionHealthConfiguration.DefaultBuilder<Builder> { @Override public TestConnectionHealthConfiguration build() { return new TestConnectionHealthConfiguration(this); } } } }
1,370
0
Create_ds/aws-sdk-java-v2/core/crt-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/crt-core/src/main/java/software/amazon/awssdk/crtcore/CrtConfigurationUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.crtcore; import java.util.Optional; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.crt.http.HttpMonitoringOptions; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.crt.io.TlsContext; import software.amazon.awssdk.utils.NumericUtils; @SdkProtectedApi public final class CrtConfigurationUtils { private CrtConfigurationUtils() { } public static Optional<HttpProxyOptions> resolveProxy(CrtProxyConfiguration proxyConfiguration, TlsContext tlsContext) { if (proxyConfiguration == null) { return Optional.empty(); } HttpProxyOptions clientProxyOptions = new HttpProxyOptions(); clientProxyOptions.setHost(proxyConfiguration.host()); clientProxyOptions.setPort(proxyConfiguration.port()); if ("https".equalsIgnoreCase(proxyConfiguration.scheme())) { clientProxyOptions.setTlsContext(tlsContext); } if (proxyConfiguration.username() != null && proxyConfiguration.password() != null) { clientProxyOptions.setAuthorizationUsername(proxyConfiguration.username()); clientProxyOptions.setAuthorizationPassword(proxyConfiguration.password()); clientProxyOptions.setAuthorizationType(HttpProxyOptions.HttpProxyAuthorizationType.Basic); } else { clientProxyOptions.setAuthorizationType(HttpProxyOptions.HttpProxyAuthorizationType.None); } return Optional.of(clientProxyOptions); } public static Optional<HttpMonitoringOptions> resolveHttpMonitoringOptions(CrtConnectionHealthConfiguration config) { if (config == null) { return Optional.empty(); } HttpMonitoringOptions httpMonitoringOptions = new HttpMonitoringOptions(); httpMonitoringOptions.setMinThroughputBytesPerSecond(config.minimumThroughputInBps()); int seconds = NumericUtils.saturatedCast(config.minimumThroughputTimeout().getSeconds()); httpMonitoringOptions.setAllowableThroughputFailureIntervalSeconds(seconds); return Optional.of(httpMonitoringOptions); } }
1,371
0
Create_ds/aws-sdk-java-v2/core/crt-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/crt-core/src/main/java/software/amazon/awssdk/crtcore/CrtConnectionHealthConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.crtcore; import java.time.Duration; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.Validate; /** * The base class for CRT connection health configuration */ @SdkPublicApi public abstract class CrtConnectionHealthConfiguration { private final long minimumThroughputInBps; private final Duration minimumThroughputTimeout; protected CrtConnectionHealthConfiguration(DefaultBuilder<?> builder) { this.minimumThroughputInBps = Validate.paramNotNull(builder.minimumThroughputInBps, "minimumThroughputInBps"); this.minimumThroughputTimeout = Validate.isPositive(builder.minimumThroughputTimeout, "minimumThroughputTimeout"); } /** * @return the minimum amount of throughput, in bytes per second, for a connection to be considered healthy. */ public final long minimumThroughputInBps() { return minimumThroughputInBps; } /** * @return How long a connection is allowed to be unhealthy before getting shut down. */ public final Duration minimumThroughputTimeout() { return minimumThroughputTimeout; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CrtConnectionHealthConfiguration that = (CrtConnectionHealthConfiguration) o; if (minimumThroughputInBps != that.minimumThroughputInBps) { return false; } return minimumThroughputTimeout.equals(that.minimumThroughputTimeout); } @Override public int hashCode() { int result = (int) (minimumThroughputInBps ^ (minimumThroughputInBps >>> 32)); result = 31 * result + minimumThroughputTimeout.hashCode(); return result; } /** * A builder for {@link CrtConnectionHealthConfiguration}. * * <p>All implementations of this interface are mutable and not thread safe.</p> */ public interface Builder { /** * Sets a throughput threshold for connections. Throughput below this value will be considered unhealthy. * * @param minimumThroughputInBps minimum amount of throughput, in bytes per second, for a connection to be * considered healthy. * @return Builder */ Builder minimumThroughputInBps(Long minimumThroughputInBps); /** * Sets how long a connection is allowed to be unhealthy before getting shut down. * * <p> * It only supports seconds precision * * @param minimumThroughputTimeout How long a connection is allowed to be unhealthy * before getting shut down. * @return Builder */ Builder minimumThroughputTimeout(Duration minimumThroughputTimeout); CrtConnectionHealthConfiguration build(); } protected abstract static class DefaultBuilder<B extends Builder> implements Builder { private Long minimumThroughputInBps; private Duration minimumThroughputTimeout; protected DefaultBuilder() { } protected DefaultBuilder(CrtConnectionHealthConfiguration configuration) { this.minimumThroughputInBps = configuration.minimumThroughputInBps; this.minimumThroughputTimeout = configuration.minimumThroughputTimeout; } @Override public B minimumThroughputInBps(Long minimumThroughputInBps) { this.minimumThroughputInBps = minimumThroughputInBps; return (B) this; } @Override public B minimumThroughputTimeout(Duration minimumThroughputTimeout) { this.minimumThroughputTimeout = minimumThroughputTimeout; return (B) this; } } }
1,372
0
Create_ds/aws-sdk-java-v2/core/crt-core/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/core/crt-core/src/main/java/software/amazon/awssdk/crtcore/CrtProxyConfiguration.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.crtcore; import static software.amazon.awssdk.utils.ProxyConfigProvider.fromSystemEnvironmentSettings; import java.util.Objects; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.utils.ProxyConfigProvider; import software.amazon.awssdk.utils.ProxySystemSetting; import software.amazon.awssdk.utils.StringUtils; /** * The base class for AWS CRT proxy configuration */ @SdkPublicApi public abstract class CrtProxyConfiguration { private final String scheme; private final String host; private final int port; private final String username; private final String password; private final Boolean useSystemPropertyValues; private final Boolean useEnvironmentVariableValues; protected CrtProxyConfiguration(DefaultBuilder<?> builder) { this.useSystemPropertyValues = builder.useSystemPropertyValues; this.useEnvironmentVariableValues = builder.useEnvironmentVariableValues; this.scheme = builder.scheme; ProxyConfigProvider proxyConfigProvider = fromSystemEnvironmentSettings(builder.useSystemPropertyValues, builder.useEnvironmentVariableValues , builder.scheme); this.host = resolveHost(builder, proxyConfigProvider); this.port = resolvePort(builder, proxyConfigProvider); this.username = resolveUsername(builder, proxyConfigProvider); this.password = resolvePassword(builder, proxyConfigProvider); } private static String resolvePassword(DefaultBuilder<?> builder, ProxyConfigProvider proxyConfigProvider) { if (!StringUtils.isEmpty(builder.password) || proxyConfigProvider == null) { return builder.password; } else { return proxyConfigProvider.password().orElseGet(() -> builder.password); } } private static String resolveUsername(DefaultBuilder<?> builder, ProxyConfigProvider proxyConfigProvider) { if (!StringUtils.isEmpty(builder.username) || proxyConfigProvider == null) { return builder.username; } else { return proxyConfigProvider.userName().orElseGet(() -> builder.username); } } private static int resolvePort(DefaultBuilder<?> builder, ProxyConfigProvider proxyConfigProvider) { if (builder.port != 0 || proxyConfigProvider == null) { return builder.port; } else { return proxyConfigProvider.port(); } } private static String resolveHost(DefaultBuilder<?> builder, ProxyConfigProvider proxyConfigProvider) { if (builder.host != null || proxyConfigProvider == null) { return builder.host; } else { return proxyConfigProvider.host(); } } /** * @return The proxy scheme. */ public final String scheme() { return scheme; } /** * @return The proxy host from the configuration if set, else from the "https.proxyHost" or "http.proxyHost" system property, * based on the scheme used, if {@link Builder#useSystemPropertyValues(Boolean)} is set to true */ public final String host() { return host; } /** * @return The proxy port from the configuration if set, else from the "https.proxyPort" or "http.proxyPort" system property, * based on the scheme used, if {@link Builder#useSystemPropertyValues(Boolean)} is set to true */ public final int port() { return port; } /** * @return The proxy username from the configuration if set, else from the "https.proxyUser" or "http.proxyUser" system * property, based on the scheme used, if {@link Builder#useSystemPropertyValues(Boolean)} is set to true * */ public final String username() { return username; } /** * @return The proxy password from the configuration if set, else from the "https.proxyPassword" or "http.proxyPassword" * system property, based on the scheme used, if {@link Builder#useSystemPropertyValues(Boolean)} is set * to true * */ public final String password() { return password; } /** * Indicates whether environment variables are utilized for proxy configuration. * * @return {@code true} if environment variables are being used for proxy configuration, {@code false} otherwise. */ public final Boolean isUseEnvironmentVariableValues() { return useEnvironmentVariableValues; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CrtProxyConfiguration that = (CrtProxyConfiguration) o; if (port != that.port) { return false; } if (!Objects.equals(scheme, that.scheme)) { return false; } if (!Objects.equals(host, that.host)) { return false; } if (!Objects.equals(username, that.username)) { return false; } if (!Objects.equals(password, that.password)) { return false; } if (!Objects.equals(useSystemPropertyValues, that.useSystemPropertyValues)) { return false; } return Objects.equals(useEnvironmentVariableValues, that.useEnvironmentVariableValues); } @Override public int hashCode() { int result = scheme != null ? scheme.hashCode() : 0; result = 31 * result + (host != null ? host.hashCode() : 0); result = 31 * result + port; result = 31 * result + (username != null ? username.hashCode() : 0); result = 31 * result + (password != null ? password.hashCode() : 0); result = 31 * result + (useSystemPropertyValues != null ? useSystemPropertyValues.hashCode() : 0); result = 31 * result + (useEnvironmentVariableValues != null ? useEnvironmentVariableValues.hashCode() : 0); result = 31 * result + (scheme != null ? scheme.hashCode() : 0); return result; } /** * Builder for {@link CrtProxyConfiguration}. */ public interface Builder { /** * Set the hostname of the proxy. * @param host The proxy host. * @return This object for method chaining. */ Builder host(String host); /** * Set the port that the proxy expects connections on. * @param port The proxy port. * @return This object for method chaining. */ Builder port(int port); /** * The HTTP scheme to use for connecting to the proxy. Valid values are {@code http} and {@code https}. * <p> * The client defaults to {@code http} if none is given. * * @param scheme The proxy scheme. * @return This object for method chaining. */ Builder scheme(String scheme); /** * The username to use for basic proxy authentication * <p> * If not set, the client will not use basic authentication * * @param username The basic authentication username. * @return This object for method chaining. */ Builder username(String username); /** * The password to use for basic proxy authentication * <p> * If not set, the client will not use basic authentication * * @param password The basic authentication password. * @return This object for method chaining. */ Builder password(String password); /** * The option whether to use system property values from {@link ProxySystemSetting} if any of the config options are * missing. The value is set to "true" by default which means SDK will automatically use system property values if options * are not provided during building the {@link CrtProxyConfiguration} object. To disable this behaviour, set this value to * false.It is important to note that when this property is set to "true," all proxy settings will exclusively originate * from system properties, and no partial settings will be obtained from EnvironmentVariableValues. * * @param useSystemPropertyValues The option whether to use system property values * @return This object for method chaining. */ Builder useSystemPropertyValues(Boolean useSystemPropertyValues); /** * The option whether to use environment variable values from {@link ProxySystemSetting} if any of the config options are * missing. The value is set to "true" by default which means SDK will automatically use environment variable values if * options are not provided during building the {@link CrtProxyConfiguration} object. To disable this behavior, set this * value to false.It is important to note that when this property is set to "true," all proxy settings will exclusively * originate from environment variableValues, and no partial settings will be obtained from SystemPropertyValues. * * @param useEnvironmentVariableValues The option whether to use environment variable values * @return This object for method chaining. */ Builder useEnvironmentVariableValues(Boolean useEnvironmentVariableValues); CrtProxyConfiguration build(); } protected abstract static class DefaultBuilder<B extends Builder> implements Builder { private String scheme; private String host; private int port = 0; private String username; private String password; private Boolean useSystemPropertyValues = Boolean.TRUE; private Boolean useEnvironmentVariableValues = Boolean.TRUE; protected DefaultBuilder() { } protected DefaultBuilder(CrtProxyConfiguration proxyConfiguration) { this.useSystemPropertyValues = proxyConfiguration.useSystemPropertyValues; this.useEnvironmentVariableValues = proxyConfiguration.useEnvironmentVariableValues; this.scheme = proxyConfiguration.scheme; this.host = proxyConfiguration.host; this.port = proxyConfiguration.port; this.username = proxyConfiguration.username; this.password = proxyConfiguration.password; } @Override public B scheme(String scheme) { this.scheme = scheme; return (B) this; } @Override public B host(String host) { this.host = host; return (B) this; } @Override public B port(int port) { this.port = port; return (B) this; } @Override public B username(String username) { this.username = username; return (B) this; } @Override public B password(String password) { this.password = password; return (B) this; } @Override public B useSystemPropertyValues(Boolean useSystemPropertyValues) { this.useSystemPropertyValues = useSystemPropertyValues; return (B) this; } @Override public B useEnvironmentVariableValues(Boolean useEnvironmentVariableValues) { this.useEnvironmentVariableValues = useEnvironmentVariableValues; return (B) this; } public B setuseEnvironmentVariableValues(Boolean useEnvironmentVariableValues) { return useEnvironmentVariableValues(useEnvironmentVariableValues); } public void setUseSystemPropertyValues(Boolean useSystemPropertyValues) { useSystemPropertyValues(useSystemPropertyValues); } } }
1,373
0
Create_ds/aws-sdk-java-v2/core/checksums-spi/src/main/java/software/amazon/awssdk/checksums
Create_ds/aws-sdk-java-v2/core/checksums-spi/src/main/java/software/amazon/awssdk/checksums/spi/ChecksumAlgorithm.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.checksums.spi; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * An interface for declaring the implementation of a checksum. */ @SdkProtectedApi public interface ChecksumAlgorithm { /** * The ID of the checksum algorithm. This is matched against algorithm * names used in smithy traits * (e.g. "CRC32C" from the aws.protocols#HTTPChecksum smithy trait) */ String algorithmId(); }
1,374
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/TestBearerToken.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token; import java.time.Instant; import java.util.Optional; import software.amazon.awssdk.auth.token.credentials.SdkToken; public class TestBearerToken implements SdkToken { private String token; private Instant expirationTime; @Override public String token() { return token; } @Override public Optional<Instant> expirationTime() { return Optional.ofNullable(expirationTime); } private TestBearerToken(String token, Instant expirationTime) { this.token = token; this.expirationTime = expirationTime; } public static TestBearerToken create(String token, Instant expirationTime){ return new TestBearerToken(token, expirationTime); } public static TestBearerToken create(String token){ return new TestBearerToken(token, null); } }
1,375
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/signer/SdkTokenExecutionAttributeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token.signer; import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.identity.spi.Identity; class SdkTokenExecutionAttributeTest { private static final SelectedAuthScheme<Identity> EMPTY_SELECTED_AUTH_SCHEME = new SelectedAuthScheme<>(CompletableFuture.completedFuture(Mockito.mock(Identity.class)), (HttpSigner<Identity>) Mockito.mock(HttpSigner.class), AuthSchemeOption.builder().schemeId("mock").build()); private ExecutionAttributes attributes; @BeforeEach public void setup() { this.attributes = new ExecutionAttributes(); } @Test public void awsCredentials_oldAndNewAttributeAreMirrored() { SdkToken token = Mockito.mock(SdkToken.class); // If selected auth scheme is null, writing non-null old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); attributes.putAttribute(SdkTokenExecutionAttribute.SDK_TOKEN, token); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME).identity().join()).isSameAs(token); // If selected auth scheme is null, writing null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); attributes.putAttribute(SdkTokenExecutionAttribute.SDK_TOKEN, null); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME).identity().join()).isNull(); // If selected auth scheme is non-null, writing non-null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, EMPTY_SELECTED_AUTH_SCHEME); attributes.putAttribute(SdkTokenExecutionAttribute.SDK_TOKEN, token); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME).identity().join()).isSameAs(token); // If selected auth scheme is non-null, writing null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, EMPTY_SELECTED_AUTH_SCHEME); attributes.putAttribute(SdkTokenExecutionAttribute.SDK_TOKEN, null); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME).identity().join()).isNull(); // Writing non-null new property can be read with old property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, new SelectedAuthScheme<>(CompletableFuture.completedFuture(token), EMPTY_SELECTED_AUTH_SCHEME.signer(), EMPTY_SELECTED_AUTH_SCHEME.authSchemeOption())); assertThat(attributes.getAttribute(SdkTokenExecutionAttribute.SDK_TOKEN)).isSameAs(token); // Writing null new property can be read with old property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, new SelectedAuthScheme<>(CompletableFuture.completedFuture(null), EMPTY_SELECTED_AUTH_SCHEME.signer(), EMPTY_SELECTED_AUTH_SCHEME.authSchemeOption())); assertThat(attributes.getAttribute(SdkTokenExecutionAttribute.SDK_TOKEN)).isNull(); // Null selected auth scheme can be read with old property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); assertThat(attributes.getAttribute(SdkTokenExecutionAttribute.SDK_TOKEN)).isNull(); } }
1,376
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/internal/LazyTokenProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token.internal; import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.utils.SdkAutoCloseable; public class LazyTokenProviderTest { @SuppressWarnings("unchecked") private final Supplier<SdkTokenProvider> credentialsConstructor = Mockito.mock(Supplier.class); private final SdkTokenProvider credentials = Mockito.mock(SdkTokenProvider.class); @BeforeEach public void reset() { Mockito.reset(credentials, credentialsConstructor); Mockito.when(credentialsConstructor.get()).thenReturn(credentials); } @Test public void creationDoesntInvokeSupplier() { LazyTokenProvider.create(credentialsConstructor); Mockito.verifyNoMoreInteractions(credentialsConstructor); } @Test public void resolveCredentialsInvokesSupplierExactlyOnce() { LazyTokenProvider credentialsProvider = LazyTokenProvider.create(credentialsConstructor); credentialsProvider.resolveToken(); credentialsProvider.resolveToken(); Mockito.verify(credentialsConstructor).get(); Mockito.verify(credentials, Mockito.times(2)).resolveToken(); } @Test public void delegatesClosesInitializerAndValue() { CloseableSupplier initializer = Mockito.mock(CloseableSupplier.class); CloseableCredentialsProvider value = Mockito.mock(CloseableCredentialsProvider.class); Mockito.when(initializer.get()).thenReturn(value); LazyTokenProvider.create(initializer).close(); Mockito.verify(initializer).close(); Mockito.verify(value).close(); } @Test public void delegatesClosesInitializerEvenIfGetFails() { CloseableSupplier initializer = Mockito.mock(CloseableSupplier.class); Mockito.when(initializer.get()).thenThrow(new RuntimeException()); LazyTokenProvider.create(initializer).close(); Mockito.verify(initializer).close(); } private interface CloseableSupplier extends Supplier<SdkTokenProvider>, SdkAutoCloseable {} private interface CloseableCredentialsProvider extends SdkAutoCloseable, SdkTokenProvider {} }
1,377
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/credentials/ProfileTokenProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token.credentials; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.function.Supplier; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.utils.StringInputStream; class ProfileTokenProviderTest { @Test void missingProfileFile_throwsException() { ProfileTokenProvider provider = new ProfileTokenProvider.BuilderImpl() .defaultProfileFileLoader(() -> ProfileFile.builder() .content(new StringInputStream("")) .type(ProfileFile.Type.CONFIGURATION) .build()) .build(); assertThatThrownBy(provider::resolveToken).isInstanceOf(SdkClientException.class); } @Test void emptyProfileFile_throwsException() { ProfileTokenProvider provider = new ProfileTokenProvider.BuilderImpl() .defaultProfileFileLoader(() -> ProfileFile.builder() .content(new StringInputStream("")) .type(ProfileFile.Type.CONFIGURATION) .build()) .build(); assertThatThrownBy(provider::resolveToken).isInstanceOf(SdkClientException.class); } @Test void missingProfile_throwsException() { ProfileFile file = profileFile("[default]\n" + "aws_access_key_id = defaultAccessKey\n" + "aws_secret_access_key = defaultSecretAccessKey"); ProfileTokenProvider provider = ProfileTokenProvider.builder().profileFile(() -> file).profileName("sso").build(); assertThatThrownBy(provider::resolveToken).isInstanceOf(SdkClientException.class); } @Test void compatibleProfileSettings_callsLoader() { ProfileFile file = profileFile("[default]"); ProfileTokenProvider provider = ProfileTokenProvider.builder().profileFile(() -> file).profileName("default").build(); assertThatThrownBy(provider::resolveToken).hasMessageContaining("does not have sso_session property"); } @Test void resolveToken_profileFileSupplier_suppliesObjectPerCall() { ProfileFile file1 = profileFile("[profile sso]\n" + "aws_access_key_id = defaultAccessKey\n" + "aws_secret_access_key = defaultSecretAccessKey\n" + "sso_session = xyz"); ProfileFile file2 = profileFile("[profile sso]\n" + "aws_access_key_id = modifiedAccessKey\n" + "aws_secret_access_key = modifiedSecretAccessKey\n" + "sso_session = xyz"); Supplier<ProfileFile> supplier = Mockito.mock(Supplier.class); ProfileTokenProvider provider = ProfileTokenProvider.builder().profileFile(supplier).profileName("sso").build(); Mockito.when(supplier.get()).thenReturn(file1, file2); assertThatThrownBy(provider::resolveToken).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(provider::resolveToken).isInstanceOf(IllegalArgumentException.class); Mockito.verify(supplier, Mockito.times(2)).get(); } private ProfileFile profileFile(String string) { return ProfileFile.builder() .content(new StringInputStream(string)) .type(ProfileFile.Type.CONFIGURATION) .build(); } }
1,378
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/credentials/SdkTokenProviderChainTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token.credentials; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.time.Instant; import java.util.Arrays; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import software.amazon.awssdk.auth.token.TestBearerToken; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.TokenIdentity; public class SdkTokenProviderChainTest { public static final Instant SAMPLE_EXPIRATION_TIME = Instant.ofEpochMilli(1642108606L); public static final String SAMPLE_TOKEN_STRING = "mJ_9.B5f-4.1Jmv"; /** * Tests that, by default, the chain remembers which provider was able to provide token, and only calls that provider * for any additional calls to getToken. */ @Test public void resolveToken_reuseEnabled_reusesLastProvider() { MockTokenProvider provider1 = new MockTokenProvider("Failed!"); MockTokenProvider provider2 = new MockTokenProvider(); SdkTokenProviderChain chain = SdkTokenProviderChain.builder() .tokenProviders(provider1, provider2) .build(); assertEquals(0, provider1.getTokenCallCount); assertEquals(0, provider2.getTokenCallCount); chain.resolveToken(); assertEquals(1, provider1.getTokenCallCount); assertEquals(1, provider2.getTokenCallCount); chain.resolveToken(); assertEquals(1, provider1.getTokenCallCount); assertEquals(2, provider2.getTokenCallCount); chain.resolveToken(); assertEquals(1, provider1.getTokenCallCount); assertEquals(3, provider2.getTokenCallCount); } /** * Tests that, when provider caching is disabled, the chain will always try all providers in the chain, starting with the * first, until it finds a provider that can return token. */ @Test public void resolveToken_reuseDisabled_alwaysGoesThroughChain() { MockTokenProvider provider1 = new MockTokenProvider("Failed!"); MockTokenProvider provider2 = new MockTokenProvider(); SdkTokenProviderChain chain = SdkTokenProviderChain.builder() .tokenProviders(provider1, provider2) .reuseLastProviderEnabled(false) .build(); assertEquals(0, provider1.getTokenCallCount); assertEquals(0, provider2.getTokenCallCount); chain.resolveToken(); assertEquals(1, provider1.getTokenCallCount); assertEquals(1, provider2.getTokenCallCount); chain.resolveToken(); assertEquals(2, provider1.getTokenCallCount); assertEquals(2, provider2.getTokenCallCount); } /** * Tests that getToken throws an Exception if all providers in the chain fail to provide token. */ @Test public void resolveToken_allProvidersFail_throwsExceptionWithMessageFromAllProviders() { MockTokenProvider provider1 = new MockTokenProvider("Failed!"); MockTokenProvider provider2 = new MockTokenProvider("Bad!"); SdkTokenProviderChain chain = SdkTokenProviderChain.builder() .tokenProviders(provider1, provider2) .build(); SdkClientException e = assertThrows(SdkClientException.class, () -> chain.resolveToken()); assertThat(e.getMessage()).contains(provider1.exceptionMessage); assertThat(e.getMessage()).contains(provider2.exceptionMessage); } @Test public void resolveToken_emptyChain_throwsException() { assertThrowsIllegalArgument(() -> SdkTokenProviderChain.of()); assertThrowsIllegalArgument(() -> SdkTokenProviderChain .builder() .tokenProviders() .build()); assertThrowsIllegalArgument(() -> SdkTokenProviderChain .builder() .tokenProviders(Arrays.asList()) .build()); } private void assertThrowsIllegalArgument(Executable executable) { IllegalArgumentException e = assertThrows(IllegalArgumentException.class, executable); assertThat(e.getMessage()).contains("No token providers were specified."); } /** * Tests that the chain is setup correctly with the overloaded methods that accept the AwsCredentialsProvider type. */ @Test public void createMethods_withOldTokenType_work() { SdkTokenProvider provider = new MockTokenProvider(); assertChainResolvesCorrectly(SdkTokenProviderChain.of(provider)); assertChainResolvesCorrectly(SdkTokenProviderChain.builder().tokenProviders(provider).build()); assertChainResolvesCorrectly(SdkTokenProviderChain.builder().tokenProviders(Arrays.asList(provider)).build()); assertChainResolvesCorrectly(SdkTokenProviderChain.builder().addTokenProvider(provider).build()); } /** * Tests that the chain is setup correctly with the overloaded methods that accept the IdentityProvider type. */ @Test public void createMethods_withNewTokenType_work() { IdentityProvider<TokenIdentity> provider = new MockTokenProvider(); assertChainResolvesCorrectly(SdkTokenProviderChain.of(provider)); assertChainResolvesCorrectly(SdkTokenProviderChain.builder().tokenProviders(provider).build()); assertChainResolvesCorrectly(SdkTokenProviderChain.builder().tokenIdentityProviders(Arrays.asList(provider)).build()); assertChainResolvesCorrectly(SdkTokenProviderChain.builder().addTokenProvider(provider).build()); } private static void assertChainResolvesCorrectly(SdkTokenProviderChain chain) { SdkToken token = chain.resolveToken(); assertThat(token.token()).isEqualTo(SAMPLE_TOKEN_STRING); } private static final class MockTokenProvider implements SdkTokenProvider { private final SdkTokenProvider sdkTokenProvider; private final String exceptionMessage; int getTokenCallCount = 0; private MockTokenProvider() { this(null); } private MockTokenProvider(String exceptionMessage) { sdkTokenProvider = StaticTokenProvider.create(TestBearerToken.create(SAMPLE_TOKEN_STRING, SAMPLE_EXPIRATION_TIME)); this.exceptionMessage = exceptionMessage; } @Override public SdkToken resolveToken() { getTokenCallCount++; if (exceptionMessage != null) { throw new RuntimeException(exceptionMessage); } else { return sdkTokenProvider.resolveToken(); } } } }
1,379
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/credentials
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/credentials/internal/TokenUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token.credentials.internal; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.TokenUtils; import software.amazon.awssdk.auth.token.TestBearerToken; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.identity.spi.TokenIdentity; public class TokenUtilsTest { @Test public void toSdkToken_null_returnsNull() { assertThat(TokenUtils.toSdkToken(null)).isNull(); } @Test public void toSdkToken_SdkToken_returnsAsIs() { TokenIdentity input = TestBearerToken.create("t"); SdkToken output = TokenUtils.toSdkToken(input); assertThat(output).isSameAs(input); } @Test public void toSdkToken_TokenIdentity_returnsSdkToken() { TokenIdentity tokenIdentity = TokenIdentity.create("token"); SdkToken sdkToken = TokenUtils.toSdkToken(tokenIdentity); assertThat(sdkToken.token()).isEqualTo("token"); } }
1,380
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/credentials
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/token/credentials/aws/DefaultAwsTokenProviderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.token.credentials.aws; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.token.credentials.aws.DefaultAwsTokenProvider; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.utils.StringInputStream; public class DefaultAwsTokenProviderTest { @Test public void defaultCreate() { DefaultAwsTokenProvider tokenProvider = DefaultAwsTokenProvider.create(); assertThatThrownBy(tokenProvider::resolveToken) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Unable to load token"); } @Test public void profileFile() { DefaultAwsTokenProvider tokenProvider = DefaultAwsTokenProvider.builder() .profileFile(() -> profileFile("[default]")) .profileName("default") .build(); assertThatThrownBy(tokenProvider::resolveToken) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Unable to load token"); } private ProfileFile profileFile(String string) { return ProfileFile.builder() .content(new StringInputStream(string)) .type(ProfileFile.Type.CONFIGURATION) .build(); } }
1,381
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/S3SignerExecutionAttributeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.SignerProperty; import software.amazon.awssdk.identity.spi.Identity; class S3SignerExecutionAttributeTest { private static final SelectedAuthScheme<Identity> EMPTY_SELECTED_AUTH_SCHEME = new SelectedAuthScheme<>(CompletableFuture.completedFuture(Mockito.mock(Identity.class)), (HttpSigner<Identity>) Mockito.mock(HttpSigner.class), AuthSchemeOption.builder().schemeId("mock").build()); private ExecutionAttributes attributes; @BeforeEach public void setup() { this.attributes = new ExecutionAttributes(); } @Test public void enableChunkedEncoding_oldAndNewAttributeAreMirrored() { assertOldAndNewBooleanAttributesAreMirrored(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING, AwsV4FamilyHttpSigner.CHUNK_ENCODING_ENABLED); } @Test public void enablePayloadSigning_oldAndNewAttributeAreMirrored() { assertOldAndNewBooleanAttributesAreMirrored(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, AwsV4FamilyHttpSigner.PAYLOAD_SIGNING_ENABLED); } private void assertOldAndNewBooleanAttributesAreMirrored(ExecutionAttribute<Boolean> attribute, SignerProperty<Boolean> property) { assertOldAndNewAttributesAreMirrored(attribute, property, true, true); assertOldAndNewAttributesAreMirrored(attribute, property, false, false); } private <T, U> void assertOldAndNewAttributesAreMirrored(ExecutionAttribute<T> oldAttribute, SignerProperty<U> newProperty, T oldPropertyValue, U newPropertyValue) { // If selected auth scheme is null, writing non-null old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); assertOldAttributeWrite_canBeReadFromNewAttribute(oldAttribute, newProperty, oldPropertyValue, newPropertyValue); // If selected auth scheme is null, writing null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); assertOldAttributeWrite_canBeReadFromNewAttribute(oldAttribute, newProperty, null, null); // If selected auth scheme is non-null, writing non-null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, EMPTY_SELECTED_AUTH_SCHEME); assertOldAttributeWrite_canBeReadFromNewAttribute(oldAttribute, newProperty, oldPropertyValue, newPropertyValue); // If selected auth scheme is non-null, writing null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, EMPTY_SELECTED_AUTH_SCHEME); assertOldAttributeWrite_canBeReadFromNewAttribute(oldAttribute, newProperty, null, null); // Writing non-null new property can be read with old property assertNewPropertyWrite_canBeReadFromNewAttribute(oldAttribute, newProperty, oldPropertyValue, newPropertyValue); // Writing null new property can be read with old property assertNewPropertyWrite_canBeReadFromNewAttribute(oldAttribute, newProperty, null, null); // Null selected auth scheme can be read with old property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); assertThat(attributes.getAttribute(oldAttribute)).isNull(); } private <T, U> void assertNewPropertyWrite_canBeReadFromNewAttribute(ExecutionAttribute<T> oldAttribute, SignerProperty<U> newProperty, T oldPropertyValue, U newPropertyValue) { AuthSchemeOption newOption = EMPTY_SELECTED_AUTH_SCHEME.authSchemeOption().copy(o -> o.putSignerProperty(newProperty, newPropertyValue)); attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, new SelectedAuthScheme<>(EMPTY_SELECTED_AUTH_SCHEME.identity(), EMPTY_SELECTED_AUTH_SCHEME.signer(), newOption)); assertThat(attributes.getAttribute(oldAttribute)).isEqualTo(oldPropertyValue); } private <T, U> void assertOldAttributeWrite_canBeReadFromNewAttribute(ExecutionAttribute<T> attributeToWrite, SignerProperty<U> propertyToRead, T valueToWrite, U propertyToExpect) { attributes.putAttribute(attributeToWrite, valueToWrite); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME) .authSchemeOption() .signerProperty(propertyToRead)).isEqualTo(propertyToExpect); } }
1,382
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/BearerTokenSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.ByteArrayInputStream; import java.net.URI; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.token.signer.SdkTokenExecutionAttribute; import software.amazon.awssdk.auth.token.TestBearerToken; import software.amazon.awssdk.auth.signer.params.TokenSignerParams; import software.amazon.awssdk.auth.token.signer.aws.BearerTokenSigner; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; class BearerTokenSignerTest { private static final String BEARER_AUTH_MARKER = "Bearer "; @Test public void whenTokenExists_requestIsSignedCorrectly() { String tokenValue = "mF_9.B5f-4.1JqM"; BearerTokenSigner tokenSigner = BearerTokenSigner.create(); SdkHttpFullRequest signedRequest = tokenSigner.sign(generateBasicRequest(), executionAttributes(TestBearerToken.create(tokenValue))); String expectedHeader = createExpectedHeader(tokenValue); assertThat(signedRequest.firstMatchingHeader("Authorization")).hasValue(expectedHeader); } @Test public void whenTokenIsMissing_exceptionIsThrown() { BearerTokenSigner tokenSigner = BearerTokenSigner.create(); assertThatThrownBy(() -> tokenSigner.sign(generateBasicRequest(), executionAttributes(null))) .isInstanceOf(NullPointerException.class) .hasMessageContaining("token"); } @Test public void usingParamMethod_worksCorrectly() { String tokenValue = "mF_9.B5f-4.1JqM"; BearerTokenSigner tokenSigner = BearerTokenSigner.create(); SdkHttpFullRequest signedRequest = tokenSigner.sign(generateBasicRequest(), TokenSignerParams.builder() .token(TestBearerToken.create(tokenValue)) .build()); String expectedHeader = createExpectedHeader(tokenValue); assertThat(signedRequest.firstMatchingHeader("Authorization")).hasValue(expectedHeader); } private static String createExpectedHeader(String token) { return BEARER_AUTH_MARKER + token; } private static ExecutionAttributes executionAttributes(TestBearerToken token) { ExecutionAttributes executionAttributes = new ExecutionAttributes(); executionAttributes.putAttribute(SdkTokenExecutionAttribute.SDK_TOKEN, token); return executionAttributes; } private static SdkHttpFullRequest generateBasicRequest() { return SdkHttpFullRequest.builder() .contentStreamProvider(() -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes())) .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .uri(URI.create("http://demo.us-east-1.amazonaws.com")) .build(); } }
1,383
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/NonStreamingAsyncBodyAws4SignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import io.reactivex.Flowable; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.signer.params.SignerChecksumParams; import software.amazon.awssdk.auth.signer.params.Aws4SignerParams; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.http.ContentStreamProvider; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.regions.Region; public class NonStreamingAsyncBodyAws4SignerTest { @Test void test_sign_computesCorrectSignature() { Aws4Signer aws4Signer = Aws4Signer.create(); AsyncAws4Signer asyncAws4Signer = AsyncAws4Signer.create(); byte[] content = "Hello AWS!".getBytes(StandardCharsets.UTF_8); ContentStreamProvider syncBody = () -> new ByteArrayInputStream(content); AsyncRequestBody asyncBody = AsyncRequestBody.fromBytes(content); SdkHttpFullRequest httpRequest = SdkHttpFullRequest.builder() .protocol("https") .host("my-cool-aws-service.us-west-2.amazonaws.com") .method(SdkHttpMethod.GET) .putHeader("header1", "headerval1") .contentStreamProvider(syncBody) .build(); AwsCredentials credentials = AwsBasicCredentials.create("akid", "skid"); Aws4SignerParams signerParams = Aws4SignerParams.builder() .awsCredentials(credentials) .signingClockOverride(Clock.fixed(Instant.EPOCH, ZoneId.of("UTC"))) .signingName("my-cool-aws-service") .signingRegion(Region.US_WEST_2) .build(); List<String> syncSignature = aws4Signer.sign(httpRequest, signerParams).headers().get("Authorization"); List<String> asyncSignature = asyncAws4Signer.signWithBody(httpRequest, asyncBody, signerParams).join() .headers().get("Authorization"); assertThat(asyncSignature).isEqualTo(syncSignature); } @Test void test_sign_publisherThrows_exceptionPropagated() { AsyncAws4Signer asyncAws4Signer = AsyncAws4Signer.create(); RuntimeException error = new RuntimeException("error"); Flowable<ByteBuffer> errorPublisher = Flowable.error(error); AsyncRequestBody asyncBody = new AsyncRequestBody() { @Override public Optional<Long> contentLength() { return Optional.of(42L); } @Override public void subscribe(Subscriber<? super ByteBuffer> subscriber) { errorPublisher.subscribe(subscriber); } }; SdkHttpFullRequest httpRequest = SdkHttpFullRequest.builder() .protocol("https") .host("my-cool-aws-service.us-west-2.amazonaws.com") .method(SdkHttpMethod.GET) .putHeader("header1", "headerval1") .build(); AwsCredentials credentials = AwsBasicCredentials.create("akid", "skid"); Aws4SignerParams signerParams = Aws4SignerParams.builder() .awsCredentials(credentials) .signingClockOverride(Clock.fixed(Instant.EPOCH, ZoneId.of("UTC"))) .signingName("my-cool-aws-service") .signingRegion(Region.US_WEST_2) .build(); assertThatThrownBy(asyncAws4Signer.signWithBody(httpRequest, asyncBody, signerParams)::join) .hasCause(error); } @Test void test_sign_futureCancelled_propagatedToPublisher() { SdkHttpFullRequest httpRequest = SdkHttpFullRequest.builder() .protocol("https") .host("my-cool-aws-service.us-west-2.amazonaws.com") .method(SdkHttpMethod.GET) .putHeader("header1", "headerval1") .build(); AwsCredentials credentials = AwsBasicCredentials.create("akid", "skid"); Aws4SignerParams signerParams = Aws4SignerParams.builder() .awsCredentials(credentials) .signingClockOverride(Clock.fixed(Instant.EPOCH, ZoneId.of("UTC"))) .signingName("my-cool-aws-service") .signingRegion(Region.US_WEST_2) .build(); AsyncRequestBody mockRequestBody = mock(AsyncRequestBody.class); Subscription mockSubscription = mock(Subscription.class); doAnswer((Answer<Void>) invocationOnMock -> { Subscriber subscriber = invocationOnMock.getArgument(0, Subscriber.class); subscriber.onSubscribe(mockSubscription); return null; }).when(mockRequestBody).subscribe(any(Subscriber.class)); AsyncAws4Signer asyncAws4Signer = AsyncAws4Signer.create(); CompletableFuture<SdkHttpFullRequest> signedRequestFuture = asyncAws4Signer.signWithBody(httpRequest, mockRequestBody, signerParams); signedRequestFuture.cancel(true); verify(mockSubscription).cancel(); } @Test void test_sign_computesCorrectSignatureWithChecksum() { Aws4Signer aws4Signer = Aws4Signer.create(); AsyncAws4Signer asyncAws4Signer = AsyncAws4Signer.create(); byte[] content = "abc".getBytes(StandardCharsets.UTF_8); ContentStreamProvider syncBody = () -> new ByteArrayInputStream(content); AsyncRequestBody asyncBody = AsyncRequestBody.fromBytes(content); SdkHttpFullRequest httpRequest = SdkHttpFullRequest.builder() .protocol("https") .host("my-cool-aws-service.us-west-2.amazonaws.com") .method(SdkHttpMethod.GET) .putHeader("header1", "headerval1") .contentStreamProvider(syncBody) .build(); AwsCredentials credentials = AwsBasicCredentials.create("akid", "skid"); Aws4SignerParams signerParams = Aws4SignerParams.builder() .awsCredentials(credentials) .signingClockOverride(Clock.fixed(Instant.EPOCH, ZoneId.of("UTC"))) .signingName("my-cool-aws-service") .signingRegion(Region.US_WEST_2) .checksumParams(SignerChecksumParams.builder().algorithm(Algorithm.SHA256) .checksumHeaderName("x-amzn-header") .isStreamingRequest(true) .build()) .build(); List<String> syncSignature = aws4Signer.sign(httpRequest, signerParams).headers().get("Authorization"); final SdkHttpFullRequest sdkHttpFullRequest = asyncAws4Signer.signWithBody(httpRequest, asyncBody, signerParams).join(); List<String> asyncSignature = sdkHttpFullRequest.headers().get("Authorization"); assertThat(asyncSignature).isEqualTo(syncSignature); final List<String> stringList = sdkHttpFullRequest.headers().get("x-amzn-header"); assertThat(stringList.stream().findFirst()).hasValue("ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0="); assertThat(sdkHttpFullRequest.firstMatchingHeader(("x-amzn-trailer"))).isNotPresent(); } }
1,384
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/EventStreamAws4SignerTest.java
package software.amazon.awssdk.auth.signer; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import io.reactivex.Flowable; import java.net.URI; import java.nio.ByteBuffer; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; import java.util.Base64; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.signer.internal.SignerTestUtils; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.regions.Region; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; import software.amazon.eventstream.MessageDecoder; public class EventStreamAws4SignerTest { /** * Verify that when an event stream is open from one day to the next, the signature is properly signed for the day of the * event. */ @Test public void openStreamEventSignaturesCanRollOverBetweenDays() { EventStreamAws4Signer signer = EventStreamAws4Signer.create(); Region region = Region.US_WEST_2; AwsCredentials credentials = AwsBasicCredentials.create("a", "s"); String signingName = "name"; AdjustableClock clock = new AdjustableClock(); clock.time = Instant.parse("2020-01-01T23:59:59Z"); SdkHttpFullRequest initialRequest = SdkHttpFullRequest.builder() .uri(URI.create("http://localhost:8080")) .method(SdkHttpMethod.GET) .build(); SdkHttpFullRequest signedRequest = SignerTestUtils.signRequest(signer, initialRequest, credentials, signingName, clock, region.id()); ByteBuffer event = new Message(Collections.emptyMap(), "foo".getBytes(UTF_8)).toByteBuffer(); Callable<ByteBuffer> lastEvent = () -> { clock.time = Instant.parse("2020-01-02T00:00:00Z"); return event; }; AsyncRequestBody requestBody = AsyncRequestBody.fromPublisher(Flowable.concatArray(Flowable.just(event), Flowable.fromCallable(lastEvent))); AsyncRequestBody signedBody = SignerTestUtils.signAsyncRequest(signer, signedRequest, requestBody, credentials, signingName, clock, region.id()); List<Message> signedMessages = readMessages(signedBody); assertThat(signedMessages.size()).isEqualTo(3); Map<String, HeaderValue> firstMessageHeaders = signedMessages.get(0).getHeaders(); assertThat(firstMessageHeaders.get(":date").getTimestamp()).isEqualTo("2020-01-01T23:59:59Z"); assertThat(Base64.getEncoder().encodeToString(firstMessageHeaders.get(":chunk-signature").getByteArray())) .isEqualTo("EFt7ZU043r/TJE8U+1GxJXscmNxoqmIdGtUIl8wE9u0="); Map<String, HeaderValue> lastMessageHeaders = signedMessages.get(2).getHeaders(); assertThat(lastMessageHeaders.get(":date").getTimestamp()).isEqualTo("2020-01-02T00:00:00Z"); assertThat(Base64.getEncoder().encodeToString(lastMessageHeaders.get(":chunk-signature").getByteArray())) .isEqualTo("UTRGo0D7BQytiVkH1VofR/8f3uFsM4V5QR1A8grr1+M="); } private List<Message> readMessages(AsyncRequestBody signedBody) { MessageDecoder decoder = new MessageDecoder(); Flowable.fromPublisher(signedBody).blockingForEach(x -> decoder.feed(x.array())); return decoder.getDecodedMessages(); } private static class AdjustableClock extends Clock { private Instant time; @Override public ZoneId getZone() { return ZoneOffset.UTC; } @Override public Clock withZone(ZoneId zone) { throw new UnsupportedOperationException(); } @Override public Instant instant() { return time; } } }
1,385
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/AwsS3V4SignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import java.net.URI; import java.nio.ByteBuffer; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import java.util.concurrent.ThreadLocalRandom; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams; import software.amazon.awssdk.auth.signer.params.AwsS3V4SignerParams; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.regions.Region; class AwsS3V4SignerTest { private static final Clock UTC_EPOCH_CLOCK = Clock.fixed(Instant.EPOCH, ZoneOffset.UTC); @Test public void signWithParams_urlsAreNotNormalized() { byte[] bytes = new byte[1000]; ThreadLocalRandom.current().nextBytes(bytes); ByteBuffer buffer = ByteBuffer.wrap(bytes); URI target = URI.create("https://test.com/./foo"); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .contentStreamProvider(RequestBody.fromByteBuffer(buffer) .contentStreamProvider()) .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .build(); AwsS3V4Signer signer = AwsS3V4Signer.create(); SdkHttpFullRequest signedRequest = signer.sign(request, AwsS3V4SignerParams.builder() .awsCredentials(AwsBasicCredentials.create("akid", "skid")) .signingRegion(Region.US_WEST_2) .signingName("s3") .signingClockOverride(UTC_EPOCH_CLOCK) .build()); assertThat(signedRequest.firstMatchingHeader("Authorization")) .hasValue("AWS4-HMAC-SHA256 Credential=akid/19700101/us-west-2/s3/aws4_request, " + "SignedHeaders=host;x-amz-content-sha256;x-amz-date, " + "Signature=a3b97f9de337ab254f3b366c3d0b3c67016d2d8d8ba7e0e4ddab0ccebe84992a"); } @Test public void signWithExecutionAttributes_urlsAreNotNormalized() { byte[] bytes = new byte[1000]; ThreadLocalRandom.current().nextBytes(bytes); ByteBuffer buffer = ByteBuffer.wrap(bytes); URI target = URI.create("https://test.com/./foo"); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .contentStreamProvider(RequestBody.fromByteBuffer(buffer) .contentStreamProvider()) .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .build(); ExecutionAttributes attributes = ExecutionAttributes.builder() .put(AwsSignerExecutionAttribute.AWS_CREDENTIALS, AwsBasicCredentials.create("akid", "skid")) .put(AwsSignerExecutionAttribute.SIGNING_REGION, Region.US_WEST_2) .put(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, "s3") .put(AwsSignerExecutionAttribute.SIGNING_CLOCK, UTC_EPOCH_CLOCK) .build(); AwsS3V4Signer signer = AwsS3V4Signer.create(); SdkHttpFullRequest signedRequest = signer.sign(request, attributes); assertThat(signedRequest.firstMatchingHeader("Authorization")) .hasValue("AWS4-HMAC-SHA256 Credential=akid/19700101/us-west-2/s3/aws4_request, " + "SignedHeaders=host;x-amz-content-sha256;x-amz-date, " + "Signature=a3b97f9de337ab254f3b366c3d0b3c67016d2d8d8ba7e0e4ddab0ccebe84992a"); } @Test public void presignWithParams_urlsAreNotNormalized() { byte[] bytes = new byte[1000]; ThreadLocalRandom.current().nextBytes(bytes); ByteBuffer buffer = ByteBuffer.wrap(bytes); URI target = URI.create("https://test.com/./foo"); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .contentStreamProvider(RequestBody.fromByteBuffer(buffer) .contentStreamProvider()) .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .build(); AwsS3V4Signer signer = AwsS3V4Signer.create(); SdkHttpFullRequest signedRequest = signer.presign(request, Aws4PresignerParams.builder() .awsCredentials(AwsBasicCredentials.create("akid", "skid")) .signingRegion(Region.US_WEST_2) .signingName("s3") .signingClockOverride(UTC_EPOCH_CLOCK) .build()); assertThat(signedRequest.firstMatchingRawQueryParameter("X-Amz-Signature")) .hasValue("3a9d36d37e9a554b7a3803f58ee7539b5d1f52fdfe89ce6fd40fb25762a35ec3"); } @Test public void presignWithExecutionAttributes_urlsAreNotNormalized() { byte[] bytes = new byte[1000]; ThreadLocalRandom.current().nextBytes(bytes); ByteBuffer buffer = ByteBuffer.wrap(bytes); URI target = URI.create("https://test.com/./foo"); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .contentStreamProvider(RequestBody.fromByteBuffer(buffer) .contentStreamProvider()) .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .build(); ExecutionAttributes attributes = ExecutionAttributes.builder() .put(AwsSignerExecutionAttribute.AWS_CREDENTIALS, AwsBasicCredentials.create("akid", "skid")) .put(AwsSignerExecutionAttribute.SIGNING_REGION, Region.US_WEST_2) .put(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, "s3") .put(AwsSignerExecutionAttribute.SIGNING_CLOCK, UTC_EPOCH_CLOCK) .build(); AwsS3V4Signer signer = AwsS3V4Signer.create(); SdkHttpFullRequest signedRequest = signer.presign(request, attributes); assertThat(signedRequest.firstMatchingRawQueryParameter("X-Amz-Signature")) .hasValue("3a9d36d37e9a554b7a3803f58ee7539b5d1f52fdfe89ce6fd40fb25762a35ec3"); } @Test public void signWithParams_doesNotFailWithEncodedCharacters() { URI target = URI.create("https://test.com/%20foo"); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .build(); AwsS3V4Signer signer = AwsS3V4Signer.create(); assertDoesNotThrow(() -> signer.sign(request, AwsS3V4SignerParams.builder() .awsCredentials(AwsBasicCredentials.create("akid", "skid")) .signingRegion(Region.US_WEST_2) .signingName("s3") .build())); } @Test public void signWithExecutionAttributes_doesNotFailWithEncodedCharacters() { URI target = URI.create("https://test.com/%20foo"); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .build(); ExecutionAttributes attributes = ExecutionAttributes.builder() .put(AwsSignerExecutionAttribute.AWS_CREDENTIALS, AwsBasicCredentials.create("akid", "skid")) .put(AwsSignerExecutionAttribute.SIGNING_REGION, Region.US_WEST_2) .put(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, "s3") .build(); AwsS3V4Signer signer = AwsS3V4Signer.create(); assertDoesNotThrow(() -> signer.sign(request, attributes)); } @Test public void presignWithParams_doesNotFailWithEncodedCharacters() { URI target = URI.create("https://test.com/%20foo"); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .build(); AwsS3V4Signer signer = AwsS3V4Signer.create(); assertDoesNotThrow(() -> signer.presign(request, Aws4PresignerParams.builder() .awsCredentials(AwsBasicCredentials.create("akid", "skid")) .signingRegion(Region.US_WEST_2) .signingName("s3") .build())); } @Test public void presignWithExecutionAttributes_doesNotFailWithEncodedCharacters() { URI target = URI.create("https://test.com/%20foo"); SdkHttpFullRequest request = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .uri(target) .encodedPath(target.getPath()) .build(); ExecutionAttributes attributes = ExecutionAttributes.builder() .put(AwsSignerExecutionAttribute.AWS_CREDENTIALS, AwsBasicCredentials.create("akid", "skid")) .put(AwsSignerExecutionAttribute.SIGNING_REGION, Region.US_WEST_2) .put(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, "s3") .build(); AwsS3V4Signer signer = AwsS3V4Signer.create(); assertDoesNotThrow(() -> signer.presign(request, attributes)); } }
1,386
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/Aws4EventStreamSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static software.amazon.awssdk.auth.signer.internal.BaseEventStreamAsyncAws4Signer.EVENT_STREAM_DATE; import static software.amazon.awssdk.auth.signer.internal.BaseEventStreamAsyncAws4Signer.EVENT_STREAM_SIGNATURE; import io.reactivex.Flowable; import io.reactivex.functions.BiFunction; import io.reactivex.functions.Function; import io.reactivex.subscribers.TestSubscriber; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.Clock; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; import org.assertj.core.util.Lists; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.signer.internal.SignerTestUtils; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; import software.amazon.eventstream.MessageDecoder; /** * Unit tests for the {@link EventStreamAws4Signer}. */ public class Aws4EventStreamSignerTest { interface TestVector { SdkHttpFullRequest.Builder httpFullRequest(); List<String> requestBody(); AsyncRequestBody requestBodyPublisher(); Flowable<Message> expectedMessagePublisher(); } private static final List<Instant> SIGNING_INSTANTS = Stream.of( // Note: This first Instant is used for signing the request not an event OffsetDateTime.of(1981, 1, 16, 6, 30, 0, 0, ZoneOffset.UTC).toInstant(), OffsetDateTime.of(1981, 1, 16, 6, 30, 1, 0, ZoneOffset.UTC).toInstant(), OffsetDateTime.of(1981, 1, 16, 6, 30, 2, 0, ZoneOffset.UTC).toInstant(), OffsetDateTime.of(1981, 1, 16, 6, 30, 3, 0, ZoneOffset.UTC).toInstant(), OffsetDateTime.of(1981, 1, 16, 6, 30, 4, 0, ZoneOffset.UTC).toInstant() ).collect(Collectors.toList()); private EventStreamAws4Signer signer = EventStreamAws4Signer.create(); @Test public void testEventStreamSigning() { TestVector testVector = generateTestVector(); SdkHttpFullRequest.Builder request = testVector.httpFullRequest(); AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); SdkHttpFullRequest signedRequest = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingClock(), "us-east-1"); AsyncRequestBody transformedPublisher = SignerTestUtils.signAsyncRequest(signer, signedRequest, testVector.requestBodyPublisher(), credentials, "demo", signingClock(), "us-east-1"); TestSubscriber testSubscriber = TestSubscriber.create(); Flowable.fromPublisher(transformedPublisher) .flatMap(new Function<ByteBuffer, Publisher<?>>() { Queue<Message> messages = new LinkedList<>(); MessageDecoder decoder = new MessageDecoder(message -> messages.offer(message)); @Override public Publisher<?> apply(ByteBuffer byteBuffer) throws Exception { decoder.feed(byteBuffer.array()); List<Message> messageList = new ArrayList<>(); while (!messages.isEmpty()) { messageList.add(messages.poll()); } return Flowable.fromIterable(messageList); } }) .subscribe(testSubscriber); testSubscriber.assertNoErrors(); testSubscriber.assertComplete(); testSubscriber.assertValueSequence(testVector.expectedMessagePublisher().blockingIterable()); } /** * Test that without demand from subscriber, trailing empty frame is not delivered */ @Test public void testBackPressure() { TestVector testVector = generateTestVector(); SdkHttpFullRequest.Builder request = testVector.httpFullRequest(); AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); SdkHttpFullRequest signedRequest = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingClock(), "us-east-1"); AsyncRequestBody transformedPublisher = SignerTestUtils.signAsyncRequest(signer, signedRequest, testVector.requestBodyPublisher(), credentials, "demo", signingClock(), "us-east-1"); Subscriber<Object> subscriber = Mockito.spy(new Subscriber<Object>() { @Override public void onSubscribe(Subscription s) { //Only request the number of request body (excluding trailing empty frame) s.request(testVector.requestBody().size()); } @Override public void onNext(Object o) { } @Override public void onError(Throwable t) { fail("onError should never been called"); } @Override public void onComplete() { fail("onComplete should never been called"); } }); Flowable.fromPublisher(transformedPublisher) .flatMap(new Function<ByteBuffer, Publisher<?>>() { Queue<Message> messages = new LinkedList<>(); MessageDecoder decoder = new MessageDecoder(message -> messages.offer(message)); @Override public Publisher<?> apply(ByteBuffer byteBuffer) throws Exception { decoder.feed(byteBuffer.array()); List<Message> messageList = new ArrayList<>(); while (!messages.isEmpty()) { messageList.add(messages.poll()); } return Flowable.fromIterable(messageList); } }) .subscribe(subscriber); // The number of events equal to the size of request body (excluding trailing empty frame) verify(subscriber, times(testVector.requestBody().size())).onNext(any()); // subscriber is not terminated (no onError/onComplete) since trailing empty frame is not delivered yet verify(subscriber, never()).onError(any()); verify(subscriber, never()).onComplete(); } TestVector generateTestVector() { return new TestVector() { List<String> requestBody = Lists.newArrayList("A", "B", "C"); @Override public List<String> requestBody() { return requestBody; } @Override public SdkHttpFullRequest.Builder httpFullRequest() { //Header signature: "79f246d8652f08dd3cfaf84cc0d8b4fcce032332c78d43ea1ed6f4f6586ab59d"; //Signing key: "29dc0a760fed568677d74136ad02d315a07d31b8f321f5c43350f284dac892c"; return SdkHttpFullRequest.builder() .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("content-encoding", "application/vnd.amazon.eventstream") .putHeader("x-amz-content-sha256", "STREAMING-AWS4-HMAC-SHA256-EVENTS") .encodedPath("/streaming") .protocol("https") .host("demo.us-east-1.amazonaws.com"); } @Override public AsyncRequestBody requestBodyPublisher() { List<ByteBuffer> bodyBytes = requestBody.stream() .map(s -> ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8))) .collect(Collectors.toList()); Publisher<ByteBuffer> bodyPublisher = Flowable.fromIterable(bodyBytes); return AsyncRequestBody.fromPublisher(bodyPublisher); } @Override public Flowable<Message> expectedMessagePublisher() { Flowable<String> sigsHex = Flowable.just( "7aabf85b765e6a4d0d500b6e968657b14726fa3e1eb7e839302728ffd77629a5", "f72aa9642f571d24a6e1ae42f10f073ad9448d8a028b6bcd82da081335adda02", "632af120435b57ec241d8bfbb12e496dfd5e2730a1a02ac0ab6eaa230ae02e9a", "c6f679ddb3af68f5e82f0cf6761244cb2338cf11e7d01a24130aea1b7c17e53e"); // The Last data frame is empty Flowable<String> payloads = Flowable.fromIterable(requestBody).concatWith(Flowable.just("")); return sigsHex.zipWith(payloads, new BiFunction<String, String, Message>() { // The first Instant was used to sign the request private int idx = 1; @Override public Message apply(String sig, String payload) throws Exception { Map<String, HeaderValue> headers = new HashMap<>(); headers.put(EVENT_STREAM_DATE, HeaderValue.fromTimestamp(SIGNING_INSTANTS.get(idx++))); headers.put(EVENT_STREAM_SIGNATURE, HeaderValue.fromByteArray(BinaryUtils.fromHex(sig))); return new Message(headers, payload.getBytes(StandardCharsets.UTF_8)); } } ); } }; } /** * @return A clock that returns the values from {@link #SIGNING_INSTANTS} in order. * @throws IllegalStateException When there are no more instants to return. */ private static Clock signingClock() { return new Clock() { private AtomicInteger timeIndex = new AtomicInteger(0); @Override public Instant instant() { int idx; // Note: we use an atomic because Clock must be threadsafe, // though probably not necessary for our tests if ((idx = timeIndex.getAndIncrement()) >= SIGNING_INSTANTS.size()) { throw new IllegalStateException("Clock ran out of Instants to return! " + idx); } return SIGNING_INSTANTS.get(idx); } @Override public ZoneId getZone() { return ZoneOffset.UTC; } @Override public Clock withZone(ZoneId zone) { throw new UnsupportedOperationException(); } }; } }
1,387
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/Aws4SignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.time.Clock; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.SimpleTimeZone; import java.util.TimeZone; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.signer.internal.Aws4SignerUtils; import software.amazon.awssdk.auth.signer.internal.SignerConstant; import software.amazon.awssdk.auth.signer.params.SignerChecksumParams; import software.amazon.awssdk.auth.signer.internal.SignerTestUtils; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; /** * Unit tests for the {@link Aws4Signer}. */ @RunWith(MockitoJUnitRunner.class) public class Aws4SignerTest { private static final String AWS_4_HMAC_SHA_256_AUTHORIZATION = "AWS4-HMAC-SHA256 Credential=access/19810216/us-east-1/demo/aws4_request, "; private static final String SIGNER_HEADER_WITH_CHECKSUMS_IN_HEADER = "SignedHeaders=host;x-amz-archive-description;x-amz-date;x-amzn-header-crc, "; private static final String SIGNER_HEADER_WITH_CHECKSUMS_IN_TRAILER = "SignedHeaders=host;x-amz-archive-description;x-amz-date;x-amz-trailer, "; private Aws4Signer signer = Aws4Signer.create(); @Mock private Clock signingOverrideClock; SdkHttpFullRequest.Builder request; AwsBasicCredentials credentials; @Before public void setupCase() { mockClock(); credentials = AwsBasicCredentials.create("access", "secret"); request = SdkHttpFullRequest.builder() .contentStreamProvider(() -> new ByteArrayInputStream("abc".getBytes())) .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .uri(URI.create("http://demo.us-east-1.amazonaws.com")); } @Test public void testSigning() throws Exception { final String expectedAuthorizationHeaderWithoutSha256Header = AWS_4_HMAC_SHA_256_AUTHORIZATION + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=77fe7c02927966018667f21d1dc3dfad9057e58401cbb9ed64f1b7868288e35a"; final String expectedAuthorizationHeaderWithSha256Header = AWS_4_HMAC_SHA_256_AUTHORIZATION + "SignedHeaders=host;x-amz-archive-description;x-amz-date;x-amz-sha256, " + "Signature=e73e20539446307a5dc71252dbd5b97e861f1d1267456abda3ebd8d57e519951"; AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); // Test request without 'x-amz-sha256' header SdkHttpFullRequest.Builder request = generateBasicRequest(); SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(signed.firstMatchingHeader("Authorization")) .hasValue(expectedAuthorizationHeaderWithoutSha256Header); // Test request with 'x-amz-sha256' header request = generateBasicRequest(); request.putHeader("x-amz-sha256", "required"); signed = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorizationHeaderWithSha256Header); } @Test public void queryParamsWithNullValuesAreStillSignedWithTrailingEquals() throws Exception { final String expectedAuthorizationHeaderWithoutSha256Header = AWS_4_HMAC_SHA_256_AUTHORIZATION + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=c45a3ff1f028e83017f3812c06b4440f0b3240264258f6e18cd683b816990ba4"; AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); // Test request without 'x-amz-sha256' header SdkHttpFullRequest.Builder request = generateBasicRequest().putRawQueryParameter("Foo", (String) null); SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorizationHeaderWithoutSha256Header); } @Test public void testPresigning() throws Exception { final String expectedAmzSignature = "bf7ae1c2f266d347e290a2aee7b126d38b8a695149d003b9fab2ed1eb6d6ebda"; final String expectedAmzCredentials = "access/19810216/us-east-1/demo/aws4_request"; final String expectedAmzHeader = "19810216T063000Z"; final String expectedAmzExpires = "604800"; AwsBasicCredentials credentials = AwsBasicCredentials.create("access", "secret"); // Test request without 'x-amz-sha256' header SdkHttpFullRequest request = generateBasicRequest().build(); SdkHttpFullRequest signed = SignerTestUtils.presignRequest(signer, request, credentials, null, "demo", signingOverrideClock, "us-east-1"); assertEquals(expectedAmzSignature, signed.rawQueryParameters().get("X-Amz-Signature").get(0)); assertEquals(expectedAmzCredentials, signed.rawQueryParameters().get("X-Amz-Credential").get(0)); assertEquals(expectedAmzHeader, signed.rawQueryParameters().get("X-Amz-Date").get(0)); assertEquals(expectedAmzExpires, signed.rawQueryParameters().get("X-Amz-Expires").get(0)); } /** * Tests that if passed anonymous credentials, signer will not generate a signature. */ @Test public void testAnonymous() throws Exception { AwsCredentials credentials = AnonymousCredentialsProvider.create().resolveCredentials(); SdkHttpFullRequest request = generateBasicRequest().build(); SignerTestUtils.signRequest(signer, request, credentials, "demo", signingOverrideClock, "us-east-1"); assertNull(request.headers().get("Authorization")); } /** * x-amzn-trace-id should not be signed as it may be mutated by proxies or load balancers. */ @Test public void xAmznTraceId_NotSigned() throws Exception { AwsBasicCredentials credentials = AwsBasicCredentials.create("akid", "skid"); SdkHttpFullRequest.Builder request = generateBasicRequest(); request.putHeader("X-Amzn-Trace-Id", " Root=1-584b150a-708479cb060007ffbf3ee1da;Parent=36d3dbcfd150aac9;Sampled=1"); SdkHttpFullRequest actual = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(actual.firstMatchingHeader("Authorization")) .hasValue("AWS4-HMAC-SHA256 Credential=akid/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=581d0042389009a28d461124138f1fe8eeb8daed87611d2a2b47fd3d68d81d73"); } /** * Multi-value headers should be comma separated. */ @Test public void canonicalizedHeaderString_multiValueHeaders_areCommaSeparated() throws Exception { AwsBasicCredentials credentials = AwsBasicCredentials.create("akid", "skid"); SdkHttpFullRequest.Builder request = generateBasicRequest(); request.appendHeader("foo","bar"); request.appendHeader("foo","baz"); SdkHttpFullRequest actual = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); // We cannot easily test the canonical header string value, but the below signature asserts that it contains: // foo:bar,baz assertThat(actual.firstMatchingHeader("Authorization")) .hasValue("AWS4-HMAC-SHA256 Credential=akid/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=foo;host;x-amz-archive-description;x-amz-date, " + "Signature=1253bc1751048ea299e688cbe07a2224292e5cc606a079cb40459ad987793c19"); } /** * Canonical headers should remove excess white space before and after values, and convert sequential spaces to a single * space. */ @Test public void canonicalizedHeaderString_valuesWithExtraWhitespace_areTrimmed() throws Exception { AwsBasicCredentials credentials = AwsBasicCredentials.create("akid", "skid"); SdkHttpFullRequest.Builder request = generateBasicRequest(); request.putHeader("My-header1"," a b c "); request.putHeader("My-Header2"," \"a b c\" "); SdkHttpFullRequest actual = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); // We cannot easily test the canonical header string value, but the below signature asserts that it contains: // my-header1:a b c // my-header2:"a b c" assertThat(actual.firstMatchingHeader("Authorization")) .hasValue("AWS4-HMAC-SHA256 Credential=akid/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=host;my-header1;my-header2;x-amz-archive-description;x-amz-date, " + "Signature=6d3520e3397e7aba593d8ebd8361fc4405e90aed71bc4c7a09dcacb6f72460b9"); } /** * Query strings with empty keys should not be included in the canonical string. */ @Test public void canonicalizedQueryString_keyWithEmptyNames_doNotGetSigned() throws Exception { AwsBasicCredentials credentials = AwsBasicCredentials.create("akid", "skid"); SdkHttpFullRequest.Builder request = generateBasicRequest(); request.putRawQueryParameter("", (String) null); SdkHttpFullRequest actual = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1"); assertThat(actual.firstMatchingHeader("Authorization")) .hasValue("AWS4-HMAC-SHA256 Credential=akid/19810216/us-east-1/demo/aws4_request, " + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=581d0042389009a28d461124138f1fe8eeb8daed87611d2a2b47fd3d68d81d73"); } private SdkHttpFullRequest.Builder generateBasicRequest() { return SdkHttpFullRequest.builder() .contentStreamProvider(() -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes())) .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .uri(URI.create("http://demo.us-east-1.amazonaws.com")); } private void mockClock() { Calendar c = new GregorianCalendar(); c.set(1981, 1, 16, 6, 30, 0); c.setTimeZone(TimeZone.getTimeZone("UTC")); when(signingOverrideClock.millis()).thenReturn(c.getTimeInMillis()); } private String getOldTimeStamp(Date date) { final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'"); dateTimeFormat.setTimeZone(new SimpleTimeZone(0, "UTC")); return dateTimeFormat.format(date); } @Test public void getTimeStamp() { Date now = new Date(); String timeStamp = Aws4SignerUtils.formatTimestamp(now.getTime()); String old = getOldTimeStamp(now); assertEquals(old, timeStamp); } private String getOldDateStamp(Date date) { final SimpleDateFormat dateStampFormat = new SimpleDateFormat("yyyyMMdd"); dateStampFormat.setTimeZone(new SimpleTimeZone(0, "UTC")); return dateStampFormat.format(date); } @Test public void getDateStamp() { Date now = new Date(); String dateStamp = Aws4SignerUtils.formatDateStamp(now.getTime()); String old = getOldDateStamp(now); assertEquals(old, dateStamp); } @Test public void signing_with_Crc32Checksum_WithOut_x_amz_sha25_header() throws Exception { //Note here x_amz_sha25_header is not present in SignedHeaders String expectedAuthorization = AWS_4_HMAC_SHA_256_AUTHORIZATION + SIGNER_HEADER_WITH_CHECKSUMS_IN_HEADER + "Signature=c1804802dc623d1689e7d0a7f9f5caee3588cc8d3df4495425129dbd52965d1f"; final SignerChecksumParams signerChecksumParams = SignerChecksumParams.builder() .algorithm(Algorithm.CRC32) .checksumHeaderName("x-amzn-header-crc") .isStreamingRequest(false) .build(); SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.contentStreamProvider( () -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes(StandardCharsets.UTF_8)) ).build(), credentials, "demo", signingOverrideClock, "us-east-1", signerChecksumParams); assertThat(signed.firstMatchingHeader("x-amzn-header-crc").get()).contains("oL+a/g=="); assertThat(signed.firstMatchingHeader(SignerConstant.X_AMZ_CONTENT_SHA256)).isNotPresent(); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorization); } @Test public void signing_with_Crc32Checksum_with_streaming_input_request() throws Exception { //Note here x_amz_sha25_header is not present in SignedHeaders String expectedAuthorization = AWS_4_HMAC_SHA_256_AUTHORIZATION + SIGNER_HEADER_WITH_CHECKSUMS_IN_HEADER + "Signature=c1804802dc623d1689e7d0a7f9f5caee3588cc8d3df4495425129dbd52965d1f"; final SignerChecksumParams signerChecksumParams = SignerChecksumParams.builder() .algorithm(Algorithm.CRC32) .checksumHeaderName("x-amzn-header-crc") .isStreamingRequest(true) .build(); SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.contentStreamProvider( () -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes(StandardCharsets.UTF_8)) ).build(), credentials, "demo", signingOverrideClock, "us-east-1", signerChecksumParams); assertThat(signed.firstMatchingHeader("x-amzn-header-crc").get()).contains("oL+a/g=="); assertThat(signed.firstMatchingHeader(SignerConstant.X_AMZ_CONTENT_SHA256)).isNotPresent(); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorization); } @Test public void signing_with_Crc32Checksum_with_x_amz_sha25_header_preset() throws Exception { //Note here x_amz_sha25_header is present in SignedHeaders, we make sure checksum is calculated even in this case. String expectedAuthorization = AWS_4_HMAC_SHA_256_AUTHORIZATION + "SignedHeaders=host;x-amz-archive-description;x-amz-content-sha256;x-amz-date;x-amzn-header-crc, " + "Signature=bc931232666f226854cdd9c9962dc03d791cf4024f5ca032fab996c1d15e4a5d"; final SignerChecksumParams signerChecksumParams = SignerChecksumParams.builder() .algorithm(Algorithm.CRC32) .checksumHeaderName("x-amzn-header-crc") .isStreamingRequest(true).build(); request = generateBasicRequest(); // presetting of the header request.putHeader(SignerConstant.X_AMZ_CONTENT_SHA256, "required"); SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.build(), credentials, "demo", signingOverrideClock, "us-east-1", signerChecksumParams); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorization); assertThat(signed.firstMatchingHeader("x-amzn-header-crc").get()).contains("oL+a/g=="); assertThat(signed.firstMatchingHeader(SignerConstant.X_AMZ_CONTENT_SHA256)).isPresent(); } @Test public void signing_with_NoHttpChecksum_As_No_impact_on_Signature() throws Exception { //Note here x_amz_sha25_header is not present in SignedHeaders String expectedAuthorization = AWS_4_HMAC_SHA_256_AUTHORIZATION + "SignedHeaders=host;x-amz-archive-description;x-amz-date, " + "Signature=77fe7c02927966018667f21d1dc3dfad9057e58401cbb9ed64f1b7868288e35a"; SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.contentStreamProvider( () -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes(StandardCharsets.UTF_8)) ).build(), credentials, "demo", signingOverrideClock, "us-east-1", null); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorization); assertThat(signed.firstMatchingHeader("x-amzn-header-crc")).isNotPresent(); } @Test public void signing_with_Crc32Checksum_with_header_already_present() throws Exception { String expectedAuthorization = AWS_4_HMAC_SHA_256_AUTHORIZATION + SIGNER_HEADER_WITH_CHECKSUMS_IN_HEADER + "Signature=f6fad563460f2ac50fe2ab5f5f5d77a787e357897ac6e9bb116ff12d30f45589"; final SignerChecksumParams signerChecksumParams = SignerChecksumParams.builder() .algorithm(Algorithm.CRC32) .checksumHeaderName("x-amzn-header-crc") .isStreamingRequest(false) .build(); SdkHttpFullRequest signed = SignerTestUtils.signRequest(signer, request.contentStreamProvider( () -> new ByteArrayInputStream("{\"TableName\": \"foo\"}".getBytes(StandardCharsets.UTF_8)) ) .appendHeader("x-amzn-header-crc", "preCalculatedChecksum") .build(), credentials, "demo", signingOverrideClock, "us-east-1", signerChecksumParams); assertThat(signed.firstMatchingHeader("x-amzn-header-crc")).hasValue("preCalculatedChecksum"); assertThat(signed.firstMatchingHeader(SignerConstant.X_AMZ_CONTENT_SHA256)).isNotPresent(); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorization); } @Test public void signing_with_Crc32Checksum_with__trailer_header_already_present() throws Exception { String expectedAuthorization = AWS_4_HMAC_SHA_256_AUTHORIZATION + SIGNER_HEADER_WITH_CHECKSUMS_IN_TRAILER + "Signature=3436c4bc175d31e87a591802e64756cebf2d1c6c2054d26ca3dc91bdd3de303e"; final SignerChecksumParams signerChecksumParams = SignerChecksumParams.builder() .algorithm(Algorithm.CRC32) .checksumHeaderName("x-amzn-header-crc") .isStreamingRequest(false) .build(); SdkHttpFullRequest signed = SignerTestUtils.signRequest( signer, request.contentStreamProvider(() -> new ByteArrayInputStream(("{\"TableName" + "\": " + "\"foo\"}").getBytes(StandardCharsets.UTF_8))) .appendHeader("x-amz-trailer", "x-amzn-header-crc") .build(), credentials, "demo", signingOverrideClock, "us-east-1", signerChecksumParams); assertThat(signed.firstMatchingHeader("x-amzn-header-crc")).isNotPresent(); assertThat(signed.firstMatchingHeader("x-amz-trailer")).contains("x-amzn-header-crc"); assertThat(signed.firstMatchingHeader(SignerConstant.X_AMZ_CONTENT_SHA256)).isNotPresent(); assertThat(signed.firstMatchingHeader("Authorization")).hasValue(expectedAuthorization); } }
1,388
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/Aws4UnsignedPayloadSignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import java.io.ByteArrayInputStream; import java.net.URI; import java.time.Clock; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.signer.params.Aws4SignerParams; import software.amazon.awssdk.auth.signer.params.SignerChecksumParams; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.regions.Region; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class Aws4UnsignedPayloadSignerTest { final static SignerChecksumParams CRC32_HEADER_SIGNER_PARAMS = SignerChecksumParams.builder() .algorithm(Algorithm.CRC32) .checksumHeaderName("x-amzn-header-crc") .isStreamingRequest(false) .build(); AwsBasicCredentials credentials; Aws4SignerParams signerParams; @Mock private Clock signingOverrideClock; @Before public void setupCase() { mockClock(); credentials = AwsBasicCredentials.create("access", "secret"); signerParams = Aws4SignerParams.builder() .awsCredentials(credentials) .signingName("demo") .checksumParams(CRC32_HEADER_SIGNER_PARAMS) .signingClockOverride(signingOverrideClock) .signingRegion(Region.of("us-east-1")) .build(); } @Test public void testAws4UnsignedPayloadSignerUsingHttpWherePayloadIsSigned() { final Aws4UnsignedPayloadSigner signer = Aws4UnsignedPayloadSigner.create(); SdkHttpFullRequest.Builder request = getHttpRequestBuilder("abc", "http"); SdkHttpFullRequest signed = signer.sign(request.build(), signerParams); assertThat(signed.firstMatchingHeader("x-amzn-header-crc")).hasValue("NSRBwg=="); } @Test public void testAws4UnsignedPayloadSignerWithHttpsRequest() { final Aws4UnsignedPayloadSigner signer = Aws4UnsignedPayloadSigner.create(); SdkHttpFullRequest.Builder request = getHttpRequestBuilder("abc", "https"); SdkHttpFullRequest signed = signer.sign(request.build(), signerParams); assertThat(signed.firstMatchingHeader("x-amzn-header-crc")).isNotPresent(); } private void mockClock() { Calendar c = new GregorianCalendar(); c.set(1981, 1, 16, 6, 30, 0); c.setTimeZone(TimeZone.getTimeZone("UTC")); when(signingOverrideClock.millis()).thenReturn(c.getTimeInMillis()); } private SdkHttpFullRequest.Builder getHttpRequestBuilder(String testString, String protocol) { SdkHttpFullRequest.Builder request = SdkHttpFullRequest.builder() .contentStreamProvider(() -> new ByteArrayInputStream(testString.getBytes())) .method(SdkHttpMethod.POST) .putHeader("Host", "demo.us-east-1.amazonaws.com") .putHeader("x-amz-archive-description", "test test") .encodedPath("/") .protocol(protocol) .uri(URI.create(protocol + "://demo.us-east-1.amazonaws.com")); return request; } }
1,389
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/AwsSignerExecutionAttributeTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.CRC32; import static software.amazon.awssdk.checksums.DefaultChecksumAlgorithm.SHA256; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import java.util.Collections; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.core.SelectedAuthScheme; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.ChecksumSpecs; import software.amazon.awssdk.core.interceptor.ExecutionAttribute; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute; import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner; import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner; import software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner; import software.amazon.awssdk.http.auth.aws.signer.RegionSet; import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption; import software.amazon.awssdk.http.auth.spi.signer.HttpSigner; import software.amazon.awssdk.http.auth.spi.signer.SignerProperty; import software.amazon.awssdk.identity.spi.Identity; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.RegionScope; class AwsSignerExecutionAttributeTest { private static final SelectedAuthScheme<Identity> EMPTY_SELECTED_AUTH_SCHEME = new SelectedAuthScheme<>(CompletableFuture.completedFuture(Mockito.mock(Identity.class)), (HttpSigner<Identity>) Mockito.mock(HttpSigner.class), AuthSchemeOption.builder().schemeId("mock").build()); private ExecutionAttributes attributes; private Clock testClock; @BeforeEach public void setup() { this.attributes = new ExecutionAttributes(); this.testClock = Clock.fixed(Instant.now(), ZoneOffset.UTC); } @Test public void awsCredentials_oldAndNewAttributeAreMirrored() { AwsCredentials creds = Mockito.mock(AwsCredentials.class); // If selected auth scheme is null, writing non-null old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); attributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, creds); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME).identity().join()).isSameAs(creds); // If selected auth scheme is null, writing null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); attributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, null); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME).identity().join()).isNull(); // If selected auth scheme is non-null, writing non-null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, EMPTY_SELECTED_AUTH_SCHEME); attributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, creds); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME).identity().join()).isSameAs(creds); // If selected auth scheme is non-null, writing null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, EMPTY_SELECTED_AUTH_SCHEME); attributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, null); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME).identity().join()).isNull(); // Writing non-null new property can be read with old property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, new SelectedAuthScheme<>(CompletableFuture.completedFuture(creds), EMPTY_SELECTED_AUTH_SCHEME.signer(), EMPTY_SELECTED_AUTH_SCHEME.authSchemeOption())); assertThat(attributes.getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS)).isSameAs(creds); // Writing null new property can be read with old property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, new SelectedAuthScheme<>(CompletableFuture.completedFuture(null), EMPTY_SELECTED_AUTH_SCHEME.signer(), EMPTY_SELECTED_AUTH_SCHEME.authSchemeOption())); assertThat(attributes.getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS)).isNull(); // Null selected auth scheme can be read with old property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); assertThat(attributes.getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS)).isNull(); } @Test public void signingRegion_oldAndNewAttributeAreMirrored() { assertOldAndNewAttributesAreMirrored(AwsSignerExecutionAttribute.SIGNING_REGION, AwsV4HttpSigner.REGION_NAME, Region.US_EAST_1, "us-east-1"); } @Test public void signingRegionScope_oldAndNewAttributeAreMirrored() { assertOldAndNewAttributesAreMirrored(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE, AwsV4aHttpSigner.REGION_SET, RegionScope.create("foo"), RegionSet.create("foo") ); } @Test public void signingRegionScope_mappingToOldWithMoreThanOneRegionThrows() { RegionSet regionSet = RegionSet.create("foo1,foo2"); AuthSchemeOption newOption = EMPTY_SELECTED_AUTH_SCHEME.authSchemeOption().copy(o -> o.putSignerProperty(AwsV4aHttpSigner.REGION_SET, regionSet)); attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, new SelectedAuthScheme<>(EMPTY_SELECTED_AUTH_SCHEME.identity(), EMPTY_SELECTED_AUTH_SCHEME.signer(), newOption)); assertThrows(IllegalArgumentException.class, () -> attributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE)); } @Test public void signingName_oldAndNewAttributeAreMirrored() { assertOldAndNewAttributesAreMirrored(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, AwsV4FamilyHttpSigner.SERVICE_SIGNING_NAME, "ServiceName"); } @Test public void doubleUrlEncode_oldAndNewAttributeAreMirrored() { assertOldAndNewBooleanAttributesAreMirrored(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE, AwsV4FamilyHttpSigner.DOUBLE_URL_ENCODE); } @Test public void signerNormalizePath_oldAndNewAttributeAreMirrored() { assertOldAndNewBooleanAttributesAreMirrored(AwsSignerExecutionAttribute.SIGNER_NORMALIZE_PATH, AwsV4FamilyHttpSigner.NORMALIZE_PATH); } @Test public void signingClock_oldAndNewAttributeAreMirrored() { assertOldAndNewAttributesAreMirrored(AwsSignerExecutionAttribute.SIGNING_CLOCK, HttpSigner.SIGNING_CLOCK, Mockito.mock(Clock.class)); } @Test public void checksum_AttributeWriteReflectedInProperty() { assertOldAttributeWrite_canBeReadFromNewAttributeCases(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, AwsV4FamilyHttpSigner.CHECKSUM_ALGORITHM, ChecksumSpecs.builder() .isRequestChecksumRequired(true) .headerName("beepboop") .isRequestStreaming(true) .isValidationEnabled(true) .responseValidationAlgorithms( Collections.singletonList(Algorithm.CRC32)) .algorithm(Algorithm.SHA256) .build(), SHA256); } @Test public void checksum_PropertyWriteReflectedInAttribute() { ChecksumSpecs initialValue = ChecksumSpecs.builder() .isRequestChecksumRequired(true) .headerName("x-amz-checksum-sha256") .isRequestStreaming(true) .isValidationEnabled(true) .responseValidationAlgorithms( Collections.singletonList(Algorithm.CRC32)) .algorithm(Algorithm.SHA256) .build(); attributes.putAttribute(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, initialValue); assertNewPropertyWrite_canBeReadFromNewAttribute(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, AwsV4FamilyHttpSigner.CHECKSUM_ALGORITHM, initialValue, SHA256); } @Test public void checksum_NullPropertyWriteReflectedInAttribute() { ChecksumSpecs initialValue = ChecksumSpecs.builder() .isRequestChecksumRequired(true) .headerName("x-amz-checksum-sha256") .isRequestStreaming(true) .isValidationEnabled(true) .responseValidationAlgorithms( Collections.singletonList(Algorithm.CRC32)) .algorithm(Algorithm.SHA256) .build(); attributes.putAttribute(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, initialValue); ChecksumSpecs expectedValue = ChecksumSpecs.builder() .isRequestChecksumRequired(true) .isRequestStreaming(true) .isValidationEnabled(true) .responseValidationAlgorithms( Collections.singletonList(Algorithm.CRC32)) .build(); assertNewPropertyWrite_canBeReadFromNewAttribute(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, AwsV4FamilyHttpSigner.CHECKSUM_ALGORITHM, expectedValue, null); } @Test public void checksum_PropertyWriteReflectedInAttributeAndHeaderName() { // We need to set up the attribute first, so that ChecksumSpecs information is not lost ChecksumSpecs valueToWrite = ChecksumSpecs.builder() .isRequestChecksumRequired(true) .headerName("x-amz-checksum-sha256") .isRequestStreaming(true) .isValidationEnabled(true) .responseValidationAlgorithms( Collections.singletonList(Algorithm.CRC32)) .algorithm(Algorithm.SHA256) .build(); attributes.putAttribute(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, valueToWrite); // The header name should be updated to reflect the change in algorithm ChecksumSpecs expectedValue = ChecksumSpecs.builder() .isRequestChecksumRequired(true) .headerName("x-amz-checksum-crc32") .isRequestStreaming(true) .isValidationEnabled(true) .responseValidationAlgorithms( Collections.singletonList(Algorithm.CRC32)) .algorithm(Algorithm.CRC32) .build(); assertNewPropertyWrite_canBeReadFromNewAttribute(SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS, AwsV4FamilyHttpSigner.CHECKSUM_ALGORITHM, expectedValue, CRC32); } private void assertOldAndNewBooleanAttributesAreMirrored(ExecutionAttribute<Boolean> attribute, SignerProperty<Boolean> property) { assertOldAndNewAttributesAreMirrored(attribute, property, true); assertOldAndNewAttributesAreMirrored(attribute, property, false); } private <T> void assertOldAndNewAttributesAreMirrored(ExecutionAttribute<T> attributeToWrite, SignerProperty<T> propertyToRead, T valueToWrite) { assertOldAndNewAttributesAreMirrored(attributeToWrite, propertyToRead, valueToWrite, valueToWrite); } private <T, U> void assertOldAndNewAttributesAreMirrored(ExecutionAttribute<T> oldAttribute, SignerProperty<U> newProperty, T oldPropertyValue, U newPropertyValue) { assertOldAttributeWrite_canBeReadFromNewAttributeCases(oldAttribute, newProperty, oldPropertyValue, newPropertyValue); assertNewPropertyWrite_canBeReadFromNewAttributeCases(oldAttribute, newProperty, oldPropertyValue, newPropertyValue); // Null selected auth scheme can be read with old property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); assertThat(attributes.getAttribute(oldAttribute)).isNull(); } private <T, U> void assertNewPropertyWrite_canBeReadFromNewAttribute(ExecutionAttribute<T> oldAttribute, SignerProperty<U> newProperty, T oldPropertyValue, U newPropertyValue) { AuthSchemeOption newOption = EMPTY_SELECTED_AUTH_SCHEME.authSchemeOption().copy(o -> o.putSignerProperty(newProperty, newPropertyValue)); attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, new SelectedAuthScheme<>(EMPTY_SELECTED_AUTH_SCHEME.identity(), EMPTY_SELECTED_AUTH_SCHEME.signer(), newOption)); assertThat(attributes.getAttribute(oldAttribute)).isEqualTo(oldPropertyValue); } private <T, U> void assertNewPropertyWrite_canBeReadFromNewAttributeCases(ExecutionAttribute<T> attributeToWrite, SignerProperty<U> propertyToRead, T valueToWrite, U propertyToExpect) { // Writing non-null new property can be read with old property assertNewPropertyWrite_canBeReadFromNewAttribute(attributeToWrite, propertyToRead, valueToWrite, propertyToExpect); // Writing null new property can be read with old property assertNewPropertyWrite_canBeReadFromNewAttribute(attributeToWrite, propertyToRead, null, null); } private <T, U> void assertOldAttributeWrite_canBeReadFromNewAttribute(ExecutionAttribute<T> attributeToWrite, SignerProperty<U> propertyToRead, T valueToWrite, U propertyToExpect) { attributes.putAttribute(attributeToWrite, valueToWrite); assertThat(attributes.getAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME) .authSchemeOption() .signerProperty(propertyToRead)).isEqualTo(propertyToExpect); } private <T, U> void assertOldAttributeWrite_canBeReadFromNewAttributeCases(ExecutionAttribute<T> attributeToWrite, SignerProperty<U> propertyToRead, T valueToWrite, U propertyToExpect) { // If selected auth scheme is null, writing non-null old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); assertOldAttributeWrite_canBeReadFromNewAttribute(attributeToWrite, propertyToRead, valueToWrite, propertyToExpect); // If selected auth scheme is null, writing null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, null); assertOldAttributeWrite_canBeReadFromNewAttribute(attributeToWrite, propertyToRead, null, null); // If selected auth scheme is non-null, writing non-null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, EMPTY_SELECTED_AUTH_SCHEME); assertOldAttributeWrite_canBeReadFromNewAttribute(attributeToWrite, propertyToRead, valueToWrite, propertyToExpect); // If selected auth scheme is non-null, writing null to old property can be read with new property attributes.putAttribute(SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME, EMPTY_SELECTED_AUTH_SCHEME); assertOldAttributeWrite_canBeReadFromNewAttribute(attributeToWrite, propertyToRead, null, null); } }
1,390
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/AbstractAws4SignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.signer.internal.AbstractAws4Signer; public class AbstractAws4SignerTest { @Test public void test() { assertEquals( "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", AbstractAws4Signer.EMPTY_STRING_SHA256_HEX); } }
1,391
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/Aws4SignerRequestParamsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer.internal; import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import java.time.Instant; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.signer.params.Aws4SignerParams; import software.amazon.awssdk.regions.Region; /** * Tests for {@link Aws4SignerRequestParams}. */ public class Aws4SignerRequestParamsTest { @Test public void appliesOffset_PositiveOffset() { offsetTest(5); } @Test public void appliesOffset_NegativeOffset() { offsetTest(-5); } private void offsetTest(int offsetSeconds) { Aws4SignerParams signerParams = Aws4SignerParams.builder() .awsCredentials(AwsBasicCredentials.create("akid", "skid")) .doubleUrlEncode(false) .signingName("test-service") .signingRegion(Region.US_WEST_2) .timeOffset(offsetSeconds) .build(); Instant now = Instant.now(); Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signerParams); Instant requestSigningInstant = Instant.ofEpochMilli(requestParams.getRequestSigningDateTimeMilli()); // The offset is subtracted from the current time if (offsetSeconds > 0) { assertThat(requestSigningInstant).isBefore(now); } else { assertThat(requestSigningInstant).isAfter(now); } Duration diff = Duration.between(requestSigningInstant, now.minusSeconds(offsetSeconds)); // Allow some wiggle room in the difference since we can't use a clock // override for complete accuracy as it doesn't apply the offset when // using a clock override assertThat(diff).isLessThanOrEqualTo(Duration.ofMillis(100)); } }
1,392
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/AwsChunkedEncodingInputStreamTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.core.internal.chunked.AwsChunkedEncodingConfig; import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsSignedChunkedEncodingInputStream; import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsS3V4ChunkSigner; /** * Runs unit tests that check that the class AwsChunkedEncodingInputStream supports params required for Sigv4 chunk * signing. */ @RunWith(MockitoJUnitRunner.class) public class AwsChunkedEncodingInputStreamTest { private static final String REQUEST_SIGNATURE = "a0c7e7324d9c209c4a86a1c1452d60862591b7370a725364d52ba490210f2d9d"; private static final String CHUNK_SIGNATURE_1 = "3d5a2da1f773f64fdde2c6ca7d18c4bfee2a5a76b8153854c2a722c3fe8549cc"; private static final String CHUNK_SIGNATURE_2 = "0362eef10ceccf47fc1bf944a9df45a3e7dd5ea936e118b00e3d649b1d825f2f"; private static final String CHUNK_SIGNATURE_3 = "4722d8dac986015bdabeb5fafcb45db7b5585329befa485849c4938fed2aaaa2"; private static final String SIGNATURE_KEY = "chunk-signature="; private static final String EMPTY_STRING = ""; private static final String CRLF = "\r\n"; private static final int DEFAULT_CHUNK_SIZE = 128 * 1024; private static final int SIGV4_CHUNK_SIGNATURE_LENGTH = 64; @Mock AwsS3V4ChunkSigner chunkSigner; @Test public void streamContentLength_smallObject_calculatedCorrectly() { long streamContentLength = AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(10, SIGV4_CHUNK_SIGNATURE_LENGTH, AwsChunkedEncodingConfig.create()); assertThat(streamContentLength).isEqualTo(182); } @Test public void streamContentLength_largeObject_calculatedCorrectly() { long streamContentLength = AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(DEFAULT_CHUNK_SIZE + 10, SIGV4_CHUNK_SIGNATURE_LENGTH, AwsChunkedEncodingConfig.create()); assertThat(streamContentLength).isEqualTo(131344); } @Test public void streamContentLength_differentChunkSize_calculatedCorrectly() { int chunkSize = 64 * 1024; AwsChunkedEncodingConfig chunkConfig = AwsChunkedEncodingConfig.builder().chunkSize(chunkSize).build(); long streamContentLength = AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(chunkSize + 10, SIGV4_CHUNK_SIGNATURE_LENGTH, chunkConfig); assertThat(streamContentLength).isEqualTo(65808); } @Test(expected = IllegalArgumentException.class) public void streamContentLength_negative_throwsException() { AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(-1, SIGV4_CHUNK_SIGNATURE_LENGTH, AwsChunkedEncodingConfig.create()); } @Test public void chunkedEncodingStream_smallObject_createsCorrectChunks() throws IOException { when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1) .thenReturn(CHUNK_SIGNATURE_2); String chunkData = "helloworld"; ByteArrayInputStream input = new ByteArrayInputStream(chunkData.getBytes()); AwsSignedChunkedEncodingInputStream stream = AwsSignedChunkedEncodingInputStream.builder() .inputStream(input) .awsChunkSigner(chunkSigner) .headerSignature(REQUEST_SIGNATURE) .awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create()) .build(); int expectedChunks = 2; consumeAndVerify(stream, expectedChunks); Mockito.verify(chunkSigner, times(1)).signChunk(chunkData.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE); Mockito.verify(chunkSigner, times(1)).signChunk(EMPTY_STRING.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_1); } @Test public void chunkedEncodingStream_largeObject_createsCorrectChunks() throws IOException { when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1) .thenReturn(CHUNK_SIGNATURE_2) .thenReturn(CHUNK_SIGNATURE_3); String chunk1Data = StringUtils.repeat('a', DEFAULT_CHUNK_SIZE); String chunk2Data = "a"; ByteArrayInputStream input = new ByteArrayInputStream(chunk1Data.concat(chunk2Data).getBytes()); AwsSignedChunkedEncodingInputStream stream = AwsSignedChunkedEncodingInputStream.builder() .inputStream(input) .headerSignature(REQUEST_SIGNATURE) .awsChunkSigner(chunkSigner) .awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create()) .build(); int expectedChunks = 3; consumeAndVerify(stream, expectedChunks); Mockito.verify(chunkSigner, times(1)).signChunk(chunk1Data.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE); Mockito.verify(chunkSigner, times(1)).signChunk(chunk2Data.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_1); Mockito.verify(chunkSigner, times(1)).signChunk(EMPTY_STRING.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_2); } @Test public void chunkedEncodingStream_emptyString_createsCorrectChunks() throws IOException { when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1); String chunkData = EMPTY_STRING; ByteArrayInputStream input = new ByteArrayInputStream(chunkData.getBytes()); AwsSignedChunkedEncodingInputStream stream = AwsSignedChunkedEncodingInputStream.builder() .inputStream(input) .awsChunkSigner(chunkSigner) .headerSignature(REQUEST_SIGNATURE) .awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create()).build(); int expectedChunks = 1; consumeAndVerify(stream, expectedChunks); Mockito.verify(chunkSigner, times(1)).signChunk(chunkData.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE); } private void consumeAndVerify(AwsSignedChunkedEncodingInputStream stream, int numChunks) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(stream, output); String result = new String(output.toByteArray(), StandardCharsets.UTF_8); assertChunks(result, numChunks); } private void assertChunks(String result, int numExpectedChunks) { List<String> lines = Stream.of(result.split(CRLF)).collect(Collectors.toList()); assertThat(lines.size()).isEqualTo(numExpectedChunks * 2 - 1); for (int i = 0; i < lines.size(); i = i + 2) { String chunkMetadata = lines.get(i); String signatureValue = chunkMetadata.substring(chunkMetadata.indexOf(SIGNATURE_KEY) + SIGNATURE_KEY.length()); assertThat(signatureValue.length()).isEqualTo(SIGV4_CHUNK_SIGNATURE_LENGTH); } } }
1,393
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/Aws4SignerPathNormalizationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer.internal; import static org.junit.Assert.assertEquals; import java.util.Arrays; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.auth.signer.internal.AbstractAws4Signer.CanonicalRequest; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.utils.ToString; /** * Tests how canonical resource paths are created including normalization */ public class Aws4SignerPathNormalizationTest { public static Iterable<TestCase> data() { return Arrays.asList( // Handling slash tc("Empty path -> (initial) slash added", "", "/"), tc("Slash -> unchanged", "/", "/"), tc("Single segment with initial slash -> unchanged", "/foo", "/foo"), tc("Single segment no slash -> slash prepended", "foo", "/foo"), tc("Multiple segments -> unchanged", "/foo/bar", "/foo/bar"), tc("Multiple segments with trailing slash -> unchanged", "/foo/bar/", "/foo/bar/"), // Double URL encoding tc("Multiple segments, urlEncoded slash -> encodes percent", "/foo%2Fbar", "/foo%252Fbar", true, true), // No double-url-encoding + normalization tc("Single segment, dot -> should remove dot", "/.", "/"), tc("Single segment, double dot -> unchanged", "/..", "/.."), tc("Multiple segments with dot -> should remove dot", "/foo/./bar", "/foo/bar"), tc("Multiple segments with ending dot -> should remove dot and trailing slash", "/foo/bar/.", "/foo/bar"), tc("Multiple segments with dots -> should remove dots and preceding segment", "/foo/bar/../baz", "/foo/baz"), tc("First segment has colon -> unchanged, url encoded first", "foo:/bar", "/foo%3A/bar", true, true), // Double-url-encoding + normalization tc("Multiple segments, urlEncoded slash -> encodes percent", "/foo%2F.%2Fbar", "/foo%252F.%252Fbar", true, true), // Double-url-encoding + no normalization tc("No url encode, Multiple segments with dot -> unchanged", "/foo/./bar", "/foo/./bar", false, false), tc("Multiple segments with dots -> unchanged", "/foo/bar/../baz", "/foo/bar/../baz", false, false) ); } @ParameterizedTest @MethodSource("data") public void verifyNormalizedPath(TestCase tc) { String canonicalRequest = tc.canonicalRequest.string(); String[] requestParts = canonicalRequest.split("\\n"); String canonicalPath = requestParts[1]; assertEquals(tc.expectedPath, canonicalPath); } private static TestCase tc(String name, String path, String expectedPath) { return new TestCase(name, path, expectedPath, false, true); } private static TestCase tc(String name, String path, String expectedPath, boolean urlEncode, boolean normalizePath) { return new TestCase(name, path, expectedPath, urlEncode, normalizePath); } private static class TestCase { private String name; private String path; private String expectedPath; private CanonicalRequest canonicalRequest; public TestCase(String name, String path, String expectedPath, boolean urlEncode, boolean normalizePath) { SdkHttpFullRequest request = SdkHttpFullRequest.builder() .protocol("https") .host("localhost") .encodedPath(path) .method(SdkHttpMethod.PUT) .build(); this.name = name; this.path = path; this.expectedPath = expectedPath; this.canonicalRequest = new CanonicalRequest(request, request.toBuilder(), "sha-256", urlEncode, normalizePath); } @Override public String toString() { return ToString.builder("TestCase") .add("name", name) .add("path", path) .add("expectedPath", expectedPath) .build(); } } }
1,394
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/ContentChecksumTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer.internal; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class ContentChecksumTest { @Test void equals_hashcode() { EqualsVerifier.forClass(ContentChecksum.class) .usingGetClass() .verify(); } }
1,395
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/SignerTestUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer.internal; import java.time.Clock; import java.time.Instant; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams; import software.amazon.awssdk.auth.signer.params.Aws4SignerParams; import software.amazon.awssdk.auth.signer.params.SignerChecksumParams; import software.amazon.awssdk.core.async.AsyncRequestBody; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.regions.Region; public class SignerTestUtils { public static SdkHttpFullRequest signRequest(BaseAws4Signer signer, SdkHttpFullRequest request, AwsCredentials credentials, String signingName, Clock signingDateOverride, String region) { Aws4SignerParams signerParams = Aws4SignerParams.builder() .awsCredentials(credentials) .signingName(signingName) .signingClockOverride(signingDateOverride) .signingRegion(Region.of(region)) .build(); return signer.sign(request, signerParams); } public static SdkHttpFullRequest signRequest(BaseAws4Signer signer, SdkHttpFullRequest request, AwsCredentials credentials, String signingName, Clock signingDateOverride, String region, SignerChecksumParams signerChecksumParams) { Aws4SignerParams signerParams = Aws4SignerParams.builder() .awsCredentials(credentials) .signingName(signingName) .signingClockOverride(signingDateOverride) .signingRegion(Region.of(region)) .checksumParams(signerChecksumParams) .build(); return signer.sign(request, signerParams); } public static AsyncRequestBody signAsyncRequest(BaseAsyncAws4Signer signer, SdkHttpFullRequest request, AsyncRequestBody asyncRequestBody, AwsCredentials credentials, String signingName, Clock signingDateOverride, String region) { Aws4SignerParams signerParams = Aws4SignerParams.builder() .awsCredentials(credentials) .signingName(signingName) .signingClockOverride(signingDateOverride) .signingRegion(Region.of(region)) .build(); final Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signerParams); return signer.signAsync(request, asyncRequestBody, requestParams, signerParams); } public static SdkHttpFullRequest presignRequest(BaseAws4Signer presigner, SdkHttpFullRequest request, AwsCredentials credentials, Instant expiration, String signingName, Clock signingDateOverride, String region) { Aws4PresignerParams signerParams = Aws4PresignerParams.builder() .awsCredentials(credentials) .expirationTime(expiration) .signingName(signingName) .signingClockOverride(signingDateOverride) .signingRegion(Region.of(region)) .build(); return presigner.presign(request, signerParams); } }
1,396
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/BaseEventStreamAsyncAws4SignerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer.internal; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; import java.util.Random; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.eventstream.HeaderValue; import software.amazon.eventstream.Message; public class BaseEventStreamAsyncAws4SignerTest { private static Map<String, HeaderValue> headers; @BeforeAll public static void setup() { headers = new LinkedHashMap<>(); headers.put("header1", HeaderValue.fromInteger(42)); headers.put("header2", HeaderValue.fromBoolean(false)); headers.put("header3", HeaderValue.fromString("Hello world")); } @Test public void toDebugString_emptyPayload_generatesCorrectString() { Message m = new Message(headers, new byte[0]); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, false)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=}"); } @Test public void toDebugString_noHeaders_emptyPayload_generatesCorrectString() { Message m = new Message(new LinkedHashMap<>(), new byte[0]); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, false)) .isEqualTo("Message = {headers={}, payload=}"); } @Test public void toDebugString_largePayload_truncate_generatesCorrectString() { byte[] payload = new byte[128]; new Random().nextBytes(payload); Message m = new Message(headers, payload); byte[] first32 = Arrays.copyOf(payload, 32); String expectedPayloadString = BinaryUtils.toHex(first32); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, true)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=" + expectedPayloadString + "...}"); } @Test public void toDebugString_largePayload_noTruncate_generatesCorrectString() { byte[] payload = new byte[128]; new Random().nextBytes(payload); Message m = new Message(headers, payload); String expectedPayloadString = BinaryUtils.toHex(payload); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, false)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=" + expectedPayloadString + "}"); } @Test public void toDebugString_smallPayload_truncate_doesNotAddEllipsis() { byte[] payload = new byte[8]; new Random().nextBytes(payload); Message m = new Message(headers, payload); String expectedPayloadString = BinaryUtils.toHex(payload); assertThat(BaseEventStreamAsyncAws4Signer.toDebugString(m, true)) .isEqualTo("Message = {headers={header1={42}, header2={false}, header3={\"Hello world\"}}, payload=" + expectedPayloadString + "}"); } }
1,397
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/DigestComputingSubscriberTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import io.reactivex.Flowable; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Test; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.checksums.Algorithm; import software.amazon.awssdk.core.checksums.SdkChecksum; import software.amazon.awssdk.utils.BinaryUtils; public class DigestComputingSubscriberTest { @Test public void test_computesCorrectSha256() { String testString = "AWS SDK for Java"; String expectedDigest = "004c6bbd87e7fe70109b3bc23c8b1ab8f18a8bede0ed38c9233f6cdfd4f7b5d6"; DigestComputingSubscriber subscriber = DigestComputingSubscriber.forSha256(); Flowable<ByteBuffer> publisher = Flowable.just(ByteBuffer.wrap(testString.getBytes(StandardCharsets.UTF_8))); publisher.subscribe(subscriber); String computedDigest = BinaryUtils.toHex(subscriber.digestBytes().join()); assertThat(computedDigest).isEqualTo(expectedDigest); } @Test public void test_futureCancelledBeforeSubscribe_cancelsSubscription() { Subscription mockSubscription = mock(Subscription.class); DigestComputingSubscriber subscriber = DigestComputingSubscriber.forSha256(); subscriber.digestBytes().cancel(true); subscriber.onSubscribe(mockSubscription); verify(mockSubscription).cancel(); verify(mockSubscription, times(0)).request(anyLong()); } @Test public void test_publisherCallsOnError_errorPropagatedToFuture() { Subscription mockSubscription = mock(Subscription.class); DigestComputingSubscriber subscriber = DigestComputingSubscriber.forSha256(); subscriber.onSubscribe(mockSubscription); RuntimeException error = new RuntimeException("error"); subscriber.onError(error); assertThatThrownBy(subscriber.digestBytes()::join).hasCause(error); } @Test void test_computesCorrectSdkChecksum() { String testString = "Hello world"; String expectedDigest = "64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c"; String expectedChecksum = "e1AsOh9IyGCa4hLN+2Od7jlnP14="; final SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(Algorithm.SHA1); DigestComputingSubscriber subscriber = DigestComputingSubscriber.forSha256(sdkChecksum); Flowable<ByteBuffer> publisher = Flowable.just(ByteBuffer.wrap(testString.getBytes(StandardCharsets.UTF_8))); publisher.subscribe(subscriber); String computedDigest = BinaryUtils.toHex(subscriber.digestBytes().join()); assertThat(computedDigest).isEqualTo(expectedDigest); assertThat(BinaryUtils.toBase64(sdkChecksum.getChecksumBytes())).isEqualTo(expectedChecksum); } }
1,398
0
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer
Create_ds/aws-sdk-java-v2/core/auth/src/test/java/software/amazon/awssdk/auth/signer/internal/ChunkedEncodingFunctionalTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.auth.signer.internal; import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsS3V4ChunkSigner; import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsSignedChunkedEncodingInputStream; import software.amazon.awssdk.core.internal.chunked.AwsChunkedEncodingConfig; import software.amazon.awssdk.utils.BinaryUtils; /** * Functional tests for the AwsChunkedEncodingInputStream using Sigv4 for chunk signing. */ public class ChunkedEncodingFunctionalTest { private static final byte[] SIGNATURE = "signature".getBytes(StandardCharsets.UTF_8); private static final byte[] SIGNING_KEY = "signingkey".getBytes(StandardCharsets.UTF_8); private static final String DATE_TIME = "20201216T011309Z"; private static final String SCOPE = "20201216/us-west-2/s3/aws4_request"; private static final String CRLF = "\r\n"; private static final int DEFAULT_CHUNK_SIZE = 128 * 1024; @Test public void chunkedEncodingStream_smallObject_createsCorrectChunks() throws IOException { String chunkData = "helloworld"; String expectedChunkOutput = "a;chunk-signature=a0c7e7324d9c209c4a86a1c1452d60862591b7370a725364d52ba490210f2d9d" + CRLF + "helloworld" + CRLF + "0;chunk-signature=4722d8dac986015bdabeb5fafcb45db7b5585329befa485849c4938fed2aaaa2" + CRLF + CRLF; ByteArrayInputStream input = new ByteArrayInputStream(chunkData.getBytes()); AwsSignedChunkedEncodingInputStream stream = createChunkedEncodingInputStream(input); verifySignedPayload(expectedChunkOutput, stream); } @Test public void chunkedEncodingStream_largeObject_createsCorrectChunks() throws IOException { String chunk1Data = StringUtils.repeat('a', DEFAULT_CHUNK_SIZE); String chunk2Data = "a"; String expectedChunkOutput = "20000;chunk-signature=be3155d539d4f5daf575096ab6d7090070b5ad00be6b802a8eb4c8bacd6e7dcb" + CRLF + chunk1Data + CRLF + "1;chunk-signature=0362eef10ceccf47fc1bf944a9df45a3e7dd5ea936e118b00e3d649b1d825f2f" + CRLF + chunk2Data + CRLF + "0;chunk-signature=3d5a2da1f773f64fdde2c6ca7d18c4bfee2a5a76b8153854c2a722c3fe8549cc" + CRLF + CRLF; ByteArrayInputStream input = new ByteArrayInputStream(chunk1Data.concat(chunk2Data).getBytes()); AwsSignedChunkedEncodingInputStream stream = createChunkedEncodingInputStream(input); verifySignedPayload(expectedChunkOutput, stream); } @Test public void chunkedEncodingStream_emptyString_createsCorrectChunks() throws IOException { String chunkData = ""; String expectedChunkOutput = "0;chunk-signature=67a2a80cee05190f0376fa861594fcfa351606cfdcf932b45781ddd6e4d78501" + CRLF + CRLF; ByteArrayInputStream input = new ByteArrayInputStream(chunkData.getBytes()); AwsSignedChunkedEncodingInputStream stream = createChunkedEncodingInputStream(input); verifySignedPayload(expectedChunkOutput, stream); } private void verifySignedPayload(String expectedChunkOutput, AwsSignedChunkedEncodingInputStream stream) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(stream, output); String result = new String(output.toByteArray(), StandardCharsets.UTF_8); assertThat(result).isEqualTo(expectedChunkOutput); } private AwsSignedChunkedEncodingInputStream createChunkedEncodingInputStream(ByteArrayInputStream input) { AwsS3V4ChunkSigner chunkSigner = new AwsS3V4ChunkSigner(SIGNING_KEY, DATE_TIME, SCOPE); String signatureHex = BinaryUtils.toHex(SIGNATURE); return AwsSignedChunkedEncodingInputStream.builder().inputStream(input) .headerSignature(signatureHex).awsChunkSigner(chunkSigner) .awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create()).build(); } }
1,399