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/services/ssooidc/src/test/java/software/amazon/awssdk/services/ssooidc
Create_ds/aws-sdk-java-v2/services/ssooidc/src/test/java/software/amazon/awssdk/services/ssooidc/internal/SsoOidcTokenProviderTest.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.services.ssooidc.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.utils.UserHomeDirectoryUtils.userHomeDirectory; import com.google.common.jimfs.Configuration; import com.google.common.jimfs.Jimfs; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.time.Instant; import java.util.Locale; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.awscore.internal.token.TokenManager; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.ssooidc.SsoOidcClient; import software.amazon.awssdk.services.ssooidc.SsoOidcTokenProvider; import software.amazon.awssdk.services.ssooidc.internal.common.SsoOidcTokenRefreshTestBase; import software.amazon.awssdk.services.ssooidc.model.CreateTokenRequest; import software.amazon.awssdk.services.ssooidc.model.CreateTokenResponse; import software.amazon.awssdk.services.ssooidc.model.UnauthorizedClientException; import software.amazon.awssdk.utils.BinaryUtils; public class SsoOidcTokenProviderTest { public static final String START_URL = "https://d-123.awsapps.com/start"; public static final String REGION = "region"; private TokenManager<SsoOidcToken> mockTokenManager; private SsoOidcClient ssoOidcClient; private FileSystem testFs; private Path cache; public static String deriveCacheKey(String startUrl) { try { MessageDigest sha1 = MessageDigest.getInstance("sha1"); sha1.update(startUrl.getBytes(StandardCharsets.UTF_8)); return BinaryUtils.toHex(sha1.digest()).toLowerCase(Locale.ENGLISH); } catch (NoSuchAlgorithmException e) { throw SdkClientException.create("Unable to derive cache key", e); } } @BeforeEach public void setup() throws IOException { File cacheDirectory = SsoOidcTokenRefreshTestBase.DEFAULT_TOKEN_LOCATION.toFile(); if(! cacheDirectory.exists()){ cacheDirectory.mkdirs(); } Path file = Paths.get(cacheDirectory.getPath()+ deriveCacheKey(START_URL) + ".json"); if(file.toFile().exists()){ file.toFile().delete(); } Files.createDirectories(file.getParent()); Files.createFile(file); mockTokenManager = OnDiskTokenManager.create(START_URL); ssoOidcClient = mock(SsoOidcClient.class); } @AfterEach public void teardown() throws IOException { Path path = Paths.get(userHomeDirectory(), ".aws", "sso", "cache"); Path resolve = path.resolve(deriveCacheKey(START_URL) + ".json"); Files.deleteIfExists(resolve); } @Test public void resolveToken_usesTokenManager() { SsoOidcToken ssoOidcToken = SsoOidcToken.builder() .accessToken("accesstoken") .expiresAt(Instant.now().plus(Duration.ofDays(1))) .build(); mockTokenManager.storeToken(ssoOidcToken); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); assertThat(tokenProvider.resolveToken()).isEqualTo(ssoOidcToken); } private SsoOidcTokenProvider.Builder getDefaultSsoOidcTokenProviderBuilder() { return SsoOidcTokenProvider.builder().sessionName(START_URL).ssoOidcClient(ssoOidcClient); } @Test public void resolveToken_cachedValueNotPresent_throws() { SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); assertThatThrownBy(tokenProvider::resolveToken) .isInstanceOf(SdkClientException.class) .hasMessageContaining("Unable to load"); } // { // "documentation": "Valid token with all fields", // "currentTime": "2021-12-25T13:30:00Z", // "cachedToken": { // "startUrl": "https://d-123.awsapps.com/start", // "region": "us-west-2", // "accessToken": "cachedtoken", // "expiresAt": "2021-12-25T21:30:00Z", // "clientId": "clientid", // "clientSecret": "YSBzZWNyZXQ=", // "registrationExpiresAt": "2022-12-25T13:30:00Z", // "refreshToken": "cachedrefreshtoken" // }, // "expectedToken": { // "token": "cachedtoken", // "expiration": "2021-12-25T21:30:00Z" // } // }, @Test public void standardTest_Valid_token_with_all_fields() { SsoOidcToken token = getDefaultTokenBuilder() .expiresAt(Instant.now().plusSeconds(10000)).registrationExpiresAt(Instant.now().plusSeconds(90000)) .build(); mockTokenManager.storeToken(token); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); SdkToken resolvedToken = tokenProvider.resolveToken(); assertThat(resolvedToken.token()).isEqualTo(token.token()); assertThat(resolvedToken.expirationTime()).isEqualTo(token.expirationTime()); } @Test public void refresh_returns_cached_token_when_service_calls_fails() { SsoOidcToken nearToExpiryToken = getDefaultTokenBuilder() .expiresAt(Instant.now().plusSeconds(5000)).registrationExpiresAt(Instant.now().plusSeconds(10000)) .build(); mockTokenManager.storeToken(nearToExpiryToken); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))).thenThrow(UnauthorizedClientException.class); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); SdkToken resolvedToken = tokenProvider.resolveToken(); assertThat(resolvedToken.token()).isEqualTo(nearToExpiryToken.token()); assertThat(resolvedToken.expirationTime()).isEqualTo(nearToExpiryToken.expirationTime()); } @Test public void refresh_fails_when_supplier_fails_due_to_Non_service_issues() { SsoOidcToken nearToExpiryToken = getDefaultTokenBuilder() .expiresAt(Instant.now().minusSeconds(2)).registrationExpiresAt(Instant.now().minusSeconds(2)) .build(); mockTokenManager.storeToken(nearToExpiryToken); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))).thenThrow(SdkClientException.class); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); assertThatExceptionOfType(SdkClientException.class).isThrownBy(() -> tokenProvider.resolveToken()); } // { // "documentation": "Minimal valid cached token", // "currentTime": "2021-12-25T13:30:00Z", // "cachedToken": { // "accessToken": "cachedtoken", // "expiresAt": "2021-12-25T21:30:00Z" // }, // "expectedToken": { // "token": "cachedtoken", // "expiration": "2021-12-25T21:30:00Z" // } // }, @Test public void standardTest_Minimal_valid_cached_token() { Instant expiresAt = Instant.now().plusSeconds(3600); SsoOidcToken ssoOidcToken = SsoOidcToken.builder().accessToken("cachedtoken").expiresAt(expiresAt).build(); mockTokenManager.storeToken(ssoOidcToken); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); assertThat(tokenProvider.resolveToken()).isEqualTo(ssoOidcToken); } // { // "documentation": "Minimal expired cached token", // "currentTime": "2021-12-25T13:30:00Z", // "cachedToken": { // "accessToken": "cachedtoken", // "expiresAt": "2021-12-25T13:00:00Z" // }, // "expectedException": "ExpiredToken" // } @Test public void standardTest_Minimal_expired_cached_token() { String startUrl = START_URL; Instant expiresAt = Instant.parse("2021-12-25T13:00:00Z"); SsoOidcToken ssoOidcToken = SsoOidcToken.builder().startUrl(startUrl).clientId("clientId").clientSecret("clientSecret") .accessToken("cachedtoken").expiresAt(expiresAt).build(); mockTokenManager.storeToken(ssoOidcToken); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))) .thenReturn(CreateTokenResponse.builder().accessToken("cachedtoken") .expiresIn(-1) .build()); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); assertThatThrownBy(tokenProvider::resolveToken).isInstanceOf(SdkClientException.class).hasMessageContaining("expired"); } // { // "documentation": "Token missing the expiresAt field", // "currentTime": "2021-12-25T13:30:00Z", // "cachedToken": { // "accessToken": "cachedtoken" // }, // "expectedException": "InvalidToken" // }, @Test public void standardTest_Token_missing_the_expiresAt_field() { SsoOidcToken ssoOidcToken = SsoOidcToken.builder() .startUrl(START_URL) .accessToken("cachedtoken").clientId("client").clientSecret("secret") .expiresAt(Instant.parse("2021-12-25T13:00:00Z")) .build(); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))) .thenReturn(CreateTokenResponse.builder().accessToken("cachedtoken") .build()); mockTokenManager.storeToken(ssoOidcToken); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); assertThatThrownBy(tokenProvider::resolveToken) .isInstanceOf(NullPointerException.class) .hasMessageContaining("expiresIn must not be null."); } // { // "documentation": "Token missing the accessToken field", // "currentTime": "2021-12-25T13:30:00Z", // "cachedToken": { // "expiresAt": "2021-12-25T13:00:00Z" // }, // "expectedException": "InvalidToken" // }, @Test public void standardTest_Token_missing_the_accessToken_field() { SsoOidcToken ssoOidcToken = SsoOidcToken.builder() .startUrl(START_URL) .accessToken("cachedtoken").clientId("client").clientSecret("secret") .expiresAt(Instant.parse("2021-12-25T13:00:00Z")) .build(); mockTokenManager.storeToken(ssoOidcToken); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))) .thenReturn(CreateTokenResponse.builder().expiresIn(3600).build()); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); assertThatThrownBy(tokenProvider::resolveToken) .isInstanceOf(NullPointerException.class) .hasMessageContaining("accessToken must not be null."); } @Test public void refresh_token_from_service_when_token_outside_expiry_window() { SsoOidcToken nearToExpiryToken = getDefaultTokenBuilder() .expiresAt(Instant.now().plusSeconds(59)) .registrationExpiresAt(Instant.now().plusSeconds(59)).build(); mockTokenManager.storeToken(nearToExpiryToken); int extendedExpiryTimeInSeconds = 120; when(ssoOidcClient.createToken(any(CreateTokenRequest.class))).thenReturn(getDefaultServiceResponse().expiresIn(extendedExpiryTimeInSeconds).build()); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); SsoOidcToken resolvedToken = (SsoOidcToken) tokenProvider.resolveToken(); assertThat(resolvedToken.token()).isEqualTo("serviceToken"); assertThat(resolvedToken.refreshToken()).isEqualTo("refreshedToken"); Duration extendedExpiryDate = Duration.between(resolvedToken.expirationTime().get(), Instant.now()); // Base properties of tokens are retained. assertThat(Duration.ofSeconds(extendedExpiryTimeInSeconds)).isGreaterThanOrEqualTo(extendedExpiryDate); assertThat(resolvedToken.clientId()).isEqualTo(nearToExpiryToken.clientId()); assertThat(resolvedToken.clientSecret()).isEqualTo(nearToExpiryToken.clientSecret()); assertThat(resolvedToken.region()).isEqualTo(nearToExpiryToken.region()); assertThat(resolvedToken.startUrl()).isEqualTo(nearToExpiryToken.startUrl()); assertThat(resolvedToken.registrationExpiresAt()).isEqualTo(nearToExpiryToken.registrationExpiresAt()); } @Test public void refresh_token_does_not_fetch_from_service_when_token_inside_expiry_window() { SsoOidcToken cachedDiskToken = getDefaultTokenBuilder() .expiresAt(Instant.now().plusSeconds(120)).registrationExpiresAt(Instant.now().plusSeconds(120)) .build(); mockTokenManager.storeToken(cachedDiskToken); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))).thenReturn(getDefaultServiceResponse().build()); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().prefetchTime(Duration.ofSeconds(90)).build(); SdkToken resolvedToken = tokenProvider.resolveToken(); assertThat(resolvedToken).isEqualTo(cachedDiskToken); verify(ssoOidcClient, never()).createToken(any(CreateTokenRequest.class)); } @Test public void token_is_obtained_from_inmemory_when_token_is_within_inmemory_stale_time() { Instant futureExpiryDate = Instant.now().plus(Duration.ofDays(1)); SsoOidcToken cachedDiskToken = getDefaultTokenBuilder() .expiresAt(futureExpiryDate).registrationExpiresAt(Instant.parse("2022-12-25T11:30:00Z")).build(); mockTokenManager.storeToken(cachedDiskToken); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))).thenReturn(getDefaultServiceResponse().build()); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().build(); SdkToken resolvedToken = tokenProvider.resolveToken(); assertThat(resolvedToken).isEqualTo(cachedDiskToken); verify(ssoOidcClient, never()).createToken(any(CreateTokenRequest.class)); SdkToken consecutiveToken = tokenProvider.resolveToken(); assertThat(consecutiveToken).isEqualTo(resolvedToken); verify(ssoOidcClient, never()).createToken(any(CreateTokenRequest.class)); } // Test to make sure cache fetches from Cached values. @Test public void token_is_obtained_from_refresher_and_then_refresher_cache_if_its_within_stale_time() { Instant closeToExpireTime = Instant.now().plus(Duration.ofMinutes(4)); SsoOidcToken cachedDiskToken = getDefaultTokenBuilder().accessToken("fourMinutesToExpire") .expiresAt(closeToExpireTime) .registrationExpiresAt(Instant.parse("2022-12-25T11:30:00Z")).build(); mockTokenManager.storeToken(cachedDiskToken); Instant eightMinutesFromNow = Instant.now().plus(Duration.ofMinutes(8)); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))).thenReturn(getDefaultServiceResponse().accessToken( "eightMinutesExpiry").expiresIn((int) eightMinutesFromNow.getEpochSecond()).build()); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().staleTime(Duration.ofMinutes(7)).build(); SdkToken resolvedToken = tokenProvider.resolveToken(); // Resolves to fresh token assertThat(resolvedToken.token()).isEqualTo("eightMinutesExpiry"); verify(ssoOidcClient, times(1)).createToken(any(CreateTokenRequest.class)); SdkToken consecutiveToken = tokenProvider.resolveToken(); assertThat(consecutiveToken).isEqualTo(resolvedToken); verify(ssoOidcClient, times(1)).createToken(any(CreateTokenRequest.class)); SdkToken thirdTokenAccess = tokenProvider.resolveToken(); assertThat(thirdTokenAccess).isEqualTo(resolvedToken); verify(ssoOidcClient, times(1)).createToken(any(CreateTokenRequest.class)); } @Test public void token_is_retrieved_from_service_when_service_returns_tokens_with_short_expiration() { Instant closeToExpireTime = Instant.now().plus(Duration.ofSeconds(4)); SsoOidcToken cachedDiskToken = getDefaultTokenBuilder().accessToken("fourMinutesToExpire") .expiresAt(closeToExpireTime) .registrationExpiresAt(Instant.parse("2022-12-25T11:30:00Z")) .build(); mockTokenManager.storeToken(cachedDiskToken); CreateTokenResponse eightSecondExpiryToken = getDefaultServiceResponse().accessToken( "eightSecondExpiryToken").expiresIn(8).build(); CreateTokenResponse eightySecondExpiryToken = getDefaultServiceResponse().accessToken( "eightySecondExpiryToken").expiresIn(80).build(); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))).thenReturn(eightSecondExpiryToken).thenReturn(eightySecondExpiryToken); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder().staleTime(Duration.ofSeconds(10)).build(); SdkToken resolvedToken = tokenProvider.resolveToken(); assertThat(resolvedToken.token()).contains("eightSecondExpiryToken"); verify(ssoOidcClient, times(1)).createToken(any(CreateTokenRequest.class)); SdkToken consecutiveToken = tokenProvider.resolveToken(); assertThat(consecutiveToken.token()).contains("eightySecondExpiryToken"); verify(ssoOidcClient, times(2)).createToken(any(CreateTokenRequest.class)); } @Test public void token_is_retrieved_automatically_when_prefetch_time_is_set() throws InterruptedException { Instant closeToExpireTime = Instant.now().plus(Duration.ofMillis(3)); SsoOidcToken cachedDiskToken = getDefaultTokenBuilder().accessToken("closeToExpire") .expiresAt(closeToExpireTime) .registrationExpiresAt(Instant.parse("2022-12-25T11:30:00Z")) .build(); mockTokenManager.storeToken(cachedDiskToken); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))) .thenReturn(getDefaultServiceResponse().accessToken("tokenGreaterThanStaleButLessThanPrefetch").expiresIn(1) .build()) .thenReturn(getDefaultServiceResponse().accessToken("tokenVeryHighExpiry").expiresIn(20000).build()); SsoOidcTokenProvider tokenProvider = getDefaultSsoOidcTokenProviderBuilder() .asyncTokenUpdateEnabled(true) .staleTime(Duration.ofSeconds(50)) .prefetchTime(Duration.ofSeconds(300)) .build(); Thread.sleep(100); SdkToken sdkToken = tokenProvider.resolveToken(); assertThat(sdkToken.token()).isEqualTo("tokenGreaterThanStaleButLessThanPrefetch"); Thread.sleep(1000); // Sleep to make sure Async prefetch thread gets picked up and it calls createToken to get new token. verify(ssoOidcClient, times(1)).createToken(any(CreateTokenRequest.class)); SdkToken highExpiryDateToken = tokenProvider.resolveToken(); Thread.sleep(1000); assertThat(highExpiryDateToken.token()).isEqualTo("tokenVeryHighExpiry"); } private CreateTokenResponse someOne(CreateTokenResponse.Builder builder, String tokenGreaterThanStaleButLessThanPrefetch, int i) { return builder.accessToken(tokenGreaterThanStaleButLessThanPrefetch).expiresIn(i).build(); } @Test public void tokenProvider_throws_exception_if_client_is_null() { assertThatExceptionOfType(NullPointerException.class).isThrownBy( () -> SsoOidcTokenProvider.builder().sessionName(START_URL).build()).withMessage("ssoOidcClient must not be null."); } @Test public void tokenProvider_throws_exception_if_start_url_is_null() { assertThatExceptionOfType(NullPointerException.class).isThrownBy( () -> SsoOidcTokenProvider.builder().ssoOidcClient(ssoOidcClient).build()).withMessage("sessionName must not be " + "null."); } private CreateTokenResponse.Builder getDefaultServiceResponse() { return CreateTokenResponse.builder().accessToken( "serviceToken").expiresIn(3600).refreshToken( "refreshedToken"); } private SsoOidcToken.Builder getDefaultTokenBuilder() { return SsoOidcToken.builder() .startUrl(START_URL) .region("us-west-2") .accessToken("cachedtoken") .expiresAt(Instant.parse("2022-12-25T13:30:00Z")) .clientId("clientid") .clientSecret("YSBzZWNyZXQ=") .registrationExpiresAt(Instant.parse("2022-12-25T13:40:00Z")) .refreshToken("cachedrefreshtoken"); } }
4,800
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/test/java/software/amazon/awssdk/services/ssooidc/internal
Create_ds/aws-sdk-java-v2/services/ssooidc/src/test/java/software/amazon/awssdk/services/ssooidc/internal/common/SsoOidcTokenRefreshTestBase.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.services.ssooidc.internal.common; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static software.amazon.awssdk.services.ssooidc.internal.SsoOidcTokenProviderTest.deriveCacheKey; import static software.amazon.awssdk.utils.UserHomeDirectoryUtils.userHomeDirectory; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.time.Instant; import java.util.Optional; import java.util.function.Supplier; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.auth.token.internal.ProfileTokenProviderLoader; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.services.ssooidc.SsoOidcClient; import software.amazon.awssdk.services.ssooidc.SsoOidcTokenProvider; import software.amazon.awssdk.services.ssooidc.internal.OnDiskTokenManager; import software.amazon.awssdk.services.ssooidc.internal.SsoOidcToken; import software.amazon.awssdk.services.ssooidc.model.CreateTokenRequest; import software.amazon.awssdk.services.ssooidc.model.CreateTokenResponse; import software.amazon.awssdk.services.ssooidc.model.InvalidRequestException; import software.amazon.awssdk.utils.StringInputStream; public abstract class SsoOidcTokenRefreshTestBase { protected static final String REGION = "us-east-1"; protected boolean shouldMockServiceClient; protected SsoOidcClient ssoOidcClient; protected String testStartUrl; protected String testSessionName = "sso-prod"; protected String baseTokenResourceFile; protected ProfileTokenProviderLoader profileTokenProviderLoader; public static final Path DEFAULT_TOKEN_LOCATION = Paths.get(userHomeDirectory(), ".aws", "sso", "cache"); @BeforeEach public void setUp() throws IOException { initializeClient(); initializeProfileProperties(); File cacheDirectory = DEFAULT_TOKEN_LOCATION.toFile(); if(! cacheDirectory.exists()){ cacheDirectory.mkdirs(); } Path file = DEFAULT_TOKEN_LOCATION.resolve(deriveCacheKey(this.testStartUrl)).getFileName(); try { Files.createDirectories(file.getParent()); Files.createFile(file); }catch (Exception e){ } } @AfterAll public static void cleanUp(){ File cacheDirectory = DEFAULT_TOKEN_LOCATION.toFile(); if(cacheDirectory.exists()){ cacheDirectory.delete(); } } protected abstract void initializeClient(); protected void initializeProfileProperties() { String profileContent = "[profile sso-refresh]\n" + "sso_region=us-east-1\n" + "sso_start_url=" + testStartUrl + "\n"; ProfileFile profile = ProfileFile.builder() .content(new StringInputStream(profileContent)) .type(ProfileFile.Type.CONFIGURATION) .build(); profileTokenProviderLoader = new ProfileTokenProviderLoader(() -> profile, "sso-refresh"); } @Test public void tokenReadFromCacheLocation_when_tokenIsWithinExpiry() throws IOException { // Creating a token and saving to disc OnDiskTokenManager onDiskTokenManager = OnDiskTokenManager.create(testSessionName); SsoOidcToken tokenFromJsonFile = getTokenFromJsonFile(baseTokenResourceFile) .expiresAt(Instant.now().plusSeconds(3600)).build(); onDiskTokenManager.storeToken(tokenFromJsonFile); //Creating default token provider SdkTokenProvider awsTokenProvider = defaultTokenProvider(); SdkToken resolvedToken = awsTokenProvider.resolveToken(); assertThat(resolvedToken).isEqualTo(tokenFromJsonFile); } @Test public void tokenReadFromService_And_DiscCacheUpdate_whenTokenInCacheIsExpired() { // Creating a token and saving to disc OnDiskTokenManager onDiskTokenManager = OnDiskTokenManager.create(testSessionName); SsoOidcToken tokenFromJsonFile = getTokenFromJsonFile(baseTokenResourceFile).expiresAt(Instant.now().minusSeconds(10)).build(); onDiskTokenManager.storeToken(tokenFromJsonFile); //Creating default token provider SdkTokenProvider awsTokenProvider = defaultTokenProvider(); SsoOidcToken firstResolvedToken = (SsoOidcToken) awsTokenProvider.resolveToken(); assert_oldCachedToken_isNoSameAs_NewResolvedToken(tokenFromJsonFile, firstResolvedToken); Optional<SsoOidcToken> loadedFromDiscAfterSecondRefresh = onDiskTokenManager.loadToken(); assertThat(loadedFromDiscAfterSecondRefresh).hasValue(firstResolvedToken); // Token taken from Cache SsoOidcToken secondResolvedToken = (SsoOidcToken) awsTokenProvider.resolveToken(); assertThat(firstResolvedToken).isEqualTo(secondResolvedToken); assertThat(secondResolvedToken).isNotEqualTo(tokenFromJsonFile); assertThat(onDiskTokenManager.loadToken()).hasValue(secondResolvedToken); } @Test public void tokenProvider_with_customStaleTime_refreshes_token() throws IOException, InterruptedException { // Creating a token and saving to disc OnDiskTokenManager onDiskTokenManager = OnDiskTokenManager.create(testSessionName); SsoOidcToken tokenFromJsonFile = getTokenFromJsonFile(baseTokenResourceFile).expiresAt(Instant.now().minusSeconds(10)).build(); onDiskTokenManager.storeToken(tokenFromJsonFile); //Creating default token provider SdkTokenProvider awsTokenProvider = tokenProviderBuilderWithClient().staleTime(Duration.ofMinutes(70)).sessionName(testSessionName).build(); // Resolve first Time SsoOidcToken firstResolvedToken = (SsoOidcToken) awsTokenProvider.resolveToken(); assert_oldCachedToken_isNoSameAs_NewResolvedToken(tokenFromJsonFile, firstResolvedToken); Optional<SsoOidcToken> loadedFromDiscAfterSecondRefresh = onDiskTokenManager.loadToken(); assertThat(loadedFromDiscAfterSecondRefresh).hasValue(firstResolvedToken); // Resolve second time Thread.sleep(1000); SsoOidcToken secondResolvedToken = (SsoOidcToken) awsTokenProvider.resolveToken(); assert_oldCachedToken_isNoSameAs_NewResolvedToken(firstResolvedToken, secondResolvedToken); loadedFromDiscAfterSecondRefresh = onDiskTokenManager.loadToken(); assertThat(loadedFromDiscAfterSecondRefresh).hasValue(secondResolvedToken); } @Test public void asyncCredentialUpdateEnabled_prefetch_when_prefetch_time_expired() throws InterruptedException, IOException { // Creating a token and saving to disc OnDiskTokenManager onDiskTokenManager = OnDiskTokenManager.create(testSessionName); SsoOidcToken tokenFromJsonFile = getTokenFromJsonFile(baseTokenResourceFile).build(); onDiskTokenManager.storeToken(tokenFromJsonFile); //Creating default token provider SsoOidcTokenProvider awsTokenProvider = tokenProviderBuilderWithClient().staleTime(Duration.ofMinutes(5)).asyncTokenUpdateEnabled(true) .prefetchTime(Duration.ofMinutes(10)) .sessionName(testSessionName).prefetchTime(Duration.ofMillis(100)).build(); // Make sure that tokens are refreshed from service after the autoRefreshDuration time awsTokenProvider.resolveToken(); SsoOidcToken refreshedTokenInDisc = onDiskTokenManager.loadToken().get(); assert_oldCachedToken_isNoSameAs_NewResolvedToken(tokenFromJsonFile, refreshedTokenInDisc); // Make sure that tokens are refreshed from disc for consecutive refresh awsTokenProvider.resolveToken(); Thread.sleep(100); awsTokenProvider.close(); SsoOidcToken refreshedTokenAfterPrefetch = onDiskTokenManager.loadToken().get(); assertThat(refreshedTokenAfterPrefetch).isEqualTo(refreshedTokenInDisc); } @Test public void tokenNotRefreshed_when_serviceRequestFailure() throws IOException { // Creating a token and saving to disc OnDiskTokenManager onDiskTokenManager = OnDiskTokenManager.create(testSessionName); if (shouldMockServiceClient) { when(ssoOidcClient.createToken(any(CreateTokenRequest.class))).thenThrow(InvalidRequestException.builder().build()); } SsoOidcToken tokenFromJsonFile = getTokenFromJsonFile(baseTokenResourceFile) .clientId("Incorrect Client Id").expiresAt(Instant.now().minusSeconds(10)).build(); onDiskTokenManager.storeToken(tokenFromJsonFile); //Creating default token provider SdkTokenProvider awsTokenProvider = defaultTokenProvider(); assertThatExceptionOfType(SdkClientException.class).isThrownBy(() -> awsTokenProvider.resolveToken()).withMessage( "Token is expired"); // Cached token is same as before assertThat(onDiskTokenManager.loadToken().get()).isEqualTo(tokenFromJsonFile); } private SdkTokenProvider defaultTokenProvider() { if (shouldMockServiceClient) { return tokenProviderBuilderWithClient().sessionName(testSessionName) .ssoOidcClient(this.ssoOidcClient).build(); } // return profileTokenProviderLoader.tokenProvider().get(); // TODO : remove the custom client before GA. return tokenProviderBuilderWithClient().sessionName(testSessionName) .ssoOidcClient(this.ssoOidcClient).build(); } private SsoOidcTokenProvider.Builder tokenProviderBuilderWithClient() { return SsoOidcTokenProvider.builder().ssoOidcClient(ssoOidcClient); } private void assert_oldCachedToken_isNoSameAs_NewResolvedToken(SsoOidcToken firstResolvedToken, SsoOidcToken secondResolvedToken) { assertThat(secondResolvedToken).isNotEqualTo(firstResolvedToken); assertThat(secondResolvedToken.expirationTime().get()).isAfter(firstResolvedToken.expirationTime().get()); assertThat(secondResolvedToken.token()).isNotEqualTo(firstResolvedToken.token()); assertThat(secondResolvedToken.refreshToken()).isEqualTo(firstResolvedToken.refreshToken()); assertThat(secondResolvedToken.startUrl()).isEqualTo(firstResolvedToken.startUrl()); assertThat(secondResolvedToken.clientId()).isEqualTo(firstResolvedToken.clientId()); assertThat(secondResolvedToken.clientSecret()).isEqualTo(firstResolvedToken.clientSecret()); } protected SsoOidcClient mockSsoOidcClient() { ssoOidcClient = mock(SsoOidcClient.class); SsoOidcToken baseToken = getTokenFromJsonFile(baseTokenResourceFile).build(); Supplier<CreateTokenResponse> responseSupplier = () -> CreateTokenResponse.builder().expiresIn(3600) .accessToken(RandomStringUtils.randomAscii(20)) .refreshToken(baseToken.refreshToken()) .build(); when(ssoOidcClient.createToken(any(CreateTokenRequest.class))) .thenReturn(responseSupplier.get()).thenReturn(responseSupplier.get()).thenReturn(responseSupplier.get()); return ssoOidcClient; } private SsoOidcToken.Builder getTokenFromJsonFile(String fileName) { String content = null; try { content = new String(Files.readAllBytes(Paths.get(fileName))); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Could not load resource file " + fileName, e); } JsonNode jsonNode = JsonNode.parser().parse(content); return SsoOidcToken.builder() .accessToken(jsonNode.field("accessToken").get().asString()) .refreshToken(jsonNode.field("refreshToken").get().asString()) .clientId(jsonNode.field("clientId").get().asString()) .clientSecret(jsonNode.field("clientSecret").get().asString()) .region(jsonNode.field("region").get().asString()) .startUrl(jsonNode.field("startUrl").get().asString()) .expiresAt(Instant.parse(jsonNode.field("expiresAt").get().asString())); } }
4,801
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ssooidc/src/it/java/software/amazon/awssdk/services/ssooidc/SsoOidcTokenRefreshIntegrationTest.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.services.ssooidc; import org.junit.jupiter.api.Disabled; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ssooidc.internal.common.SsoOidcTokenRefreshTestBase; @Disabled("Disabled since base registered tokens comes with expiration date and registration of token requires manual login") public class SsoOidcTokenRefreshIntegrationTest extends SsoOidcTokenRefreshTestBase { // TODO : Remove this gamma specific startUrl and endpoint before GA release. @Override public void initializeClient() { shouldMockServiceClient = false; // Follow registration steps to get the base token. baseTokenResourceFile = "src/it/resources/baseCreateToken.json"; testStartUrl = "http://caws-sono-testing.awsapps.com/start-beta"; ssoOidcClient = SsoOidcClient.builder() .region(Region.of(REGION)) .credentialsProvider(AnonymousCredentialsProvider.create()) .build(); } }
4,802
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services/ssooidc/SsoOidcTokenProvider.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.services.ssooidc; import java.time.Duration; import java.time.Instant; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.awscore.internal.token.CachedTokenRefresher; import software.amazon.awssdk.awscore.internal.token.TokenManager; import software.amazon.awssdk.awscore.internal.token.TokenRefresher; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.services.ssooidc.internal.OnDiskTokenManager; import software.amazon.awssdk.services.ssooidc.internal.SsoOidcToken; import software.amazon.awssdk.services.ssooidc.internal.SsoOidcTokenTransformer; import software.amazon.awssdk.services.ssooidc.model.CreateTokenRequest; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.SdkAutoCloseable; import software.amazon.awssdk.utils.Validate; /** * Implementation of {@link SdkTokenProvider} that is capable of loading and * storing SSO tokens to {@code ~/.aws/sso/cache}. This is also capable of * refreshing the cached token via the SSO-OIDC service. */ @SdkPublicApi @ThreadSafe public final class SsoOidcTokenProvider implements SdkTokenProvider, SdkAutoCloseable { private static final Duration DEFAULT_STALE_DURATION = Duration.ofMinutes(1); private static final Duration DEFAULT_PREFETCH_DURATION = Duration.ofMinutes(5); private static final Logger log = Logger.loggerFor(SsoOidcTokenProvider.class); private final TokenManager<SsoOidcToken> onDiskTokenManager; private final TokenRefresher<SsoOidcToken> tokenRefresher; private final SsoOidcClient ssoOidcClient; private final Duration staleTime; private final Duration prefetchTime; private SsoOidcTokenProvider(BuilderImpl builder) { Validate.paramNotNull(builder.sessionName, "sessionName"); Validate.paramNotNull(builder.ssoOidcClient, "ssoOidcClient"); this.ssoOidcClient = builder.ssoOidcClient; this.staleTime = builder.staleTime == null ? DEFAULT_STALE_DURATION : builder.staleTime; this.prefetchTime = builder.prefetchTime == null ? DEFAULT_PREFETCH_DURATION : builder.prefetchTime; this.onDiskTokenManager = OnDiskTokenManager.create(builder.sessionName); this.tokenRefresher = CachedTokenRefresher.builder() .tokenRetriever(getDefaultSsoTokenRetriever(this.ssoOidcClient, this.onDiskTokenManager, this.staleTime, this.prefetchTime)) .exceptionHandler(exceptionHandler()) .prefetchTime(this.prefetchTime) .staleDuration(this.staleTime) .asyncRefreshEnabled(builder.asyncTokenUpdateEnabled) .build(); } private Function<SdkException, SsoOidcToken> exceptionHandler() { return e -> { if (e instanceof AwsServiceException) { log.warn(() -> "Failed to fetch token.", e); // If we fail to get token from service then fetch the previous cached token from disc. return onDiskTokenManager.loadToken() .orElseThrow(() -> SdkClientException.create("Unable to load SSO token")); } throw e; }; } @Override public SdkToken resolveToken() { SsoOidcToken ssoOidcToken = tokenRefresher.refreshIfStaleAndFetch(); if (isExpired(ssoOidcToken)) { throw SdkClientException.create("Token is expired"); } return ssoOidcToken; } public static Builder builder() { return new BuilderImpl(); } @Override public void close() { tokenRefresher.close(); } public interface Builder { /** * The sessionName used to retrieve the SSO token. */ Builder sessionName(String sessionName); /** * * Client to fetch token from SSO OIDC service. */ Builder ssoOidcClient(SsoOidcClient ssoOidcClient); /** * Configure the amount of time, relative to Sso-Oidc token , that the cached tokens in refresher are considered * stale and should no longer be used. * * <p>By default, this is 5 minute.</p> */ Builder staleTime(Duration onDiskStaleDuration); /** * * Configure the amount of time, relative to Sso-Oidc token , that the cached tokens in refresher are considered * prefetched from service.. */ Builder prefetchTime(Duration prefetchTime); /** * Configure whether the provider should fetch tokens asynchronously in the background. If this is true, * threads are less likely to block when token are loaded, but additional resources are used to maintain * the provider. * * <p>By default, this is disabled.</p> */ Builder asyncTokenUpdateEnabled(Boolean asyncTokenUpdateEnabled); SsoOidcTokenProvider build(); } private boolean isExpired(SsoOidcToken token) { Instant expiration = token.expirationTime().get(); Instant now = Instant.now(); return now.isAfter(expiration); } private static boolean isWithinRefreshWindow(SsoOidcToken token, Duration staleTime) { Instant expiration = token.expirationTime().get(); Instant now = Instant.now(); return expiration.isAfter(now.plus(staleTime)); } private static void validateToken(SsoOidcToken token) { Validate.notNull(token.token(), "token cannot be null"); Validate.notNull(token.expirationTime(), "expirationTime cannot be null"); } private static class BuilderImpl implements Builder { private String sessionName; private SsoOidcClient ssoOidcClient; private Duration staleTime; private Duration prefetchTime; private Boolean asyncTokenUpdateEnabled = false; private BuilderImpl() { } @Override public Builder sessionName(String sessionName) { this.sessionName = sessionName; return this; } @Override public Builder ssoOidcClient(SsoOidcClient ssoOidcClient) { this.ssoOidcClient = ssoOidcClient; return this; } @Override public Builder staleTime(Duration staleTime) { this.staleTime = staleTime; return this; } @Override public Builder prefetchTime(Duration prefetchTime) { this.prefetchTime = prefetchTime; return this; } @Override public Builder asyncTokenUpdateEnabled(Boolean asyncTokenUpdateEnabled) { this.asyncTokenUpdateEnabled = asyncTokenUpdateEnabled; return this; } @Override public SsoOidcTokenProvider build() { return new SsoOidcTokenProvider(this); } } private static Supplier<SsoOidcToken> getDefaultSsoTokenRetriever(SsoOidcClient ssoOidcClient, TokenManager<SsoOidcToken> tokenManager, Duration staleTime, Duration prefetchTime) { return () -> { SsoOidcToken baseToken = tokenManager.loadToken() .orElseThrow(() -> SdkClientException.create("Unable to load SSO token")); validateToken(baseToken); if (isWithinRefreshWindow(baseToken, staleTime) && isWithinRefreshWindow(baseToken, prefetchTime)) { return baseToken; } SsoOidcTokenTransformer ssoOidcTokenTransformer = SsoOidcTokenTransformer.create(baseToken); SsoOidcToken refreshToken = ssoOidcTokenTransformer.transform(ssoOidcClient.createToken( CreateTokenRequest.builder() .grantType("refresh_token") .clientId(baseToken.clientId()) .clientSecret(baseToken.clientSecret()) .refreshToken(baseToken.refreshToken()) .build())); tokenManager.storeToken(refreshToken); return refreshToken; }; } }
4,803
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services/ssooidc/SsoOidcProfileTokenProviderFactory.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.services.ssooidc; import java.util.Objects; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.auth.token.credentials.ChildProfileTokenProviderFactory; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.profiles.Profile; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.profiles.internal.ProfileSection; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Factory for creating {@link SsoOidcTokenProvider}. */ @SdkProtectedApi public final class SsoOidcProfileTokenProviderFactory implements ChildProfileTokenProviderFactory { private static final String MISSING_PROPERTY_ERROR_FORMAT = "'%s' must be set to use bearer tokens loading in the " + "'%s' profile."; @Override public SdkTokenProvider create(ProfileFile profileFile, Profile profile) { return new SsoOidcProfileTokenProvider(profileFile, profile); } public SdkTokenProvider create(Supplier<ProfileFile> profileFile, String profileName) { return new SsoOidcSuppliedProfileTokenProvider(profileFile, profileName); } private static final class SsoOidcSuppliedProfileTokenProvider implements SdkTokenProvider, SdkAutoCloseable { private final Supplier<ProfileFile> profileFile; private final String profileName; private volatile ProfileFile currentProfileFile; private volatile SsoOidcProfileTokenProvider currentTokenProvider; private SsoOidcSuppliedProfileTokenProvider(Supplier<ProfileFile> profileFile, String profileName) { this.profileFile = profileFile; this.profileName = profileName; } @Override public SdkToken resolveToken() { return sdkTokenProvider().resolveToken(); } private SdkTokenProvider sdkTokenProvider() { ProfileFile profileFileInstance = profileFile.get(); if (!Objects.equals(profileFileInstance, currentProfileFile)) { synchronized (this) { if (!Objects.equals(profileFileInstance, currentProfileFile)) { Profile profileInstance = resolveProfile(profileFileInstance, profileName); currentProfileFile = profileFileInstance; currentTokenProvider = new SsoOidcProfileTokenProvider(profileFileInstance, profileInstance); } } } return currentTokenProvider; } private Profile resolveProfile(ProfileFile profileFile, String profileName) { return profileFile.profile(profileName) .orElseThrow(() -> { String errorMessage = String.format("Profile file contained no information for profile" + "'%s': %s", profileName, profileFile); return SdkClientException.builder().message(errorMessage).build(); }); } @Override public void close() { IoUtils.closeQuietly(currentTokenProvider, null); } } /** * A wrapper for a {@link SdkTokenProvider} that is returned by this factory when {@link #create(ProfileFile,Profile)} is * invoked. This wrapper is important because it ensures the token provider is closed when it is no longer needed. */ private static final class SsoOidcProfileTokenProvider implements SdkTokenProvider, SdkAutoCloseable { private final SsoOidcTokenProvider sdkTokenProvider; private SsoOidcProfileTokenProvider(ProfileFile profileFile, Profile profile) { String profileSsoSectionName = profile.property( ProfileSection.SSO_SESSION .getPropertyKeyName()).orElseThrow(() -> new IllegalStateException( "Profile " + profile.name() + " does not have sso_session property")); Profile ssoProfile = profileFile.getSection( ProfileSection.SSO_SESSION.getSectionTitle(), profileSsoSectionName).orElseThrow(() -> new IllegalArgumentException( "Sso-session section not found with sso-session title " + profileSsoSectionName + ".")); String startUrl = requireProperty(ssoProfile, ProfileProperty.SSO_START_URL); String region = requireProperty(ssoProfile, ProfileProperty.SSO_REGION); if (ssoProfile.property(ProfileProperty.SSO_ACCOUNT_ID).isPresent() || ssoProfile.property(ProfileProperty.SSO_ROLE_NAME).isPresent()) { throw new IllegalStateException("sso_account_id or sso_role_name properties must not be defined for" + "profiles that provide ssooidc providers"); } this.sdkTokenProvider = SsoOidcTokenProvider.builder() .sessionName(ssoProfile.name()) .ssoOidcClient(SsoOidcClient.builder() .region(Region.of(region)) .credentialsProvider( AnonymousCredentialsProvider.create()) .build()) .build(); } private String requireProperty(Profile profile, String requiredProperty) { return profile.property(requiredProperty) .orElseThrow(() -> new IllegalArgumentException(String.format(MISSING_PROPERTY_ERROR_FORMAT, requiredProperty, profile.name()))); } @Override public SdkToken resolveToken() { return this.sdkTokenProvider.resolveToken(); } @Override public void close() { IoUtils.closeQuietly(sdkTokenProvider, null); } } }
4,804
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services/ssooidc
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services/ssooidc/internal/SsoOidcTokenTransformer.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.services.ssooidc.internal; import java.time.Instant; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.internal.token.TokenTransformer; import software.amazon.awssdk.services.ssooidc.model.CreateTokenResponse; import software.amazon.awssdk.utils.Validate; /** * Transformer to transform CreateTokenResponse to SsoToken. */ @SdkInternalApi public final class SsoOidcTokenTransformer implements TokenTransformer<SsoOidcToken, CreateTokenResponse> { private final SsoOidcToken baseToken; private SsoOidcTokenTransformer(SsoOidcToken baseToken) { Validate.notNull(baseToken.startUrl(), "startUrl is null "); Validate.notNull(baseToken.clientId(), "clientId is null "); Validate.notNull(baseToken.clientSecret(), "clientSecret is null "); this.baseToken = baseToken; } public static SsoOidcTokenTransformer create(SsoOidcToken baseToken) { Validate.paramNotNull(baseToken, "baseToken"); return new SsoOidcTokenTransformer(baseToken); } @Override public SsoOidcToken transform(CreateTokenResponse awsResponse) { Validate.paramNotNull(awsResponse.accessToken(), "accessToken"); Validate.paramNotNull(awsResponse.expiresIn(), "expiresIn"); return SsoOidcToken.builder() .accessToken(awsResponse.accessToken()) .refreshToken(awsResponse.refreshToken()) .expiresAt(awsResponse.expiresIn() != null ? Instant.now().plusSeconds(awsResponse.expiresIn()) : null) .startUrl(baseToken.startUrl()) .registrationExpiresAt(baseToken.registrationExpiresAt()) .region(baseToken.region()) .clientSecret(baseToken.clientSecret()) .clientId(baseToken.clientId()) .build(); } }
4,805
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services/ssooidc
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services/ssooidc/internal/OnDiskTokenManager.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.services.ssooidc.internal; import static software.amazon.awssdk.utils.UserHomeDirectoryUtils.userHomeDirectory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.util.Locale; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.awscore.internal.token.TokenManager; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.protocols.jsoncore.JsonNode; import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser; import software.amazon.awssdk.thirdparty.jackson.core.JsonGenerator; import software.amazon.awssdk.utils.BinaryUtils; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Validate; /** * Implementation of {@link TokenManager} that can load and store SSO tokens * from and to disk. */ @SdkInternalApi public final class OnDiskTokenManager implements TokenManager<SsoOidcToken> { private static final Path DEFAULT_TOKEN_LOCATION = Paths.get(userHomeDirectory(), ".aws", "sso", "cache"); private final JsonNodeParser jsonParser = JsonNodeParser.builder().removeErrorLocations(true).build(); private final String sessionName; private final Path tokenLocation; private OnDiskTokenManager(Path cacheLocation, String sessionName) { Validate.notNull(cacheLocation, "cacheLocation must not be null"); this.sessionName = Validate.notNull(sessionName, "sessionName must not be null"); Validate.notBlank(sessionName, "sessionName must not be blank"); String cacheKey = deriveCacheKey(sessionName); this.tokenLocation = cacheLocation.resolve(cacheKey + ".json"); } @Override public Optional<SsoOidcToken> loadToken() { if (!Files.exists(tokenLocation)) { return Optional.empty(); } try (InputStream cachedTokenStream = Files.newInputStream(tokenLocation)) { String content = IoUtils.toUtf8String(cachedTokenStream); return Optional.of(unmarshalToken(content)); } catch (IOException e) { throw SdkClientException.create("Failed to load cached token at " + tokenLocation, e); } } @Override public void storeToken(SsoOidcToken token) { try (OutputStream os = Files.newOutputStream(tokenLocation)) { os.write(marshalToken(token)); } catch (IOException e) { throw SdkClientException.create("Unable to write token to location " + tokenLocation, e); } } @Override public void close() { } public static OnDiskTokenManager create(Path cacheLocation, String sessionName) { return new OnDiskTokenManager(cacheLocation, sessionName); } public static OnDiskTokenManager create(String sessionName) { return create(DEFAULT_TOKEN_LOCATION, sessionName); } private SsoOidcToken unmarshalToken(String contents) { JsonNode node = jsonParser.parse(contents); SsoOidcToken.Builder tokenBuilder = SsoOidcToken.builder(); JsonNode accessToken = node.field("accessToken") .orElseThrow(() -> SdkClientException.create("required member 'accessToken' not found")); tokenBuilder.accessToken(accessToken.text()); JsonNode expiresAt = node.field("expiresAt") .orElseThrow(() -> SdkClientException.create("required member 'expiresAt' not found")); tokenBuilder.expiresAt(Instant.parse(expiresAt.text())); node.field("refreshToken").map(JsonNode::text).ifPresent(tokenBuilder::refreshToken); node.field("clientId").map(JsonNode::text).ifPresent(tokenBuilder::clientId); node.field("clientSecret").map(JsonNode::text).ifPresent(tokenBuilder::clientSecret); node.field("registrationExpiresAt") .map(JsonNode::text) .map(Instant::parse) .ifPresent(tokenBuilder::registrationExpiresAt); node.field("region").map(JsonNode::text).ifPresent(tokenBuilder::region); node.field("startUrl").map(JsonNode::text).ifPresent(tokenBuilder::startUrl); return tokenBuilder.build(); } private byte[] marshalToken(SsoOidcToken token) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator generator = null; try { generator = JsonNodeParser.DEFAULT_JSON_FACTORY.createGenerator(baos); generator.writeStartObject(); generator.writeStringField("accessToken", token.token()); generator.writeStringField("expiresAt", DateTimeFormatter.ISO_INSTANT.format(token.expirationTime().get())); if (token.refreshToken() != null) { generator.writeStringField("refreshToken", token.refreshToken()); } if (token.clientId() != null) { generator.writeStringField("clientId", token.clientId()); } if (token.clientSecret() != null) { generator.writeStringField("clientSecret", token.clientSecret()); } if (token.registrationExpiresAt() != null) { generator.writeStringField("registrationExpiresAt", DateTimeFormatter.ISO_INSTANT.format(token.registrationExpiresAt())); } if (token.region() != null) { generator.writeStringField("region", token.region()); } if (token.startUrl() != null) { generator.writeStringField("startUrl", token.startUrl()); } generator.writeEndObject(); generator.close(); return baos.toByteArray(); } catch (IOException e) { throw SdkClientException.create("Unable to marshal token to JSON", e); } finally { if (generator != null) { IoUtils.closeQuietly(generator, null); } } } private static String deriveCacheKey(String sessionName) { try { MessageDigest sha1 = MessageDigest.getInstance("sha1"); sha1.update(sessionName.getBytes(StandardCharsets.UTF_8)); return BinaryUtils.toHex(sha1.digest()).toLowerCase(Locale.ENGLISH); } catch (NoSuchAlgorithmException e) { throw SdkClientException.create("Unable to derive cache key", e); } } }
4,806
0
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services/ssooidc
Create_ds/aws-sdk-java-v2/services/ssooidc/src/main/java/software/amazon/awssdk/services/ssooidc/internal/SsoOidcToken.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.services.ssooidc.internal; import java.time.Instant; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.token.credentials.SdkToken; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; /** * Represents a cached SSO token. * * <code> * { * "accessToken": "string", * "expiresAt": "2019-11-14T04:05:45Z", * "refreshToken": "string", * "clientId": "ABCDEFG323242423121312312312312312", * "clientSecret": "ABCDE123", * "registrationExpiresAt": "2022-03-06T19:53:17Z", * "region": "us-west-2", * "startUrl": "https://d-abc123.awsapps.com/start" * } * </code> */ @SdkInternalApi public final class SsoOidcToken implements SdkToken { private final String accessToken; private final Instant expiresAt; private final String refreshToken; private final String clientId; private final String clientSecret; private final Instant registrationExpiresAt; private final String region; private final String startUrl; private SsoOidcToken(BuilderImpl builder) { Validate.paramNotNull(builder.accessToken, "accessToken"); Validate.paramNotNull(builder.expiresAt, "expiresAt"); this.accessToken = builder.accessToken; this.expiresAt = builder.expiresAt; this.refreshToken = builder.refreshToken; this.clientId = builder.clientId; this.clientSecret = builder.clientSecret; this.registrationExpiresAt = builder.registrationExpiresAt; this.region = builder.region; this.startUrl = builder.startUrl; } @Override public String token() { return accessToken; } @Override public Optional<Instant> expirationTime() { return Optional.of(expiresAt); } public String refreshToken() { return refreshToken; } public String clientId() { return clientId; } public String clientSecret() { return clientSecret; } public Instant registrationExpiresAt() { return registrationExpiresAt; } public String region() { return region; } public String startUrl() { return startUrl; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SsoOidcToken ssoOidcToken = (SsoOidcToken) o; return Objects.equals(accessToken, ssoOidcToken.accessToken) && Objects.equals(expiresAt, ssoOidcToken.expiresAt) && Objects.equals(refreshToken, ssoOidcToken.refreshToken) && Objects.equals(clientId, ssoOidcToken.clientId) && Objects.equals(clientSecret, ssoOidcToken.clientSecret) && Objects.equals(registrationExpiresAt, ssoOidcToken.registrationExpiresAt) && Objects.equals(region, ssoOidcToken.region) && Objects.equals(startUrl, ssoOidcToken.startUrl); } @Override public int hashCode() { int result = Objects.hashCode(accessToken); result = 31 * result + Objects.hashCode(expiresAt); result = 31 * result + Objects.hashCode(refreshToken); result = 31 * result + Objects.hashCode(clientId); result = 31 * result + Objects.hashCode(clientSecret); result = 31 * result + Objects.hashCode(registrationExpiresAt); result = 31 * result + Objects.hashCode(region); result = 31 * result + Objects.hashCode(startUrl); return result; } @Override public String toString() { return ToString.builder("SsoOidcToken") .add("accessToken", accessToken) .add("expiresAt", expiresAt) .add("refreshToken", refreshToken) .add("clientId", clientId) .add("clientSecret", clientSecret) .add("registrationExpiresAt", registrationExpiresAt) .add("region", region) .add("startUrl", startUrl) .build(); } public static Builder builder() { return new BuilderImpl(); } public interface Builder { Builder accessToken(String accessToken); Builder expiresAt(Instant expiresAt); Builder refreshToken(String refreshToken); Builder clientId(String clientId); Builder clientSecret(String clientSecret); Builder registrationExpiresAt(Instant registrationExpiresAt); Builder region(String region); Builder startUrl(String startUrl); SsoOidcToken build(); } private static class BuilderImpl implements Builder { private String accessToken; private Instant expiresAt; private String refreshToken; private String clientId; private String clientSecret; private Instant registrationExpiresAt; private String region; private String startUrl; @Override public Builder accessToken(String accessToken) { this.accessToken = accessToken; return this; } @Override public Builder expiresAt(Instant expiresAt) { this.expiresAt = expiresAt; return this; } @Override public Builder refreshToken(String refreshToken) { this.refreshToken = refreshToken; return this; } @Override public Builder clientId(String clientId) { this.clientId = clientId; return this; } @Override public Builder clientSecret(String clientSecret) { this.clientSecret = clientSecret; return this; } @Override public Builder registrationExpiresAt(Instant registrationExpiresAt) { this.registrationExpiresAt = registrationExpiresAt; return this; } @Override public Builder region(String region) { this.region = region; return this; } @Override public Builder startUrl(String startUrl) { this.startUrl = startUrl; return this; } @Override public SsoOidcToken build() { return new SsoOidcToken(this); } } }
4,807
0
Create_ds/aws-sdk-java-v2/services/waf/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/waf/src/it/java/software/amazon/awssdk/services/waf/WafIntegrationTest.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.services.waf; import java.io.IOException; import java.time.Duration; import java.util.List; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.core.retry.backoff.FixedDelayBackoffStrategy; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.waf.model.ChangeAction; import software.amazon.awssdk.services.waf.model.CreateIpSetRequest; import software.amazon.awssdk.services.waf.model.CreateIpSetResponse; import software.amazon.awssdk.services.waf.model.GetChangeTokenRequest; import software.amazon.awssdk.services.waf.model.GetChangeTokenResponse; import software.amazon.awssdk.services.waf.model.GetIpSetRequest; import software.amazon.awssdk.services.waf.model.GetIpSetResponse; import software.amazon.awssdk.services.waf.model.IPSet; import software.amazon.awssdk.services.waf.model.IPSetDescriptor; import software.amazon.awssdk.services.waf.model.IPSetDescriptorType; import software.amazon.awssdk.services.waf.model.IPSetUpdate; import software.amazon.awssdk.services.waf.model.ListIpSetsRequest; import software.amazon.awssdk.services.waf.model.ListIpSetsResponse; import software.amazon.awssdk.services.waf.model.UpdateIpSetRequest; import software.amazon.awssdk.services.waf.model.WafNonEmptyEntityException; import software.amazon.awssdk.testutils.Waiter; import software.amazon.awssdk.testutils.service.AwsTestBase; public class WafIntegrationTest extends AwsTestBase { private static final String IP_SET_NAME = "java-sdk-ipset-" + System.currentTimeMillis(); private static final String IP_ADDRESS_RANGE = "192.0.2.0/24"; private static WafClient client = null; private static String ipSetId = null; @BeforeClass public static void setup() throws IOException { FixedDelayBackoffStrategy fixedBackoffStrategy = FixedDelayBackoffStrategy.create(Duration.ofSeconds(30)); setUpCredentials(); client = WafClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(Region.AWS_GLOBAL) .overrideConfiguration(cfg -> cfg.retryPolicy(r -> r.backoffStrategy(fixedBackoffStrategy))) .build(); } @AfterClass public static void tearDown() throws IOException { if (client != null) { deleteIpSet(); } } private static void deleteIpSet() { if (ipSetId != null) { Waiter.run(() -> client.deleteIPSet(r -> r.ipSetId(ipSetId).changeToken(newChangeToken()))) .ignoringException(WafNonEmptyEntityException.class) .orFailAfter(Duration.ofMinutes(2)); } } private static String newChangeToken() { GetChangeTokenResponse result = client.getChangeToken(GetChangeTokenRequest.builder().build()); return result.changeToken(); } @Test public void testOperations() throws InterruptedException { ipSetId = testCreateIpSet(); testGetIpSet(); testUpdateIpSet(); } private String testCreateIpSet() { final String changeToken = newChangeToken(); CreateIpSetResponse createResult = client.createIPSet(CreateIpSetRequest.builder() .changeToken(changeToken) .name(IP_SET_NAME).build()); Assert.assertEquals(changeToken, createResult.changeToken()); final IPSet ipSet = createResult.ipSet(); Assert.assertNotNull(ipSet); Assert.assertEquals(IP_SET_NAME, ipSet.name()); Assert.assertTrue(ipSet.ipSetDescriptors().isEmpty()); Assert.assertNotNull(ipSet.ipSetId()); return ipSet.ipSetId(); } private void testGetIpSet() { GetIpSetResponse getResult = client.getIPSet(GetIpSetRequest.builder() .ipSetId(ipSetId) .build()); IPSet ipSet = getResult.ipSet(); Assert.assertNotNull(ipSet); Assert.assertEquals(IP_SET_NAME, ipSet.name()); Assert.assertTrue(ipSet.ipSetDescriptors().isEmpty()); Assert.assertNotNull(ipSet.ipSetId()); Assert.assertEquals(ipSetId, ipSet.ipSetId()); ListIpSetsResponse listResult = client.listIPSets(ListIpSetsRequest.builder() .limit(1) .build()); Assert.assertNotNull(listResult.ipSets()); Assert.assertFalse(listResult.ipSets().isEmpty()); } private void testUpdateIpSet() { final IPSetDescriptor ipSetDescriptor = IPSetDescriptor.builder() .type(IPSetDescriptorType.IPV4) .value(IP_ADDRESS_RANGE) .build(); final IPSetUpdate ipToInsert = IPSetUpdate.builder() .ipSetDescriptor(ipSetDescriptor) .action(ChangeAction.INSERT) .build(); client.updateIPSet(UpdateIpSetRequest.builder() .ipSetId(ipSetId) .changeToken(newChangeToken()) .updates(ipToInsert).build()); GetIpSetResponse getResult = client.getIPSet(GetIpSetRequest.builder() .ipSetId(ipSetId).build()); IPSet ipSet = getResult.ipSet(); Assert.assertNotNull(ipSet); Assert.assertEquals(IP_SET_NAME, ipSet.name()); Assert.assertNotNull(ipSet.ipSetId()); Assert.assertEquals(ipSetId, ipSet.ipSetId()); List<IPSetDescriptor> actualList = ipSet.ipSetDescriptors(); Assert.assertFalse(actualList.isEmpty()); Assert.assertEquals(1, actualList.size()); IPSetDescriptor actualIpSetDescriptor = actualList.get(0); Assert.assertEquals(ipSetDescriptor.type(), actualIpSetDescriptor.type()); Assert.assertEquals(ipSetDescriptor.value(), actualIpSetDescriptor.value()); final IPSetUpdate ipToDelete = IPSetUpdate.builder() .ipSetDescriptor(ipSetDescriptor) .action(ChangeAction.DELETE) .build(); client.updateIPSet(UpdateIpSetRequest.builder() .ipSetId(ipSetId) .changeToken(newChangeToken()) .updates(ipToDelete) .build()); } }
4,808
0
Create_ds/aws-sdk-java-v2/services/waf/src/it/java/software/amazon/awssdk/services/waf
Create_ds/aws-sdk-java-v2/services/waf/src/it/java/software/amazon/awssdk/services/waf/regional/WafRegionalIntegrationTest.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.services.waf.regional; import org.junit.Test; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.waf.model.ListResourcesForWebAclRequest; import software.amazon.awssdk.services.waf.model.WafNonexistentItemException; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class WafRegionalIntegrationTest extends AwsIntegrationTestBase { /** * Calls an operation specific to WAF Regional. If we get a modeled exception back then we called the * right service. */ @Test(expected = WafNonexistentItemException.class) public void smokeTest() { final WafRegionalClient client = WafRegionalClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(Region.US_WEST_2) .build(); client.listResourcesForWebACL(ListResourcesForWebAclRequest.builder().webACLId("foo").build()); } }
4,809
0
Create_ds/aws-sdk-java-v2/services/directconnect/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/directconnect/src/it/java/software/amazon/awssdk/services/directconnect/IntegrationTestBase.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.services.directconnect; import java.io.IOException; import org.junit.BeforeClass; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.testutils.service.AwsTestBase; public class IntegrationTestBase extends AwsTestBase { protected static DirectConnectClient dc; @BeforeClass public static void setUp() throws IOException { setUpCredentials(); dc = DirectConnectClient.builder() .region(Region.US_WEST_1) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); } }
4,810
0
Create_ds/aws-sdk-java-v2/services/directconnect/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/directconnect/src/it/java/software/amazon/awssdk/services/directconnect/ServiceIntegrationTest.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.services.directconnect; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.core.SdkGlobalTime; import software.amazon.awssdk.services.directconnect.model.CreateConnectionRequest; import software.amazon.awssdk.services.directconnect.model.CreateConnectionResponse; import software.amazon.awssdk.services.directconnect.model.DeleteConnectionRequest; import software.amazon.awssdk.services.directconnect.model.DescribeConnectionsRequest; import software.amazon.awssdk.services.directconnect.model.DescribeConnectionsResponse; import software.amazon.awssdk.services.directconnect.model.DescribeLocationsRequest; import software.amazon.awssdk.services.directconnect.model.DescribeLocationsResponse; import software.amazon.awssdk.services.directconnect.model.DirectConnectException; import software.amazon.awssdk.services.directconnect.model.Location; import software.amazon.awssdk.testutils.Waiter; import software.amazon.awssdk.utils.Logger; public class ServiceIntegrationTest extends IntegrationTestBase { private static final Logger log = Logger.loggerFor(ServiceIntegrationTest.class); private static final String CONNECTION_NAME = "test-connection-name"; private static final String EXPECTED_CONNECTION_STATUS = "requested"; private static String connectionId; @BeforeClass public static void setup() { CreateConnectionResponse result = dc.createConnection(CreateConnectionRequest.builder() .connectionName(CONNECTION_NAME) .bandwidth("1Gbps") .location("EqSV5") .build()); connectionId = result.connectionId(); } @AfterClass public static void tearDown() { boolean cleanedUp = Waiter.run(() -> dc.deleteConnection(r -> r.connectionId(connectionId))) .ignoringException(DirectConnectException.class) .orReturnFalse(); if (!cleanedUp) { log.warn(() -> "Failed to clean up connection: " + connectionId); } } @Test public void describeLocations_ReturnsNonEmptyList() { DescribeLocationsResponse describeLocations = dc.describeLocations(DescribeLocationsRequest.builder().build()); assertTrue(describeLocations.locations().size() > 0); for (Location location : describeLocations.locations()) { assertNotNull(location.locationCode()); assertNotNull(location.locationName()); } } @Test public void describeConnections_ReturnsNonEmptyList() { DescribeConnectionsResponse describeConnectionsResult = dc.describeConnections(DescribeConnectionsRequest.builder().build()); assertTrue(describeConnectionsResult.connections().size() > 0); assertNotNull(describeConnectionsResult.connections().get(0).connectionId()); assertNotNull(describeConnectionsResult.connections().get(0).connectionName()); assertNotNull(describeConnectionsResult.connections().get(0).connectionState()); assertNotNull(describeConnectionsResult.connections().get(0).location()); assertNotNull(describeConnectionsResult.connections().get(0).region()); } @Test public void describeConnections_FilteredByCollectionId_ReturnsOnlyOneConnection() { DescribeConnectionsResponse describeConnectionsResult = dc.describeConnections(DescribeConnectionsRequest.builder() .connectionId(connectionId) .build()); assertThat(describeConnectionsResult.connections(), hasSize(1)); assertEquals(connectionId, describeConnectionsResult.connections().get(0).connectionId()); assertEquals(EXPECTED_CONNECTION_STATUS, describeConnectionsResult.connections().get(0).connectionStateAsString()); } /** * In the following test, we purposely setting the time offset to trigger a clock skew error. * The time offset must be fixed and then we validate the global value for time offset has been * update. */ @Test public void testClockSkew() { SdkGlobalTime.setGlobalTimeOffset(3600); DirectConnectClient clockSkewClient = DirectConnectClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); clockSkewClient.describeConnections(DescribeConnectionsRequest.builder().build()); assertTrue(SdkGlobalTime.getGlobalTimeOffset() < 60); } }
4,811
0
Create_ds/aws-sdk-java-v2/services/docdb/src/test/java/software/amazon/awssdk/services/docdb
Create_ds/aws-sdk-java-v2/services/docdb/src/test/java/software/amazon/awssdk/services/docdb/internal/PresignRequestWireMockTest.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.services.docdb.internal; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.anyRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import java.net.URI; import java.util.List; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.docdb.DocDbClient; @RunWith(MockitoJUnitRunner.class) public class PresignRequestWireMockTest { @ClassRule public static final WireMockRule WIRE_MOCK = new WireMockRule(0); public static DocDbClient client; @BeforeClass public static void setup() { client = DocDbClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + WIRE_MOCK.port())) .build(); } @Before public void reset() { WIRE_MOCK.resetAll(); } @Test public void copyDbClusterSnapshotWithSourceRegionSendsPresignedUrl() { verifyMethodCallSendsPresignedUrl(() -> client.copyDBClusterSnapshot(r -> r.sourceRegion("us-west-2")), "CopyDBClusterSnapshot"); } @Test public void copyDBSnapshotWithSourceRegionSendsPresignedUrl() { verifyMethodCallSendsPresignedUrl(() -> client.copyDBClusterSnapshot(r -> r.sourceRegion("us-west-2")), "CopyDBClusterSnapshot"); } @Test public void createDbClusterWithSourceRegionSendsPresignedUrl() { verifyMethodCallSendsPresignedUrl(() -> client.createDBCluster(r -> r.sourceRegion("us-west-2")), "CreateDBCluster"); } @Test public void createDBInstanceReadReplicaWithSourceRegionSendsPresignedUrl() { verifyMethodCallSendsPresignedUrl(() -> client.createDBCluster(r -> r.sourceRegion("us-west-2")), "CreateDBCluster"); } public void verifyMethodCallSendsPresignedUrl(Runnable methodCall, String actionName) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody("<body/>"))); methodCall.run(); List<LoggedRequest> requests = findAll(anyRequestedFor(anyUrl())); assertThat(requests).isNotEmpty(); LoggedRequest lastRequest = requests.get(0); String lastRequestBody = new String(lastRequest.getBody(), UTF_8); assertThat(lastRequestBody).contains("PreSignedUrl=https%3A%2F%2Frds.us-west-2.amazonaws.com%3FAction%3D" + actionName + "%26Version%3D2014-10-31%26DestinationRegion%3Dus-east-1%26"); } }
4,812
0
Create_ds/aws-sdk-java-v2/services/docdb/src/test/java/software/amazon/awssdk/services/docdb
Create_ds/aws-sdk-java-v2/services/docdb/src/test/java/software/amazon/awssdk/services/docdb/internal/PresignRequestHandlerTest.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.services.docdb.internal; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; import java.net.URI; import java.net.URISyntaxException; import java.time.Clock; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.awscore.endpoint.DefaultServiceEndpointBuilder; import software.amazon.awssdk.core.Protocol; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.docdb.model.CopyDbClusterSnapshotRequest; import software.amazon.awssdk.services.docdb.model.DocDbRequest; import software.amazon.awssdk.services.docdb.transform.CopyDbClusterSnapshotRequestMarshaller; /** * Unit Tests for {@link RdsPresignInterceptor} */ public class PresignRequestHandlerTest { private static final AwsBasicCredentials CREDENTIALS = AwsBasicCredentials.create("foo", "bar"); private static final Region DESTINATION_REGION = Region.of("us-west-2"); private static final RdsPresignInterceptor<CopyDbClusterSnapshotRequest> presignInterceptor = new CopyDbClusterSnapshotPresignInterceptor(); private final CopyDbClusterSnapshotRequestMarshaller marshaller = new CopyDbClusterSnapshotRequestMarshaller(RdsPresignInterceptor.PROTOCOL_FACTORY); @Test public void testSetsPresignedUrl() { CopyDbClusterSnapshotRequest request = makeTestRequest(); SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshallRequest(request)); assertNotNull(presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0)); } @Test public void testComputesPresignedUrlCorrectlyForCopyDbClusterSnapshotRequest() { // Note: test data was baselined by performing actual calls, with real // credentials to RDS and checking that they succeeded. Then the // request was recreated with all the same parameters but with test // credentials. final CopyDbClusterSnapshotRequest request = CopyDbClusterSnapshotRequest.builder() .sourceDBClusterSnapshotIdentifier("arn:aws:rds:us-east-1:123456789012:snapshot:rds:test-instance-ss-2016-12-20-23-19") .targetDBClusterSnapshotIdentifier("test-instance-ss-copy-2") .sourceRegion("us-east-1") .kmsKeyId("arn:aws:kms:us-west-2:123456789012:key/11111111-2222-3333-4444-555555555555") .build(); Calendar c = new GregorianCalendar(); c.setTimeZone(TimeZone.getTimeZone("UTC")); // 20161221T180735Z // Note: month is 0-based c.set(2016, Calendar.DECEMBER, 21, 18, 7, 35); Clock signingDateOverride = Mockito.mock(Clock.class); when(signingDateOverride.millis()).thenReturn(c.getTimeInMillis()); RdsPresignInterceptor<CopyDbClusterSnapshotRequest> interceptor = new CopyDbClusterSnapshotPresignInterceptor(signingDateOverride); SdkHttpRequest presignedRequest = modifyHttpRequest(interceptor, request, marshallRequest(request)); final String expectedPreSignedUrl = "https://rds.us-east-1.amazonaws.com?" + "Action=CopyDBClusterSnapshot" + "&Version=2014-10-31" + "&SourceDBClusterSnapshotIdentifier=arn%3Aaws%3Ards%3Aus-east-1%3A123456789012%3Asnapshot%3Ards%3Atest-instance-ss-2016-12-20-23-19" + "&TargetDBClusterSnapshotIdentifier=test-instance-ss-copy-2" + "&KmsKeyId=arn%3Aaws%3Akms%3Aus-west-2%3A123456789012%3Akey%2F11111111-2222-3333-4444-555555555555" + "&DestinationRegion=us-west-2" + "&X-Amz-Algorithm=AWS4-HMAC-SHA256" + "&X-Amz-Date=20161221T180735Z" + "&X-Amz-SignedHeaders=host" + "&X-Amz-Expires=604800" + "&X-Amz-Credential=foo%2F20161221%2Fus-east-1%2Frds%2Faws4_request" + "&X-Amz-Signature=00822ebbba95e2e6ac09112aa85621fbef060a596e3e1480f9f4ac61493e9821"; assertEquals(expectedPreSignedUrl, presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0)); } @Test public void testSkipsPresigningIfUrlSet() { CopyDbClusterSnapshotRequest request = CopyDbClusterSnapshotRequest.builder() .sourceRegion("us-west-2") .preSignedUrl("PRESIGNED") .build(); SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshallRequest(request)); assertEquals("PRESIGNED", presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0)); } @Test public void testSkipsPresigningIfSourceRegionNotSet() { CopyDbClusterSnapshotRequest request = CopyDbClusterSnapshotRequest.builder().build(); SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshallRequest(request)); assertNull(presignedRequest.rawQueryParameters().get("PreSignedUrl")); } @Test public void testParsesDestinationRegionfromRequestEndpoint() throws URISyntaxException { CopyDbClusterSnapshotRequest request = CopyDbClusterSnapshotRequest.builder() .sourceRegion("us-east-1") .build(); Region destination = Region.of("us-west-2"); SdkHttpFullRequest marshalled = marshallRequest(request); final SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshalled); final URI presignedUrl = new URI(presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0)); assertTrue(presignedUrl.toString().contains("DestinationRegion=" + destination.id())); } @Test public void testSourceRegionRemovedFromOriginalRequest() { CopyDbClusterSnapshotRequest request = makeTestRequest(); SdkHttpFullRequest marshalled = marshallRequest(request); SdkHttpRequest actual = modifyHttpRequest(presignInterceptor, request, marshalled); assertFalse(actual.rawQueryParameters().containsKey("SourceRegion")); } private SdkHttpFullRequest marshallRequest(CopyDbClusterSnapshotRequest request) { SdkHttpFullRequest.Builder marshalled = marshaller.marshall(request).toBuilder(); URI endpoint = new DefaultServiceEndpointBuilder("rds", Protocol.HTTPS.toString()) .withRegion(DESTINATION_REGION) .getServiceEndpoint(); return marshalled.uri(endpoint).build(); } private ExecutionAttributes executionAttributes() { return new ExecutionAttributes().putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, CREDENTIALS) .putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, DESTINATION_REGION) .putAttribute(SdkExecutionAttribute.PROFILE_FILE_SUPPLIER, ProfileFile::defaultProfileFile) .putAttribute(SdkExecutionAttribute.PROFILE_NAME, "default"); } private CopyDbClusterSnapshotRequest makeTestRequest() { return CopyDbClusterSnapshotRequest.builder() .sourceDBClusterSnapshotIdentifier("arn:aws:rds:us-east-1:123456789012:snapshot:rds:test-instance-ss-2016-12-20-23-19") .targetDBClusterSnapshotIdentifier("test-instance-ss-copy-2") .sourceRegion("us-east-1") .kmsKeyId("arn:aws:kms:us-west-2:123456789012:key/11111111-2222-3333-4444-555555555555") .build(); } private SdkHttpRequest modifyHttpRequest(ExecutionInterceptor interceptor, DocDbRequest request, SdkHttpFullRequest httpRequest) { InterceptorContext context = InterceptorContext.builder().request(request).httpRequest(httpRequest).build(); return interceptor.modifyHttpRequest(context, executionAttributes()); } }
4,813
0
Create_ds/aws-sdk-java-v2/services/docdb/src/main/java/software/amazon/awssdk/services/docdb
Create_ds/aws-sdk-java-v2/services/docdb/src/main/java/software/amazon/awssdk/services/docdb/internal/CopyDbClusterSnapshotPresignInterceptor.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.services.docdb.internal; import java.time.Clock; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.services.docdb.model.CopyDbClusterSnapshotRequest; import software.amazon.awssdk.services.docdb.transform.CopyDbClusterSnapshotRequestMarshaller; /** * Handler for pre-signing {@link CopyDbClusterSnapshotRequest}. */ @SdkInternalApi public final class CopyDbClusterSnapshotPresignInterceptor extends RdsPresignInterceptor<CopyDbClusterSnapshotRequest> { public static final CopyDbClusterSnapshotRequestMarshaller MARSHALLER = new CopyDbClusterSnapshotRequestMarshaller(PROTOCOL_FACTORY); public CopyDbClusterSnapshotPresignInterceptor() { super(CopyDbClusterSnapshotRequest.class); } @SdkTestInternalApi CopyDbClusterSnapshotPresignInterceptor(Clock signingDateOverride) { super(CopyDbClusterSnapshotRequest.class, signingDateOverride); } @Override protected PresignableRequest adaptRequest(final CopyDbClusterSnapshotRequest originalRequest) { return new PresignableRequest() { @Override public String getSourceRegion() { return originalRequest.sourceRegion(); } @Override public SdkHttpFullRequest marshall() { return MARSHALLER.marshall(originalRequest); } }; } }
4,814
0
Create_ds/aws-sdk-java-v2/services/docdb/src/main/java/software/amazon/awssdk/services/docdb
Create_ds/aws-sdk-java-v2/services/docdb/src/main/java/software/amazon/awssdk/services/docdb/internal/CreateDbClusterPresignInterceptor.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.services.docdb.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.services.docdb.model.CreateDbClusterRequest; import software.amazon.awssdk.services.docdb.transform.CreateDbClusterRequestMarshaller; /** * Handler for pre-signing {@link CreateDbClusterRequest}. */ @SdkInternalApi public final class CreateDbClusterPresignInterceptor extends RdsPresignInterceptor<CreateDbClusterRequest> { public static final CreateDbClusterRequestMarshaller MARSHALLER = new CreateDbClusterRequestMarshaller(PROTOCOL_FACTORY); public CreateDbClusterPresignInterceptor() { super(CreateDbClusterRequest.class); } @Override protected PresignableRequest adaptRequest(final CreateDbClusterRequest originalRequest) { return new PresignableRequest() { @Override public String getSourceRegion() { return originalRequest.sourceRegion(); } @Override public SdkHttpFullRequest marshall() { return MARSHALLER.marshall(originalRequest); } }; } }
4,815
0
Create_ds/aws-sdk-java-v2/services/docdb/src/main/java/software/amazon/awssdk/services/docdb
Create_ds/aws-sdk-java-v2/services/docdb/src/main/java/software/amazon/awssdk/services/docdb/internal/RdsPresignInterceptor.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.services.docdb.internal; import static software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute.AWS_CREDENTIALS; import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME; import java.net.URI; import java.time.Clock; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.CredentialUtils; import software.amazon.awssdk.auth.signer.Aws4Signer; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams; import software.amazon.awssdk.awscore.AwsExecutionAttribute; import software.amazon.awssdk.awscore.endpoint.DefaultServiceEndpointBuilder; import software.amazon.awssdk.core.Protocol; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.protocols.query.AwsQueryProtocolFactory; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.docdb.model.DocDbRequest; import software.amazon.awssdk.utils.CompletableFutureUtils; /** * Abstract pre-sign handler that follows the pre-signing scheme outlined in the 'RDS Presigned URL for Cross-Region Copying' * SEP. * * @param <T> The request type. */ @SdkInternalApi public abstract class RdsPresignInterceptor<T extends DocDbRequest> implements ExecutionInterceptor { private static final URI CUSTOM_ENDPOINT_LOCALHOST = URI.create("http://localhost"); protected static final AwsQueryProtocolFactory PROTOCOL_FACTORY = AwsQueryProtocolFactory .builder() // Need an endpoint to marshall but this will be overwritten in modifyHttpRequest .clientConfiguration(SdkClientConfiguration.builder() .option(SdkClientOption.ENDPOINT, CUSTOM_ENDPOINT_LOCALHOST) .build()) .build(); private static final String SERVICE_NAME = "rds"; private static final String PARAM_SOURCE_REGION = "SourceRegion"; private static final String PARAM_DESTINATION_REGION = "DestinationRegion"; private static final String PARAM_PRESIGNED_URL = "PreSignedUrl"; public interface PresignableRequest { String getSourceRegion(); SdkHttpFullRequest marshall(); } private final Class<T> requestClassToPreSign; private final Clock signingOverrideClock; protected RdsPresignInterceptor(Class<T> requestClassToPreSign) { this(requestClassToPreSign, null); } protected RdsPresignInterceptor(Class<T> requestClassToPreSign, Clock signingOverrideClock) { this.requestClassToPreSign = requestClassToPreSign; this.signingOverrideClock = signingOverrideClock; } @Override public final SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest request = context.httpRequest(); SdkRequest originalRequest = context.request(); if (!requestClassToPreSign.isInstance(originalRequest)) { return request; } if (request.firstMatchingRawQueryParameter(PARAM_PRESIGNED_URL).isPresent()) { return request; } PresignableRequest presignableRequest = adaptRequest(requestClassToPreSign.cast(originalRequest)); String sourceRegion = presignableRequest.getSourceRegion(); if (sourceRegion == null) { return request; } String destinationRegion = executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION).id(); URI endpoint = createEndpoint(sourceRegion, SERVICE_NAME, executionAttributes); SdkHttpFullRequest.Builder marshalledRequest = presignableRequest.marshall().toBuilder().uri(endpoint); SdkHttpFullRequest requestToPresign = marshalledRequest.method(SdkHttpMethod.GET) .putRawQueryParameter(PARAM_DESTINATION_REGION, destinationRegion) .removeQueryParameter(PARAM_SOURCE_REGION) .build(); requestToPresign = presignRequest(requestToPresign, executionAttributes, sourceRegion); String presignedUrl = requestToPresign.getUri().toString(); return request.toBuilder() .putRawQueryParameter(PARAM_PRESIGNED_URL, presignedUrl) // Remove the unmodeled params to stop them getting onto the wire .removeQueryParameter(PARAM_SOURCE_REGION) .build(); } /** * Adapts the request to the {@link PresignableRequest}. * * @param originalRequest the original request * @return a PresignableRequest */ protected abstract PresignableRequest adaptRequest(T originalRequest); private SdkHttpFullRequest presignRequest(SdkHttpFullRequest request, ExecutionAttributes attributes, String signingRegion) { Aws4Signer signer = Aws4Signer.create(); Aws4PresignerParams presignerParams = Aws4PresignerParams.builder() .signingRegion(Region.of(signingRegion)) .signingName(SERVICE_NAME) .signingClockOverride(signingOverrideClock) .awsCredentials(resolveCredentials(attributes)) .build(); return signer.presign(request, presignerParams); } private AwsCredentials resolveCredentials(ExecutionAttributes attributes) { return attributes.getOptionalAttribute(SELECTED_AUTH_SCHEME) .map(selectedAuthScheme -> selectedAuthScheme.identity()) .map(identityFuture -> CompletableFutureUtils.joinLikeSync(identityFuture)) .filter(identity -> identity instanceof AwsCredentialsIdentity) .map(identity -> { AwsCredentialsIdentity awsCredentialsIdentity = (AwsCredentialsIdentity) identity; return CredentialUtils.toCredentials(awsCredentialsIdentity); }).orElse(attributes.getAttribute(AWS_CREDENTIALS)); } private URI createEndpoint(String regionName, String serviceName, ExecutionAttributes attributes) { Region region = Region.of(regionName); if (region == null) { throw SdkClientException.builder() .message("{" + serviceName + ", " + regionName + "} was not " + "found in region metadata. Update to latest version of SDK and try again.") .build(); } return new DefaultServiceEndpointBuilder(SERVICE_NAME, Protocol.HTTPS.toString()) .withRegion(region) .withProfileFile(attributes.getAttribute(SdkExecutionAttribute.PROFILE_FILE_SUPPLIER)) .withProfileName(attributes.getAttribute(SdkExecutionAttribute.PROFILE_NAME)) .withDualstackEnabled(attributes.getAttribute(AwsExecutionAttribute.DUALSTACK_ENDPOINT_ENABLED)) .withFipsEnabled(attributes.getAttribute(AwsExecutionAttribute.FIPS_ENDPOINT_ENABLED)) .getServiceEndpoint(); } }
4,816
0
Create_ds/aws-sdk-java-v2/services/ses/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ses/src/it/java/software/amazon/awssdk/services/ses/IntegrationTestBase.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.services.ses; import static org.junit.Assert.fail; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.junit.BeforeClass; import software.amazon.awssdk.services.ses.model.ListVerifiedEmailAddressesRequest; import software.amazon.awssdk.services.ses.model.ListVerifiedEmailAddressesResponse; import software.amazon.awssdk.services.ses.model.VerifyEmailAddressRequest; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Base class for AWS Email integration tests; responsible for loading AWS account credentials for * running the tests, instantiating clients, etc. */ public abstract class IntegrationTestBase extends AwsTestBase { public static final String HUDSON_EMAIL_LIST = "no-reply@amazon.com"; protected static final String RAW_MESSAGE_FILE_PATH = "/software/amazon/awssdk/services/email/rawMimeMessage.txt"; public static String DESTINATION; public static String SOURCE; protected static SesClient email; /** * Loads the AWS account info for the integration tests and creates client objects for tests to * use. */ @BeforeClass public static void setUp() throws FileNotFoundException, IOException { setUpCredentials(); if (DESTINATION == null) { DESTINATION = System.getProperty("user.name").equals("webuser") ? HUDSON_EMAIL_LIST : System.getProperty("user.name") + "@amazon.com"; SOURCE = DESTINATION; } email = SesClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } protected static void sendVerificationEmail() { ListVerifiedEmailAddressesResponse verifiedEmails = email.listVerifiedEmailAddresses(ListVerifiedEmailAddressesRequest.builder().build()); for (String email : verifiedEmails.verifiedEmailAddresses()) { if (email.equals(DESTINATION)) { return; } } email.verifyEmailAddress(VerifyEmailAddressRequest.builder().emailAddress(DESTINATION).build()); fail("Please check your email and verify your email address."); } protected String loadRawMessage(String messagePath) throws Exception { String rawMessage = IOUtils.toString(getClass().getResourceAsStream(messagePath)); rawMessage = rawMessage.replace("@DESTINATION@", DESTINATION); rawMessage = rawMessage.replace("@SOURCE@", SOURCE); return rawMessage; } protected InputStream loadRawMessageAsStream(String messagePath) throws Exception { return IOUtils.toInputStream(loadRawMessage(messagePath)); } }
4,817
0
Create_ds/aws-sdk-java-v2/services/ses/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ses/src/it/java/software/amazon/awssdk/services/ses/EmailIntegrationTest.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.services.ses; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import java.util.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.services.ses.model.Body; import software.amazon.awssdk.services.ses.model.Content; import software.amazon.awssdk.services.ses.model.DeleteIdentityRequest; import software.amazon.awssdk.services.ses.model.Destination; import software.amazon.awssdk.services.ses.model.GetIdentityVerificationAttributesRequest; import software.amazon.awssdk.services.ses.model.GetIdentityVerificationAttributesResponse; import software.amazon.awssdk.services.ses.model.GetSendQuotaRequest; import software.amazon.awssdk.services.ses.model.GetSendQuotaResponse; import software.amazon.awssdk.services.ses.model.IdentityType; import software.amazon.awssdk.services.ses.model.IdentityVerificationAttributes; import software.amazon.awssdk.services.ses.model.ListIdentitiesRequest; import software.amazon.awssdk.services.ses.model.Message; import software.amazon.awssdk.services.ses.model.MessageRejectedException; import software.amazon.awssdk.services.ses.model.SendEmailRequest; import software.amazon.awssdk.services.ses.model.VerificationStatus; import software.amazon.awssdk.services.ses.model.VerifyDomainIdentityRequest; import software.amazon.awssdk.services.ses.model.VerifyEmailIdentityRequest; public class EmailIntegrationTest extends IntegrationTestBase { private static final String DOMAIN = "invalid-test-domain"; private static final String EMAIL = "no-reply@amazon.com"; private static String DOMAIN_VERIFICATION_TOKEN; @BeforeClass public static void setup() { email.verifyEmailIdentity(VerifyEmailIdentityRequest.builder().emailAddress(EMAIL).build()); DOMAIN_VERIFICATION_TOKEN = email.verifyDomainIdentity(VerifyDomainIdentityRequest.builder().domain(DOMAIN).build()) .verificationToken(); } @AfterClass public static void tearDown() { email.deleteIdentity(DeleteIdentityRequest.builder().identity(EMAIL).build()); email.deleteIdentity(DeleteIdentityRequest.builder().identity(DOMAIN).build()); } @Test public void getSendQuota_ReturnsNonZeroQuotas() { GetSendQuotaResponse result = email.getSendQuota(GetSendQuotaRequest.builder().build()); assertThat(result.max24HourSend(), greaterThan(0.0)); assertThat(result.maxSendRate(), greaterThan(0.0)); } @Test public void listIdentities_WithNonVerifiedIdentity_ReturnsIdentityInList() { // Don't need to actually verify for it to show up in listIdentities List<String> identities = email.listIdentities(ListIdentitiesRequest.builder().build()).identities(); assertThat(identities, hasItem(EMAIL)); assertThat(identities, hasItem(DOMAIN)); } @Test public void listIdentities_FilteredForDomainIdentities_OnlyHasDomainIdentityInList() { List<String> identities = email.listIdentities( ListIdentitiesRequest.builder().identityType(IdentityType.DOMAIN).build()).identities(); assertThat(identities, not(hasItem(EMAIL))); assertThat(identities, hasItem(DOMAIN)); } @Test public void listIdentities_FilteredForEmailIdentities_OnlyHasEmailIdentityInList() { List<String> identities = email.listIdentities( ListIdentitiesRequest.builder().identityType(IdentityType.EMAIL_ADDRESS).build()).identities(); assertThat(identities, hasItem(EMAIL)); assertThat(identities, not(hasItem(DOMAIN))); } @Test public void listIdentitites_MaxResultsSetToOne_HasNonNullNextToken() { assertNotNull(email.listIdentities(ListIdentitiesRequest.builder().maxItems(1).build()).nextToken()); } @Test(expected = SdkServiceException.class) public void listIdentities_WithInvalidNextToken_ThrowsException() { email.listIdentities(ListIdentitiesRequest.builder().nextToken("invalid-next-token").build()); } @Test(expected = MessageRejectedException.class) public void sendEmail_ToUnverifiedIdentity_ThrowsException() { email.sendEmail(SendEmailRequest.builder().destination(Destination.builder().toAddresses(EMAIL).build()) .message(newMessage("test")).source(EMAIL).build()); } @Test public void getIdentityVerificationAttributes_ForNonVerifiedEmail_ReturnsPendingVerificatonStatus() { GetIdentityVerificationAttributesResponse result = email .getIdentityVerificationAttributes(GetIdentityVerificationAttributesRequest.builder().identities(EMAIL).build()); IdentityVerificationAttributes identityVerificationAttributes = result.verificationAttributes().get(EMAIL); assertEquals(VerificationStatus.PENDING, identityVerificationAttributes.verificationStatus()); // Verificaton token not applicable for email identities assertNull(identityVerificationAttributes.verificationToken()); } @Test public void getIdentityVerificationAttributes_ForNonVerifiedDomain_ReturnsPendingVerificatonStatus() { GetIdentityVerificationAttributesResponse result = email .getIdentityVerificationAttributes(GetIdentityVerificationAttributesRequest.builder() .identities(DOMAIN).build()); IdentityVerificationAttributes identityVerificationAttributes = result.verificationAttributes().get(DOMAIN); assertEquals(VerificationStatus.PENDING, identityVerificationAttributes.verificationStatus()); assertEquals(DOMAIN_VERIFICATION_TOKEN, identityVerificationAttributes.verificationToken()); } private Message newMessage(String subject) { Content content = Content.builder().data(subject).build(); Message message = Message.builder().subject(content).body(Body.builder().text(content).build()).build(); return message; } }
4,818
0
Create_ds/aws-sdk-java-v2/services/autoscaling/src/test/java/software/amazon/awssdk/services/autoscaling
Create_ds/aws-sdk-java-v2/services/autoscaling/src/test/java/software/amazon/awssdk/services/autoscaling/waiters/AutoScalingWaiterTest.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.services.autoscaling.waiters; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static software.amazon.awssdk.services.autoscaling.model.LifecycleState.IN_SERVICE; import static software.amazon.awssdk.services.autoscaling.model.LifecycleState.PENDING; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.core.retry.backoff.BackoffStrategy; import software.amazon.awssdk.core.waiters.WaiterOverrideConfiguration; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.services.autoscaling.AutoScalingClient; import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsRequest; import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsResponse; public class AutoScalingWaiterTest { private AutoScalingClient client; @Before public void setup() { client = mock(AutoScalingClient.class); } @Test(timeout = 30_000) @SuppressWarnings("unchecked") public void waitUntilGroupInServiceWorks() { DescribeAutoScalingGroupsRequest request = DescribeAutoScalingGroupsRequest.builder().build(); DescribeAutoScalingGroupsResponse response1 = DescribeAutoScalingGroupsResponse.builder() .autoScalingGroups(asg -> asg.minSize(2) .instances(i -> i.lifecycleState(PENDING), i -> i.lifecycleState(IN_SERVICE), i -> i.lifecycleState(IN_SERVICE)), asg -> asg.minSize(2) .instances(i -> i.lifecycleState(PENDING), i -> i.lifecycleState(PENDING), i -> i.lifecycleState(IN_SERVICE))) .build(); DescribeAutoScalingGroupsResponse response2 = DescribeAutoScalingGroupsResponse.builder() .autoScalingGroups(asg -> asg.minSize(2) .instances(i -> i.lifecycleState(PENDING), i -> i.lifecycleState(IN_SERVICE), i -> i.lifecycleState(IN_SERVICE)), asg -> asg.minSize(2) .instances(i -> i.lifecycleState(IN_SERVICE), i -> i.lifecycleState(IN_SERVICE), i -> i.lifecycleState(IN_SERVICE))) .build(); when(client.describeAutoScalingGroups(any(DescribeAutoScalingGroupsRequest.class))).thenReturn(response1, response2); AutoScalingWaiter waiter = AutoScalingWaiter.builder() .overrideConfiguration(WaiterOverrideConfiguration.builder() .maxAttempts(3) .backoffStrategy(BackoffStrategy.none()) .build()) .client(client) .build(); WaiterResponse<DescribeAutoScalingGroupsResponse> response = waiter.waitUntilGroupInService(request); assertThat(response.attemptsExecuted()).isEqualTo(2); assertThat(response.matched().response()).hasValueSatisfying(r -> assertThat(r).isEqualTo(response2)); } }
4,819
0
Create_ds/aws-sdk-java-v2/services/autoscaling/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/autoscaling/src/it/java/software/amazon/awssdk/services/autoscaling/IntegrationTestBase.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.services.autoscaling; import java.io.IOException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Base class for AutoScaling integration tests. Provides several convenience methods for creating * test data, test data values, and automatically loads the AWS credentials from a properties file * on disk and instantiates clients for the test subclasses to use. */ public abstract class IntegrationTestBase extends AwsTestBase { private static final Region REGION = Region.US_EAST_1; /** Shared Autoscaling client for all tests to use. */ protected static AutoScalingClient autoscaling; /** Shared Autoscaling async client for tests to use. */ protected static AutoScalingAsyncClient autoscalingAsync; /** Shared SNS client for tests to use. */ /** * Loads the AWS account info for the integration tests and creates an AutoScaling client for * tests to use. */ public static void setUp() throws IOException { setUpCredentials(); autoscaling = AutoScalingClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(REGION) .build(); autoscalingAsync = AutoScalingAsyncClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(REGION) .build(); } }
4,820
0
Create_ds/aws-sdk-java-v2/services/autoscaling/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/autoscaling/src/it/java/software/amazon/awssdk/services/autoscaling/AutoScalingIntegrationTest.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.services.autoscaling; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkGlobalTime; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.autoscaling.model.DescribePoliciesRequest; /** * Smoke tests for Autoscaling service. This class tests query protocol path. * Do not remove until we have generated smoke tests for this service. */ public class AutoScalingIntegrationTest extends IntegrationTestBase { @BeforeAll public static void beforeAll() throws IOException { setUp(); } @Test public void describeAutoScalingGroups() { autoscaling.describeAutoScalingGroups(); autoscalingAsync.describeAutoScalingGroups().join(); } @Test public void describeTerminationPolicyTypes() { autoscaling.describeTerminationPolicyTypes(); autoscalingAsync.describeAutoScalingGroups().join(); } @Test public void testClockSkewAs() { SdkGlobalTime.setGlobalTimeOffset(3600); AutoScalingClient clockSkewClient = AutoScalingClient.builder() .region(Region.US_EAST_1) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); clockSkewClient.describePolicies(DescribePoliciesRequest.builder().build()); assertTrue(SdkGlobalTime.getGlobalTimeOffset() < 60); } }
4,821
0
Create_ds/aws-sdk-java-v2/services/cloudformation/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudformation/src/it/java/software/amazon/awssdk/services/cloudformation/CloudFormationIntegrationTestBase.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.services.cloudformation; import org.junit.BeforeClass; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Base class for CloudFormation integration tests. Loads AWS credentials from a properties file and * creates a client for callers to use. */ public class CloudFormationIntegrationTestBase extends AwsTestBase { protected static CloudFormationClient cf; /** * Loads the AWS account info for the integration tests and creates an S3 client for tests to * use. */ @BeforeClass public static void setUp() throws Exception { cf = CloudFormationClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(Region.AP_NORTHEAST_1) .build(); } }
4,822
0
Create_ds/aws-sdk-java-v2/services/cloudformation/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudformation/src/it/java/software/amazon/awssdk/services/cloudformation/ClockSkewIntegrationTest.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.services.cloudformation; import static org.junit.Assert.assertTrue; import org.junit.Test; import software.amazon.awssdk.core.SdkGlobalTime; import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest; public class ClockSkewIntegrationTest extends CloudFormationIntegrationTestBase { /** * In the following test, we purposely setting the time offset to trigger a clock skew error. * The time offset must be fixed and then we validate the global value for time offset has been * update. */ @Test public void testClockSkew() { SdkGlobalTime.setGlobalTimeOffset(3600); // Need to create a new client to have the time offset take affect CloudFormationClient clockSkewClient = CloudFormationClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); clockSkewClient.describeStacks(DescribeStacksRequest.builder().build()); assertTrue(SdkGlobalTime.getGlobalTimeOffset() < 60); } }
4,823
0
Create_ds/aws-sdk-java-v2/services/cloudformation/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudformation/src/it/java/software/amazon/awssdk/services/cloudformation/SendEmptyListIntegrationTest.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.services.cloudformation; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudformation.model.CreateStackRequest; import software.amazon.awssdk.services.cloudformation.model.DeleteStackRequest; import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest; import software.amazon.awssdk.services.cloudformation.model.Tag; import software.amazon.awssdk.services.cloudformation.model.UpdateStackRequest; import software.amazon.awssdk.services.cloudformation.waiters.CloudFormationWaiter; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; /** * See https://github.com/aws/aws-sdk-java/issues/721. Cloudformation treats empty lists as removing * that list of values. */ public class SendEmptyListIntegrationTest extends AwsIntegrationTestBase { private static final String STARTING_TEMPLATE = "{" + " \"AWSTemplateFormatVersion\" : \"2010-09-09\"," + " \"Resources\" : {" + " \"JavaSdkCfSendEmptyListTest\" : {" + " \"Type\" : \"AWS::S3::Bucket\"" + " }" + " }" + "}"; private static final String UPDATED_TEMPLATE = "{" + " \"AWSTemplateFormatVersion\" : \"2010-09-09\"," + " \"Resources\" : {" + " \"JavaSdkCfSendEmptyListTestUpdated\" : {" + " \"Type\" : \"AWS::S3::Bucket\"" + " }" + " }" + "}"; private CloudFormationClient cf; private CloudFormationWaiter waiter; private String stackName; @Before public void setup() { stackName = getClass().getSimpleName() + "-" + System.currentTimeMillis(); cf = CloudFormationClient.builder() .credentialsProvider(StaticCredentialsProvider.create(getCredentials())) .region(Region.US_WEST_2) .build(); cf.createStack(CreateStackRequest.builder() .stackName(stackName) .templateBody(STARTING_TEMPLATE) .tags(Tag.builder().key("FooKey").value("FooValue").build()).build()); waiter = cf.waiter(); waiter.waitUntilStackCreateComplete(b -> b.stackName(stackName)); } @After public void tearDown() { cf.deleteStack(DeleteStackRequest.builder().stackName(stackName).build()); } @Test public void explicitlyEmptyTagList_RemovesTagsFromStack() { assertThat(getTagsForStack(stackName), not(empty())); cf.updateStack(UpdateStackRequest.builder() .stackName(stackName) .templateBody(STARTING_TEMPLATE) .tags(Collections.emptyList()).build()); waiter.waitUntilStackUpdateComplete(b -> b.stackName(stackName)); assertThat(getTagsForStack(stackName), empty()); } @Test public void autoConstructedEmptyTagList_DoesNotRemoveTagsFromStack() { assertThat(getTagsForStack(stackName), not(empty())); cf.updateStack(UpdateStackRequest.builder() .stackName(stackName) .templateBody(UPDATED_TEMPLATE).build()); waiter.waitUntilStackUpdateComplete(b -> b.stackName(stackName)); assertThat(getTagsForStack(stackName), not(empty())); } private List<Tag> getTagsForStack(String stackName) { return cf.describeStacks( DescribeStacksRequest.builder().stackName(stackName).build()) .stacks().get(0) .tags(); } }
4,824
0
Create_ds/aws-sdk-java-v2/services/elasticache/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/elasticache/src/it/java/software/amazon/awssdk/services/elasticache/ElastiCacheIntegrationTestBase.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.services.elasticache; import org.junit.BeforeClass; import software.amazon.awssdk.testutils.service.AwsTestBase; public class ElastiCacheIntegrationTestBase extends AwsTestBase { protected static final String MEMCACHED_ENGINE = "memcached"; protected static final String REDIS_ENGINE = "redis"; protected static ElastiCacheClient elasticache; @BeforeClass public static void setUp() throws Exception { setUpCredentials(); elasticache = ElastiCacheClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } }
4,825
0
Create_ds/aws-sdk-java-v2/services/elasticache/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/elasticache/src/it/java/software/amazon/awssdk/services/elasticache/ParameterGroupsIntegrationTest.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.services.elasticache; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static software.amazon.awssdk.testutils.SdkAsserts.assertNotEmpty; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Test; import software.amazon.awssdk.services.elasticache.model.CacheNodeTypeSpecificParameter; import software.amazon.awssdk.services.elasticache.model.CacheParameterGroup; import software.amazon.awssdk.services.elasticache.model.CreateCacheParameterGroupRequest; import software.amazon.awssdk.services.elasticache.model.DeleteCacheParameterGroupRequest; import software.amazon.awssdk.services.elasticache.model.DescribeCacheParameterGroupsRequest; import software.amazon.awssdk.services.elasticache.model.DescribeCacheParameterGroupsResponse; import software.amazon.awssdk.services.elasticache.model.DescribeCacheParametersRequest; import software.amazon.awssdk.services.elasticache.model.DescribeCacheParametersResponse; import software.amazon.awssdk.services.elasticache.model.DescribeEngineDefaultParametersRequest; import software.amazon.awssdk.services.elasticache.model.EngineDefaults; import software.amazon.awssdk.services.elasticache.model.ModifyCacheParameterGroupRequest; import software.amazon.awssdk.services.elasticache.model.ModifyCacheParameterGroupResponse; import software.amazon.awssdk.services.elasticache.model.Parameter; import software.amazon.awssdk.services.elasticache.model.ParameterNameValue; import software.amazon.awssdk.services.elasticache.model.ResetCacheParameterGroupRequest; import software.amazon.awssdk.services.elasticache.model.ResetCacheParameterGroupResponse; public class ParameterGroupsIntegrationTest extends ElastiCacheIntegrationTestBase { private static final String DESCRIPTION = "Java SDK integ test param group"; private static final String CACHE_PARAMETER_GROUP_FAMILY = "memcached1.4"; private String cacheParameterGroupName; /** Releases all resources created by tests. */ @After public void tearDown() throws Exception { if (cacheParameterGroupName != null) { try { elasticache.deleteCacheParameterGroup( DeleteCacheParameterGroupRequest.builder().cacheParameterGroupName(cacheParameterGroupName).build()); } catch (Exception e) { // Ignored or expected. } } } /** Tests that we can call the parameter group operations in the ElastiCache API. */ @Test public void testParameterGroupOperations() throws Exception { // Describe Engine Default Parameters EngineDefaults engineDefaults = elasticache .describeEngineDefaultParameters( DescribeEngineDefaultParametersRequest.builder().cacheParameterGroupFamily(CACHE_PARAMETER_GROUP_FAMILY) .build()).engineDefaults(); assertTrue(engineDefaults.cacheNodeTypeSpecificParameters().size() > 0); CacheNodeTypeSpecificParameter cacheNodeParameter = engineDefaults.cacheNodeTypeSpecificParameters().get(0); assertNotEmpty(cacheNodeParameter.parameterName()); assertTrue(cacheNodeParameter.cacheNodeTypeSpecificValues().size() > 0); assertEquals(CACHE_PARAMETER_GROUP_FAMILY, engineDefaults.cacheParameterGroupFamily()); assertTrue(engineDefaults.parameters().size() > 0); Parameter parameter = engineDefaults.parameters().get(0); assertNotEmpty(parameter.parameterName()); assertNotEmpty(parameter.parameterValue()); // Create Cache Parameter Group cacheParameterGroupName = "java-sdk-integ-test-" + System.currentTimeMillis(); CacheParameterGroup cacheParameterGroup = elasticache.createCacheParameterGroup( CreateCacheParameterGroupRequest.builder().cacheParameterGroupName(cacheParameterGroupName) .cacheParameterGroupFamily(CACHE_PARAMETER_GROUP_FAMILY).description(DESCRIPTION) .build()).cacheParameterGroup(); assertEquals(CACHE_PARAMETER_GROUP_FAMILY, cacheParameterGroup.cacheParameterGroupFamily()); assertEquals(cacheParameterGroupName, cacheParameterGroup.cacheParameterGroupName()); assertEquals(DESCRIPTION, cacheParameterGroup.description()); // Describe Cache Parameters DescribeCacheParametersResponse describeCacheParameters = elasticache.describeCacheParameters( DescribeCacheParametersRequest.builder().cacheParameterGroupName(cacheParameterGroupName).build()); assertTrue(describeCacheParameters.cacheNodeTypeSpecificParameters().size() > 0); cacheNodeParameter = describeCacheParameters.cacheNodeTypeSpecificParameters().get(0); assertNotEmpty(cacheNodeParameter.parameterName()); assertTrue(cacheNodeParameter.cacheNodeTypeSpecificValues().size() > 0); assertTrue(describeCacheParameters.parameters().size() > 0); parameter = describeCacheParameters.parameters().get(0); assertNotEmpty(parameter.parameterName()); assertNotEmpty(parameter.parameterValue()); // Modify Cache Parameter Group List<ParameterNameValue> paramsToModify = new ArrayList<ParameterNameValue>(); paramsToModify.add(ParameterNameValue.builder().parameterName("max_item_size").parameterValue("100000").build()); ModifyCacheParameterGroupResponse modifyCacheParameterGroup = elasticache .modifyCacheParameterGroup( ModifyCacheParameterGroupRequest.builder().cacheParameterGroupName(cacheParameterGroupName) .parameterNameValues(paramsToModify).build()); assertEquals(cacheParameterGroupName, modifyCacheParameterGroup.cacheParameterGroupName()); // Reset Cache Parameter Group List<ParameterNameValue> paramsToReset = new ArrayList<ParameterNameValue>(); paramsToReset.add(ParameterNameValue.builder().parameterName("binding_protocol").build()); ResetCacheParameterGroupResponse resetCacheParameterGroup = elasticache.resetCacheParameterGroup( ResetCacheParameterGroupRequest.builder().cacheParameterGroupName(cacheParameterGroupName) .parameterNameValues(paramsToReset).build()); assertEquals(cacheParameterGroupName, resetCacheParameterGroup.cacheParameterGroupName()); // Describe Cache Parameter Groups DescribeCacheParameterGroupsResponse describeCacheParameterGroups = elasticache.describeCacheParameterGroups( DescribeCacheParameterGroupsRequest.builder().cacheParameterGroupName(cacheParameterGroupName).build()); assertEquals(1, describeCacheParameterGroups.cacheParameterGroups().size()); CacheParameterGroup parameterGroup = describeCacheParameterGroups.cacheParameterGroups().get(0); assertEquals(CACHE_PARAMETER_GROUP_FAMILY, parameterGroup.cacheParameterGroupFamily()); assertEquals(cacheParameterGroupName, parameterGroup.cacheParameterGroupName()); assertEquals(DESCRIPTION, parameterGroup.description()); // Delete Cache Parameter Group elasticache.deleteCacheParameterGroup( DeleteCacheParameterGroupRequest.builder().cacheParameterGroupName(cacheParameterGroupName).build()); } }
4,826
0
Create_ds/aws-sdk-java-v2/services/sfn/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sfn/src/it/java/software/amazon/awssdk/services/sfn/SfnIntegrationTest.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.services.sfn; import static org.junit.Assert.assertNotNull; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class SfnIntegrationTest extends AwsIntegrationTestBase { private static SfnClient sfnClient; private static String activityArn; @BeforeClass public static void setUpClient() { sfnClient = SfnClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); activityArn = sfnClient.createActivity(b -> b.name("test")).activityArn(); } @AfterClass public static void cleanUp() { if (activityArn != null) { sfnClient.deleteActivity(b -> b.activityArn(activityArn)); } } @Test public void getActivityTask_shouldWorkByDefault(){ assertNotNull(sfnClient.getActivityTask(b -> b.activityArn(activityArn))); } }
4,827
0
Create_ds/aws-sdk-java-v2/services/sfn/src/main/java/software/amazon/awssdk/services/sfn
Create_ds/aws-sdk-java-v2/services/sfn/src/main/java/software/amazon/awssdk/services/sfn/internal/SfnHttpConfigurationOptions.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.services.sfn.internal; import java.time.Duration; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.utils.AttributeMap; /** * Sfn specific http configurations. */ @SdkInternalApi public final class SfnHttpConfigurationOptions { private static final AttributeMap OPTIONS = AttributeMap .builder() // Sfn has long polling APIs such as getActivityTask that could take up to // 60 seconds to respond .put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofSeconds(65)) .build(); private SfnHttpConfigurationOptions() { } public static AttributeMap defaultHttpConfig() { return OPTIONS; } }
4,828
0
Create_ds/aws-sdk-java-v2/services/devicefarm/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/devicefarm/src/it/java/software/amazon/awssdk/services/devicefarm/DeviceFarmIntegrationTest.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.services.devicefarm; import static org.junit.Assert.assertNotNull; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.devicefarm.model.CreateProjectRequest; import software.amazon.awssdk.services.devicefarm.model.CreateProjectResponse; import software.amazon.awssdk.services.devicefarm.model.DeleteProjectRequest; import software.amazon.awssdk.services.devicefarm.model.ListDevicePoolsRequest; import software.amazon.awssdk.services.devicefarm.model.Project; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Smoke tests for device farm service. */ public class DeviceFarmIntegrationTest extends AwsTestBase { private static final String PROJECT_NAME = "df-java-project-" + System.currentTimeMillis(); private static DeviceFarmClient client; private static String projectArn; @BeforeClass public static void setup() throws Exception { setUpCredentials(); client = DeviceFarmClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(Region.US_WEST_2) .build(); } @AfterClass public static void teardown() { client.deleteProject(DeleteProjectRequest.builder().arn(projectArn).build()); } @Test public void testCreateProject() { CreateProjectResponse result = client .createProject(CreateProjectRequest.builder() .name(PROJECT_NAME) .build()); final Project project = result.project(); assertNotNull(project); projectArn = project.arn(); assertNotNull(projectArn); } @Test(expected = SdkServiceException.class) public void testExceptionHandling() { client.listDevicePools(ListDevicePoolsRequest.builder().nextToken("fake-token").build()); } }
4,829
0
Create_ds/aws-sdk-java-v2/services/polly/src/test/java/software/amazon/awssdk/services/polly/internal
Create_ds/aws-sdk-java-v2/services/polly/src/test/java/software/amazon/awssdk/services/polly/internal/presigner/DefaultPollyPresignerTest.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.services.polly.internal.presigner; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.io.Closeable; import java.io.IOException; import java.net.URI; import java.net.URL; import java.time.Duration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.polly.model.OutputFormat; import software.amazon.awssdk.services.polly.model.SynthesizeSpeechRequest; import software.amazon.awssdk.services.polly.presigner.PollyPresigner; import software.amazon.awssdk.services.polly.presigner.model.PresignedSynthesizeSpeechRequest; import software.amazon.awssdk.services.polly.presigner.model.SynthesizeSpeechPresignRequest; /** * Tests for {@link DefaultPollyPresigner}. */ class DefaultPollyPresignerTest { private static final SynthesizeSpeechRequest BASIC_SYNTHESIZE_SPEECH_REQUEST = SynthesizeSpeechRequest.builder() .voiceId("Salli") .outputFormat(OutputFormat.PCM) .text("Hello presigners!") .build(); private IdentityProvider<AwsCredentialsIdentity> credentialsProvider; @BeforeEach public void methodSetup() { credentialsProvider = StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")); } @Test void presign_requestLevelCredentials_honored() { IdentityProvider<AwsCredentialsIdentity> requestCedentialsProvider = StaticCredentialsProvider.create( AwsBasicCredentials.create("akid2", "skid2") ); PollyPresigner presigner = DefaultPollyPresigner.builder() .region(Region.US_EAST_1) .credentialsProvider(credentialsProvider) .build(); SynthesizeSpeechRequest synthesizeSpeechRequest = BASIC_SYNTHESIZE_SPEECH_REQUEST.toBuilder() .overrideConfiguration(AwsRequestOverrideConfiguration.builder() .credentialsProvider(requestCedentialsProvider).build()) .build(); SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder() .synthesizeSpeechRequest(synthesizeSpeechRequest) .signatureDuration(Duration.ofHours(3)) .build(); PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest = presigner.presignSynthesizeSpeech(presignRequest); assertThat(presignedSynthesizeSpeechRequest.url().getQuery()).contains("X-Amz-Credential=akid2"); } @Test void presign_requestLevelHeaders_included() { PollyPresigner presigner = DefaultPollyPresigner.builder() .region(Region.US_EAST_1) .credentialsProvider(credentialsProvider) .build(); SynthesizeSpeechRequest synthesizeSpeechRequest = BASIC_SYNTHESIZE_SPEECH_REQUEST.toBuilder() .overrideConfiguration(AwsRequestOverrideConfiguration.builder() .putHeader("Header1", "Header1Value") .putHeader("Header2", "Header2Value") .build()) .build(); SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder() .synthesizeSpeechRequest(synthesizeSpeechRequest) .signatureDuration(Duration.ofHours(3)) .build(); PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest = presigner.presignSynthesizeSpeech(presignRequest); assertThat(presignedSynthesizeSpeechRequest.httpRequest().headers().keySet()).contains("Header1", "Header2"); } @Test void presign_includesRequestLevelHeaders_notBrowserCompatible() { PollyPresigner presigner = DefaultPollyPresigner.builder() .region(Region.US_EAST_1) .credentialsProvider(credentialsProvider) .build(); SynthesizeSpeechRequest synthesizeSpeechRequest = BASIC_SYNTHESIZE_SPEECH_REQUEST.toBuilder() .overrideConfiguration(AwsRequestOverrideConfiguration.builder() .putHeader("Header1", "Header1Value") .putHeader("Header2", "Header2Value") .build()) .build(); SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder() .synthesizeSpeechRequest(synthesizeSpeechRequest) .signatureDuration(Duration.ofHours(3)) .build(); PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest = presigner.presignSynthesizeSpeech(presignRequest); assertThat(presignedSynthesizeSpeechRequest.isBrowserExecutable()).isFalse(); } @Test void presign_includesRequestLevelQueryParams_included() { PollyPresigner presigner = DefaultPollyPresigner.builder() .region(Region.US_EAST_1) .credentialsProvider(credentialsProvider) .build(); SynthesizeSpeechRequest synthesizeSpeechRequest = BASIC_SYNTHESIZE_SPEECH_REQUEST.toBuilder() .overrideConfiguration(AwsRequestOverrideConfiguration.builder() .putRawQueryParameter("QueryParam1", "Param1Value") .build()) .build(); SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder() .synthesizeSpeechRequest(synthesizeSpeechRequest) .signatureDuration(Duration.ofHours(3)) .build(); PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest = presigner.presignSynthesizeSpeech(presignRequest); assertThat(presignedSynthesizeSpeechRequest.httpRequest().rawQueryParameters().keySet()).contains("QueryParam1"); } @Test void presign_endpointOverriden() { PollyPresigner presigner = DefaultPollyPresigner.builder() .region(Region.US_EAST_1) .credentialsProvider(credentialsProvider) .endpointOverride(URI.create("http://some-other-polly-endpoint.aws:1234")) .build(); SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder() .synthesizeSpeechRequest(BASIC_SYNTHESIZE_SPEECH_REQUEST) .signatureDuration(Duration.ofHours(3)) .build(); PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest = presigner.presignSynthesizeSpeech(presignRequest); URL presignedUrl = presignedSynthesizeSpeechRequest.url(); assertThat(presignedUrl.getProtocol()).isEqualTo("http"); assertThat(presignedUrl.getHost()).isEqualTo("some-other-polly-endpoint.aws"); assertThat(presignedUrl.getPort()).isEqualTo(1234); } @Test void close_closesCustomCloseableCredentialsProvider() throws IOException { TestCredentialsProvider mockCredentialsProvider = mock(TestCredentialsProvider.class); PollyPresigner presigner = DefaultPollyPresigner.builder() .region(Region.US_EAST_1) .credentialsProvider(mockCredentialsProvider) .build(); presigner.close(); verify(mockCredentialsProvider).close(); } @Test void presigner_credentialsProviderSetAsAwsCredentialsProvider_delegatesCorrectly() { AwsCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid")); DefaultPollyPresigner presigner1 = (DefaultPollyPresigner) DefaultPollyPresigner.builder() .region(Region.US_EAST_1) .credentialsProvider(credentialsProvider) .build(); DefaultPollyPresigner presigner2 = (DefaultPollyPresigner) DefaultPollyPresigner.builder() .region(Region.US_EAST_1) .credentialsProvider((IdentityProvider<AwsCredentialsIdentity>) credentialsProvider) .build(); assertThat(presigner1.credentialsProvider()).isSameAs(presigner2.credentialsProvider()); } @Test void presigner_credentialsProviderSetToNullByBuilder_createsDefaultCredentialsProvider() { DefaultPollyPresigner presigner = (DefaultPollyPresigner) DefaultPollyPresigner.builder() .region(Region.US_EAST_1) .credentialsProvider(null) .build(); IdentityProvider<? extends AwsCredentialsIdentity> awsCredentialsProvider = presigner.credentialsProvider(); assertThat(awsCredentialsProvider).isNotNull(); } private interface TestCredentialsProvider extends IdentityProvider<AwsCredentialsIdentity>, Closeable { } }
4,830
0
Create_ds/aws-sdk-java-v2/services/polly/src/test/java/software/amazon/awssdk/services/polly/internal/presigner/model
Create_ds/aws-sdk-java-v2/services/polly/src/test/java/software/amazon/awssdk/services/polly/internal/presigner/model/transform/SynthesizeSpeechRequestMarshallerTest.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.services.polly.internal.presigner.model.transform; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkField; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.services.polly.model.SynthesizeSpeechRequest; public class SynthesizeSpeechRequestMarshallerTest { private static Map<String, Object> properties; @BeforeAll public static void setup() { properties = new HashMap<>(); properties.put("Engine", "engine"); properties.put("LanguageCode", "languageCode"); properties.put("LexiconNames", Arrays.asList("Lexicon1", "Lexicon2", "Lexicon3")); properties.put("OutputFormat", "outputFormat"); properties.put("SampleRate", "sampleRate"); properties.put("SpeechMarkTypes", Arrays.asList("SpeechMark1", "SpeechMark2")); properties.put("Text", "text"); properties.put("TextType", "textType"); properties.put("VoiceId", "voiceId"); } // Test to ensure that we are testing with all the known properties for // this request. If this test fails, it means Polly added a new field to // SynthesizeSpeechRequest and the marshaller and/or properties map above // wasn't updated. @Test public void marshall_allPropertiesAccountedFor() { SynthesizeSpeechRequest request = SynthesizeSpeechRequest.builder().build(); request.sdkFields().forEach(f -> assertThat(properties.containsKey(f.locationName())).isTrue()); } @Test public void marshall_allPropertiesMarshalled() { SynthesizeSpeechRequest.Builder builder = setAllProperties(SynthesizeSpeechRequest.builder()); SdkHttpFullRequest.Builder marshalled = SynthesizeSpeechRequestMarshaller.getInstance().marshall(builder.build()); Map<String, List<String>> queryParams = marshalled.rawQueryParameters(); properties.keySet().forEach(k -> { Object expected = properties.get(k); List<String> actual = queryParams.get(k); if (expected instanceof List) { assertThat(actual).isEqualTo(expected); } else { assertThat(actual).containsExactly((String) expected); } }); assertThat(marshalled.contentStreamProvider()).isNull(); } @Test public void marshall_correctPath() { SdkHttpFullRequest.Builder marshalled = SynthesizeSpeechRequestMarshaller.getInstance() .marshall(SynthesizeSpeechRequest.builder().build()); assertThat(marshalled.encodedPath()).isEqualTo("/v1/speech"); } @Test public void marshall_correctMethod() { SdkHttpFullRequest.Builder marshalled = SynthesizeSpeechRequestMarshaller.getInstance() .marshall(SynthesizeSpeechRequest.builder().build()); assertThat(marshalled.method()).isEqualTo(SdkHttpMethod.GET); } private SynthesizeSpeechRequest.Builder setAllProperties(SynthesizeSpeechRequest.Builder builder) { SynthesizeSpeechRequest request = SynthesizeSpeechRequest.builder().build(); List<SdkField<?>> sdkFields = request.sdkFields(); sdkFields.forEach(f -> f.set(builder, properties.get(f.locationName()))); return builder; } }
4,831
0
Create_ds/aws-sdk-java-v2/services/polly/src/it/java/software/amazon/awssdk/services/polly/internal
Create_ds/aws-sdk-java-v2/services/polly/src/it/java/software/amazon/awssdk/services/polly/internal/presigner/DefaultPollyPresignerIntegrationTest.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.services.polly.internal.presigner; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.net.URL; import java.time.Duration; import javax.net.ssl.HttpsURLConnection; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.services.polly.model.OutputFormat; import software.amazon.awssdk.services.polly.model.SynthesizeSpeechRequest; import software.amazon.awssdk.services.polly.model.VoiceId; import software.amazon.awssdk.services.polly.presigner.PollyPresigner; import software.amazon.awssdk.services.polly.presigner.model.SynthesizeSpeechPresignRequest; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; /** * Integration tests for {@link DefaultPollyPresigner}. */ public class DefaultPollyPresignerIntegrationTest extends AwsIntegrationTestBase { private static PollyPresigner presigner; @BeforeClass public static void setup() { presigner = DefaultPollyPresigner.builder() .credentialsProvider(getCredentialsProvider()) .build(); } @Test public void presign_requestIsValid() throws IOException { SynthesizeSpeechRequest request = SynthesizeSpeechRequest.builder() .text("hello world!") .outputFormat(OutputFormat.PCM) .voiceId(VoiceId.SALLI) .build(); SynthesizeSpeechPresignRequest presignRequest = SynthesizeSpeechPresignRequest.builder() .signatureDuration(Duration.ofMinutes(45)) .synthesizeSpeechRequest(request) .build(); URL presignedUrl = presigner.presignSynthesizeSpeech(presignRequest).url(); HttpsURLConnection urlConnection = null; try { urlConnection = ((HttpsURLConnection) presignedUrl.openConnection()); urlConnection.connect(); assertThat(urlConnection.getResponseCode()).isEqualTo(200); assertThat(urlConnection.getHeaderField("Content-Type")).isEqualTo("audio/pcm"); } finally { urlConnection.getInputStream().close(); } } }
4,832
0
Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/internal
Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/internal/presigner/DefaultPollyPresigner.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.services.polly.internal.presigner; import static java.util.stream.Collectors.toMap; import static software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute.PRESIGNER_EXPIRATION; import java.net.URI; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.CredentialUtils; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.auth.signer.Aws4Signer; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.awscore.AwsExecutionAttribute; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.endpoint.DefaultServiceEndpointBuilder; import software.amazon.awssdk.awscore.endpoint.DualstackEnabledProvider; import software.amazon.awssdk.awscore.endpoint.FipsEnabledProvider; import software.amazon.awssdk.awscore.presigner.PresignRequest; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.core.ClientType; 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.core.signer.Presigner; import software.amazon.awssdk.core.signer.Signer; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.auth.aws.scheme.AwsV4AuthScheme; import software.amazon.awssdk.http.auth.spi.scheme.AuthScheme; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.identity.spi.IdentityProviders; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.profiles.ProfileFileSystemSetting; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; import software.amazon.awssdk.services.polly.auth.scheme.PollyAuthSchemeProvider; import software.amazon.awssdk.services.polly.internal.presigner.model.transform.SynthesizeSpeechRequestMarshaller; import software.amazon.awssdk.services.polly.model.PollyRequest; import software.amazon.awssdk.services.polly.presigner.PollyPresigner; import software.amazon.awssdk.services.polly.presigner.model.PresignedSynthesizeSpeechRequest; import software.amazon.awssdk.services.polly.presigner.model.SynthesizeSpeechPresignRequest; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.Validate; /** * Default implementation of {@link PollyPresigner}. */ @SdkInternalApi public final class DefaultPollyPresigner implements PollyPresigner { private static final String SIGNING_NAME = "polly"; private static final String SERVICE_NAME = "polly"; private static final Aws4Signer DEFAULT_SIGNER = Aws4Signer.create(); private final Supplier<ProfileFile> profileFile; private final String profileName; private final Region region; private final IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider; private final URI endpointOverride; private final Boolean dualstackEnabled; private final Boolean fipsEnabled; private DefaultPollyPresigner(BuilderImpl builder) { this.profileFile = ProfileFile::defaultProfileFile; this.profileName = ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow(); this.region = builder.region != null ? builder.region : DefaultAwsRegionProviderChain.builder() .profileFile(profileFile) .profileName(profileName) .build() .getRegion(); this.credentialsProvider = builder.credentialsProvider != null ? builder.credentialsProvider : DefaultCredentialsProvider.builder() .profileFile(profileFile) .profileName(profileName) .build(); this.endpointOverride = builder.endpointOverride; this.dualstackEnabled = builder.dualstackEnabled != null ? builder.dualstackEnabled : DualstackEnabledProvider.builder() .profileFile(profileFile) .profileName(profileName) .build() .isDualstackEnabled() .orElse(false); this.fipsEnabled = builder.fipsEnabled != null ? builder.fipsEnabled : FipsEnabledProvider.builder() .profileFile(profileFile) .profileName(profileName) .build() .isFipsEnabled() .orElse(false); } IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider() { return credentialsProvider; } @Override public void close() { IoUtils.closeIfCloseable(credentialsProvider, null); } public static PollyPresigner.Builder builder() { return new BuilderImpl(); } @Override public PresignedSynthesizeSpeechRequest presignSynthesizeSpeech( SynthesizeSpeechPresignRequest synthesizeSpeechPresignRequest) { return presign(PresignedSynthesizeSpeechRequest.builder(), synthesizeSpeechPresignRequest, synthesizeSpeechPresignRequest.synthesizeSpeechRequest(), SynthesizeSpeechRequestMarshaller.getInstance()::marshall) .build(); } private <T extends PollyRequest> SdkHttpFullRequest marshallRequest( T request, Function<T, SdkHttpFullRequest.Builder> marshalFn) { SdkHttpFullRequest.Builder requestBuilder = marshalFn.apply(request); applyOverrideHeadersAndQueryParams(requestBuilder, request); applyEndpoint(requestBuilder); return requestBuilder.build(); } /** * Generate a {@link PresignedRequest} from a {@link PresignedRequest} and {@link PollyRequest}. */ private <T extends PresignedRequest.Builder, U extends PollyRequest> T presign(T presignedRequest, PresignRequest presignRequest, U requestToPresign, Function<U, SdkHttpFullRequest.Builder> requestMarshaller) { ExecutionAttributes execAttrs = createExecutionAttributes(presignRequest, requestToPresign); SdkHttpFullRequest marshalledRequest = marshallRequest(requestToPresign, requestMarshaller); SdkHttpFullRequest signedHttpRequest = presignRequest(requestToPresign, marshalledRequest, execAttrs); initializePresignedRequest(presignedRequest, execAttrs, signedHttpRequest); return presignedRequest; } private void initializePresignedRequest(PresignedRequest.Builder presignedRequest, ExecutionAttributes execAttrs, SdkHttpFullRequest signedHttpRequest) { List<String> signedHeadersQueryParam = signedHttpRequest.firstMatchingRawQueryParameters("X-Amz-SignedHeaders"); Map<String, List<String>> signedHeaders = signedHeadersQueryParam.stream() .flatMap(h -> Stream.of(h.split(";"))) .collect(toMap(h -> h, h -> signedHttpRequest.firstMatchingHeader(h) .map(Collections::singletonList) .orElseGet(ArrayList::new))); boolean isBrowserExecutable = signedHttpRequest.method() == SdkHttpMethod.GET && (signedHeaders.isEmpty() || (signedHeaders.size() == 1 && signedHeaders.containsKey("host"))); presignedRequest.expiration(execAttrs.getAttribute(PRESIGNER_EXPIRATION)) .isBrowserExecutable(isBrowserExecutable) .httpRequest(signedHttpRequest) .signedHeaders(signedHeaders); } private SdkHttpFullRequest presignRequest(PollyRequest requestToPresign, SdkHttpFullRequest marshalledRequest, ExecutionAttributes executionAttributes) { Presigner presigner = resolvePresigner(requestToPresign); SdkHttpFullRequest presigned = presigner.presign(marshalledRequest, executionAttributes); List<String> signedHeadersQueryParam = presigned.firstMatchingRawQueryParameters("X-Amz-SignedHeaders"); Validate.validState(!signedHeadersQueryParam.isEmpty(), "Only SigV4 presigners are supported at this time, but the configured " + "presigner (%s) did not seem to generate a SigV4 signature.", presigner); return presigned; } private ExecutionAttributes createExecutionAttributes(PresignRequest presignRequest, PollyRequest requestToPresign) { Instant signatureExpiration = Instant.now().plus(presignRequest.signatureDuration()); AwsCredentialsIdentity credentials = resolveCredentials(resolveCredentialsProvider(requestToPresign)); Validate.validState(credentials != null, "Credential providers must never return null."); return new ExecutionAttributes() .putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, CredentialUtils.toCredentials(credentials)) .putAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, SIGNING_NAME) .putAttribute(AwsExecutionAttribute.AWS_REGION, region) .putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, region) .putAttribute(SdkInternalExecutionAttribute.IS_FULL_DUPLEX, false) .putAttribute(SdkExecutionAttribute.CLIENT_TYPE, ClientType.SYNC) .putAttribute(SdkExecutionAttribute.SERVICE_NAME, SERVICE_NAME) .putAttribute(PRESIGNER_EXPIRATION, signatureExpiration) .putAttribute(SdkInternalExecutionAttribute.AUTH_SCHEME_RESOLVER, PollyAuthSchemeProvider.defaultProvider()) .putAttribute(SdkInternalExecutionAttribute.AUTH_SCHEMES, authSchemes()) .putAttribute(SdkInternalExecutionAttribute.IDENTITY_PROVIDERS, IdentityProviders.builder() .putIdentityProvider(credentialsProvider()) .build()); } private Map<String, AuthScheme<?>> authSchemes() { AwsV4AuthScheme awsV4AuthScheme = AwsV4AuthScheme.create(); return Collections.singletonMap(awsV4AuthScheme.schemeId(), awsV4AuthScheme); } private IdentityProvider<? extends AwsCredentialsIdentity> resolveCredentialsProvider(PollyRequest request) { return request.overrideConfiguration().flatMap(AwsRequestOverrideConfiguration::credentialsIdentityProvider) .orElse(credentialsProvider); } private AwsCredentialsIdentity resolveCredentials(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { return CompletableFutureUtils.joinLikeSync(credentialsProvider.resolveIdentity()); } private Presigner resolvePresigner(PollyRequest request) { Signer signer = request.overrideConfiguration().flatMap(AwsRequestOverrideConfiguration::signer) .orElse(DEFAULT_SIGNER); return Validate.isInstanceOf(Presigner.class, signer, "Signer of type %s given in request override is not a Presigner", signer.getClass().getSimpleName()); } private void applyOverrideHeadersAndQueryParams(SdkHttpFullRequest.Builder httpRequestBuilder, PollyRequest request) { request.overrideConfiguration().ifPresent(o -> { o.headers().forEach(httpRequestBuilder::putHeader); o.rawQueryParameters().forEach(httpRequestBuilder::putRawQueryParameter); }); } private void applyEndpoint(SdkHttpFullRequest.Builder httpRequestBuilder) { URI uri = resolveEndpoint(); httpRequestBuilder.protocol(uri.getScheme()) .host(uri.getHost()) .port(uri.getPort()); } private URI resolveEndpoint() { if (endpointOverride != null) { return endpointOverride; } return new DefaultServiceEndpointBuilder(SERVICE_NAME, "https") .withRegion(region) .withProfileFile(profileFile) .withProfileName(profileName) .withDualstackEnabled(dualstackEnabled) .withFipsEnabled(fipsEnabled) .getServiceEndpoint(); } public static class BuilderImpl implements PollyPresigner.Builder { private Region region; private IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider; private URI endpointOverride; private Boolean dualstackEnabled; private Boolean fipsEnabled; @Override public Builder region(Region region) { this.region = region; return this; } @Override public Builder credentialsProvider(AwsCredentialsProvider credentialsProvider) { return credentialsProvider((IdentityProvider<? extends AwsCredentialsIdentity>) credentialsProvider); } @Override public Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { this.credentialsProvider = credentialsProvider; return this; } @Override public Builder dualstackEnabled(Boolean dualstackEnabled) { this.dualstackEnabled = dualstackEnabled; return this; } @Override public Builder fipsEnabled(Boolean fipsEnabled) { this.fipsEnabled = fipsEnabled; return this; } @Override public Builder endpointOverride(URI endpointOverride) { this.endpointOverride = endpointOverride; return this; } @Override public PollyPresigner build() { return new DefaultPollyPresigner(this); } } }
4,833
0
Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/internal/presigner/model
Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/internal/presigner/model/transform/SynthesizeSpeechRequestMarshaller.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.services.polly.internal.presigner.model.transform; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.services.polly.model.SynthesizeSpeechRequest; /** * Marshaller for {@link SynthesizeSpeechRequest} that marshalls the request into a form that can be presigned. */ @SdkInternalApi public final class SynthesizeSpeechRequestMarshaller { private static final SynthesizeSpeechRequestMarshaller INSTANCE = new SynthesizeSpeechRequestMarshaller(); public SdkHttpFullRequest.Builder marshall(SynthesizeSpeechRequest synthesizeSpeechRequest) { SdkHttpFullRequest.Builder builder = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .encodedPath("/v1/speech"); if (synthesizeSpeechRequest.text() != null) { builder.putRawQueryParameter("Text", synthesizeSpeechRequest.text()); } if (synthesizeSpeechRequest.textType() != null) { builder.putRawQueryParameter("TextType", synthesizeSpeechRequest.textTypeAsString()); } if (synthesizeSpeechRequest.voiceId() != null) { builder.putRawQueryParameter("VoiceId", synthesizeSpeechRequest.voiceIdAsString()); } if (synthesizeSpeechRequest.sampleRate() != null) { builder.putRawQueryParameter("SampleRate", synthesizeSpeechRequest.sampleRate()); } if (synthesizeSpeechRequest.outputFormat() != null) { builder.putRawQueryParameter("OutputFormat", synthesizeSpeechRequest.outputFormatAsString()); } if (synthesizeSpeechRequest.lexiconNames() != null) { builder.putRawQueryParameter("LexiconNames", synthesizeSpeechRequest.lexiconNames()); } if (synthesizeSpeechRequest.speechMarkTypes() != null) { builder.putRawQueryParameter("SpeechMarkTypes", synthesizeSpeechRequest.speechMarkTypesAsStrings()); } if (synthesizeSpeechRequest.languageCode() != null) { builder.putRawQueryParameter("LanguageCode", synthesizeSpeechRequest.languageCodeAsString()); } if (synthesizeSpeechRequest.engine() != null) { builder.putRawQueryParameter("Engine", synthesizeSpeechRequest.engineAsString()); } return builder; } public static SynthesizeSpeechRequestMarshaller getInstance() { return INSTANCE; } }
4,834
0
Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly
Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/presigner/PollyPresigner.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.services.polly.presigner; import java.net.URI; import java.net.URLConnection; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.awscore.presigner.SdkPresigner; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.polly.internal.presigner.DefaultPollyPresigner; import software.amazon.awssdk.services.polly.model.PollyRequest; import software.amazon.awssdk.services.polly.model.SynthesizeSpeechRequest; import software.amazon.awssdk.services.polly.presigner.model.PresignedSynthesizeSpeechRequest; import software.amazon.awssdk.services.polly.presigner.model.SynthesizeSpeechPresignRequest; /** * Enables signing a {@link PollyRequest} so that it can be executed without requiring any additional authentication on the * part of the caller. * <p/> * * <b>Signature Duration</b> * <p/> * * Pre-signed requests are only valid for a finite period of time, referred to as the signature duration. This signature * duration is configured when the request is generated, and cannot be longer than 7 days. Attempting to generate a signature * longer than 7 days in the future will fail at generation time. Attempting to use a pre-signed request after the signature * duration has passed will result in an access denied response from the service. * <p/> * * <b>Example Usage</b> * <p/> * * <pre> * {@code * // Create a PollyPresigner using the default region and credentials. * // This is usually done at application startup, because creating a presigner can be expensive. * PollyPresigner presigner = PollyPresigner.create(); * * // Create a SynthesizeSpeechRequest to be pre-signed * SynthesizeSpeechRequest synthesizeSpeechRequest = * SynthesizeSpeechRequest.builder() * .text("Hello Polly!") * .voiceId(VoiceId.SALLI) * .outputFormat(OutputFormat.PCM) * .build(); * * // Create a SynthesizeSpeechRequest to specify the signature duration * SynthesizeSpeechPresignRequest synthesizeSpeechPresignRequest = * SynthesizeSpeechPresignRequest.builder() * .signatureDuration(Duration.ofMinutes(10)) * .synthesizeSpeechRequest(synthesizeSpeechRequest) * .build(); * * // Generate the presigned request * PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest = * presigner.presignSynthesizeSpeech(SynthesizeSpeechPresignRequest); * * // Log the presigned URL, for example. * System.out.println("Presigned URL: " + presignedSynthesizeSpeechRequest.url()); * * // It is recommended to close the presigner when it is done being used, because some credential * // providers (e.g. if your AWS profile is configured to assume an STS role) require system resources * // that need to be freed. If you are using one presigner per application (as recommended), this * // usually is not needed. * presigner.close(); * } * </pre> * <p/> * * <b>Browser Compatibility</b> * <p/> * * Some pre-signed requests can be executed by a web browser. These "browser compatible" pre-signed requests * do not require the customer to send anything other than a "host" header when performing an HTTP GET against * the pre-signed URL. * <p/> * * Whether a pre-signed request is "browser compatible" can be determined by checking the * {@link PresignedRequest#isBrowserExecutable()} flag. It is recommended to always check this flag when the pre-signed * request needs to be executed by a browser, because some request fields will result in the pre-signed request not * being browser-compatible. * <p /> * * <b>Executing a Pre-Signed Request from Java code</b> * <p /> * * Browser-compatible requests (see above) can be executed using a web browser. All pre-signed requests can be executed * from Java code. This documentation describes two methods for executing a pre-signed request: (1) using the JDK's * {@link URLConnection} class, (2) using an SDK synchronous {@link SdkHttpClient} class. * * <p /> * <i>Using {code URLConnection}:</i> * * <p /> * <pre> * // Create a pre-signed request using one of the "presign" methods on PollyPresigner * PresignedRequest presignedRequest = ...; * * // Create a JDK HttpURLConnection for communicating with Polly * HttpURLConnection connection = (HttpURLConnection) presignedRequest.url().openConnection(); * * // Specify any headers that are needed by the service (not needed when isBrowserExecutable is true) * presignedRequest.httpRequest().headers().forEach((header, values) -> { * values.forEach(value -> { * connection.addRequestProperty(header, value); * }); * }); * * // Download the result of executing the request * try (InputStream content = connection.getInputStream()) { * System.out.println("Service returned response: "); * IoUtils.copy(content, myFileOutputstream); * } * </pre> */ @SdkPublicApi public interface PollyPresigner extends SdkPresigner { /** * Presign a {@link SynthesizeSpeechRequest} so that it can be executed at a later time without requiring additional * signing or authentication. * * @param synthesizeSpeechPresignRequest The presign request. * @return The presigned request. */ PresignedSynthesizeSpeechRequest presignSynthesizeSpeech(SynthesizeSpeechPresignRequest synthesizeSpeechPresignRequest); /** * Create an instance of this presigner using the default region and credentials chains to resolve the region and * credentials to use. */ static PollyPresigner create() { return builder().build(); } /** * @return the builder for a {@link PollyPresigner}. */ static Builder builder() { return DefaultPollyPresigner.builder(); } interface Builder extends SdkPresigner.Builder { @Override Builder region(Region region); @Override default Builder credentialsProvider(AwsCredentialsProvider credentialsProvider) { return credentialsProvider((IdentityProvider<? extends AwsCredentialsIdentity>) credentialsProvider); } @Override Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider); @Override Builder dualstackEnabled(Boolean dualstackEnabled); @Override Builder fipsEnabled(Boolean fipsEnabled); @Override Builder endpointOverride(URI endpointOverride); @Override PollyPresigner build(); } }
4,835
0
Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/presigner
Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/presigner/model/SynthesizeSpeechPresignRequest.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.services.polly.presigner.model; import java.time.Duration; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignRequest; import software.amazon.awssdk.services.polly.model.SynthesizeSpeechRequest; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A request to pre-sign a {@link software.amazon.awssdk.services.polly.presigner.PollyPresigner} so that it can be * executed at a later time without requiring additional signing or authentication. * * @see software.amazon.awssdk.services.polly.presigner.PollyPresigner#presignSynthesizeSpeech(SynthesizeSpeechPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public final class SynthesizeSpeechPresignRequest extends PresignRequest implements ToCopyableBuilder<SynthesizeSpeechPresignRequest.Builder, SynthesizeSpeechPresignRequest> { private final SynthesizeSpeechRequest synthesizeSpeechRequest; private SynthesizeSpeechPresignRequest(BuilderImpl builder) { super(builder); this.synthesizeSpeechRequest = builder.synthesizeSpeechRequest; } public SynthesizeSpeechRequest synthesizeSpeechRequest() { return synthesizeSpeechRequest; } @Override public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder extends PresignRequest.Builder, CopyableBuilder<SynthesizeSpeechPresignRequest.Builder, SynthesizeSpeechPresignRequest> { Builder synthesizeSpeechRequest(SynthesizeSpeechRequest synthesizeSpeechRequest); @Override Builder signatureDuration(Duration signatureDuration); /** * Build the presigned request, based on the configuration on this builder. */ @Override SynthesizeSpeechPresignRequest build(); } private static class BuilderImpl extends PresignRequest.DefaultBuilder<BuilderImpl> implements Builder { private SynthesizeSpeechRequest synthesizeSpeechRequest; BuilderImpl() { } private BuilderImpl(SynthesizeSpeechPresignRequest synthesizeSpeechPresignRequest) { super(synthesizeSpeechPresignRequest); this.synthesizeSpeechRequest = synthesizeSpeechPresignRequest.synthesizeSpeechRequest(); } @Override public Builder synthesizeSpeechRequest(SynthesizeSpeechRequest synthesizeSpeechRequest) { this.synthesizeSpeechRequest = synthesizeSpeechRequest; return this; } @Override public SynthesizeSpeechPresignRequest build() { return new SynthesizeSpeechPresignRequest(this); } } }
4,836
0
Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/presigner
Create_ds/aws-sdk-java-v2/services/polly/src/main/java/software/amazon/awssdk/services/polly/presigner/model/PresignedSynthesizeSpeechRequest.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.services.polly.presigner.model; import java.time.Instant; import java.util.List; import java.util.Map; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.awscore.presigner.PresignedRequest; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A pre-signed a {@link SynthesizeSpeechPresignRequest} that can be executed at a later time without requiring * additional signing or authentication. * * @see software.amazon.awssdk.services.polly.presigner.PollyPresigner#presignSynthesizeSpeech(SynthesizeSpeechPresignRequest) * @see #builder() */ @SdkPublicApi @Immutable @ThreadSafe public final class PresignedSynthesizeSpeechRequest extends PresignedRequest implements ToCopyableBuilder<PresignedSynthesizeSpeechRequest.Builder, PresignedSynthesizeSpeechRequest> { private PresignedSynthesizeSpeechRequest(BuilderImpl builder) { super(builder); } public static Builder builder() { return new BuilderImpl(); } @Override public Builder toBuilder() { return new BuilderImpl(this); } public interface Builder extends PresignedRequest.Builder, CopyableBuilder<Builder, PresignedSynthesizeSpeechRequest> { @Override Builder expiration(Instant expiration); @Override Builder isBrowserExecutable(Boolean isBrowserExecutable); @Override Builder signedHeaders(Map<String, List<String>> signedHeaders); @Override Builder signedPayload(SdkBytes signedPayload); @Override Builder httpRequest(SdkHttpRequest httpRequest); @Override PresignedSynthesizeSpeechRequest build(); } private static class BuilderImpl extends PresignedRequest.DefaultBuilder<BuilderImpl> implements Builder { BuilderImpl() { } BuilderImpl(PresignedSynthesizeSpeechRequest presignedSynthesizeSpeechRequest) { super(presignedSynthesizeSpeechRequest); } @Override public PresignedSynthesizeSpeechRequest build() { return new PresignedSynthesizeSpeechRequest(this); } } }
4,837
0
Create_ds/aws-sdk-java-v2/services/rds/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/rds/src/test/java/software/amazon/awssdk/services/rds/DefaultRdsUtilitiesTest.java
package software.amazon.awssdk.services.rds; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import java.time.Clock; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.function.Consumer; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.DefaultRdsUtilities.DefaultBuilder; import software.amazon.awssdk.services.rds.model.GenerateAuthenticationTokenRequest; public class DefaultRdsUtilitiesTest { private final ZoneId utcZone = ZoneId.of("UTC").normalized(); private final Clock fixedClock = Clock.fixed(ZonedDateTime.of(2016, 11, 7, 17, 39, 33, 0, utcZone).toInstant(), utcZone); @Test public void testTokenGenerationWithBuilderDefaultsUsingAwsCredentialsProvider() { AwsCredentialsProvider credentialsProvider = StaticCredentialsProvider.create( AwsBasicCredentials.create("access_key", "secret_key") ); DefaultBuilder utilitiesBuilder = (DefaultBuilder) RdsUtilities.builder() .credentialsProvider(credentialsProvider) .region(Region.US_EAST_1); testTokenGenerationWithBuilderDefaults(utilitiesBuilder); } @Test public void testTokenGenerationWithBuilderDefaultsUsingIdentityProvider() { IdentityProvider<AwsCredentialsIdentity> credentialsProvider = StaticCredentialsProvider.create( AwsBasicCredentials.create("access_key", "secret_key") ); DefaultBuilder utilitiesBuilder = (DefaultBuilder) RdsUtilities.builder() .credentialsProvider(credentialsProvider) .region(Region.US_EAST_1); testTokenGenerationWithBuilderDefaults(utilitiesBuilder); } private void testTokenGenerationWithBuilderDefaults(DefaultBuilder utilitiesBuilder) { DefaultRdsUtilities rdsUtilities = new DefaultRdsUtilities(utilitiesBuilder, fixedClock); String authenticationToken = rdsUtilities.generateAuthenticationToken(builder -> { builder.username("mySQLUser") .hostname("host.us-east-1.amazonaws.com") .port(3306); }); String expectedToken = "host.us-east-1.amazonaws.com:3306/?DBUser=mySQLUser&Action=connect&" + "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20161107T173933Z&X-Amz-SignedHeaders=host&" + "X-Amz-Expires=900&X-Amz-Credential=access_key%2F20161107%2Fus-east-1%2Frds-db%2Faws4_request&" + "X-Amz-Signature=87ab58107ef49f1c311a412f98b7f976b0b5152ffb559f0d36c6c9a0c5e0e362"; assertThat(authenticationToken).isEqualTo(expectedToken); } @Test public void testTokenGenerationWithOverriddenCredentialsUsingAwsCredentialsProvider() { AwsCredentialsProvider credentialsProvider = StaticCredentialsProvider.create( AwsBasicCredentials.create("foo", "bar") ); DefaultBuilder utilitiesBuilder = (DefaultBuilder) RdsUtilities.builder() .credentialsProvider(credentialsProvider) .region(Region.US_EAST_1); testTokenGenerationWithOverriddenCredentials(utilitiesBuilder, builder -> { builder.credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create("access_key", "secret_key"))); }); } @Test public void testTokenGenerationWithOverriddenCredentialsUsingIdentityProvider() { IdentityProvider<AwsCredentialsIdentity> credentialsProvider = StaticCredentialsProvider.create( AwsBasicCredentials.create("foo", "bar") ); DefaultBuilder utilitiesBuilder = (DefaultBuilder) RdsUtilities.builder() .credentialsProvider(credentialsProvider) .region(Region.US_EAST_1); testTokenGenerationWithOverriddenCredentials(utilitiesBuilder, builder -> { builder.credentialsProvider((IdentityProvider<AwsCredentialsIdentity>) StaticCredentialsProvider.create( AwsBasicCredentials.create("access_key", "secret_key"))); }); } private void testTokenGenerationWithOverriddenCredentials(DefaultBuilder utilitiesBuilder, Consumer<GenerateAuthenticationTokenRequest.Builder> credsBuilder) { DefaultRdsUtilities rdsUtilities = new DefaultRdsUtilities(utilitiesBuilder, fixedClock); String authenticationToken = rdsUtilities.generateAuthenticationToken(builder -> { builder.username("mySQLUser") .hostname("host.us-east-1.amazonaws.com") .port(3306) .applyMutation(credsBuilder); }); String expectedToken = "host.us-east-1.amazonaws.com:3306/?DBUser=mySQLUser&Action=connect&" + "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20161107T173933Z&X-Amz-SignedHeaders=host&" + "X-Amz-Expires=900&X-Amz-Credential=access_key%2F20161107%2Fus-east-1%2Frds-db%2Faws4_request&" + "X-Amz-Signature=87ab58107ef49f1c311a412f98b7f976b0b5152ffb559f0d36c6c9a0c5e0e362"; assertThat(authenticationToken).isEqualTo(expectedToken); } @Test public void testTokenGenerationWithOverriddenRegion() { IdentityProvider<AwsCredentialsIdentity> credentialsProvider = StaticCredentialsProvider.create( AwsBasicCredentials.create("access_key", "secret_key") ); DefaultBuilder utilitiesBuilder = (DefaultBuilder) RdsUtilities.builder() .credentialsProvider(credentialsProvider) .region(Region.US_WEST_2); DefaultRdsUtilities rdsUtilities = new DefaultRdsUtilities(utilitiesBuilder, fixedClock); String authenticationToken = rdsUtilities.generateAuthenticationToken(builder -> { builder.username("mySQLUser") .hostname("host.us-east-1.amazonaws.com") .port(3306) .region(Region.US_EAST_1); }); String expectedToken = "host.us-east-1.amazonaws.com:3306/?DBUser=mySQLUser&Action=connect&" + "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20161107T173933Z&X-Amz-SignedHeaders=host&" + "X-Amz-Expires=900&X-Amz-Credential=access_key%2F20161107%2Fus-east-1%2Frds-db%2Faws4_request&" + "X-Amz-Signature=87ab58107ef49f1c311a412f98b7f976b0b5152ffb559f0d36c6c9a0c5e0e362"; assertThat(authenticationToken).isEqualTo(expectedToken); } @Test public void testMissingRegionThrowsException() { IdentityProvider<AwsCredentialsIdentity> credentialsProvider = StaticCredentialsProvider.create( AwsBasicCredentials.create("access_key", "secret_key") ); DefaultBuilder utilitiesBuilder = (DefaultBuilder) RdsUtilities.builder() .credentialsProvider(credentialsProvider); DefaultRdsUtilities rdsUtilities = new DefaultRdsUtilities(utilitiesBuilder, fixedClock); assertThatThrownBy(() -> rdsUtilities.generateAuthenticationToken(builder -> { builder.username("mySQLUser") .hostname("host.us-east-1.amazonaws.com") .port(3306); })).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Region should be provided"); } @Test public void testMissingCredentialsThrowsException() { DefaultBuilder utilitiesBuilder = (DefaultBuilder) RdsUtilities.builder() .region(Region.US_WEST_2); DefaultRdsUtilities rdsUtilities = new DefaultRdsUtilities(utilitiesBuilder, fixedClock); assertThatThrownBy(() -> rdsUtilities.generateAuthenticationToken(builder -> { builder.username("mySQLUser") .hostname("host.us-east-1.amazonaws.com") .port(3306); })).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("CredentialProvider should be provided"); } }
4,838
0
Create_ds/aws-sdk-java-v2/services/rds/src/test/java/software/amazon/awssdk/services/rds
Create_ds/aws-sdk-java-v2/services/rds/src/test/java/software/amazon/awssdk/services/rds/internal/PresignRequestWireMockTest.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.services.rds.internal; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.anyRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import java.net.URI; import java.util.List; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.RdsClient; @RunWith(MockitoJUnitRunner.class) public class PresignRequestWireMockTest { @ClassRule public static final WireMockRule WIRE_MOCK = new WireMockRule(0); public static RdsClient client; @BeforeClass public static void setup() { client = RdsClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + WIRE_MOCK.port())) .build(); } @Before public void reset() { WIRE_MOCK.resetAll(); } @Test public void copyDbClusterSnapshotWithSourceRegionSendsPresignedUrl() { verifyMethodCallSendsPresignedUrl(() -> client.copyDBClusterSnapshot(r -> r.sourceRegion("us-west-2")), "CopyDBClusterSnapshot"); } @Test public void copyDBSnapshotWithSourceRegionSendsPresignedUrl() { verifyMethodCallSendsPresignedUrl(() -> client.copyDBSnapshot(r -> r.sourceRegion("us-west-2")), "CopyDBSnapshot"); } @Test public void createDbClusterWithSourceRegionSendsPresignedUrl() { verifyMethodCallSendsPresignedUrl(() -> client.createDBCluster(r -> r.sourceRegion("us-west-2")), "CreateDBCluster"); } @Test public void createDBInstanceReadReplicaWithSourceRegionSendsPresignedUrl() { verifyMethodCallSendsPresignedUrl(() -> client.createDBInstanceReadReplica(r -> r.sourceRegion("us-west-2")), "CreateDBInstanceReadReplica"); } public void verifyMethodCallSendsPresignedUrl(Runnable methodCall, String actionName) { stubFor(any(anyUrl()).willReturn(aResponse().withStatus(200).withBody("<body/>"))); methodCall.run(); List<LoggedRequest> requests = findAll(anyRequestedFor(anyUrl())); assertThat(requests).isNotEmpty(); LoggedRequest lastRequest = requests.get(0); String lastRequestBody = new String(lastRequest.getBody(), UTF_8); assertThat(lastRequestBody).contains("PreSignedUrl=https%3A%2F%2Frds.us-west-2.amazonaws.com%3FAction%3D" + actionName + "%26Version%3D2014-10-31%26DestinationRegion%3Dus-east-1%26"); } @Test public void startDBInstanceAutomatedBackupsReplicationWithSourceRegionSendsPresignedUrl() { verifyMethodCallSendsPresignedUrl(() -> client.startDBInstanceAutomatedBackupsReplication(r -> r.sourceRegion("us-west-2")), "StartDBInstanceAutomatedBackupsReplication"); } }
4,839
0
Create_ds/aws-sdk-java-v2/services/rds/src/test/java/software/amazon/awssdk/services/rds
Create_ds/aws-sdk-java-v2/services/rds/src/test/java/software/amazon/awssdk/services/rds/internal/PresignRequestHandlerTest.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.services.rds.internal; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; import java.net.URI; import java.net.URISyntaxException; import java.time.Clock; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.awscore.endpoint.DefaultServiceEndpointBuilder; import software.amazon.awssdk.core.Protocol; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.model.CopyDbSnapshotRequest; import software.amazon.awssdk.services.rds.model.RdsRequest; import software.amazon.awssdk.services.rds.transform.CopyDbSnapshotRequestMarshaller; /** * Unit Tests for {@link RdsPresignInterceptor} */ public class PresignRequestHandlerTest { private static final AwsBasicCredentials CREDENTIALS = AwsBasicCredentials.create("foo", "bar"); private static final Region DESTINATION_REGION = Region.of("us-west-2"); private static RdsPresignInterceptor<CopyDbSnapshotRequest> presignInterceptor = new CopyDbSnapshotPresignInterceptor(); private final CopyDbSnapshotRequestMarshaller marshaller = new CopyDbSnapshotRequestMarshaller(RdsPresignInterceptor.PROTOCOL_FACTORY); @Test public void testSetsPresignedUrl() { CopyDbSnapshotRequest request = makeTestRequest(); SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshallRequest(request)); assertNotNull(presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0)); } @Test public void testComputesPresignedUrlCorrectly() { // Note: test data was baselined by performing actual calls, with real // credentials to RDS and checking that they succeeded. Then the // request was recreated with all the same parameters but with test // credentials. final CopyDbSnapshotRequest request = CopyDbSnapshotRequest.builder() .sourceDBSnapshotIdentifier("arn:aws:rds:us-east-1:123456789012:snapshot:rds:test-instance-ss-2016-12-20-23-19") .targetDBSnapshotIdentifier("test-instance-ss-copy-2") .sourceRegion("us-east-1") .kmsKeyId("arn:aws:kms:us-west-2:123456789012:key/11111111-2222-3333-4444-555555555555") .build(); Calendar c = new GregorianCalendar(); c.setTimeZone(TimeZone.getTimeZone("UTC")); // 20161221T180735Z // Note: month is 0-based c.set(2016, Calendar.DECEMBER, 21, 18, 7, 35); Clock signingDateOverride = Mockito.mock(Clock.class); when(signingDateOverride.millis()).thenReturn(c.getTimeInMillis()); RdsPresignInterceptor<CopyDbSnapshotRequest> interceptor = new CopyDbSnapshotPresignInterceptor(signingDateOverride); SdkHttpRequest presignedRequest = modifyHttpRequest(interceptor, request, marshallRequest(request)); final String expectedPreSignedUrl = "https://rds.us-east-1.amazonaws.com?" + "Action=CopyDBSnapshot" + "&Version=2014-10-31" + "&SourceDBSnapshotIdentifier=arn%3Aaws%3Ards%3Aus-east-1%3A123456789012%3Asnapshot%3Ards%3Atest-instance-ss-2016-12-20-23-19" + "&TargetDBSnapshotIdentifier=test-instance-ss-copy-2" + "&KmsKeyId=arn%3Aaws%3Akms%3Aus-west-2%3A123456789012%3Akey%2F11111111-2222-3333-4444-555555555555" + "&DestinationRegion=us-west-2" + "&X-Amz-Algorithm=AWS4-HMAC-SHA256" + "&X-Amz-Date=20161221T180735Z" + "&X-Amz-SignedHeaders=host" + "&X-Amz-Expires=604800" + "&X-Amz-Credential=foo%2F20161221%2Fus-east-1%2Frds%2Faws4_request" + "&X-Amz-Signature=f839ca3c728dc96e7c978befeac648296b9f778f6724073de4217173859d13d9"; assertEquals(expectedPreSignedUrl, presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0)); } @Test public void testSkipsPresigningIfUrlSet() { CopyDbSnapshotRequest request = CopyDbSnapshotRequest.builder() .sourceRegion("us-west-2") .preSignedUrl("PRESIGNED") .build(); SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshallRequest(request)); assertEquals("PRESIGNED", presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0)); } @Test public void testSkipsPresigningIfSourceRegionNotSet() { CopyDbSnapshotRequest request = CopyDbSnapshotRequest.builder().build(); SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshallRequest(request)); assertNull(presignedRequest.rawQueryParameters().get("PreSignedUrl")); } @Test public void testParsesDestinationRegionfromRequestEndpoint() throws URISyntaxException { CopyDbSnapshotRequest request = CopyDbSnapshotRequest.builder() .sourceRegion("us-east-1") .build(); Region destination = Region.of("us-west-2"); SdkHttpFullRequest marshalled = marshallRequest(request); final SdkHttpRequest presignedRequest = modifyHttpRequest(presignInterceptor, request, marshalled); final URI presignedUrl = new URI(presignedRequest.rawQueryParameters().get("PreSignedUrl").get(0)); assertTrue(presignedUrl.toString().contains("DestinationRegion=" + destination.id())); } @Test public void testSourceRegionRemovedFromOriginalRequest() { CopyDbSnapshotRequest request = makeTestRequest(); SdkHttpFullRequest marshalled = marshallRequest(request); SdkHttpRequest actual = modifyHttpRequest(presignInterceptor, request, marshalled); assertFalse(actual.rawQueryParameters().containsKey("SourceRegion")); } private SdkHttpFullRequest marshallRequest(CopyDbSnapshotRequest request) { SdkHttpFullRequest.Builder marshalled = marshaller.marshall(request).toBuilder(); URI endpoint = new DefaultServiceEndpointBuilder("rds", Protocol.HTTPS.toString()) .withRegion(DESTINATION_REGION) .getServiceEndpoint(); return marshalled.uri(endpoint).build(); } private ExecutionAttributes executionAttributes() { return new ExecutionAttributes().putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, CREDENTIALS) .putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, DESTINATION_REGION) .putAttribute(SdkExecutionAttribute.PROFILE_FILE_SUPPLIER, ProfileFile::defaultProfileFile) .putAttribute(SdkExecutionAttribute.PROFILE_NAME, "default"); } private CopyDbSnapshotRequest makeTestRequest() { return CopyDbSnapshotRequest.builder() .sourceDBSnapshotIdentifier("arn:aws:rds:us-east-1:123456789012:snapshot:rds:test-instance-ss-2016-12-20-23-19") .targetDBSnapshotIdentifier("test-instance-ss-copy-2") .sourceRegion("us-east-1") .kmsKeyId("arn:aws:kms:us-west-2:123456789012:key/11111111-2222-3333-4444-555555555555") .build(); } private SdkHttpRequest modifyHttpRequest(ExecutionInterceptor interceptor, RdsRequest request, SdkHttpFullRequest httpRequest) { InterceptorContext context = InterceptorContext.builder().request(request).httpRequest(httpRequest).build(); return interceptor.modifyHttpRequest(context, executionAttributes()); } }
4,840
0
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/RdsUtilities.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.services.rds; import java.util.function.Consumer; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.model.GenerateAuthenticationTokenRequest; /** * Utilities for working with RDS. An instance of this class can be created by: * <p> * 1) Using the low-level client {@link RdsClient#utilities()} (or {@link RdsAsyncClient#utilities()}} method. This is * recommended as SDK will use the same configuration from the {@link RdsClient} object to create the {@link RdsUtilities} object. * * <pre> * RdsClient rdsClient = RdsClient.create(); * RdsUtilities utilities = rdsClient.utilities(); * </pre> * </p> * * <p> * 2) Directly using the {@link #builder()} method. * * <pre> * RdsUtilities utilities = RdsUtilities.builder() * .credentialsProvider(DefaultCredentialsProvider.create()) * .region(Region.US_WEST_2) * .build() * </pre> * </p> * * Note: This class does not make network calls. */ @SdkPublicApi public interface RdsUtilities { /** * Create a builder that can be used to configure and create a {@link RdsUtilities}. */ static Builder builder() { return new DefaultRdsUtilities.DefaultBuilder(); } /** * Generates an authorization tokens for IAM authentication to an RDS database. * * @param request The request used to generate the auth token * @return String to use as the RDS auth token * @throws IllegalArgumentException if the required parameters are not valid */ default String generateAuthenticationToken(Consumer<GenerateAuthenticationTokenRequest.Builder> request) { return generateAuthenticationToken(GenerateAuthenticationTokenRequest.builder().applyMutation(request).build()); } /** * Generates an authorization tokens for IAM authentication to an RDS database. * * @param request The request used to generate the auth token * @return String to use as the RDS auth token * @throws IllegalArgumentException if the required parameters are not valid */ default String generateAuthenticationToken(GenerateAuthenticationTokenRequest request) { throw new UnsupportedOperationException(); } /** * Builder for creating an instance of {@link RdsUtilities}. It can be configured using {@link RdsUtilities#builder()}. * Once configured, the {@link RdsUtilities} can created using {@link #build()}. */ @SdkPublicApi interface Builder { /** * The default region to use when working with the methods in {@link RdsUtilities} class. * * @return This object for method chaining */ Builder region(Region region); /** * The default credentials provider to use when working with the methods in {@link RdsUtilities} class. * * @return This object for method chaining */ default Builder credentialsProvider(AwsCredentialsProvider credentialsProvider) { return credentialsProvider((IdentityProvider<? extends AwsCredentialsIdentity>) credentialsProvider); } /** * The default credentials provider to use when working with the methods in {@link RdsUtilities} class. * * @return This object for method chaining */ default Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { throw new UnsupportedOperationException(); } /** * Create a {@link RdsUtilities} */ RdsUtilities build(); } }
4,841
0
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/DefaultRdsUtilities.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.services.rds; import java.time.Clock; import java.time.Duration; import java.time.Instant; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.CredentialUtils; import software.amazon.awssdk.auth.signer.Aws4Signer; import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams; import software.amazon.awssdk.awscore.client.config.AwsClientOption; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.model.GenerateAuthenticationTokenRequest; import software.amazon.awssdk.utils.CompletableFutureUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.StringUtils; @Immutable @SdkInternalApi final class DefaultRdsUtilities implements RdsUtilities { private static final Logger log = Logger.loggerFor(RdsUtilities.class); // The time the IAM token is good for. https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html private static final Duration EXPIRATION_DURATION = Duration.ofMinutes(15); private final Aws4Signer signer = Aws4Signer.create(); private final Region region; private final IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider; private final Clock clock; DefaultRdsUtilities(DefaultBuilder builder) { this(builder, Clock.systemUTC()); } /** * Test Only */ DefaultRdsUtilities(DefaultBuilder builder, Clock clock) { this.credentialsProvider = builder.credentialsProvider; this.region = builder.region; this.clock = clock; } /** * Used by RDS low-level client's utilities() method */ @SdkInternalApi static RdsUtilities create(SdkClientConfiguration clientConfiguration) { return new DefaultBuilder().clientConfiguration(clientConfiguration).build(); } @Override public String generateAuthenticationToken(GenerateAuthenticationTokenRequest request) { SdkHttpFullRequest httpRequest = SdkHttpFullRequest.builder() .method(SdkHttpMethod.GET) .protocol("https") .host(request.hostname()) .port(request.port()) .encodedPath("/") .putRawQueryParameter("DBUser", request.username()) .putRawQueryParameter("Action", "connect") .build(); Instant expirationTime = Instant.now(clock).plus(EXPIRATION_DURATION); Aws4PresignerParams presignRequest = Aws4PresignerParams.builder() .signingClockOverride(clock) .expirationTime(expirationTime) .awsCredentials(resolveCredentials(request)) .signingName("rds-db") .signingRegion(resolveRegion(request)) .build(); SdkHttpFullRequest fullRequest = signer.presign(httpRequest, presignRequest); String signedUrl = fullRequest.getUri().toString(); // Format should be: <hostname>>:<port>>/?Action=connect&DBUser=<username>>&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Expi... // Note: This must be the real RDS hostname, not proxy or tunnels String result = StringUtils.replacePrefixIgnoreCase(signedUrl, "https://", ""); log.debug(() -> "Generated RDS authentication token with expiration of " + expirationTime); return result; } private Region resolveRegion(GenerateAuthenticationTokenRequest request) { if (request.region() != null) { return request.region(); } if (this.region != null) { return this.region; } throw new IllegalArgumentException("Region should be provided either in GenerateAuthenticationTokenRequest object " + "or RdsUtilities object"); } // TODO: update this to use AwsCredentialsIdentity when we migrate Signers to accept the new type. private AwsCredentials resolveCredentials(GenerateAuthenticationTokenRequest request) { if (request.credentialsIdentityProvider() != null) { return CredentialUtils.toCredentials( CompletableFutureUtils.joinLikeSync(request.credentialsIdentityProvider().resolveIdentity())); } if (this.credentialsProvider != null) { return CredentialUtils.toCredentials(CompletableFutureUtils.joinLikeSync(this.credentialsProvider.resolveIdentity())); } throw new IllegalArgumentException("CredentialProvider should be provided either in GenerateAuthenticationTokenRequest " + "object or RdsUtilities object"); } @SdkInternalApi static final class DefaultBuilder implements Builder { private Region region; private IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider; DefaultBuilder() { } Builder clientConfiguration(SdkClientConfiguration clientConfiguration) { this.credentialsProvider = clientConfiguration.option(AwsClientOption.CREDENTIALS_IDENTITY_PROVIDER); this.region = clientConfiguration.option(AwsClientOption.AWS_REGION); return this; } @Override public Builder region(Region region) { this.region = region; return this; } @Override public Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { this.credentialsProvider = credentialsProvider; return this; } /** * Construct a {@link RdsUtilities} object. */ @Override public RdsUtilities build() { return new DefaultRdsUtilities(this); } } }
4,842
0
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/internal/StartDbInstanceAutomatedBackupsReplicationPresignInterceptor.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.services.rds.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.services.rds.model.StartDbInstanceAutomatedBackupsReplicationRequest; import software.amazon.awssdk.services.rds.transform.StartDbInstanceAutomatedBackupsReplicationRequestMarshaller; /** * Handler for pre-signing {@link StartDbInstanceAutomatedBackupsReplicationRequest}. */ @SdkInternalApi public final class StartDbInstanceAutomatedBackupsReplicationPresignInterceptor extends RdsPresignInterceptor<StartDbInstanceAutomatedBackupsReplicationRequest> { public static final StartDbInstanceAutomatedBackupsReplicationRequestMarshaller MARSHALLER = new StartDbInstanceAutomatedBackupsReplicationRequestMarshaller(PROTOCOL_FACTORY); public StartDbInstanceAutomatedBackupsReplicationPresignInterceptor() { super(StartDbInstanceAutomatedBackupsReplicationRequest.class); } @Override protected PresignableRequest adaptRequest(final StartDbInstanceAutomatedBackupsReplicationRequest originalRequest) { return new PresignableRequest() { @Override public String getSourceRegion() { return originalRequest.sourceRegion(); } @Override public SdkHttpFullRequest marshall() { return MARSHALLER.marshall(originalRequest); } }; } }
4,843
0
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/internal/CopyDbClusterSnapshotPresignInterceptor.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.services.rds.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.services.rds.model.CopyDbClusterSnapshotRequest; import software.amazon.awssdk.services.rds.transform.CopyDbClusterSnapshotRequestMarshaller; /** * Handler for pre-signing {@link CopyDbClusterSnapshotRequest}. */ @SdkInternalApi public final class CopyDbClusterSnapshotPresignInterceptor extends RdsPresignInterceptor<CopyDbClusterSnapshotRequest> { public static final CopyDbClusterSnapshotRequestMarshaller MARSHALLER = new CopyDbClusterSnapshotRequestMarshaller(PROTOCOL_FACTORY); public CopyDbClusterSnapshotPresignInterceptor() { super(CopyDbClusterSnapshotRequest.class); } @Override protected PresignableRequest adaptRequest(final CopyDbClusterSnapshotRequest originalRequest) { return new PresignableRequest() { @Override public String getSourceRegion() { return originalRequest.sourceRegion(); } @Override public SdkHttpFullRequest marshall() { return MARSHALLER.marshall(originalRequest); } }; } }
4,844
0
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/internal/CreateDbClusterPresignInterceptor.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.services.rds.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.services.rds.model.CreateDbClusterRequest; import software.amazon.awssdk.services.rds.transform.CreateDbClusterRequestMarshaller; /** * Handler for pre-signing {@link CreateDbClusterRequest}. */ @SdkInternalApi public final class CreateDbClusterPresignInterceptor extends RdsPresignInterceptor<CreateDbClusterRequest> { public static final CreateDbClusterRequestMarshaller MARSHALLER = new CreateDbClusterRequestMarshaller(PROTOCOL_FACTORY); public CreateDbClusterPresignInterceptor() { super(CreateDbClusterRequest.class); } @Override protected PresignableRequest adaptRequest(final CreateDbClusterRequest originalRequest) { return new PresignableRequest() { @Override public String getSourceRegion() { return originalRequest.sourceRegion(); } @Override public SdkHttpFullRequest marshall() { return MARSHALLER.marshall(originalRequest); } }; } }
4,845
0
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/internal/CreateDbInstanceReadReplicaPresignInterceptor.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.services.rds.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.services.rds.model.CreateDbInstanceReadReplicaRequest; import software.amazon.awssdk.services.rds.transform.CreateDbInstanceReadReplicaRequestMarshaller; /** * Handler for pre-signing {@link CreateDbInstanceReadReplicaRequest}. */ @SdkInternalApi public final class CreateDbInstanceReadReplicaPresignInterceptor extends RdsPresignInterceptor<CreateDbInstanceReadReplicaRequest> { public static final CreateDbInstanceReadReplicaRequestMarshaller MARSHALLER = new CreateDbInstanceReadReplicaRequestMarshaller(PROTOCOL_FACTORY); public CreateDbInstanceReadReplicaPresignInterceptor() { super(CreateDbInstanceReadReplicaRequest.class); } @Override protected PresignableRequest adaptRequest(final CreateDbInstanceReadReplicaRequest originalRequest) { return new PresignableRequest() { @Override public String getSourceRegion() { return originalRequest.sourceRegion(); } @Override public SdkHttpFullRequest marshall() { return MARSHALLER.marshall(originalRequest); } }; } }
4,846
0
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/internal/RdsPresignInterceptor.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.services.rds.internal; import static software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute.AWS_CREDENTIALS; import static software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME; import java.net.URI; import java.time.Clock; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.CredentialUtils; import software.amazon.awssdk.auth.signer.Aws4Signer; import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute; import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams; import software.amazon.awssdk.awscore.AwsExecutionAttribute; import software.amazon.awssdk.awscore.endpoint.DefaultServiceEndpointBuilder; import software.amazon.awssdk.core.Protocol; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.protocols.query.AwsQueryProtocolFactory; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.model.RdsRequest; import software.amazon.awssdk.utils.CompletableFutureUtils; /** * Abstract pre-sign handler that follows the pre-signing scheme outlined in the 'RDS Presigned URL for Cross-Region Copying' * SEP. * * @param <T> The request type. */ @SdkInternalApi public abstract class RdsPresignInterceptor<T extends RdsRequest> implements ExecutionInterceptor { private static final URI CUSTOM_ENDPOINT_LOCALHOST = URI.create("http://localhost"); protected static final AwsQueryProtocolFactory PROTOCOL_FACTORY = AwsQueryProtocolFactory .builder() // Need an endpoint to marshall but this will be overwritten in modifyHttpRequest .clientConfiguration(SdkClientConfiguration.builder() .option(SdkClientOption.ENDPOINT, CUSTOM_ENDPOINT_LOCALHOST) .build()) .build(); private static final String SERVICE_NAME = "rds"; private static final String PARAM_SOURCE_REGION = "SourceRegion"; private static final String PARAM_DESTINATION_REGION = "DestinationRegion"; private static final String PARAM_PRESIGNED_URL = "PreSignedUrl"; public interface PresignableRequest { String getSourceRegion(); SdkHttpFullRequest marshall(); } private final Class<T> requestClassToPreSign; private final Clock signingOverrideClock; public RdsPresignInterceptor(Class<T> requestClassToPreSign) { this(requestClassToPreSign, null); } public RdsPresignInterceptor(Class<T> requestClassToPreSign, Clock signingOverrideClock) { this.requestClassToPreSign = requestClassToPreSign; this.signingOverrideClock = signingOverrideClock; } @Override public final SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { SdkHttpRequest request = context.httpRequest(); SdkRequest originalRequest = context.request(); if (!requestClassToPreSign.isInstance(originalRequest)) { return request; } if (request.firstMatchingRawQueryParameter(PARAM_PRESIGNED_URL).isPresent()) { return request; } PresignableRequest presignableRequest = adaptRequest(requestClassToPreSign.cast(originalRequest)); String sourceRegion = presignableRequest.getSourceRegion(); if (sourceRegion == null) { return request; } String destinationRegion = executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION).id(); URI endpoint = createEndpoint(sourceRegion, SERVICE_NAME, executionAttributes); SdkHttpFullRequest.Builder marshalledRequest = presignableRequest.marshall().toBuilder().uri(endpoint); SdkHttpFullRequest requestToPresign = marshalledRequest.method(SdkHttpMethod.GET) .putRawQueryParameter(PARAM_DESTINATION_REGION, destinationRegion) .removeQueryParameter(PARAM_SOURCE_REGION) .build(); requestToPresign = presignRequest(requestToPresign, executionAttributes, sourceRegion); String presignedUrl = requestToPresign.getUri().toString(); return request.toBuilder() .putRawQueryParameter(PARAM_PRESIGNED_URL, presignedUrl) // Remove the unmodeled params to stop them getting onto the wire .removeQueryParameter(PARAM_SOURCE_REGION) .build(); } /** * Adapts the request to the {@link PresignableRequest}. * * @param originalRequest the original request * @return a PresignableRequest */ protected abstract PresignableRequest adaptRequest(T originalRequest); private SdkHttpFullRequest presignRequest(SdkHttpFullRequest request, ExecutionAttributes attributes, String signingRegion) { Aws4Signer signer = Aws4Signer.create(); Aws4PresignerParams presignerParams = Aws4PresignerParams.builder() .signingRegion(Region.of(signingRegion)) .signingName(SERVICE_NAME) .signingClockOverride(signingOverrideClock) .awsCredentials(resolveCredentials(attributes)) .build(); return signer.presign(request, presignerParams); } private AwsCredentials resolveCredentials(ExecutionAttributes attributes) { return attributes.getOptionalAttribute(SELECTED_AUTH_SCHEME) .map(selectedAuthScheme -> selectedAuthScheme.identity()) .map(identityFuture -> CompletableFutureUtils.joinLikeSync(identityFuture)) .filter(identity -> identity instanceof AwsCredentialsIdentity) .map(identity -> { AwsCredentialsIdentity awsCredentialsIdentity = (AwsCredentialsIdentity) identity; return CredentialUtils.toCredentials(awsCredentialsIdentity); }).orElse(attributes.getAttribute(AWS_CREDENTIALS)); } private URI createEndpoint(String regionName, String serviceName, ExecutionAttributes attributes) { Region region = Region.of(regionName); if (region == null) { throw SdkClientException.builder() .message("{" + serviceName + ", " + regionName + "} was not " + "found in region metadata. Update to latest version of SDK and try again.") .build(); } return new DefaultServiceEndpointBuilder(SERVICE_NAME, Protocol.HTTPS.toString()) .withRegion(region) .withProfileFile(attributes.getAttribute(SdkExecutionAttribute.PROFILE_FILE_SUPPLIER)) .withProfileName(attributes.getAttribute(SdkExecutionAttribute.PROFILE_NAME)) .withDualstackEnabled(attributes.getAttribute(AwsExecutionAttribute.DUALSTACK_ENDPOINT_ENABLED)) .withFipsEnabled(attributes.getAttribute(AwsExecutionAttribute.FIPS_ENDPOINT_ENABLED)) .getServiceEndpoint(); } }
4,847
0
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/internal/CopyDbSnapshotPresignInterceptor.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.services.rds.internal; import java.time.Clock; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.services.rds.model.CopyDbSnapshotRequest; import software.amazon.awssdk.services.rds.transform.CopyDbSnapshotRequestMarshaller; /** * Handler for pre-signing {@link CopyDbSnapshotRequest}. */ @SdkInternalApi public final class CopyDbSnapshotPresignInterceptor extends RdsPresignInterceptor<CopyDbSnapshotRequest> { public static final CopyDbSnapshotRequestMarshaller MARSHALLER = new CopyDbSnapshotRequestMarshaller(PROTOCOL_FACTORY); public CopyDbSnapshotPresignInterceptor() { super(CopyDbSnapshotRequest.class); } @SdkTestInternalApi CopyDbSnapshotPresignInterceptor(Clock signingDateOverride) { super(CopyDbSnapshotRequest.class, signingDateOverride); } @Override protected PresignableRequest adaptRequest(final CopyDbSnapshotRequest originalRequest) { return new PresignableRequest() { @Override public String getSourceRegion() { return originalRequest.sourceRegion(); } @Override public SdkHttpFullRequest marshall() { return MARSHALLER.marshall(originalRequest); } }; } }
4,848
0
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds
Create_ds/aws-sdk-java-v2/services/rds/src/main/java/software/amazon/awssdk/services/rds/model/GenerateAuthenticationTokenRequest.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.services.rds.model; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.CredentialUtils; import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity; import software.amazon.awssdk.identity.spi.IdentityProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.RdsUtilities; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * Input parameters for generating an auth token for IAM database authentication. */ @SdkPublicApi public final class GenerateAuthenticationTokenRequest implements ToCopyableBuilder<GenerateAuthenticationTokenRequest.Builder, GenerateAuthenticationTokenRequest> { private final String hostname; private final int port; private final String username; private final Region region; private final IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider; private GenerateAuthenticationTokenRequest(BuilderImpl builder) { this.hostname = Validate.notEmpty(builder.hostname, "hostname"); this.port = Validate.isPositive(builder.port, "port"); this.username = Validate.notEmpty(builder.username, "username"); this.region = builder.region; this.credentialsProvider = builder.credentialsProvider; } /** * @return The hostname of the database to connect to */ public String hostname() { return hostname; } /** * @return The port of the database to connect to */ public int port() { return port; } /** * @return The username to log in as. */ public String username() { return username; } /** * @return The region the database is hosted in. If specified, takes precedence over the value specified in * {@link RdsUtilities.Builder#region(Region)} */ public Region region() { return region; } /** * @return The credentials provider to sign the IAM auth request with. If specified, takes precedence over the value * specified in {@link RdsUtilities.Builder#credentialsProvider}} */ public AwsCredentialsProvider credentialsProvider() { return CredentialUtils.toCredentialsProvider(credentialsProvider); } /** * @return The credentials provider to sign the IAM auth request with. If specified, takes precedence over the value * specified in {@link RdsUtilities.Builder#credentialsProvider(AwsCredentialsProvider)}} */ public IdentityProvider<? extends AwsCredentialsIdentity> credentialsIdentityProvider() { return credentialsProvider; } @Override public Builder toBuilder() { return new BuilderImpl(this); } /** * Creates a builder for {@link RdsUtilities}. */ public static Builder builder() { return new BuilderImpl(); } /** * A builder for a {@link GenerateAuthenticationTokenRequest}, created with {@link #builder()}. */ @SdkPublicApi @NotThreadSafe public interface Builder extends CopyableBuilder<Builder, GenerateAuthenticationTokenRequest> { /** * The hostname of the database to connect to * * @return This object for method chaining */ Builder hostname(String endpoint); /** * The port number the database is listening on. * * @return This object for method chaining */ Builder port(int port); /** * The username to log in as. * * @return This object for method chaining */ Builder username(String userName); /** * The region the database is hosted in. If specified, takes precedence over the value specified in * {@link RdsUtilities.Builder#region(Region)} * * @return This object for method chaining */ Builder region(Region region); /** * The credentials provider to sign the IAM auth request with. If specified, takes precedence over the value * specified in {@link RdsUtilities.Builder#credentialsProvider)}} * * @return This object for method chaining */ default Builder credentialsProvider(AwsCredentialsProvider credentialsProvider) { return credentialsProvider((IdentityProvider<? extends AwsCredentialsIdentity>) credentialsProvider); } /** * The credentials provider to sign the IAM auth request with. If specified, takes precedence over the value * specified in {@link RdsUtilities.Builder#credentialsProvider}} * * @return This object for method chaining */ default Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { throw new UnsupportedOperationException(); } @Override GenerateAuthenticationTokenRequest build(); } private static final class BuilderImpl implements Builder { private String hostname; private int port; private String username; private Region region; private IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider; private BuilderImpl() { } private BuilderImpl(GenerateAuthenticationTokenRequest request) { this.hostname = request.hostname; this.port = request.port; this.username = request.username; this.region = request.region; this.credentialsProvider = request.credentialsProvider; } @Override public Builder hostname(String endpoint) { this.hostname = endpoint; return this; } @Override public Builder port(int port) { this.port = port; return this; } @Override public Builder username(String userName) { this.username = userName; return this; } @Override public Builder region(Region region) { this.region = region; return this; } @Override public Builder credentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) { this.credentialsProvider = credentialsProvider; return this; } @Override public GenerateAuthenticationTokenRequest build() { return new GenerateAuthenticationTokenRequest(this); } } }
4,849
0
Create_ds/aws-sdk-java-v2/services/swf/src/main/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/swf/src/main/java/software/amazon/awssdk/services/swf/package-info.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. */ /** * <fullname>Amazon Simple Workflow Service</fullname> * <p> * The Amazon Simple Workflow Service (Amazon SWF) makes it easy to build applications that use Amazon's cloud to * coordinate work across distributed components. In Amazon SWF, a <i>task</i> represents a logical unit of work that is * performed by a component of your workflow. Coordinating tasks in a workflow involves managing intertask dependencies, * scheduling, and concurrency in accordance with the logical flow of the application. * </p> * <p> * Amazon SWF gives you full control over implementing tasks and coordinating them without worrying about underlying * complexities such as tracking their progress and maintaining their state. * </p> * <p> * This documentation serves as reference only. For a broader overview of the Amazon SWF programming model, see the <a * href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/">Amazon SWF Developer Guide</a>. * </p> */ package software.amazon.awssdk.services.swf;
4,850
0
Create_ds/aws-sdk-java-v2/services/swf/src/main/java/software/amazon/awssdk/services/swf
Create_ds/aws-sdk-java-v2/services/swf/src/main/java/software/amazon/awssdk/services/swf/internal/SwfHttpConfigurationOptions.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.services.swf.internal; import java.time.Duration; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.utils.AttributeMap; @SdkInternalApi public final class SwfHttpConfigurationOptions { private static final AttributeMap OPTIONS = AttributeMap .builder() .put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofMillis(90_000)) .put(SdkHttpConfigurationOption.MAX_CONNECTIONS, 1000) .build(); private SwfHttpConfigurationOptions() { } public static AttributeMap defaultHttpConfig() { return OPTIONS; } }
4,851
0
Create_ds/aws-sdk-java-v2/services/cloudwatchevents/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/cloudwatchevents/src/it/java/software/amazon/awssdk/services/cloudwatchevents/CloudWatchEventsIntegrationTest.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.services.cloudwatchevents; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.services.cloudwatchevents.model.DeleteRuleRequest; import software.amazon.awssdk.services.cloudwatchevents.model.DescribeRuleRequest; import software.amazon.awssdk.services.cloudwatchevents.model.DescribeRuleResponse; import software.amazon.awssdk.services.cloudwatchevents.model.DisableRuleRequest; import software.amazon.awssdk.services.cloudwatchevents.model.EnableRuleRequest; import software.amazon.awssdk.services.cloudwatchevents.model.PutRuleRequest; import software.amazon.awssdk.services.cloudwatchevents.model.RuleState; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class CloudWatchEventsIntegrationTest extends AwsIntegrationTestBase { private static final String RULE_NAME = "rule"; private static final String RULE_DESCRIPTION = "ruleDescription"; private static final String EVENT_PATTERN = "{ \"source\": [\"aws.ec2\"] }"; private static CloudWatchEventsClient events; @BeforeClass public static void setUpClient() throws Exception { events = CloudWatchEventsClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); events.putRule(PutRuleRequest.builder() .name(RULE_NAME) .description(RULE_DESCRIPTION) .eventPattern(EVENT_PATTERN) .build() ); // By default, a newly created rule is enabled Assert.assertEquals(RuleState.ENABLED, events.describeRule(DescribeRuleRequest.builder().name(RULE_NAME).build()) .state()); } @AfterClass public static void tearDownAfterClass() throws Exception { events.deleteRule(DeleteRuleRequest.builder().name(RULE_NAME).build()); } @Test public void basicTest() { events.enableRule(EnableRuleRequest.builder().name(RULE_NAME).build()); DescribeRuleResponse describeRuleResult = events.describeRule(DescribeRuleRequest.builder() .name(RULE_NAME).build()); Assert.assertEquals(RULE_NAME, describeRuleResult.name()); Assert.assertEquals(RULE_DESCRIPTION, describeRuleResult.description()); Assert.assertEquals(RuleState.ENABLED, describeRuleResult.state()); events.disableRule(DisableRuleRequest.builder().name(RULE_NAME).build()); Assert.assertEquals(RuleState.DISABLED, events.describeRule(DescribeRuleRequest.builder().name(RULE_NAME).build()) .state()); } }
4,852
0
Create_ds/aws-sdk-java-v2/services/datapipeline/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/datapipeline/src/it/java/software/amazon/awssdk/services/datapipeline/IntegrationTestBase.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.services.datapipeline; import java.io.FileNotFoundException; import java.io.IOException; import org.junit.BeforeClass; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Base class for all STS integration tests. Loads AWS credentials from a * properties file on disk, provides helper methods for tests, and instantiates * the STS client object for all tests to use. */ public class IntegrationTestBase extends AwsTestBase { /** The shared DP client for all tests to use. */ protected static DataPipelineClient dataPipeline; @BeforeClass public static void setUp() throws FileNotFoundException, IOException { setUpCredentials(); dataPipeline = DataPipelineClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } }
4,853
0
Create_ds/aws-sdk-java-v2/services/datapipeline/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/datapipeline/src/it/java/software/amazon/awssdk/services/datapipeline/DataPipelineIntegrationTest.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.services.datapipeline; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.AfterClass; import org.junit.Test; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.services.datapipeline.model.ActivatePipelineRequest; import software.amazon.awssdk.services.datapipeline.model.ActivatePipelineResponse; import software.amazon.awssdk.services.datapipeline.model.CreatePipelineRequest; import software.amazon.awssdk.services.datapipeline.model.CreatePipelineResponse; import software.amazon.awssdk.services.datapipeline.model.DeletePipelineRequest; import software.amazon.awssdk.services.datapipeline.model.DescribeObjectsRequest; import software.amazon.awssdk.services.datapipeline.model.DescribeObjectsResponse; import software.amazon.awssdk.services.datapipeline.model.DescribePipelinesRequest; import software.amazon.awssdk.services.datapipeline.model.DescribePipelinesResponse; import software.amazon.awssdk.services.datapipeline.model.Field; import software.amazon.awssdk.services.datapipeline.model.GetPipelineDefinitionRequest; import software.amazon.awssdk.services.datapipeline.model.GetPipelineDefinitionResponse; import software.amazon.awssdk.services.datapipeline.model.ListPipelinesRequest; import software.amazon.awssdk.services.datapipeline.model.ListPipelinesResponse; import software.amazon.awssdk.services.datapipeline.model.PipelineObject; import software.amazon.awssdk.services.datapipeline.model.PutPipelineDefinitionRequest; import software.amazon.awssdk.services.datapipeline.model.PutPipelineDefinitionResponse; import software.amazon.awssdk.services.datapipeline.model.ValidatePipelineDefinitionRequest; import software.amazon.awssdk.services.datapipeline.model.ValidatePipelineDefinitionResponse; public class DataPipelineIntegrationTest extends IntegrationTestBase { private static final String PIPELINE_NAME = "my-pipeline"; private static final String PIPELINE_ID = "my-pipeline" + System.currentTimeMillis(); private static final String PIPELINE_DESCRIPTION = "my pipeline"; private static final String OBJECT_ID = "123"; private static final String OBJECT_NAME = "object"; private static final String VALID_KEY = "startDateTime"; private static final String INVALID_KEY = "radom_key"; private static final String FIELD_VALUE = "2012-09-25T17:00:00"; private static String pipelineId; @AfterClass public static void tearDown() { try { dataPipeline.deletePipeline(DeletePipelineRequest.builder().pipelineId(pipelineId).build()); } catch (Exception e) { // Do nothing. } } @Test public void testPipelineOperations() throws InterruptedException { // Create a pipeline. CreatePipelineResponse createPipelineResult = dataPipeline.createPipeline( CreatePipelineRequest.builder() .name(PIPELINE_NAME) .uniqueId(PIPELINE_ID) .description(PIPELINE_DESCRIPTION) .build()); pipelineId = createPipelineResult.pipelineId(); assertNotNull(pipelineId); // Invalid field PipelineObject pipelineObject = PipelineObject.builder() .id(OBJECT_ID + "1") .name(OBJECT_NAME) .fields(Field.builder() .key(INVALID_KEY) .stringValue(FIELD_VALUE) .build()) .build(); ValidatePipelineDefinitionResponse validatePipelineDefinitionResult = dataPipeline.validatePipelineDefinition(ValidatePipelineDefinitionRequest.builder() .pipelineId(pipelineId) .pipelineObjects(pipelineObject) .build()); assertTrue(validatePipelineDefinitionResult.errored()); assertNotNull(validatePipelineDefinitionResult.validationErrors()); assertTrue(validatePipelineDefinitionResult.validationErrors().size() > 0); assertNotNull(validatePipelineDefinitionResult.validationErrors().get(0)); assertNotNull(validatePipelineDefinitionResult.validationWarnings()); assertEquals(0, validatePipelineDefinitionResult.validationWarnings().size()); // Valid field pipelineObject = PipelineObject.builder() .id(OBJECT_ID) .name(OBJECT_NAME) .fields(Field.builder() .key(VALID_KEY) .stringValue(FIELD_VALUE) .build()) .build(); // Validate pipeline definition. validatePipelineDefinitionResult = dataPipeline.validatePipelineDefinition(ValidatePipelineDefinitionRequest.builder() .pipelineId(pipelineId) .pipelineObjects(pipelineObject) .build()); assertFalse(validatePipelineDefinitionResult.errored()); assertNotNull(validatePipelineDefinitionResult.validationErrors()); assertEquals(0, validatePipelineDefinitionResult.validationErrors().size()); assertNotNull(validatePipelineDefinitionResult.validationWarnings()); assertEquals(0, validatePipelineDefinitionResult.validationWarnings().size()); // Put pipeline definition. PutPipelineDefinitionResponse putPipelineDefinitionResult = dataPipeline.putPipelineDefinition(PutPipelineDefinitionRequest.builder() .pipelineId(pipelineId) .pipelineObjects(pipelineObject) .build()); assertFalse(putPipelineDefinitionResult.errored()); assertNotNull(putPipelineDefinitionResult.validationErrors()); assertEquals(0, putPipelineDefinitionResult.validationErrors().size()); assertNotNull(putPipelineDefinitionResult.validationWarnings()); assertEquals(0, putPipelineDefinitionResult.validationWarnings().size()); // Get pipeline definition. GetPipelineDefinitionResponse pipelineDefinitionResult = dataPipeline.getPipelineDefinition(GetPipelineDefinitionRequest.builder().pipelineId(pipelineId).build()); assertEquals(1, pipelineDefinitionResult.pipelineObjects().size()); assertEquals(OBJECT_ID, pipelineDefinitionResult.pipelineObjects().get(0).id()); assertEquals(OBJECT_NAME, pipelineDefinitionResult.pipelineObjects().get(0).name()); assertEquals(1, pipelineDefinitionResult.pipelineObjects().get(0).fields().size()); assertTrue(pipelineDefinitionResult.pipelineObjects().get(0).fields() .contains(Field.builder().key(VALID_KEY).stringValue(FIELD_VALUE).build())); // Activate a pipeline. ActivatePipelineResponse activatePipelineResult = dataPipeline.activatePipeline(ActivatePipelineRequest.builder().pipelineId(pipelineId).build()); assertNotNull(activatePipelineResult); // List pipeline. ListPipelinesResponse listPipelinesResult = dataPipeline.listPipelines(ListPipelinesRequest.builder().build()); assertTrue(listPipelinesResult.pipelineIdList().size() > 0); assertNotNull(pipelineId, listPipelinesResult.pipelineIdList().get(0).id()); assertNotNull(PIPELINE_NAME, listPipelinesResult.pipelineIdList().get(0).name()); Thread.sleep(1000 * 5); // Describe objects. DescribeObjectsResponse describeObjectsResult = dataPipeline.describeObjects(DescribeObjectsRequest.builder().pipelineId(pipelineId).objectIds(OBJECT_ID).build()); assertEquals(1, describeObjectsResult.pipelineObjects().size()); assertEquals(OBJECT_ID, describeObjectsResult.pipelineObjects().get(0).id()); assertEquals(OBJECT_NAME, describeObjectsResult.pipelineObjects().get(0).name()); assertTrue(describeObjectsResult.pipelineObjects().get(0).fields() .contains(Field.builder().key(VALID_KEY).stringValue(FIELD_VALUE).build())); assertTrue(describeObjectsResult.pipelineObjects().get(0).fields() .contains(Field.builder().key("@pipelineId").stringValue(pipelineId).build())); // Describe a pipeline. DescribePipelinesResponse describepipelinesResult = dataPipeline.describePipelines(DescribePipelinesRequest.builder().pipelineIds(pipelineId).build()); assertEquals(1, describepipelinesResult.pipelineDescriptionList().size()); assertEquals(PIPELINE_NAME, describepipelinesResult.pipelineDescriptionList().get(0).name()); assertEquals(pipelineId, describepipelinesResult.pipelineDescriptionList().get(0).pipelineId()); assertEquals(PIPELINE_DESCRIPTION, describepipelinesResult.pipelineDescriptionList().get(0).description()); assertTrue(describepipelinesResult.pipelineDescriptionList().get(0).fields().size() > 0); assertTrue(describepipelinesResult.pipelineDescriptionList().get(0).fields() .contains(Field.builder().key("name").stringValue(PIPELINE_NAME).build())); assertTrue(describepipelinesResult.pipelineDescriptionList().get(0).fields() .contains(Field.builder().key("@id").stringValue(pipelineId).build())); assertTrue(describepipelinesResult.pipelineDescriptionList().get(0).fields() .contains(Field.builder().key("uniqueId").stringValue(PIPELINE_ID).build())); // Delete a pipeline. dataPipeline.deletePipeline(DeletePipelineRequest.builder().pipelineId(pipelineId).build()); Thread.sleep(1000 * 5); try { describepipelinesResult = dataPipeline.describePipelines(DescribePipelinesRequest.builder().pipelineIds(pipelineId).build()); if (describepipelinesResult.pipelineDescriptionList().size() > 0) { fail(); } } catch (SdkServiceException e) { // Ignored or expected. } } }
4,854
0
Create_ds/aws-sdk-java-v2/services/elasticsearch/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/elasticsearch/src/it/java/software/amazon/awssdk/services/elasticsearch/ServiceIntegrationTest.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.services.elasticsearch; import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.services.elasticsearch.model.AddTagsRequest; import software.amazon.awssdk.services.elasticsearch.model.CreateElasticsearchDomainRequest; import software.amazon.awssdk.services.elasticsearch.model.DeleteElasticsearchDomainRequest; import software.amazon.awssdk.services.elasticsearch.model.DescribeElasticsearchDomainConfigRequest; import software.amazon.awssdk.services.elasticsearch.model.DescribeElasticsearchDomainRequest; import software.amazon.awssdk.services.elasticsearch.model.DescribeElasticsearchDomainsRequest; import software.amazon.awssdk.services.elasticsearch.model.DomainInfo; import software.amazon.awssdk.services.elasticsearch.model.EBSOptions; import software.amazon.awssdk.services.elasticsearch.model.ElasticsearchDomainConfig; import software.amazon.awssdk.services.elasticsearch.model.ElasticsearchDomainStatus; import software.amazon.awssdk.services.elasticsearch.model.ListDomainNamesRequest; import software.amazon.awssdk.services.elasticsearch.model.ListTagsRequest; import software.amazon.awssdk.services.elasticsearch.model.Tag; import software.amazon.awssdk.services.elasticsearch.model.VolumeType; import software.amazon.awssdk.testutils.service.AwsTestBase; public class ServiceIntegrationTest extends AwsTestBase { private static ElasticsearchClient es; private static final String DOMAIN_NAME = "java-es-test-" + System.currentTimeMillis(); @BeforeClass public static void setup() throws IOException { setUpCredentials(); es = ElasticsearchClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } @AfterClass public static void tearDown() { es.deleteElasticsearchDomain(DeleteElasticsearchDomainRequest.builder().domainName(DOMAIN_NAME).build()); } @Test public void testOperations() { String domainArn = testCreateDomain(); testListDomainNames(); testDescribeDomain(); testDescribeDomains(); testDescribeDomainConfig(); testAddAndListTags(domainArn); } private String testCreateDomain() { ElasticsearchDomainStatus status = es.createElasticsearchDomain( CreateElasticsearchDomainRequest .builder() .ebsOptions(EBSOptions.builder() .ebsEnabled(true) .volumeSize(10) .volumeType(VolumeType.STANDARD) .build()) .domainName(DOMAIN_NAME) .build()).domainStatus(); assertEquals(DOMAIN_NAME, status.domainName()); assertValidDomainStatus(status); return status.arn(); } private void testDescribeDomain() { ElasticsearchDomainStatus status = es.describeElasticsearchDomain( DescribeElasticsearchDomainRequest.builder() .domainName(DOMAIN_NAME).build()).domainStatus(); assertEquals(DOMAIN_NAME, status.domainName()); assertValidDomainStatus(status); } private void testDescribeDomains() { ElasticsearchDomainStatus status = es .describeElasticsearchDomains( DescribeElasticsearchDomainsRequest.builder() .domainNames(DOMAIN_NAME).build()) .domainStatusList().get(0); assertEquals(DOMAIN_NAME, status.domainName()); assertValidDomainStatus(status); } private void testListDomainNames() { List<String> domainNames = toDomainNameList(es.listDomainNames( ListDomainNamesRequest.builder().build()).domainNames()); assertThat(domainNames, hasItem(DOMAIN_NAME)); } private List<String> toDomainNameList(Collection<DomainInfo> domainInfos) { List<String> names = new LinkedList<String>(); for (DomainInfo info : domainInfos) { names.add(info.domainName()); } return names; } private void testDescribeDomainConfig() { ElasticsearchDomainConfig config = es .describeElasticsearchDomainConfig( DescribeElasticsearchDomainConfigRequest.builder() .domainName(DOMAIN_NAME).build()).domainConfig(); assertValidDomainConfig(config); } private void testAddAndListTags(String arn) { Tag tag = Tag.builder().key("name").value("foo").build(); es.addTags(AddTagsRequest.builder().arn(arn).tagList(tag).build()); List<Tag> tags = es.listTags(ListTagsRequest.builder().arn(arn).build()).tagList(); assertThat(tags, hasItem(tag)); } private void assertValidDomainStatus(ElasticsearchDomainStatus status) { assertTrue(status.created()); assertNotNull(status.arn()); assertNotNull(status.accessPolicies()); assertNotNull(status.advancedOptions()); assertNotNull(status.domainId()); assertNotNull(status.ebsOptions()); assertNotNull(status.elasticsearchClusterConfig()); assertNotNull(status.snapshotOptions()); } private void assertValidDomainConfig(ElasticsearchDomainConfig config) { assertNotNull(config.accessPolicies()); assertNotNull(config.advancedOptions()); assertNotNull(config.ebsOptions()); assertNotNull(config.elasticsearchClusterConfig()); assertNotNull(config.snapshotOptions()); } }
4,855
0
Create_ds/aws-sdk-java-v2/services/codecommit/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/codecommit/src/it/java/software/amazon/awssdk/services/codecommit/AwsCodeCommitServiceIntegrationTest.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.services.codecommit; import java.io.FileNotFoundException; import java.io.IOException; import java.util.UUID; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.services.codecommit.model.CreateRepositoryRequest; import software.amazon.awssdk.services.codecommit.model.DeleteRepositoryRequest; import software.amazon.awssdk.services.codecommit.model.GetRepositoryRequest; import software.amazon.awssdk.services.codecommit.model.RepositoryDoesNotExistException; import software.amazon.awssdk.services.codecommit.model.RepositoryMetadata; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Smoke test for {@link CodeCommitClient}. */ public class AwsCodeCommitServiceIntegrationTest extends AwsTestBase { private static final String REPO_NAME = "java-sdk-test-repo-" + System.currentTimeMillis(); private static CodeCommitClient client; @BeforeClass public static void setup() throws FileNotFoundException, IOException { setUpCredentials(); client = CodeCommitClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } @AfterClass public static void cleanup() { try { client.deleteRepository(DeleteRepositoryRequest.builder() .repositoryName(REPO_NAME) .build()); } catch (Exception ignored) { System.err.println("Failed to delete repository " + ignored); } } @Test public void testOperations() { // CreateRepository client.createRepository(CreateRepositoryRequest.builder() .repositoryName(REPO_NAME) .repositoryDescription("My test repo") .build()); // GetRepository RepositoryMetadata repoMd = client.getRepository(GetRepositoryRequest.builder() .repositoryName(REPO_NAME) .build() ).repositoryMetadata(); Assert.assertEquals(REPO_NAME, repoMd.repositoryName()); assertValid_RepositoryMetadata(repoMd); // Can't perform any branch-related operations since we need to create // the first branch by pushing a commit via git. // DeleteRepository client.deleteRepository(DeleteRepositoryRequest.builder() .repositoryName(REPO_NAME) .build()); } @Test(expected = RepositoryDoesNotExistException.class) public void testExceptionHandling() { String nonExistentRepoName = UUID.randomUUID().toString(); client.getRepository(GetRepositoryRequest.builder() .repositoryName(nonExistentRepoName) .build()); } private void assertValid_RepositoryMetadata(RepositoryMetadata md) { Assert.assertNotNull(md.accountId()); Assert.assertNotNull(md.arn()); Assert.assertNotNull(md.cloneUrlHttp()); Assert.assertNotNull(md.cloneUrlSsh()); Assert.assertNotNull(md.repositoryDescription()); Assert.assertNotNull(md.repositoryId()); Assert.assertNotNull(md.repositoryName()); Assert.assertNotNull(md.creationDate()); Assert.assertNotNull(md.lastModifiedDate()); } }
4,856
0
Create_ds/aws-sdk-java-v2/services/apigateway/src/test/java/software/amazon/awssdk/services/apigateway
Create_ds/aws-sdk-java-v2/services/apigateway/src/test/java/software/amazon/awssdk/services/apigateway/internal/AcceptJsonInterceptorTest.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.services.apigateway.internal; 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.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.http.SdkHttpRequest; import java.net.URI; import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link AcceptJsonInterceptor}. */ @RunWith(MockitoJUnitRunner.class) public class AcceptJsonInterceptorTest { private static final AcceptJsonInterceptor interceptor = new AcceptJsonInterceptor(); @Mock private Context.ModifyHttpRequest ctx; @Test public void doesNotClobberExistingValue() { SdkHttpRequest request = newRequest("some-value"); Mockito.when(ctx.httpRequest()).thenReturn(request); request = interceptor.modifyHttpRequest(ctx, new ExecutionAttributes()); assertThat(request.headers().get("Accept")).containsOnly("some-value"); } @Test public void addsStandardAcceptHeaderIfMissing() { SdkHttpRequest request = newRequest(null); Mockito.when(ctx.httpRequest()).thenReturn(request); request = interceptor.modifyHttpRequest(ctx, new ExecutionAttributes()); assertThat(request.headers().get("Accept")).containsOnly("application/json"); } private SdkHttpFullRequest newRequest(String accept) { SdkHttpFullRequest.Builder builder = SdkHttpFullRequest.builder() .uri(URI.create("https://amazonaws.com")) .method(SdkHttpMethod.GET); if (accept != null) { builder.appendHeader("Accept", accept); } return builder.build(); } }
4,857
0
Create_ds/aws-sdk-java-v2/services/apigateway/src/test/java/software/amazon/awssdk/services/apigateway
Create_ds/aws-sdk-java-v2/services/apigateway/src/test/java/software/amazon/awssdk/services/apigateway/model/GetUsageRequestTest.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.services.apigateway.model; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.any; import static com.github.tomakehurst.wiremock.client.WireMock.anyRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; import com.github.tomakehurst.wiremock.junit5.WireMockTest; import java.net.URI; import java.util.concurrent.CompletionException; import org.assertj.core.api.ThrowableAssert; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.apigateway.ApiGatewayAsyncClient; import software.amazon.awssdk.services.apigateway.ApiGatewayClient; @WireMockTest class GetUsageRequestTest { private int wireMockPort; private ApiGatewayClient client; private ApiGatewayAsyncClient asyncClient; @BeforeEach void setUp(WireMockRuntimeInfo wmRuntimeInfo) { wireMockPort = wmRuntimeInfo.getHttpPort(); client = ApiGatewayClient.builder() .credentialsProvider(StaticCredentialsProvider .create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_WEST_2) .endpointOverride(URI.create("http://localhost:" + wireMockPort)) .build(); asyncClient = ApiGatewayAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider .create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_WEST_2) .endpointOverride(URI.create("http://localhost:" + wireMockPort)) .build(); } @Test void marshall_syncMissingUploadIdButValidationDisabled_ThrowsException() { stubAndRespondWith(200, ""); GetUsageRequest request = getUsageRequestWithDates(null, "20221115"); assertThatNoException().isThrownBy(() -> client.getUsage(request)); } @Test void marshall_syncEmptyStartDate_encodesAsEmptyValue() { stubAndRespondWith(200, ""); GetUsageRequest request = getUsageRequestWithDates("", "20221115"); client.getUsage(request); verify(anyRequestedFor(anyUrl()).withQueryParam("startDate", equalTo(""))); } @Test void marshall_syncNonEmptyStartDate_encodesValue() { stubAndRespondWith(200, ""); GetUsageRequest request = getUsageRequestWithDates("20221101", "20221115"); client.getUsage(request); verify(anyRequestedFor(anyUrl()).withQueryParam("startDate", equalTo("20221101"))); } @Test void marshall_asyncMissingStartDateButValidationDisabled_ThrowsException() { stubAndRespondWith(200, ""); GetUsageRequest request = getUsageRequestWithDates(null, "20221115"); assertThatNoException().isThrownBy(() -> asyncClient.getUsage(request).join()); } @Test void marshall_asyncEmptyStartDate_encodesAsEmptyValue() { stubAndRespondWith(200, ""); GetUsageRequest request = getUsageRequestWithDates("", "20221115"); asyncClient.getUsage(request).join(); verify(anyRequestedFor(anyUrl()).withQueryParam("startDate", equalTo(""))); } @Test void marshall_asyncNonEmptyStartDate_encodesValue() { stubAndRespondWith(200, ""); GetUsageRequest request = getUsageRequestWithDates("20221101", "20221115"); asyncClient.getUsage(request).join(); verify(anyRequestedFor(anyUrl()).withQueryParam("startDate", equalTo("20221101"))); } private static GetUsageRequest getUsageRequestWithDates(String startDate, String endDate) { return GetUsageRequest.builder() .usagePlanId("myUsagePlanId") .startDate(startDate) .endDate(endDate) .build(); } private static void stubAndRespondWith(int status, String body) { stubFor(any(urlMatching(".*")) .willReturn(aResponse().withStatus(status).withBody(body))); } }
4,858
0
Create_ds/aws-sdk-java-v2/services/apigateway/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/apigateway/src/it/java/software/amazon/awssdk/services/apigateway/IntegrationTestBase.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.services.apigateway; import java.io.IOException; import org.junit.BeforeClass; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.testutils.service.AwsTestBase; public class IntegrationTestBase extends AwsTestBase { protected static ApiGatewayClient apiGateway; @BeforeClass public static void setUp() throws IOException { apiGateway = ApiGatewayClient.builder().region(Region.US_EAST_1).credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).build(); } }
4,859
0
Create_ds/aws-sdk-java-v2/services/apigateway/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/apigateway/src/it/java/software/amazon/awssdk/services/apigateway/ServiceIntegrationTest.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.services.apigateway; import com.google.common.util.concurrent.RateLimiter; import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import junit.framework.Assert; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.services.apigateway.model.CreateApiKeyRequest; import software.amazon.awssdk.services.apigateway.model.CreateApiKeyResponse; import software.amazon.awssdk.services.apigateway.model.CreateResourceRequest; import software.amazon.awssdk.services.apigateway.model.CreateResourceResponse; import software.amazon.awssdk.services.apigateway.model.CreateRestApiRequest; import software.amazon.awssdk.services.apigateway.model.CreateRestApiResponse; import software.amazon.awssdk.services.apigateway.model.DeleteRestApiRequest; import software.amazon.awssdk.services.apigateway.model.GetApiKeyRequest; import software.amazon.awssdk.services.apigateway.model.GetApiKeyResponse; import software.amazon.awssdk.services.apigateway.model.GetResourceRequest; import software.amazon.awssdk.services.apigateway.model.GetResourceResponse; import software.amazon.awssdk.services.apigateway.model.GetResourcesRequest; import software.amazon.awssdk.services.apigateway.model.GetResourcesResponse; import software.amazon.awssdk.services.apigateway.model.GetRestApiRequest; import software.amazon.awssdk.services.apigateway.model.GetRestApiResponse; import software.amazon.awssdk.services.apigateway.model.IntegrationType; import software.amazon.awssdk.services.apigateway.model.NotFoundException; import software.amazon.awssdk.services.apigateway.model.Op; import software.amazon.awssdk.services.apigateway.model.PatchOperation; import software.amazon.awssdk.services.apigateway.model.PutIntegrationRequest; import software.amazon.awssdk.services.apigateway.model.PutIntegrationResponse; import software.amazon.awssdk.services.apigateway.model.PutMethodRequest; import software.amazon.awssdk.services.apigateway.model.PutMethodResponse; import software.amazon.awssdk.services.apigateway.model.Resource; import software.amazon.awssdk.services.apigateway.model.RestApi; import software.amazon.awssdk.services.apigateway.model.TooManyRequestsException; import software.amazon.awssdk.services.apigateway.model.UpdateApiKeyRequest; import software.amazon.awssdk.services.apigateway.model.UpdateResourceRequest; import software.amazon.awssdk.services.apigateway.model.UpdateRestApiRequest; import software.amazon.awssdk.utils.Lazy; import software.amazon.awssdk.utils.Logger; public class ServiceIntegrationTest extends IntegrationTestBase { private static final Logger log = Logger.loggerFor(ServiceIntegrationTest.class); private static final String NAME_PREFIX = "java-sdk-integration-"; private static final String NAME = NAME_PREFIX + System.currentTimeMillis(); private static final String DESCRIPTION = "fooDesc"; // Limit deletes to once every 31 seconds // https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html#api-gateway-control-service-limits-table private static final Lazy<RateLimiter> DELETE_RATE_LIMITER = new Lazy<>(() -> RateLimiter.create(1.0 / 31)); private static String restApiId = null; @BeforeClass public static void createRestApi() { deleteStaleRestApis(); CreateRestApiResponse createRestApiResult = apiGateway.createRestApi( CreateRestApiRequest.builder().name(NAME) .description(DESCRIPTION).build()); Assert.assertNotNull(createRestApiResult); Assert.assertNotNull(createRestApiResult.description()); Assert.assertNotNull(createRestApiResult.id()); Assert.assertNotNull(createRestApiResult.name()); Assert.assertNotNull(createRestApiResult.createdDate()); Assert.assertEquals(createRestApiResult.name(), NAME); Assert.assertEquals(createRestApiResult.description(), DESCRIPTION); restApiId = createRestApiResult.id(); } @AfterClass public static void deleteRestApiKey() { if (restApiId != null) { DELETE_RATE_LIMITER.getValue().acquire(); try { apiGateway.deleteRestApi(DeleteRestApiRequest.builder().restApiId(restApiId).build()); } catch (TooManyRequestsException e) { log.warn(() -> String.format("Failed to delete REST API %s (%s). This API should be deleted automatically in a " + "future 'deleteStaleRestApis' execution.", NAME, restApiId), e); } } } private static void deleteStaleRestApis() { Instant startTime = Instant.now(); Duration maxRunTime = Duration.ofMinutes(5); Duration maxApiAge = Duration.ofDays(7); AtomicInteger success = new AtomicInteger(); AtomicInteger failure = new AtomicInteger(); log.info(() -> String.format("Searching for stale REST APIs older than %s days...", maxApiAge.toDays())); for (RestApi api : apiGateway.getRestApisPaginator().items()) { if (Instant.now().isAfter(startTime.plus(maxRunTime))) { log.info(() -> String.format("More than %s has elapsed trying to delete stale REST APIs, giving up for this run. " + "Successfully deleted: %s. Failed to delete: %s.", maxRunTime, success.get(), failure.get())); return; } Duration apiAge = Duration.between(api.createdDate(), Instant.now()); if (api.name().startsWith(NAME_PREFIX) && apiAge.compareTo(maxApiAge) > 0) { DELETE_RATE_LIMITER.getValue().acquire(); try { apiGateway.deleteRestApi(r -> r.restApiId(api.id())); log.info(() -> String.format("Successfully deleted REST API %s (%s) which was %s days old.", api.name(), api.id(), apiAge.toDays())); success.incrementAndGet(); } catch (Exception e) { log.error(() -> String.format("Failed to delete REST API %s (%s) which is %s days old.", api.name(), api.id(), apiAge.toDays()), e); failure.incrementAndGet(); } } } log.info(() -> String.format("Finished searching for stale REST APIs. Successfully deleted: %s. Failed to delete: %s.", success.get(), failure.get())); } @Test public void testUpdateRetrieveRestApi() { PatchOperation patch = PatchOperation.builder().op(Op.REPLACE) .path("/description").value("updatedDesc").build(); apiGateway.updateRestApi(UpdateRestApiRequest.builder().restApiId(restApiId) .patchOperations(patch).build()); GetRestApiResponse getRestApiResult = apiGateway .getRestApi(GetRestApiRequest.builder().restApiId(restApiId).build()); Assert.assertNotNull(getRestApiResult); Assert.assertNotNull(getRestApiResult.description()); Assert.assertNotNull(getRestApiResult.id()); Assert.assertNotNull(getRestApiResult.name()); Assert.assertNotNull(getRestApiResult.createdDate()); Assert.assertEquals(getRestApiResult.name(), NAME); Assert.assertEquals(getRestApiResult.description(), "updatedDesc"); } @Test public void testCreateUpdateRetrieveApiKey() { CreateApiKeyResponse createApiKeyResult = apiGateway .createApiKey(CreateApiKeyRequest.builder().name(NAME) .description(DESCRIPTION).build()); Assert.assertNotNull(createApiKeyResult); Assert.assertNotNull(createApiKeyResult.description()); Assert.assertNotNull(createApiKeyResult.id()); Assert.assertNotNull(createApiKeyResult.name()); Assert.assertNotNull(createApiKeyResult.createdDate()); Assert.assertNotNull(createApiKeyResult.enabled()); Assert.assertNotNull(createApiKeyResult.lastUpdatedDate()); Assert.assertNotNull(createApiKeyResult.stageKeys()); String apiKeyId = createApiKeyResult.id(); Assert.assertEquals(createApiKeyResult.name(), NAME); Assert.assertEquals(createApiKeyResult.description(), DESCRIPTION); PatchOperation patch = PatchOperation.builder().op(Op.REPLACE) .path("/description").value("updatedDesc").build(); apiGateway.updateApiKey(UpdateApiKeyRequest.builder().apiKey(apiKeyId) .patchOperations(patch).build()); GetApiKeyResponse getApiKeyResult = apiGateway .getApiKey(GetApiKeyRequest.builder().apiKey(apiKeyId).build()); Assert.assertNotNull(getApiKeyResult); Assert.assertNotNull(getApiKeyResult.description()); Assert.assertNotNull(getApiKeyResult.id()); Assert.assertNotNull(getApiKeyResult.name()); Assert.assertNotNull(getApiKeyResult.createdDate()); Assert.assertNotNull(getApiKeyResult.enabled()); Assert.assertNotNull(getApiKeyResult.lastUpdatedDate()); Assert.assertNotNull(getApiKeyResult.stageKeys()); Assert.assertEquals(getApiKeyResult.id(), apiKeyId); Assert.assertEquals(getApiKeyResult.name(), NAME); Assert.assertEquals(getApiKeyResult.description(), "updatedDesc"); } @Test public void testResourceOperations() { GetResourcesResponse resourcesResult = apiGateway .getResources(GetResourcesRequest.builder() .restApiId(restApiId).build()); List<Resource> resources = resourcesResult.items(); Assert.assertEquals(resources.size(), 1); Resource rootResource = resources.get(0); Assert.assertNotNull(rootResource); Assert.assertEquals(rootResource.path(), "/"); String rootResourceId = rootResource.id(); CreateResourceResponse createResourceResult = apiGateway .createResource(CreateResourceRequest.builder() .restApiId(restApiId) .pathPart("fooPath") .parentId(rootResourceId).build()); Assert.assertNotNull(createResourceResult); Assert.assertNotNull(createResourceResult.id()); Assert.assertNotNull(createResourceResult.parentId()); Assert.assertNotNull(createResourceResult.path()); Assert.assertNotNull(createResourceResult.pathPart()); Assert.assertEquals(createResourceResult.pathPart(), "fooPath"); Assert.assertEquals(createResourceResult.parentId(), rootResourceId); PatchOperation patch = PatchOperation.builder().op(Op.REPLACE) .path("/pathPart").value("updatedPath").build(); apiGateway.updateResource(UpdateResourceRequest.builder() .restApiId(restApiId) .resourceId(createResourceResult.id()) .patchOperations(patch).build()); GetResourceResponse getResourceResult = apiGateway .getResource(GetResourceRequest.builder() .restApiId(restApiId) .resourceId(createResourceResult.id()).build()); Assert.assertNotNull(getResourceResult); Assert.assertNotNull(getResourceResult.id()); Assert.assertNotNull(getResourceResult.parentId()); Assert.assertNotNull(getResourceResult.path()); Assert.assertNotNull(getResourceResult.pathPart()); Assert.assertEquals(getResourceResult.pathPart(), "updatedPath"); Assert.assertEquals(getResourceResult.parentId(), rootResourceId); PutMethodResponse putMethodResult = apiGateway .putMethod(PutMethodRequest.builder().restApiId(restApiId) .resourceId(createResourceResult.id()) .authorizationType("AWS_IAM").httpMethod("PUT").build()); Assert.assertNotNull(putMethodResult); Assert.assertNotNull(putMethodResult.authorizationType()); Assert.assertNotNull(putMethodResult.apiKeyRequired()); Assert.assertNotNull(putMethodResult.httpMethod()); Assert.assertEquals(putMethodResult.authorizationType(), "AWS_IAM"); Assert.assertEquals(putMethodResult.httpMethod(), "PUT"); PutIntegrationResponse putIntegrationResult = apiGateway .putIntegration(PutIntegrationRequest.builder() .restApiId(restApiId) .resourceId(createResourceResult.id()) .httpMethod("PUT").type(IntegrationType.MOCK) .uri("http://foo.bar") .integrationHttpMethod("GET").build()); Assert.assertNotNull(putIntegrationResult); Assert.assertNotNull(putIntegrationResult.cacheNamespace()); Assert.assertNotNull(putIntegrationResult.type()); Assert.assertEquals(putIntegrationResult.type(), IntegrationType.MOCK); } @Test(expected = NotFoundException.class) public void resourceWithDotSignedCorrectly() { apiGateway.createResource(r -> r.restApiId(restApiId).pathPart("fooPath").parentId(".")); } @Test(expected = NotFoundException.class) public void resourceWithDoubleDotSignedCorrectly() { apiGateway.createResource(r -> r.restApiId(restApiId).pathPart("fooPath").parentId("..")); } @Test(expected = NotFoundException.class) public void resourceWithEncodedCharactersSignedCorrectly() { apiGateway.createResource(r -> r.restApiId(restApiId).pathPart("fooPath").parentId("foo/../bar")); } }
4,860
0
Create_ds/aws-sdk-java-v2/services/apigateway/src/main/java/software/amazon/awssdk/services/apigateway
Create_ds/aws-sdk-java-v2/services/apigateway/src/main/java/software/amazon/awssdk/services/apigateway/internal/AcceptJsonInterceptor.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.services.apigateway.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.http.SdkHttpRequest; @SdkInternalApi public final class AcceptJsonInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { // Some APIG operations marshall to the 'Accept' header to specify the // format of the document returned by the service, such as GetExport // https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-export-api.html. // See the same fix in V1: // https://github.com/aws/aws-sdk-java/blob/cd2275c07df8656033bfa9baa665354bfb17a6bf/aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/internal/AcceptJsonRequestHandler.java#L29 SdkHttpRequest httpRequest = context.httpRequest(); if (!httpRequest.firstMatchingHeader("Accept").isPresent()) { return httpRequest .toBuilder() .putHeader("Accept", "application/json") .build(); } return httpRequest; } }
4,861
0
Create_ds/aws-sdk-java-v2/services/transcribestreaming/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/transcribestreaming/src/it/java/software/amazon/awssdk/services/transcribestreaming/TestSubscription.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.services.transcribestreaming; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.transcribestreaming.model.AudioEvent; import software.amazon.awssdk.services.transcribestreaming.model.AudioStream; public class TestSubscription implements Subscription { private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1; private ExecutorService executor = Executors.newFixedThreadPool(1); private AtomicLong demand = new AtomicLong(0); private final Subscriber<? super AudioStream> subscriber; private final InputStream inputStream; public TestSubscription(Subscriber<? super AudioStream> s, InputStream inputStream) { this.subscriber = s; this.inputStream = inputStream; } @Override public void request(long n) { if (n <= 0) { subscriber.onError(new IllegalArgumentException("Demand must be positive")); } demand.getAndAdd(n); executor.submit(() -> { try { do { ByteBuffer audioBuffer = getNextEvent(); if (audioBuffer.remaining() > 0) { AudioEvent audioEvent = audioEventFromBuffer(audioBuffer); subscriber.onNext(audioEvent); } else { subscriber.onComplete(); break; } } while (demand.decrementAndGet() > 0); } catch (Exception e) { subscriber.onError(e); } }); } @Override public void cancel() { } private ByteBuffer getNextEvent() { ByteBuffer audioBuffer = null; byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES]; int len = 0; try { len = inputStream.read(audioBytes); if (len <= 0) { audioBuffer = ByteBuffer.allocate(0); } else { audioBuffer = ByteBuffer.wrap(audioBytes, 0, len); } } catch (IOException e) { throw new UncheckedIOException(e); } return audioBuffer; } private AudioEvent audioEventFromBuffer(ByteBuffer bb) { return AudioEvent.builder() .audioChunk(SdkBytes.fromByteBuffer(bb)) .build(); } }
4,862
0
Create_ds/aws-sdk-java-v2/services/transcribestreaming/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/transcribestreaming/src/it/java/software/amazon/awssdk/services/transcribestreaming/TestResponseHandlers.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.services.transcribestreaming; import static software.amazon.awssdk.core.http.HttpResponseHandler.X_AMZN_REQUEST_ID_HEADER; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.core.async.SdkPublisher; import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponse; import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponseHandler; import software.amazon.awssdk.services.transcribestreaming.model.TranscriptEvent; import software.amazon.awssdk.services.transcribestreaming.model.TranscriptResultStream; public class TestResponseHandlers { private static final Logger log = LoggerFactory.getLogger(TestResponseHandlers.class); /** * A simple consumer of events to subscribe */ public static StartStreamTranscriptionResponseHandler responseHandlerBuilder_Consumer() { return StartStreamTranscriptionResponseHandler.builder() .onResponse(r -> { String idFromHeader = r.sdkHttpResponse() .firstMatchingHeader(X_AMZN_REQUEST_ID_HEADER) .orElse(null); log.debug("Received Initial response: " + idFromHeader); }) .onError(e -> { log.error("Error message: " + e.getMessage(), e); }) .onComplete(() -> { log.debug("All records stream successfully"); }) .subscriber(event -> { // Do nothing }) .build(); } /** * A classic way by implementing the interface and using helper method in {@link SdkPublisher}. */ public static StartStreamTranscriptionResponseHandler responseHandlerBuilder_Classic() { return new StartStreamTranscriptionResponseHandler() { @Override public void responseReceived(StartStreamTranscriptionResponse response) { String idFromHeader = response.sdkHttpResponse() .firstMatchingHeader(X_AMZN_REQUEST_ID_HEADER) .orElse(null); log.debug("Received Initial response: " + idFromHeader); } @Override public void onEventStream(SdkPublisher<TranscriptResultStream> publisher) { publisher // Filter to only SubscribeToShardEvents .filter(TranscriptEvent.class) // Flat map into a publisher of just records // Using .flatMapIterable(event -> event.transcript().results()) // TODO limit is broken. After limit is reached, app fails with SdkCancellationException // instead of gracefully exiting. Limit to 1000 total records //.limit(5) // Batch records into lists of 25 .buffer(25) // Print out each record batch // You won't see any data printed as the audio files we use have no voice .subscribe(batch -> { log.debug("Record Batch - " + batch); }); } @Override public void exceptionOccurred(Throwable throwable) { log.error("Error message: " + throwable.getMessage(), throwable); } @Override public void complete() { log.debug("All records stream successfully"); } }; } }
4,863
0
Create_ds/aws-sdk-java-v2/services/transcribestreaming/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/transcribestreaming/src/it/java/software/amazon/awssdk/services/transcribestreaming/TranscribeStreamingIntegrationTest.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.services.transcribestreaming; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static software.amazon.awssdk.http.Header.CONTENT_TYPE; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.time.Duration; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.internal.util.Mimetype; import software.amazon.awssdk.core.metrics.CoreMetric; import software.amazon.awssdk.http.HttpMetric; import software.amazon.awssdk.metrics.MetricCollection; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.transcribestreaming.model.AudioStream; import software.amazon.awssdk.services.transcribestreaming.model.LanguageCode; import software.amazon.awssdk.services.transcribestreaming.model.MediaEncoding; import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionRequest; import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponseHandler; import software.amazon.awssdk.utils.Logger; /** * An example test class to show the usage of * {@link TranscribeStreamingAsyncClient#startStreamTranscription(StartStreamTranscriptionRequest, Publisher, * StartStreamTranscriptionResponseHandler)} API. * * The audio files used in this class don't have voice, so there won't be any transcripted text would be empty */ public class TranscribeStreamingIntegrationTest { private static final Logger log = Logger.loggerFor(TranscribeStreamingIntegrationTest.class); private static TranscribeStreamingAsyncClient client; private static MetricPublisher mockPublisher; @BeforeClass public static void setup() { mockPublisher = mock(MetricPublisher.class); client = TranscribeStreamingAsyncClient.builder() .region(Region.US_EAST_1) .overrideConfiguration(b -> b.addExecutionInterceptor(new VerifyHeaderInterceptor()) .addMetricPublisher(mockPublisher)) .credentialsProvider(getCredentials()) .build(); } @Test public void testFileWith16kRate() throws InterruptedException { CompletableFuture<Void> result = client.startStreamTranscription(getRequest(16_000), new AudioStreamPublisher( getInputStream("silence_16kHz_s16le.wav")), TestResponseHandlers.responseHandlerBuilder_Classic()); result.join(); verifyMetrics(); } @Test public void testFileWith8kRate() throws ExecutionException, InterruptedException { CompletableFuture<Void> result = client.startStreamTranscription(getRequest(8_000), new AudioStreamPublisher( getInputStream("silence_8kHz_s16le.wav")), TestResponseHandlers.responseHandlerBuilder_Consumer()); result.get(); } private static AwsCredentialsProvider getCredentials() { return DefaultCredentialsProvider.create(); } private StartStreamTranscriptionRequest getRequest(Integer mediaSampleRateHertz) { return StartStreamTranscriptionRequest.builder() .languageCode(LanguageCode.EN_US.toString()) .mediaEncoding(MediaEncoding.PCM) .mediaSampleRateHertz(mediaSampleRateHertz) .build(); } private InputStream getInputStream(String audioFileName) { try { File inputFile = new File(getClass().getClassLoader().getResource(audioFileName).getFile()); assertTrue(inputFile.exists()); InputStream audioStream = new FileInputStream(inputFile); return audioStream; } catch (FileNotFoundException e) { throw new RuntimeException(e); } } private class AudioStreamPublisher implements Publisher<AudioStream> { private final InputStream inputStream; private AudioStreamPublisher(InputStream inputStream) { this.inputStream = inputStream; } @Override public void subscribe(Subscriber<? super AudioStream> s) { s.onSubscribe(new TestSubscription(s, inputStream)); } } private static class VerifyHeaderInterceptor implements ExecutionInterceptor { @Override public void beforeTransmission(Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { List<String> contentTypeHeader = context.httpRequest().headers().get(CONTENT_TYPE); assertThat(contentTypeHeader.size()).isEqualTo(1); assertThat(contentTypeHeader.get(0)).isEqualTo(Mimetype.MIMETYPE_EVENT_STREAM); } } private void verifyMetrics() throws InterruptedException { // wait for 100ms for metrics to be delivered to mockPublisher Thread.sleep(100); ArgumentCaptor<MetricCollection> collectionCaptor = ArgumentCaptor.forClass(MetricCollection.class); verify(mockPublisher).publish(collectionCaptor.capture()); MetricCollection capturedCollection = collectionCaptor.getValue(); assertThat(capturedCollection.name()).isEqualTo("ApiCall"); log.info(() -> "captured collection: " + capturedCollection); assertThat(capturedCollection.metricValues(CoreMetric.CREDENTIALS_FETCH_DURATION).get(0)) .isGreaterThanOrEqualTo(Duration.ZERO); assertThat(capturedCollection.metricValues(CoreMetric.MARSHALLING_DURATION).get(0)) .isGreaterThanOrEqualTo(Duration.ZERO); assertThat(capturedCollection.metricValues(CoreMetric.API_CALL_DURATION).get(0)) .isGreaterThan(Duration.ZERO); MetricCollection attemptCollection = capturedCollection.children().get(0); assertThat(attemptCollection.name()).isEqualTo("ApiCallAttempt"); assertThat(attemptCollection.metricValues(HttpMetric.HTTP_STATUS_CODE)) .containsExactly(200); assertThat(attemptCollection.metricValues(CoreMetric.SIGNING_DURATION).get(0)) .isGreaterThanOrEqualTo(Duration.ZERO); assertThat(attemptCollection.metricValues(CoreMetric.AWS_REQUEST_ID).get(0)).isNotEmpty(); assertThat(attemptCollection.metricValues(CoreMetric.SERVICE_CALL_DURATION).get(0)) .isGreaterThanOrEqualTo(Duration.ofMillis(100)); } }
4,864
0
Create_ds/aws-sdk-java-v2/services/transcribestreaming/src/main/java/software/amazon/awssdk/services/transcribestreaming
Create_ds/aws-sdk-java-v2/services/transcribestreaming/src/main/java/software/amazon/awssdk/services/transcribestreaming/internal/DefaultHttpConfigurationOptions.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.services.transcribestreaming.internal; import java.time.Duration; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.http.SdkHttpConfigurationOption; import software.amazon.awssdk.utils.AttributeMap; @SdkInternalApi public final class DefaultHttpConfigurationOptions { private static final AttributeMap OPTIONS = AttributeMap .builder() .put(SdkHttpConfigurationOption.READ_TIMEOUT, Duration.ofSeconds(100)) .put(SdkHttpConfigurationOption.WRITE_TIMEOUT, Duration.ofSeconds(30)) .build(); private DefaultHttpConfigurationOptions() { } public static AttributeMap defaultHttpConfig() { return OPTIONS; } }
4,865
0
Create_ds/aws-sdk-java-v2/services/efs/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/efs/src/it/java/software/amazon/awssdk/services/efs/ElasticFileSystemIntegrationTest.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.services.efs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.UUID; import org.junit.After; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.efs.model.CreateFileSystemRequest; import software.amazon.awssdk.services.efs.model.DeleteFileSystemRequest; import software.amazon.awssdk.services.efs.model.DescribeFileSystemsRequest; import software.amazon.awssdk.services.efs.model.FileSystemAlreadyExistsException; import software.amazon.awssdk.services.efs.model.FileSystemNotFoundException; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; import software.amazon.awssdk.utils.StringUtils; public class ElasticFileSystemIntegrationTest extends AwsIntegrationTestBase { private static EfsClient client; private String fileSystemId; @BeforeClass public static void setupFixture() throws Exception { client = EfsClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).region(Region.US_WEST_2).build(); } @After public void tearDown() { if (!StringUtils.isEmpty(fileSystemId)) { client.deleteFileSystem(DeleteFileSystemRequest.builder().fileSystemId(fileSystemId).build()); } } @Test public void describeFileSystems_ReturnsNonNull() { assertNotNull(client.describeFileSystems(DescribeFileSystemsRequest.builder().build())); } @Test public void describeFileSystem_NonExistentFileSystem_ThrowsException() { try { client.describeFileSystems(DescribeFileSystemsRequest.builder().fileSystemId("fs-00000000").build()); } catch (FileSystemNotFoundException e) { assertEquals("FileSystemNotFound", e.errorCode()); } } /** * Tests that an exception with a member in it is serialized properly. See TT0064111680 */ @Test public void createFileSystem_WithDuplicateCreationToken_ThrowsExceptionWithFileSystemIdPresent() { String creationToken = UUID.randomUUID().toString(); this.fileSystemId = client.createFileSystem(CreateFileSystemRequest.builder().creationToken(creationToken).build()) .fileSystemId(); try { client.createFileSystem(CreateFileSystemRequest.builder().creationToken(creationToken).build()).fileSystemId(); } catch (FileSystemAlreadyExistsException e) { assertEquals(fileSystemId, e.fileSystemId()); } } }
4,866
0
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/auth/StsWebIdentityTokenCredentialProviderTest.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.services.sts.auth; import org.junit.Assert; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityRequest; import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityResponse; import software.amazon.awssdk.services.sts.model.Credentials; import java.nio.file.Paths; import java.time.Instant; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class StsWebIdentityTokenCredentialProviderTest { @Mock StsClient stsClient; private EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); @BeforeEach public void setUp() { String webIdentityTokenPath = Paths.get("src/test/resources/token.jwt").toAbsolutePath().toString(); ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_ROLE_ARN.environmentVariable(), "someRole"); ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_WEB_IDENTITY_TOKEN_FILE.environmentVariable(), webIdentityTokenPath); ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_ROLE_SESSION_NAME.environmentVariable(), "tempRoleSession"); } @AfterEach public void cleanUp(){ ENVIRONMENT_VARIABLE_HELPER.reset(); } @Test void createAssumeRoleWithWebIdentityTokenCredentialsProviderWithoutStsClient_throws_Exception() { Assert.assertThrows(NullPointerException.class, () -> StsWebIdentityTokenFileCredentialsProvider.builder().refreshRequest(r -> r.build()).build()); } @Test void createAssumeRoleWithWebIdentityTokenCredentialsProviderCreateStsClient() { StsWebIdentityTokenFileCredentialsProvider provider = StsWebIdentityTokenFileCredentialsProvider.builder().stsClient(stsClient).refreshRequest(r -> r.build()) .build(); when(stsClient.assumeRoleWithWebIdentity(Mockito.any(AssumeRoleWithWebIdentityRequest.class))) .thenReturn(AssumeRoleWithWebIdentityResponse.builder() .credentials(Credentials.builder().accessKeyId("key") .expiration(Instant.now()) .sessionToken("session").secretAccessKey("secret").build()).build()); provider.resolveCredentials(); Mockito.verify(stsClient, Mockito.times(1)).assumeRoleWithWebIdentity(Mockito.any(AssumeRoleWithWebIdentityRequest.class)); } @Test void createAssumeRoleWithWebIdentityTokenCredentialsProviderStsClientBuilder() { String webIdentityTokenPath = Paths.get("src/test/resources/token.jwt").toAbsolutePath().toString(); StsWebIdentityTokenFileCredentialsProvider provider = StsWebIdentityTokenFileCredentialsProvider.builder().stsClient(stsClient) .refreshRequest(r -> r.build()) .roleArn("someRole") .webIdentityTokenFile(Paths.get(webIdentityTokenPath)) .roleSessionName("tempRoleSession") .build(); when(stsClient.assumeRoleWithWebIdentity(Mockito.any(AssumeRoleWithWebIdentityRequest.class))) .thenReturn(AssumeRoleWithWebIdentityResponse.builder() .credentials(Credentials.builder().accessKeyId("key") .expiration(Instant.now()) .sessionToken("session").secretAccessKey("secret").build()).build()); provider.resolveCredentials(); Mockito.verify(stsClient, Mockito.times(1)).assumeRoleWithWebIdentity(Mockito.any(AssumeRoleWithWebIdentityRequest.class)); } }
4,867
0
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/auth/StsAssumeRoleCredentialsProviderTest.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.services.sts.auth; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.model.AssumeRoleRequest; import software.amazon.awssdk.services.sts.model.AssumeRoleResponse; import software.amazon.awssdk.services.sts.model.Credentials; /** * Validate the functionality of {@link StsAssumeRoleCredentialsProvider}. * Inherits tests from {@link StsCredentialsProviderTestBase}. */ public class StsAssumeRoleCredentialsProviderTest extends StsCredentialsProviderTestBase<AssumeRoleRequest, AssumeRoleResponse> { @Override protected AssumeRoleRequest getRequest() { return AssumeRoleRequest.builder().build(); } @Override protected AssumeRoleResponse getResponse(Credentials credentials) { return AssumeRoleResponse.builder().credentials(credentials).build(); } @Override protected StsAssumeRoleCredentialsProvider.Builder createCredentialsProviderBuilder(AssumeRoleRequest request) { return StsAssumeRoleCredentialsProvider.builder().refreshRequest(request); } @Override protected AssumeRoleResponse callClient(StsClient client, AssumeRoleRequest request) { return client.assumeRole(request); } }
4,868
0
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/auth/StsWebIdentityTokenCredentialsProviderBaseTest.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.services.sts.auth; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.auth.StsWebIdentityTokenFileCredentialsProvider.Builder; import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityRequest; import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityResponse; import software.amazon.awssdk.services.sts.model.Credentials; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.IoUtils; /** * Validate the functionality of {@link StsWebIdentityTokenFileCredentialsProvider}. Inherits tests from {@link * StsCredentialsProviderTestBase}. */ public class StsWebIdentityTokenCredentialsProviderBaseTest extends StsCredentialsProviderTestBase<AssumeRoleWithWebIdentityRequest, AssumeRoleWithWebIdentityResponse> { private EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); @BeforeEach public void setUp() { String webIdentityTokenPath = Paths.get("src/test/resources/token.jwt").toAbsolutePath().toString(); ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_ROLE_ARN.environmentVariable(), "someRole"); ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_WEB_IDENTITY_TOKEN_FILE.environmentVariable(), webIdentityTokenPath); ENVIRONMENT_VARIABLE_HELPER.set(SdkSystemSetting.AWS_ROLE_SESSION_NAME.environmentVariable(), "tempRoleSession"); } @AfterEach public void cleanUp(){ ENVIRONMENT_VARIABLE_HELPER.reset(); } @Override protected AssumeRoleWithWebIdentityRequest getRequest() { return AssumeRoleWithWebIdentityRequest.builder().webIdentityToken(getToken(Paths.get("src/test/resources" + "/token.jwt").toAbsolutePath())).build(); } @Override protected AssumeRoleWithWebIdentityResponse getResponse(Credentials credentials) { return AssumeRoleWithWebIdentityResponse.builder().credentials(credentials).build(); } @Override protected Builder createCredentialsProviderBuilder(AssumeRoleWithWebIdentityRequest request) { return StsWebIdentityTokenFileCredentialsProvider.builder().stsClient(stsClient).refreshRequest(request); } @Override protected AssumeRoleWithWebIdentityResponse callClient(StsClient client, AssumeRoleWithWebIdentityRequest request) { return client.assumeRoleWithWebIdentity(request); } private String getToken(Path file) { try (InputStream webIdentityTokenStream = Files.newInputStream(file)) { return IoUtils.toUtf8String(webIdentityTokenStream); } catch (IOException e) { throw new UncheckedIOException(e); } } }
4,869
0
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/auth/StsAssumeRoleWithSamlCredentialsProviderTest.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.services.sts.auth; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.auth.StsAssumeRoleWithSamlCredentialsProvider.Builder; import software.amazon.awssdk.services.sts.model.AssumeRoleWithSamlRequest; import software.amazon.awssdk.services.sts.model.AssumeRoleWithSamlResponse; import software.amazon.awssdk.services.sts.model.Credentials; /** * Validate the functionality of {@link StsAssumeRoleWithSamlCredentialsProvider}. * Inherits tests from {@link StsCredentialsProviderTestBase}. */ public class StsAssumeRoleWithSamlCredentialsProviderTest extends StsCredentialsProviderTestBase<AssumeRoleWithSamlRequest, AssumeRoleWithSamlResponse> { @Override protected AssumeRoleWithSamlRequest getRequest() { return AssumeRoleWithSamlRequest.builder().build(); } @Override protected AssumeRoleWithSamlResponse getResponse(Credentials credentials) { return AssumeRoleWithSamlResponse.builder().credentials(credentials).build(); } @Override protected Builder createCredentialsProviderBuilder(AssumeRoleWithSamlRequest request) { return StsAssumeRoleWithSamlCredentialsProvider.builder().refreshRequest(request); } @Override protected AssumeRoleWithSamlResponse callClient(StsClient client, AssumeRoleWithSamlRequest request) { return client.assumeRoleWithSAML(request); } }
4,870
0
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/auth/StsGetFederationTokenCredentialsProviderTest.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.services.sts.auth; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.auth.StsGetFederationTokenCredentialsProvider.Builder; import software.amazon.awssdk.services.sts.model.Credentials; import software.amazon.awssdk.services.sts.model.GetFederationTokenRequest; import software.amazon.awssdk.services.sts.model.GetFederationTokenResponse; /** * Validate the functionality of {@link StsGetFederationTokenCredentialsProvider}. * Inherits tests from {@link StsCredentialsProviderTestBase}. */ public class StsGetFederationTokenCredentialsProviderTest extends StsCredentialsProviderTestBase<GetFederationTokenRequest, GetFederationTokenResponse> { @Override protected GetFederationTokenRequest getRequest() { return GetFederationTokenRequest.builder().build(); } @Override protected GetFederationTokenResponse getResponse(Credentials credentials) { return GetFederationTokenResponse.builder().credentials(credentials).build(); } @Override protected Builder createCredentialsProviderBuilder(GetFederationTokenRequest request) { return StsGetFederationTokenCredentialsProvider.builder().refreshRequest(request); } @Override protected GetFederationTokenResponse callClient(StsClient client, GetFederationTokenRequest request) { return client.getFederationToken(request); } }
4,871
0
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/auth/StsGetSessionTokenCredentialsProviderTest.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.services.sts.auth; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.auth.StsGetSessionTokenCredentialsProvider.Builder; import software.amazon.awssdk.services.sts.model.Credentials; import software.amazon.awssdk.services.sts.model.GetSessionTokenRequest; import software.amazon.awssdk.services.sts.model.GetSessionTokenResponse; /** * Validate the functionality of {@link StsGetSessionTokenCredentialsProvider}. * Inherits tests from {@link StsCredentialsProviderTestBase}. */ public class StsGetSessionTokenCredentialsProviderTest extends StsCredentialsProviderTestBase<GetSessionTokenRequest, GetSessionTokenResponse> { @Override protected GetSessionTokenRequest getRequest() { return GetSessionTokenRequest.builder().build(); } @Override protected GetSessionTokenResponse getResponse(Credentials credentials) { return GetSessionTokenResponse.builder().credentials(credentials).build(); } @Override protected Builder createCredentialsProviderBuilder(GetSessionTokenRequest request) { return StsGetSessionTokenCredentialsProvider.builder().refreshRequest(request); } @Override protected GetSessionTokenResponse callClient(StsClient client, GetSessionTokenRequest request) { return client.getSessionToken(request); } }
4,872
0
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/auth/StsCredentialsProviderTestBase.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.services.sts.auth; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.nio.file.Paths; import java.time.Duration; import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.model.Credentials; /** * Validates the functionality of {@link StsCredentialsProvider} and its subclasses. */ @ExtendWith(MockitoExtension.class) public abstract class StsCredentialsProviderTestBase<RequestT, ResponseT> { @Mock protected StsClient stsClient; @Test public void cachingDoesNotApplyToExpiredSession() { callClientWithCredentialsProvider(Instant.now().minus(Duration.ofSeconds(5)), 2, false); callClient(verify(stsClient, times(2)), Mockito.any()); } @Test public void cachingDoesNotApplyToExpiredSession_OverridePrefetchAndStaleTimes() { callClientWithCredentialsProvider(Instant.now().minus(Duration.ofSeconds(5)), 2, true); callClient(verify(stsClient, times(2)), Mockito.any()); } @Test public void cachingAppliesToNonExpiredSession() { callClientWithCredentialsProvider(Instant.now().plus(Duration.ofHours(5)), 2, false); callClient(verify(stsClient, times(1)), Mockito.any()); } @Test public void cachingAppliesToNonExpiredSession_OverridePrefetchAndStaleTimes() { callClientWithCredentialsProvider(Instant.now().plus(Duration.ofHours(5)), 2, true); callClient(verify(stsClient, times(1)), Mockito.any()); } @Test public void distantExpiringCredentialsUpdatedInBackground() throws InterruptedException { callClientWithCredentialsProvider(Instant.now().plusSeconds(90), 2, false); Instant endCheckTime = Instant.now().plus(Duration.ofSeconds(5)); while (Mockito.mockingDetails(stsClient).getInvocations().size() < 2 && endCheckTime.isAfter(Instant.now())) { Thread.sleep(100); } callClient(verify(stsClient, times(2)), Mockito.any()); } @Test public void distantExpiringCredentialsUpdatedInBackground_OverridePrefetchAndStaleTimes() throws InterruptedException { callClientWithCredentialsProvider(Instant.now().plusSeconds(90), 2, true); Instant endCheckTime = Instant.now().plus(Duration.ofSeconds(5)); while (Mockito.mockingDetails(stsClient).getInvocations().size() < 2 && endCheckTime.isAfter(Instant.now())) { Thread.sleep(100); } callClient(verify(stsClient, times(2)), Mockito.any()); } protected abstract RequestT getRequest(); protected abstract ResponseT getResponse(Credentials credentials); protected abstract StsCredentialsProvider.BaseBuilder<?, ? extends StsCredentialsProvider> createCredentialsProviderBuilder(RequestT request); protected abstract ResponseT callClient(StsClient client, RequestT request); public void callClientWithCredentialsProvider(Instant credentialsExpirationDate, int numTimesInvokeCredentialsProvider, boolean overrideStaleAndPrefetchTimes) { Credentials credentials = Credentials.builder().accessKeyId("a").secretAccessKey("b").sessionToken("c").expiration(credentialsExpirationDate).build(); RequestT request = getRequest(); ResponseT response = getResponse(credentials); when(callClient(stsClient, request)).thenReturn(response); StsCredentialsProvider.BaseBuilder<?, ? extends StsCredentialsProvider> credentialsProviderBuilder = createCredentialsProviderBuilder(request); if(overrideStaleAndPrefetchTimes) { //do the same values as we would do without overriding the stale and prefetch times credentialsProviderBuilder.staleTime(Duration.ofMinutes(2)); credentialsProviderBuilder.prefetchTime(Duration.ofMinutes(4)); } try (StsCredentialsProvider credentialsProvider = credentialsProviderBuilder.stsClient(stsClient).build()) { if(overrideStaleAndPrefetchTimes) { //validate that we actually stored the override values in the build provider assertThat(credentialsProvider.staleTime()).as("stale time").isEqualTo(Duration.ofMinutes(2)); assertThat(credentialsProvider.prefetchTime()).as("prefetch time").isEqualTo(Duration.ofMinutes(4)); } else { //validate that the default values are used assertThat(credentialsProvider.staleTime()).as("stale time").isEqualTo(Duration.ofMinutes(1)); assertThat(credentialsProvider.prefetchTime()).as("prefetch time").isEqualTo(Duration.ofMinutes(5)); } for (int i = 0; i < numTimesInvokeCredentialsProvider; ++i) { AwsSessionCredentials providedCredentials = (AwsSessionCredentials) credentialsProvider.resolveCredentials(); assertThat(providedCredentials.accessKeyId()).isEqualTo("a"); assertThat(providedCredentials.secretAccessKey()).isEqualTo("b"); assertThat(providedCredentials.sessionToken()).isEqualTo("c"); } } } }
4,873
0
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/auth/StsAssumeRoleWithWebIdentityCredentialsProviderTest.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.services.sts.auth; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.auth.StsAssumeRoleWithWebIdentityCredentialsProvider.Builder; import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityRequest; import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityResponse; import software.amazon.awssdk.services.sts.model.Credentials; /** * Validate the functionality of {@link StsAssumeRoleWithWebIdentityCredentialsProvider}. * Inherits tests from {@link StsCredentialsProviderTestBase}. */ public class StsAssumeRoleWithWebIdentityCredentialsProviderTest extends StsCredentialsProviderTestBase<AssumeRoleWithWebIdentityRequest, AssumeRoleWithWebIdentityResponse> { @Override protected AssumeRoleWithWebIdentityRequest getRequest() { return AssumeRoleWithWebIdentityRequest.builder().build(); } @Override protected AssumeRoleWithWebIdentityResponse getResponse(Credentials credentials) { return AssumeRoleWithWebIdentityResponse.builder().credentials(credentials).build(); } @Override protected Builder createCredentialsProviderBuilder(AssumeRoleWithWebIdentityRequest request) { return StsAssumeRoleWithWebIdentityCredentialsProvider.builder().refreshRequest(request); } @Override protected AssumeRoleWithWebIdentityResponse callClient(StsClient client, AssumeRoleWithWebIdentityRequest request) { return client.assumeRoleWithWebIdentity(request); } }
4,874
0
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/internal/StsWebIdentityCredentialsProviderFactoryTest.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.services.sts.internal; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.nio.file.Paths; import java.time.Duration; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.WebIdentityTokenCredentialsProviderFactory; import software.amazon.awssdk.auth.credentials.internal.WebIdentityCredentialsUtils; import software.amazon.awssdk.auth.credentials.internal.WebIdentityTokenCredentialProperties; class StsWebIdentityCredentialsProviderFactoryTest { @Test void stsWebIdentityCredentialsProviderFactory_with_webIdentityCredentialsUtils() { WebIdentityTokenCredentialsProviderFactory factory = WebIdentityCredentialsUtils.factory(); assertNotNull(factory); } @Test void stsWebIdentityCredentialsProviderFactory_withWebIdentityTokenCredentialProperties() { WebIdentityTokenCredentialsProviderFactory factory = new StsWebIdentityCredentialsProviderFactory(); AwsCredentialsProvider provider = factory.create( WebIdentityTokenCredentialProperties.builder() .asyncCredentialUpdateEnabled(true) .prefetchTime(Duration.ofMinutes(5)) .staleTime(Duration.ofMinutes(15)) .roleArn("role-arn") .webIdentityTokenFile(Paths.get("/path/to/file")) .roleSessionName("session-name") .roleSessionDuration(Duration.ofMinutes(60)) .build()); assertNotNull(provider); } }
4,875
0
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/internal/AssumeRoleProfileTest.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.services.sts.internal; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import software.amazon.awssdk.auth.credentials.internal.ProfileCredentialsUtils; import software.amazon.awssdk.utils.StringInputStream; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.services.sts.AssumeRoleIntegrationTest; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * Verify some basic functionality of {@link StsProfileCredentialsProviderFactory} via the way customers will encounter it: * the {@link ProfileFile}. The full functionality is verified via * {@link AssumeRoleIntegrationTest#profileCredentialsProviderCanAssumeRoles()}. */ public class AssumeRoleProfileTest { @Test public void createAssumeRoleCredentialsProviderViaProfileSucceeds() { String profileContent = "[profile source]\n" + "aws_access_key_id=defaultAccessKey\n" + "aws_secret_access_key=defaultSecretAccessKey\n" + "\n" + "[profile test]\n" + "source_profile=source\n" + "role_arn=arn:aws:iam::123456789012:role/testRole"; ProfileFile profiles = ProfileFile.builder() .content(new StringInputStream(profileContent)) .type(ProfileFile.Type.CONFIGURATION) .build(); assertThat(profiles.profile("test")).hasValueSatisfying(profile -> { assertThat(new ProfileCredentialsUtils(profiles, profile, profiles::profile).credentialsProvider()).hasValueSatisfying(credentialsProvider -> { assertThat(credentialsProvider).isInstanceOf(SdkAutoCloseable.class); ((SdkAutoCloseable) credentialsProvider).close(); }); }); } @Test public void assumeRoleOutOfOrderDefinitionSucceeds() { String profileContent = "[profile child]\n" + "source_profile=parent\n" + "role_arn=arn:aws:iam::123456789012:role/testRole\n" + "[profile source]\n" + "aws_access_key_id=defaultAccessKey\n" + "aws_secret_access_key=defaultSecretAccessKey\n" + "[profile parent]\n" + "source_profile=source\n" + "role_arn=arn:aws:iam::123456789012:role/testRole"; ProfileFile profiles = ProfileFile.builder() .content(new StringInputStream(profileContent)) .type(ProfileFile.Type.CONFIGURATION) .build(); assertThat(profiles.profile("child")).isPresent(); } }
4,876
0
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/test/java/software/amazon/awssdk/services/sts/internal/WebIdentityTokenCredentialProviderTest.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.services.sts.internal; import static org.assertj.core.api.Assertions.assertThat; import java.nio.file.Paths; import org.junit.jupiter.api.Test; import software.amazon.awssdk.auth.credentials.internal.ProfileCredentialsUtils; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.utils.SdkAutoCloseable; import software.amazon.awssdk.utils.StringInputStream; public class WebIdentityTokenCredentialProviderTest { @Test public void createAssumeRoleWithWebIdentityTokenCredentialsProviderViaProfileSucceeds() { String webIdentityTokenPath = Paths.get("/src/test/token.jwt").toAbsolutePath().toString(); String profileContent = "[profile test]\n" + "web_identity_token_file="+ webIdentityTokenPath +"\n" + "role_arn=arn:aws:iam::123456789012:role/testRole"; ProfileFile profiles = ProfileFile.builder() .content(new StringInputStream(profileContent)) .type(ProfileFile.Type.CONFIGURATION) .build(); assertThat(profiles.profile("test")).hasValueSatisfying(profile -> { assertThat(new ProfileCredentialsUtils(profiles, profile, profiles::profile).credentialsProvider()).hasValueSatisfying(credentialsProvider -> { assertThat(credentialsProvider).isInstanceOf(SdkAutoCloseable.class); assertThat(credentialsProvider).hasFieldOrProperty("stsClient"); ((SdkAutoCloseable) credentialsProvider).close(); }); }); } }
4,877
0
Create_ds/aws-sdk-java-v2/services/sts/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sts/src/it/java/software/amazon/awssdk/services/sts/IntegrationTestBase.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.services.sts; import java.io.FileNotFoundException; import java.io.IOException; import org.junit.BeforeClass; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.testutils.service.AwsTestBase; /** * Base class for all STS integration tests. Loads AWS credentials from a * properties file on disk, provides helper methods for tests, and instantiates * the STS client object for all tests to use. */ public abstract class IntegrationTestBase extends AwsTestBase { /** The shared STS client for all tests to use. */ protected static StsClient sts; @BeforeClass public static void setUp() throws FileNotFoundException, IOException { setUpCredentials(); sts = StsClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(Region.US_EAST_1) .build(); } }
4,878
0
Create_ds/aws-sdk-java-v2/services/sts/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sts/src/it/java/software/amazon/awssdk/services/sts/SecurityTokenServiceIntegrationTest.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.services.sts; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.core.SdkGlobalTime; import software.amazon.awssdk.services.sts.model.GetFederationTokenRequest; import software.amazon.awssdk.services.sts.model.GetFederationTokenResponse; import software.amazon.awssdk.services.sts.model.GetSessionTokenRequest; import software.amazon.awssdk.services.sts.model.GetSessionTokenResponse; import software.amazon.awssdk.utils.Logger; public class SecurityTokenServiceIntegrationTest extends IntegrationTestBase { private static final Logger log = Logger.loggerFor(SecurityTokenServiceIntegrationTest.class); private static final int SESSION_DURATION = 60 * 60; /** Tests that we can call GetSession to start a session. */ @Test public void testGetSessionToken() throws Exception { if (CREDENTIALS_PROVIDER_CHAIN.resolveCredentials() instanceof AwsSessionCredentials) { log.warn(() -> "testGetSessionToken() skipped due to the current credentials being session credentials. " + "Session credentials cannot be used to get other session tokens."); return; } GetSessionTokenRequest request = GetSessionTokenRequest.builder().durationSeconds(SESSION_DURATION).build(); GetSessionTokenResponse result = sts.getSessionToken(request); assertNotNull(result.credentials().accessKeyId()); assertNotNull(result.credentials().expiration()); assertNotNull(result.credentials().secretAccessKey()); assertNotNull(result.credentials().sessionToken()); } /** Tests that we can call GetFederatedSession to start a federated session. */ @Test public void testGetFederatedSessionToken() throws Exception { if (CREDENTIALS_PROVIDER_CHAIN.resolveCredentials() instanceof AwsSessionCredentials) { log.warn(() -> "testGetFederatedSessionToken() skipped due to the current credentials being session credentials. " + "Session credentials cannot be used to get federation tokens."); return; } GetFederationTokenRequest request = GetFederationTokenRequest.builder() .durationSeconds(SESSION_DURATION) .name("Name").build(); GetFederationTokenResponse result = sts.getFederationToken(request); assertNotNull(result.credentials().accessKeyId()); assertNotNull(result.credentials().expiration()); assertNotNull(result.credentials().secretAccessKey()); assertNotNull(result.credentials().sessionToken()); assertNotNull(result.federatedUser().arn()); assertNotNull(result.federatedUser().federatedUserId()); } }
4,879
0
Create_ds/aws-sdk-java-v2/services/sts/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sts/src/it/java/software/amazon/awssdk/services/sts/AssumeRoleIntegrationTest.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.services.sts; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNotNull; import java.time.Duration; import java.util.Comparator; import java.util.Optional; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.auth.credentials.internal.ProfileCredentialsUtils; import software.amazon.awssdk.core.auth.policy.Action; import software.amazon.awssdk.core.auth.policy.Policy; import software.amazon.awssdk.core.auth.policy.Principal; import software.amazon.awssdk.core.auth.policy.Resource; import software.amazon.awssdk.core.auth.policy.Statement; import software.amazon.awssdk.core.auth.policy.Statement.Effect; import software.amazon.awssdk.profiles.Profile; import software.amazon.awssdk.profiles.ProfileFile; import software.amazon.awssdk.services.iam.model.AccessKeyMetadata; import software.amazon.awssdk.services.iam.model.CreateAccessKeyResponse; import software.amazon.awssdk.services.iam.model.EntityAlreadyExistsException; import software.amazon.awssdk.services.iam.model.MalformedPolicyDocumentException; import software.amazon.awssdk.services.sts.model.AssumeRoleRequest; import software.amazon.awssdk.services.sts.model.AssumeRoleResponse; import software.amazon.awssdk.services.sts.model.StsException; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.testutils.Waiter; import software.amazon.awssdk.utils.SdkAutoCloseable; import software.amazon.awssdk.utils.StringInputStream; //TODO This could be useful to cleanup and present as a customer sample public class AssumeRoleIntegrationTest extends IntegrationTestBaseWithIAM { private static final int SESSION_DURATION = 60 * 60; private static final String USER_NAME = "assume-role-integration-test-user"; private static final String USER_ARN_FORMAT = "arn:aws:iam::%s:user/" + USER_NAME; private static String USER_ARN; private static final String POLICY_NAME = "AssumeRoleIntegrationTestPolicy"; private static final String POLICY_ARN_FORMAT = "arn:aws:iam::%s:policy/" + POLICY_NAME; private static final String ROLE_NAME = "assume-role-integration-test-role"; private static final String ROLE_ARN_FORMAT = "arn:aws:iam::%s:role/" + ROLE_NAME; private static String ROLE_ARN; private static final String ASSUME_ROLE = "sts:AssumeRole"; private static AwsCredentials userCredentials; @BeforeClass public static void setup() { String accountId = sts.getCallerIdentity().account(); USER_ARN = String.format(USER_ARN_FORMAT, accountId); ROLE_ARN = String.format(ROLE_ARN_FORMAT, accountId); // Create a user try { iam.createUser(r -> r.userName(USER_NAME)); } catch (EntityAlreadyExistsException e) { // Test user already exists - awesome. } // Create a managed policy that allows the user to assume a role try { iam.createPolicy(r -> r.policyName("AssumeRoleIntegrationTestPolicy") .policyDocument(new Policy().withStatements(new Statement(Effect.Allow) .withActions(new Action(ASSUME_ROLE)) .withResources(new Resource("*"))) .toJson())); } catch (EntityAlreadyExistsException e) { // Policy already exists - awesome. } // Attach the policy to the user (if it isn't already attached) iam.attachUserPolicy(r -> r.userName(USER_NAME).policyArn(String.format(POLICY_ARN_FORMAT, accountId))); // Try to create a role that can be assumed by the user, until the eventual consistency catches up. try { String rolePolicyDoc = new Policy() .withStatements(new Statement(Effect.Allow) .withPrincipals(new Principal("AWS", USER_ARN, false)) .withActions(new Action(ASSUME_ROLE))) .toJson(); Waiter.run(() -> iam.createRole(r -> r.roleName(ROLE_NAME) .assumeRolePolicyDocument(rolePolicyDoc))) .ignoringException(MalformedPolicyDocumentException.class) .orFailAfter(Duration.ofMinutes(2)); } catch (EntityAlreadyExistsException e) { // Role already exists - awesome. } // Delete the oldest credentials for the user. We don't want to hit our limit. iam.listAccessKeysPaginator(r -> r.userName(USER_NAME)) .accessKeyMetadata().stream() .min(Comparator.comparing(AccessKeyMetadata::createDate)) .ifPresent(key -> iam.deleteAccessKey(r -> r.userName(USER_NAME).accessKeyId(key.accessKeyId()))); // Create new credentials for the user CreateAccessKeyResponse createAccessKeyResult = iam.createAccessKey(r -> r.userName(USER_NAME)); userCredentials = AwsBasicCredentials.create(createAccessKeyResult.accessKey().accessKeyId(), createAccessKeyResult.accessKey().secretAccessKey()); // Try to assume the role to make sure we won't hit issues during testing. StsClient userCredentialSts = StsClient.builder() .credentialsProvider(() -> userCredentials) .build(); Waiter.run(() -> userCredentialSts.assumeRole(r -> r.durationSeconds(SESSION_DURATION) .roleArn(ROLE_ARN) .roleSessionName("Test"))) .ignoringException(StsException.class) .orFailAfter(Duration.ofMinutes(5)); } /** Tests that we can call assumeRole successfully. */ @Test public void testAssumeRole() throws InterruptedException { AssumeRoleRequest assumeRoleRequest = AssumeRoleRequest.builder() .durationSeconds(SESSION_DURATION) .roleArn(ROLE_ARN) .roleSessionName("Name") .build(); StsClient sts = StsClient.builder().credentialsProvider(StaticCredentialsProvider.create(userCredentials)).build(); AssumeRoleResponse assumeRoleResult = sts.assumeRole(assumeRoleRequest); assertNotNull(assumeRoleResult.assumedRoleUser()); assertNotNull(assumeRoleResult.assumedRoleUser().arn()); assertNotNull(assumeRoleResult.assumedRoleUser().assumedRoleId()); assertNotNull(assumeRoleResult.credentials()); } @Test public void profileCredentialsProviderCanAssumeRoles() throws InterruptedException { String ASSUME_ROLE_PROFILE = "[source]\n" + "aws_access_key_id = " + userCredentials.accessKeyId() + "\n" + "aws_secret_access_key = " + userCredentials.secretAccessKey() + "\n" + "\n" + "[test]\n" + "region = us-west-1\n" + "source_profile = source\n" + "role_arn = " + ROLE_ARN; ProfileFile profiles = ProfileFile.builder() .content(new StringInputStream(ASSUME_ROLE_PROFILE)) .type(ProfileFile.Type.CREDENTIALS) .build(); Optional<Profile> profile = profiles.profile("test"); AwsCredentialsProvider awsCredentialsProvider = new ProfileCredentialsUtils(profiles, profile.get(), profiles::profile).credentialsProvider().get(); // Try to assume the role until the eventual consistency catches up. AwsCredentials awsCredentials = Waiter.run(awsCredentialsProvider::resolveCredentials) .ignoringException(StsException.class) .orFail(); assertThat(awsCredentials.accessKeyId()).isNotBlank(); assertThat(awsCredentials.secretAccessKey()).isNotBlank(); ((SdkAutoCloseable) awsCredentialsProvider).close(); } @Test public void profileCredentialProviderCanAssumeRolesWithEnvironmentCredentialSource() throws InterruptedException { EnvironmentVariableHelper.run(helper -> { helper.set("AWS_ACCESS_KEY_ID", userCredentials.accessKeyId()); helper.set("AWS_SECRET_ACCESS_KEY", userCredentials.secretAccessKey()); helper.remove("AWS_SESSION_TOKEN"); String ASSUME_ROLE_PROFILE = "[test]\n" + "region = us-west-1\n" + "credential_source = Environment\n" + "role_arn = " + ROLE_ARN; ProfileFile profiles = ProfileFile.builder() .content(new StringInputStream(ASSUME_ROLE_PROFILE)) .type(ProfileFile.Type.CREDENTIALS) .build(); Optional<Profile> profile = profiles.profile("test"); AwsCredentialsProvider awsCredentialsProvider = new ProfileCredentialsUtils(profiles, profile.get(), profiles::profile).credentialsProvider().get(); // Try to assume the role until the eventual consistency catches up. AwsCredentials awsCredentials = Waiter.run(awsCredentialsProvider::resolveCredentials) .ignoringException(StsException.class) .orFail(); assertThat(awsCredentials.accessKeyId()).isNotBlank(); assertThat(awsCredentials.secretAccessKey()).isNotBlank(); ((SdkAutoCloseable) awsCredentialsProvider).close(); }); } @Test public void profileCredentialProviderWithEnvironmentCredentialSourceAndSystemProperties() throws InterruptedException { System.setProperty("aws.accessKeyId", userCredentials.accessKeyId()); System.setProperty("aws.secretAccessKey", userCredentials.secretAccessKey()); try { EnvironmentVariableHelper.run(helper -> { helper.remove("AWS_ACCESS_KEY_ID"); helper.remove("AWS_SECRET_ACCESS_KEY"); helper.remove("AWS_SESSION_TOKEN"); String ASSUME_ROLE_PROFILE = "[test]\n" + "region = us-west-1\n" + "credential_source = Environment\n" + "role_arn = " + ROLE_ARN; ProfileFile profiles = ProfileFile.builder() .content(new StringInputStream(ASSUME_ROLE_PROFILE)) .type(ProfileFile.Type.CREDENTIALS) .build(); Optional<Profile> profile = profiles.profile("test"); AwsCredentialsProvider awsCredentialsProvider = new ProfileCredentialsUtils(profiles, profile.get(), profiles::profile).credentialsProvider().get(); // Try to assume the role until the eventual consistency catches up. AwsCredentials awsCredentials = Waiter.run(awsCredentialsProvider::resolveCredentials) .ignoringException(StsException.class) .orFail(); assertThat(awsCredentials.accessKeyId()).isNotBlank(); assertThat(awsCredentials.secretAccessKey()).isNotBlank(); ((SdkAutoCloseable) awsCredentialsProvider).close(); }); } finally { System.clearProperty("aws.accessKeyId"); System.clearProperty("aws.secretAccessKey"); } } }
4,880
0
Create_ds/aws-sdk-java-v2/services/sts/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/sts/src/it/java/software/amazon/awssdk/services/sts/IntegrationTestBaseWithIAM.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.services.sts; import java.io.FileNotFoundException; import java.io.IOException; import org.junit.BeforeClass; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iam.IamClient; /** * Base class for all STS integration tests that also need IAM */ public abstract class IntegrationTestBaseWithIAM extends IntegrationTestBase { /** The shared IAM client for all tests to use. */ protected static IamClient iam; @BeforeClass public static void setUp() throws FileNotFoundException, IOException { IntegrationTestBase.setUp(); iam = IamClient.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(Region.AWS_GLOBAL) .build(); } }
4,881
0
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/auth/StsWebIdentityTokenFileCredentialsProvider.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.services.sts.auth; import static software.amazon.awssdk.services.sts.internal.StsAuthUtils.toAwsSessionCredentials; import static software.amazon.awssdk.utils.StringUtils.trim; import static software.amazon.awssdk.utils.Validate.notNull; import java.nio.file.Path; import java.nio.file.Paths; import java.util.function.Consumer; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.auth.credentials.internal.WebIdentityTokenCredentialProperties; import software.amazon.awssdk.core.SdkSystemSetting; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.internal.AssumeRoleWithWebIdentityRequestSupplier; import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityRequest; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An implementation of {@link AwsCredentialsProvider} that periodically sends an {@link AssumeRoleWithWebIdentityRequest} to the * AWS Security Token Service to maintain short-lived sessions to use for authentication. These sessions are updated using a * single calling thread (by default) or asynchronously (if {@link Builder#asyncCredentialUpdateEnabled(Boolean)} is set). * * Unlike {@link StsAssumeRoleWithWebIdentityCredentialsProvider}, this reads the web identity information, including AWS role * ARN, AWS session name and the location of a web identity token file from system properties and environment variables. The * web identity token file is expected to contain the web identity token to use with each request. * * If the credentials are not successfully updated before expiration, calls to {@link #resolveCredentials()} will block until * they are updated successfully. * * Users of this provider must {@link #close()} it when they are finished using it. * * This is created using {@link #builder()}. */ @SdkPublicApi public final class StsWebIdentityTokenFileCredentialsProvider extends StsCredentialsProvider implements ToCopyableBuilder<StsWebIdentityTokenFileCredentialsProvider.Builder, StsWebIdentityTokenFileCredentialsProvider> { private final AwsCredentialsProvider credentialsProvider; private final RuntimeException loadException; private final Supplier<AssumeRoleWithWebIdentityRequest> assumeRoleWithWebIdentityRequest; private final Path webIdentityTokenFile; private final String roleArn; private final String roleSessionName; private final Supplier<AssumeRoleWithWebIdentityRequest> assumeRoleWithWebIdentityRequestFromBuilder; private StsWebIdentityTokenFileCredentialsProvider(Builder builder) { super(builder, "sts-assume-role-with-web-identity-credentials-provider"); Path webIdentityTokenFile = builder.webIdentityTokenFile != null ? builder.webIdentityTokenFile : Paths.get(trim(SdkSystemSetting.AWS_WEB_IDENTITY_TOKEN_FILE .getStringValueOrThrow())); String roleArn = builder.roleArn != null ? builder.roleArn : trim(SdkSystemSetting.AWS_ROLE_ARN.getStringValueOrThrow()); String sessionName = builder.roleSessionName != null ? builder.roleSessionName : SdkSystemSetting.AWS_ROLE_SESSION_NAME.getStringValue() .orElse("aws-sdk-java-" + System.currentTimeMillis()); WebIdentityTokenCredentialProperties credentialProperties = WebIdentityTokenCredentialProperties.builder() .roleArn(roleArn) .roleSessionName(builder.roleSessionName) .webIdentityTokenFile(webIdentityTokenFile) .build(); this.assumeRoleWithWebIdentityRequest = builder.assumeRoleWithWebIdentityRequestSupplier != null ? builder.assumeRoleWithWebIdentityRequestSupplier : () -> AssumeRoleWithWebIdentityRequest.builder() .roleArn(credentialProperties.roleArn()) .roleSessionName(sessionName) .build(); AwsCredentialsProvider credentialsProviderLocal = null; RuntimeException loadExceptionLocal = null; try { AssumeRoleWithWebIdentityRequestSupplier supplier = AssumeRoleWithWebIdentityRequestSupplier.builder() .assumeRoleWithWebIdentityRequest(assumeRoleWithWebIdentityRequest.get()) .webIdentityTokenFile(credentialProperties.webIdentityTokenFile()) .build(); credentialsProviderLocal = StsAssumeRoleWithWebIdentityCredentialsProvider.builder() .stsClient(builder.stsClient) .refreshRequest(supplier) .build(); } catch (RuntimeException e) { // If we couldn't load the credentials provider for some reason, save an exception describing why. This exception // will only be raised on calls to getCredentials. We don't want to raise an exception here because it may be // expected (eg. in the default credential chain). loadExceptionLocal = e; } this.loadException = loadExceptionLocal; this.credentialsProvider = credentialsProviderLocal; this.webIdentityTokenFile = builder.webIdentityTokenFile; this.roleArn = builder.roleArn; this.roleSessionName = builder.roleSessionName; this.assumeRoleWithWebIdentityRequestFromBuilder = builder.assumeRoleWithWebIdentityRequestSupplier; } public static Builder builder() { return new Builder(); } @Override public AwsCredentials resolveCredentials() { if (loadException != null) { throw loadException; } return credentialsProvider.resolveCredentials(); } @Override public String toString() { return ToString.create("StsWebIdentityTokenFileCredentialsProvider"); } @Override protected AwsSessionCredentials getUpdatedCredentials(StsClient stsClient) { AssumeRoleWithWebIdentityRequest request = assumeRoleWithWebIdentityRequest.get(); notNull(request, "AssumeRoleWithWebIdentityRequest can't be null"); return toAwsSessionCredentials(stsClient.assumeRoleWithWebIdentity(request).credentials()); } @Override public Builder toBuilder() { return new Builder(this); } public static final class Builder extends BaseBuilder<Builder, StsWebIdentityTokenFileCredentialsProvider> { private String roleArn; private String roleSessionName; private Path webIdentityTokenFile; private Supplier<AssumeRoleWithWebIdentityRequest> assumeRoleWithWebIdentityRequestSupplier; private StsClient stsClient; private Builder() { super(StsWebIdentityTokenFileCredentialsProvider::new); } private Builder(StsWebIdentityTokenFileCredentialsProvider provider) { super(StsWebIdentityTokenFileCredentialsProvider::new); this.roleArn = provider.roleArn; this.roleSessionName = provider.roleSessionName; this.webIdentityTokenFile = provider.webIdentityTokenFile; this.assumeRoleWithWebIdentityRequestSupplier = provider.assumeRoleWithWebIdentityRequestFromBuilder; this.stsClient = provider.stsClient; } /** * The Custom {@link StsClient} that will be used to fetch AWS service credentials. * <ul> * <li>This SDK client must be closed by the caller when it is ready to be disposed.</li> * <li>This SDK client's retry policy should handle IdpCommunicationErrorException </li> * </ul> * @param stsClient The STS client to use for communication with STS. * Make sure IdpCommunicationErrorException is retried in the retry policy for this client. * Make sure the custom STS client is closed when it is ready to be disposed. * @return Returns a reference to this object so that method calls can be chained together. */ @Override public Builder stsClient(StsClient stsClient) { this.stsClient = stsClient; return super.stsClient(stsClient); } /** * <p> * The Amazon Resource Name (ARN) of the IAM role that is associated with the Sts. * If not provided this will be read from SdkSystemSetting.AWS_ROLE_ARN. * </p> * * @param roleArn The Amazon Resource Name (ARN) of the IAM role that is associated with the Sts cluster. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder roleArn(String roleArn) { this.roleArn = roleArn; return this; } /** * <p> * Sets Amazon Resource Name (ARN) of the IAM role that is associated with the Sts. * By default this will be read from SdkSystemSetting.AWS_ROLE_ARN. * </p> * * @param roleArn The Amazon Resource Name (ARN) of the IAM role that is associated with the Sts cluster. */ public void setRoleArn(String roleArn) { roleArn(roleArn); } /** * <p> * Sets the role session name that should be used by this credentials provider. * By default this is read from SdkSystemSetting.AWS_ROLE_SESSION_NAME * </p> * * @param roleSessionName role session name that should be used by this credentials provider * @return Returns a reference to this object so that method calls can be chained together. */ public Builder roleSessionName(String roleSessionName) { this.roleSessionName = roleSessionName; return this; } /** * <p> * Sets the role session name that should be used by this credentials provider. * By default this is read from SdkSystemSetting.AWS_ROLE_SESSION_NAME * </p> * * @param roleSessionName role session name that should be used by this credentials provider. */ public void setRoleSessionName(String roleSessionName) { roleSessionName(roleSessionName); } /** * <p> * Sets the absolute path to the web identity token file that should be used by this credentials provider. * By default this will be read from SdkSystemSetting.AWS_WEB_IDENTITY_TOKEN_FILE. * </p> * * @param webIdentityTokenFile absolute path to the web identity token file that should be used by this credentials * provider. * @return Returns a reference to this object so that method calls can be chained together. */ public Builder webIdentityTokenFile(Path webIdentityTokenFile) { this.webIdentityTokenFile = webIdentityTokenFile; return this; } public void setWebIdentityTokenFile(Path webIdentityTokenFile) { webIdentityTokenFile(webIdentityTokenFile); } /** * Configure the {@link AssumeRoleWithWebIdentityRequest} that should be periodically sent to the STS service to update * the session token when it gets close to expiring. * * @param assumeRoleWithWebIdentityRequest The request to send to STS whenever the assumed session expires. * @return This object for chained calls. */ public Builder refreshRequest(AssumeRoleWithWebIdentityRequest assumeRoleWithWebIdentityRequest) { return refreshRequest(() -> assumeRoleWithWebIdentityRequest); } /** * Similar to {@link #refreshRequest(AssumeRoleWithWebIdentityRequest)}, but takes a {@link Supplier} to supply the * request to STS. * * @param assumeRoleWithWebIdentityRequestSupplier A supplier * @return This object for chained calls. */ public Builder refreshRequest(Supplier<AssumeRoleWithWebIdentityRequest> assumeRoleWithWebIdentityRequestSupplier) { this.assumeRoleWithWebIdentityRequestSupplier = assumeRoleWithWebIdentityRequestSupplier; return this; } /** * Similar to {@link #refreshRequest(AssumeRoleWithWebIdentityRequest)}, but takes a lambda to configure a new {@link * AssumeRoleWithWebIdentityRequest.Builder}. This removes the need to call {@link * AssumeRoleWithWebIdentityRequest#builder()} and {@link AssumeRoleWithWebIdentityRequest.Builder#build()}. */ public Builder refreshRequest(Consumer<AssumeRoleWithWebIdentityRequest.Builder> assumeRoleWithWebIdentityRequest) { return refreshRequest(AssumeRoleWithWebIdentityRequest.builder().applyMutation(assumeRoleWithWebIdentityRequest) .build()); } @Override public StsWebIdentityTokenFileCredentialsProvider build() { return new StsWebIdentityTokenFileCredentialsProvider(this); } } }
4,882
0
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/auth/StsAssumeRoleWithWebIdentityCredentialsProvider.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.services.sts.auth; import static software.amazon.awssdk.services.sts.internal.StsAuthUtils.toAwsSessionCredentials; import static software.amazon.awssdk.utils.Validate.notNull; import java.util.function.Consumer; import java.util.function.Supplier; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityRequest; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An implementation of {@link AwsCredentialsProvider} that periodically sends an {@link AssumeRoleWithWebIdentityRequest} to the * AWS Security Token Service to maintain short-lived sessions to use for authentication. These sessions are updated using a * single calling thread (by default) or asynchronously (if {@link Builder#asyncCredentialUpdateEnabled(Boolean)} is set). * * If the credentials are not successfully updated before expiration, calls to {@link #resolveCredentials()} will block until * they are updated successfully. * * Users of this provider must {@link #close()} it when they are finished using it. * * This is created using {@link #builder()}. */ @SdkPublicApi @ThreadSafe public final class StsAssumeRoleWithWebIdentityCredentialsProvider extends StsCredentialsProvider implements ToCopyableBuilder<StsAssumeRoleWithWebIdentityCredentialsProvider.Builder, StsAssumeRoleWithWebIdentityCredentialsProvider> { private final Supplier<AssumeRoleWithWebIdentityRequest> assumeRoleWithWebIdentityRequest; /** * @see #builder() */ private StsAssumeRoleWithWebIdentityCredentialsProvider(Builder builder) { super(builder, "sts-assume-role-with-web-identity-credentials-provider"); notNull(builder.assumeRoleWithWebIdentityRequestSupplier, "Assume role with web identity request must not be null."); this.assumeRoleWithWebIdentityRequest = builder.assumeRoleWithWebIdentityRequestSupplier; } /** * Create a builder for an {@link StsAssumeRoleWithWebIdentityCredentialsProvider}. */ public static Builder builder() { return new Builder(); } @Override protected AwsSessionCredentials getUpdatedCredentials(StsClient stsClient) { AssumeRoleWithWebIdentityRequest request = assumeRoleWithWebIdentityRequest.get(); notNull(request, "AssumeRoleWithWebIdentityRequest can't be null"); return toAwsSessionCredentials(stsClient.assumeRoleWithWebIdentity(request).credentials()); } @Override public String toString() { return ToString.create("StsAssumeRoleWithWebIdentityCredentialsProvider"); } @Override public Builder toBuilder() { return new Builder(this); } /** * A builder (created by {@link StsAssumeRoleWithWebIdentityCredentialsProvider#builder()}) for creating a * {@link StsAssumeRoleWithWebIdentityCredentialsProvider}. */ @NotThreadSafe public static final class Builder extends BaseBuilder<Builder, StsAssumeRoleWithWebIdentityCredentialsProvider> { private Supplier<AssumeRoleWithWebIdentityRequest> assumeRoleWithWebIdentityRequestSupplier; private Builder() { super(StsAssumeRoleWithWebIdentityCredentialsProvider::new); } public Builder(StsAssumeRoleWithWebIdentityCredentialsProvider provider) { super(StsAssumeRoleWithWebIdentityCredentialsProvider::new, provider); this.assumeRoleWithWebIdentityRequestSupplier = provider.assumeRoleWithWebIdentityRequest; } /** * Configure the {@link AssumeRoleWithWebIdentityRequest} that should be periodically sent to the STS service to update * the session token when it gets close to expiring. * * @param assumeRoleWithWebIdentityRequest The request to send to STS whenever the assumed session expires. * @return This object for chained calls. */ public Builder refreshRequest(AssumeRoleWithWebIdentityRequest assumeRoleWithWebIdentityRequest) { return refreshRequest(() -> assumeRoleWithWebIdentityRequest); } /** * Similar to {@link #refreshRequest(AssumeRoleWithWebIdentityRequest)}, but takes a {@link Supplier} to supply the * request to STS. * * @param assumeRoleWithWebIdentityRequest A supplier * @return This object for chained calls. */ public Builder refreshRequest(Supplier<AssumeRoleWithWebIdentityRequest> assumeRoleWithWebIdentityRequest) { this.assumeRoleWithWebIdentityRequestSupplier = assumeRoleWithWebIdentityRequest; return this; } /** * Similar to {@link #refreshRequest(AssumeRoleWithWebIdentityRequest)}, but takes a lambda to configure a new * {@link AssumeRoleWithWebIdentityRequest.Builder}. This removes the need to called * {@link AssumeRoleWithWebIdentityRequest#builder()} and {@link AssumeRoleWithWebIdentityRequest.Builder#build()}. */ public Builder refreshRequest(Consumer<AssumeRoleWithWebIdentityRequest.Builder> assumeRoleWithWebIdentityRequest) { return refreshRequest(AssumeRoleWithWebIdentityRequest.builder().applyMutation(assumeRoleWithWebIdentityRequest) .build()); } @Override public StsAssumeRoleWithWebIdentityCredentialsProvider build() { return super.build(); } } }
4,883
0
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/auth/StsGetSessionTokenCredentialsProvider.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.services.sts.auth; import static software.amazon.awssdk.services.sts.internal.StsAuthUtils.toAwsSessionCredentials; import java.util.function.Consumer; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.model.GetSessionTokenRequest; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An implementation of {@link AwsCredentialsProvider} that periodically sends a {@link GetSessionTokenRequest} to the AWS * Security Token Service to maintain short-lived sessions to use for authentication. These sessions are updated using a single * calling thread (by default) or asynchronously (if {@link Builder#asyncCredentialUpdateEnabled(Boolean)} is set). * * If the credentials are not successfully updated before expiration, calls to {@link #resolveCredentials()} will block until * they are updated successfully. * * Users of this provider must {@link #close()} it when they are finished using it. * * This is created using {@link #builder()}. */ @SdkPublicApi @ThreadSafe public class StsGetSessionTokenCredentialsProvider extends StsCredentialsProvider implements ToCopyableBuilder<StsGetSessionTokenCredentialsProvider.Builder, StsGetSessionTokenCredentialsProvider> { private final GetSessionTokenRequest getSessionTokenRequest; /** * @see #builder() */ private StsGetSessionTokenCredentialsProvider(Builder builder) { super(builder, "sts-get-token-credentials-provider"); Validate.notNull(builder.getSessionTokenRequest, "Get session token request must not be null."); this.getSessionTokenRequest = builder.getSessionTokenRequest; } /** * Create a builder for an {@link StsGetSessionTokenCredentialsProvider}. */ public static Builder builder() { return new Builder(); } @Override protected AwsSessionCredentials getUpdatedCredentials(StsClient stsClient) { return toAwsSessionCredentials(stsClient.getSessionToken(getSessionTokenRequest).credentials()); } @Override public String toString() { return ToString.create("StsGetSessionTokenCredentialsProvider"); } @Override public Builder toBuilder() { return new Builder(this); } /** * A builder (created by {@link StsGetSessionTokenCredentialsProvider#builder()}) for creating a * {@link StsGetSessionTokenCredentialsProvider}. */ @NotThreadSafe public static final class Builder extends BaseBuilder<Builder, StsGetSessionTokenCredentialsProvider> { private GetSessionTokenRequest getSessionTokenRequest = GetSessionTokenRequest.builder().build(); private Builder() { super(StsGetSessionTokenCredentialsProvider::new); } public Builder(StsGetSessionTokenCredentialsProvider provider) { super(StsGetSessionTokenCredentialsProvider::new, provider); this.getSessionTokenRequest = provider.getSessionTokenRequest; } /** * Configure the {@link GetSessionTokenRequest} that should be periodically sent to the STS service to update the session * token when it gets close to expiring. * * If this is not specified, default values are used. * * @param getSessionTokenRequest The request to send to STS whenever the assumed session expires. * @return This object for chained calls. */ public Builder refreshRequest(GetSessionTokenRequest getSessionTokenRequest) { this.getSessionTokenRequest = getSessionTokenRequest; return this; } /** * Similar to {@link #refreshRequest(GetSessionTokenRequest)}, but takes a lambda to configure a new * {@link GetSessionTokenRequest.Builder}. This removes the need to called * {@link GetSessionTokenRequest#builder()} and {@link GetSessionTokenRequest.Builder#build()}. */ public Builder refreshRequest(Consumer<GetSessionTokenRequest.Builder> getFederationTokenRequest) { return refreshRequest(GetSessionTokenRequest.builder().applyMutation(getFederationTokenRequest).build()); } @Override public StsGetSessionTokenCredentialsProvider build() { return super.build(); } } }
4,884
0
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/auth/StsGetFederationTokenCredentialsProvider.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.services.sts.auth; import static software.amazon.awssdk.services.sts.internal.StsAuthUtils.toAwsSessionCredentials; import java.util.function.Consumer; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.model.GetFederationTokenRequest; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An implementation of {@link AwsCredentialsProvider} that periodically sends a {@link GetFederationTokenRequest} to the AWS * Security Token Service to maintain short-lived sessions to use for authentication. These sessions are updated using a single * calling thread (by default) or asynchronously (if {@link Builder#asyncCredentialUpdateEnabled(Boolean)} is set). * * If the credentials are not successfully updated before expiration, calls to {@link #resolveCredentials()} will block until * they are updated successfully. * * Users of this provider must {@link #close()} it when they are finished using it. * * This is created using {@link #builder()}. */ @SdkPublicApi @ThreadSafe public class StsGetFederationTokenCredentialsProvider extends StsCredentialsProvider implements ToCopyableBuilder<StsGetFederationTokenCredentialsProvider.Builder, StsGetFederationTokenCredentialsProvider> { private final GetFederationTokenRequest getFederationTokenRequest; /** * @see #builder() */ private StsGetFederationTokenCredentialsProvider(Builder builder) { super(builder, "sts-get-federation-token-credentials-provider"); Validate.notNull(builder.getFederationTokenRequest, "Get session token request must not be null."); this.getFederationTokenRequest = builder.getFederationTokenRequest; } /** * Create a builder for an {@link StsGetFederationTokenCredentialsProvider}. */ public static Builder builder() { return new Builder(); } @Override protected AwsSessionCredentials getUpdatedCredentials(StsClient stsClient) { return toAwsSessionCredentials(stsClient.getFederationToken(getFederationTokenRequest).credentials()); } @Override public String toString() { return ToString.create("StsGetFederationTokenCredentialsProvider"); } @Override public Builder toBuilder() { return new Builder(this); } /** * A builder (created by {@link StsGetFederationTokenCredentialsProvider#builder()}) for creating a * {@link StsGetFederationTokenCredentialsProvider}. */ @NotThreadSafe public static final class Builder extends BaseBuilder<Builder, StsGetFederationTokenCredentialsProvider> { private GetFederationTokenRequest getFederationTokenRequest; private Builder() { super(StsGetFederationTokenCredentialsProvider::new); } public Builder(StsGetFederationTokenCredentialsProvider provider) { super(StsGetFederationTokenCredentialsProvider::new, provider); this.getFederationTokenRequest = provider.getFederationTokenRequest; } /** * Configure the {@link GetFederationTokenRequest} that should be periodically sent to the STS service to update the * session token when it gets close to expiring. * * @param getFederationTokenRequest The request to send to STS whenever the assumed session expires. * @return This object for chained calls. */ public Builder refreshRequest(GetFederationTokenRequest getFederationTokenRequest) { this.getFederationTokenRequest = getFederationTokenRequest; return this; } /** * Similar to {@link #refreshRequest(GetFederationTokenRequest)}, but takes a lambda to configure a new * {@link GetFederationTokenRequest.Builder}. This removes the need to called * {@link GetFederationTokenRequest#builder()} and {@link GetFederationTokenRequest.Builder#build()}. */ public Builder refreshRequest(Consumer<GetFederationTokenRequest.Builder> getFederationTokenRequest) { return refreshRequest(GetFederationTokenRequest.builder().applyMutation(getFederationTokenRequest).build()); } @Override public StsGetFederationTokenCredentialsProvider build() { return super.build(); } } }
4,885
0
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/auth/StsAssumeRoleCredentialsProvider.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.services.sts.auth; import static software.amazon.awssdk.services.sts.internal.StsAuthUtils.toAwsSessionCredentials; import java.util.function.Consumer; import java.util.function.Supplier; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.model.AssumeRoleRequest; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An implementation of {@link AwsCredentialsProvider} that periodically sends an {@link AssumeRoleRequest} to the AWS * Security Token Service to maintain short-lived sessions to use for authentication. These sessions are updated using a single * calling thread (by default) or asynchronously (if {@link Builder#asyncCredentialUpdateEnabled(Boolean)} is set). * * If the credentials are not successfully updated before expiration, calls to {@link #resolveCredentials()} will block until * they are updated successfully. * * Users of this provider must {@link #close()} it when they are finished using it. * * This is created using {@link StsAssumeRoleCredentialsProvider#builder()}. */ @SdkPublicApi @ThreadSafe public final class StsAssumeRoleCredentialsProvider extends StsCredentialsProvider implements ToCopyableBuilder<StsAssumeRoleCredentialsProvider.Builder, StsAssumeRoleCredentialsProvider> { private Supplier<AssumeRoleRequest> assumeRoleRequestSupplier; /** * @see #builder() */ private StsAssumeRoleCredentialsProvider(Builder builder) { super(builder, "sts-assume-role-credentials-provider"); Validate.notNull(builder.assumeRoleRequestSupplier, "Assume role request must not be null."); this.assumeRoleRequestSupplier = builder.assumeRoleRequestSupplier; } /** * Create a builder for an {@link StsAssumeRoleCredentialsProvider}. */ public static Builder builder() { return new Builder(); } @Override protected AwsSessionCredentials getUpdatedCredentials(StsClient stsClient) { AssumeRoleRequest assumeRoleRequest = assumeRoleRequestSupplier.get(); Validate.notNull(assumeRoleRequest, "Assume role request must not be null."); return toAwsSessionCredentials(stsClient.assumeRole(assumeRoleRequest).credentials()); } @Override public String toString() { return ToString.create("StsAssumeRoleCredentialsProvider"); } @Override public Builder toBuilder() { return new Builder(this); } /** * A builder (created by {@link StsAssumeRoleCredentialsProvider#builder()}) for creating a * {@link StsAssumeRoleCredentialsProvider}. */ @NotThreadSafe public static final class Builder extends BaseBuilder<Builder, StsAssumeRoleCredentialsProvider> { private Supplier<AssumeRoleRequest> assumeRoleRequestSupplier; private Builder() { super(StsAssumeRoleCredentialsProvider::new); } private Builder(StsAssumeRoleCredentialsProvider provider) { super(StsAssumeRoleCredentialsProvider::new, provider); this.assumeRoleRequestSupplier = provider.assumeRoleRequestSupplier; } /** * Configure the {@link AssumeRoleRequest} that should be periodically sent to the STS service to update the assumed * credentials. * * @param assumeRoleRequest The request to send to STS whenever the assumed session expires. * @return This object for chained calls. */ public Builder refreshRequest(AssumeRoleRequest assumeRoleRequest) { return refreshRequest(() -> assumeRoleRequest); } /** * Similar to {@link #refreshRequest(AssumeRoleRequest)}, but takes a {@link Supplier} to supply the request to * STS. * * @param assumeRoleRequestSupplier A supplier * @return This object for chained calls. */ public Builder refreshRequest(Supplier<AssumeRoleRequest> assumeRoleRequestSupplier) { this.assumeRoleRequestSupplier = assumeRoleRequestSupplier; return this; } /** * Similar to {@link #refreshRequest(AssumeRoleRequest)}, but takes a lambda to configure a new * {@link AssumeRoleRequest.Builder}. This removes the need to called {@link AssumeRoleRequest#builder()} and * {@link AssumeRoleRequest.Builder#build()}. */ public Builder refreshRequest(Consumer<AssumeRoleRequest.Builder> assumeRoleRequest) { return refreshRequest(AssumeRoleRequest.builder().applyMutation(assumeRoleRequest).build()); } @Override public StsAssumeRoleCredentialsProvider build() { return super.build(); } } }
4,886
0
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/auth/StsCredentialsProvider.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.services.sts.auth; import java.time.Duration; import java.time.Instant; import java.util.Optional; import java.util.function.Function; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.SdkAutoCloseable; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; import software.amazon.awssdk.utils.cache.CachedSupplier; import software.amazon.awssdk.utils.cache.NonBlocking; import software.amazon.awssdk.utils.cache.RefreshResult; /** * An implementation of {@link AwsCredentialsProvider} that is extended within this package to provide support for periodically- * updating session credentials. * * When credentials get close to expiration, this class will attempt to update them automatically either with a single calling * thread (by default) or asynchronously (if {@link #asyncCredentialUpdateEnabled} is true). If the credentials expire, this * class will block all calls to {@link #resolveCredentials()} until the credentials are updated. * * Users of this provider must {@link #close()} it when they are finished using it. */ @ThreadSafe @SdkPublicApi public abstract class StsCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { private static final Logger log = Logger.loggerFor(StsCredentialsProvider.class); private static final Duration DEFAULT_STALE_TIME = Duration.ofMinutes(1); private static final Duration DEFAULT_PREFETCH_TIME = Duration.ofMinutes(5); /** * The STS client that should be used for periodically updating the session credentials. */ final StsClient stsClient; /** * The session cache that handles automatically updating the credentials when they get close to expiring. */ private final CachedSupplier<AwsSessionCredentials> sessionCache; private final Duration staleTime; private final Duration prefetchTime; private final Boolean asyncCredentialUpdateEnabled; StsCredentialsProvider(BaseBuilder<?, ?> builder, String asyncThreadName) { this.stsClient = Validate.notNull(builder.stsClient, "STS client must not be null."); this.staleTime = Optional.ofNullable(builder.staleTime).orElse(DEFAULT_STALE_TIME); this.prefetchTime = Optional.ofNullable(builder.prefetchTime).orElse(DEFAULT_PREFETCH_TIME); this.asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled; CachedSupplier.Builder<AwsSessionCredentials> cacheBuilder = CachedSupplier.builder(this::updateSessionCredentials) .cachedValueName(toString()); if (builder.asyncCredentialUpdateEnabled) { cacheBuilder.prefetchStrategy(new NonBlocking(asyncThreadName)); } this.sessionCache = cacheBuilder.build(); } /** * Update the expiring session credentials by calling STS. Invoked by {@link CachedSupplier} when the credentials * are close to expiring. */ private RefreshResult<AwsSessionCredentials> updateSessionCredentials() { AwsSessionCredentials credentials = getUpdatedCredentials(stsClient); Instant actualTokenExpiration = credentials.expirationTime() .orElseThrow(() -> new IllegalStateException("Sourced credentials have no expiration value")); return RefreshResult.builder(credentials) .staleTime(actualTokenExpiration.minus(staleTime)) .prefetchTime(actualTokenExpiration.minus(prefetchTime)) .build(); } @Override public AwsCredentials resolveCredentials() { AwsSessionCredentials credentials = sessionCache.get(); credentials.expirationTime().ifPresent(t -> { log.debug(() -> "Using STS credentials with expiration time of " + t); }); return credentials; } @Override public void close() { sessionCache.close(); } /** * The amount of time, relative to STS token expiration, that the cached credentials are considered stale and * should no longer be used. All threads will block until the value is updated. */ public Duration staleTime() { return staleTime; } /** * The amount of time, relative to STS token expiration, that the cached credentials are considered close to stale * and should be updated. */ public Duration prefetchTime() { return prefetchTime; } /** * Implemented by a child class to call STS and get a new set of credentials to be used by this provider. */ abstract AwsSessionCredentials getUpdatedCredentials(StsClient stsClient); /** * Extended by child class's builders to share configuration across credential providers. */ @NotThreadSafe @SdkPublicApi public abstract static class BaseBuilder<B extends BaseBuilder<B, T>, T extends ToCopyableBuilder<B, T>> implements CopyableBuilder<B, T> { private final Function<B, T> providerConstructor; private Boolean asyncCredentialUpdateEnabled = false; private StsClient stsClient; private Duration staleTime; private Duration prefetchTime; BaseBuilder(Function<B, T> providerConstructor) { this.providerConstructor = providerConstructor; } BaseBuilder(Function<B, T> providerConstructor, StsCredentialsProvider provider) { this.providerConstructor = providerConstructor; this.asyncCredentialUpdateEnabled = provider.asyncCredentialUpdateEnabled; this.stsClient = provider.stsClient; this.staleTime = provider.staleTime; this.prefetchTime = provider.prefetchTime; } /** * Configure the {@link StsClient} to use when calling STS to update the session. This client should not be shut * down as long as this credentials provider is in use. * * @param stsClient The STS client to use for communication with STS. * @return This object for chained calls. */ @SuppressWarnings("unchecked") public B stsClient(StsClient stsClient) { this.stsClient = stsClient; return (B) this; } /** * Configure whether the provider should fetch credentials asynchronously in the background. If this is true, * threads are less likely to block when credentials are loaded, but additional resources are used to maintain * the provider. * * <p>By default, this is disabled.</p> */ @SuppressWarnings("unchecked") public B asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) { this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled; return (B) this; } /** * Configure the amount of time, relative to STS token expiration, that the cached credentials are considered * stale and must be updated. All threads will block until the value is updated. * * <p>By default, this is 1 minute.</p> */ @SuppressWarnings("unchecked") public B staleTime(Duration staleTime) { this.staleTime = staleTime; return (B) this; } /** * Configure the amount of time, relative to STS token expiration, that the cached credentials are considered * close to stale and should be updated. * * Prefetch updates will occur between the specified time and the stale time of the provider. Prefetch updates may be * asynchronous. See {@link #asyncCredentialUpdateEnabled}. * * <p>By default, this is 5 minutes.</p> */ @SuppressWarnings("unchecked") public B prefetchTime(Duration prefetchTime) { this.prefetchTime = prefetchTime; return (B) this; } /** * Build the credentials provider using the configuration applied to this builder. */ @SuppressWarnings("unchecked") public T build() { return providerConstructor.apply((B) this); } } }
4,887
0
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/auth/StsAssumeRoleWithSamlCredentialsProvider.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.services.sts.auth; import static software.amazon.awssdk.services.sts.internal.StsAuthUtils.toAwsSessionCredentials; import java.util.function.Consumer; import java.util.function.Supplier; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkPublicApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.model.AssumeRoleWithSamlRequest; import software.amazon.awssdk.utils.ToString; import software.amazon.awssdk.utils.Validate; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * An implementation of {@link AwsCredentialsProvider} that periodically sends an {@link AssumeRoleWithSamlRequest} to the AWS * Security Token Service to maintain short-lived sessions to use for authentication. These sessions are updated using a single * calling thread (by default) or asynchronously (if {@link Builder#asyncCredentialUpdateEnabled(Boolean)} is set). * * If the credentials are not successfully updated before expiration, calls to {@link #resolveCredentials()} will block until * they are updated successfully. * * Users of this provider must {@link #close()} it when they are finished using it. * * This is created using {@link StsAssumeRoleWithSamlCredentialsProvider#builder()}. */ @SdkPublicApi @ThreadSafe public final class StsAssumeRoleWithSamlCredentialsProvider extends StsCredentialsProvider implements ToCopyableBuilder<StsAssumeRoleWithSamlCredentialsProvider.Builder, StsAssumeRoleWithSamlCredentialsProvider> { private final Supplier<AssumeRoleWithSamlRequest> assumeRoleWithSamlRequestSupplier; /** * @see #builder() */ private StsAssumeRoleWithSamlCredentialsProvider(Builder builder) { super(builder, "sts-assume-role-with-saml-credentials-provider"); Validate.notNull(builder.assumeRoleWithSamlRequestSupplier, "Assume role with SAML request must not be null."); this.assumeRoleWithSamlRequestSupplier = builder.assumeRoleWithSamlRequestSupplier; } /** * Create a builder for an {@link StsAssumeRoleWithSamlCredentialsProvider}. */ public static Builder builder() { return new Builder(); } @Override protected AwsSessionCredentials getUpdatedCredentials(StsClient stsClient) { AssumeRoleWithSamlRequest assumeRoleWithSamlRequest = assumeRoleWithSamlRequestSupplier.get(); Validate.notNull(assumeRoleWithSamlRequest, "Assume role with saml request must not be null."); return toAwsSessionCredentials(stsClient.assumeRoleWithSAML(assumeRoleWithSamlRequest).credentials()); } @Override public String toString() { return ToString.create("StsAssumeRoleWithSamlCredentialsProvider"); } @Override public Builder toBuilder() { return new Builder(this); } /** * A builder (created by {@link StsAssumeRoleWithSamlCredentialsProvider#builder()}) for creating a * {@link StsAssumeRoleWithSamlCredentialsProvider}. */ @NotThreadSafe public static final class Builder extends BaseBuilder<Builder, StsAssumeRoleWithSamlCredentialsProvider> { private Supplier<AssumeRoleWithSamlRequest> assumeRoleWithSamlRequestSupplier; private Builder() { super(StsAssumeRoleWithSamlCredentialsProvider::new); } public Builder(StsAssumeRoleWithSamlCredentialsProvider provider) { super(StsAssumeRoleWithSamlCredentialsProvider::new, provider); this.assumeRoleWithSamlRequestSupplier = provider.assumeRoleWithSamlRequestSupplier; } /** * Configure the {@link AssumeRoleWithSamlRequest} that should be periodically sent to the STS service to update * the session token when it gets close to expiring. * * @param assumeRoleWithSamlRequest The request to send to STS whenever the assumed session expires. * @return This object for chained calls. */ public Builder refreshRequest(AssumeRoleWithSamlRequest assumeRoleWithSamlRequest) { return refreshRequest(() -> assumeRoleWithSamlRequest); } /** * Similar to {@link #refreshRequest(AssumeRoleWithSamlRequest)}, but takes a {@link Supplier} to supply the request to * STS. * * @param assumeRoleWithSamlRequestSupplier A supplier * @return This object for chained calls. */ public Builder refreshRequest(Supplier<AssumeRoleWithSamlRequest> assumeRoleWithSamlRequestSupplier) { this.assumeRoleWithSamlRequestSupplier = assumeRoleWithSamlRequestSupplier; return this; } /** * Similar to {@link #refreshRequest(AssumeRoleWithSamlRequest)}, but takes a lambda to configure a new * {@link AssumeRoleWithSamlRequest.Builder}. This removes the need to called {@link AssumeRoleWithSamlRequest#builder()} * and {@link AssumeRoleWithSamlRequest.Builder#build()}. */ public Builder refreshRequest(Consumer<AssumeRoleWithSamlRequest.Builder> assumeRoleWithSamlRequest) { return refreshRequest(AssumeRoleWithSamlRequest.builder().applyMutation(assumeRoleWithSamlRequest).build()); } @Override public StsAssumeRoleWithSamlCredentialsProvider build() { return super.build(); } } }
4,888
0
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/internal/StsAuthUtils.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.services.sts.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.services.sts.model.Credentials; @SdkInternalApi public final class StsAuthUtils { private StsAuthUtils() { } public static AwsSessionCredentials toAwsSessionCredentials(Credentials credentials) { return AwsSessionCredentials.builder() .accessKeyId(credentials.accessKeyId()) .secretAccessKey(credentials.secretAccessKey()) .sessionToken(credentials.sessionToken()) .expirationTime(credentials.expiration()) .build(); } }
4,889
0
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/internal/StsWebIdentityCredentialsProviderFactory.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.services.sts.internal; import java.net.URI; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.WebIdentityTokenCredentialsProviderFactory; import software.amazon.awssdk.auth.credentials.internal.WebIdentityTokenCredentialProperties; import software.amazon.awssdk.core.retry.conditions.OrRetryCondition; import software.amazon.awssdk.core.retry.conditions.RetryCondition; import software.amazon.awssdk.profiles.Profile; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.StsClientBuilder; import software.amazon.awssdk.services.sts.auth.StsAssumeRoleWithWebIdentityCredentialsProvider; import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityRequest; import software.amazon.awssdk.services.sts.model.IdpCommunicationErrorException; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.NumericUtils; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * An implementation of {@link WebIdentityTokenCredentialsProviderFactory} that allows users to assume a role using a web identity * token file specified in either a {@link Profile} or environment variables. */ @SdkProtectedApi public final class StsWebIdentityCredentialsProviderFactory implements WebIdentityTokenCredentialsProviderFactory { @Override public AwsCredentialsProvider create(WebIdentityTokenCredentialProperties credentialProperties) { return new StsWebIdentityCredentialsProvider(credentialProperties); } /** * A wrapper for a {@link StsAssumeRoleWithWebIdentityCredentialsProvider} that is returned by this factory when * {@link #create(WebIdentityTokenCredentialProperties)} is invoked. This wrapper is important because it ensures the parent * credentials provider is closed when the assume-role credentials provider is no longer needed. */ private static final class StsWebIdentityCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { private final StsClient stsClient; private final StsAssumeRoleWithWebIdentityCredentialsProvider credentialsProvider; private StsWebIdentityCredentialsProvider(WebIdentityTokenCredentialProperties credentialProperties) { String roleSessionName = credentialProperties.roleSessionName(); String sessionName = roleSessionName != null ? roleSessionName : "aws-sdk-java-" + System.currentTimeMillis(); Boolean asyncCredentialUpdateEnabled = credentialProperties.asyncCredentialUpdateEnabled() != null ? credentialProperties.asyncCredentialUpdateEnabled() : false; OrRetryCondition retryCondition = OrRetryCondition.create(context -> context.exception() instanceof IdpCommunicationErrorException, RetryCondition.defaultRetryCondition()); this.stsClient = StsClient.builder() .applyMutation(this::configureEndpoint) .credentialsProvider(AnonymousCredentialsProvider.create()) .overrideConfiguration(o -> o.retryPolicy(r -> r.retryCondition(retryCondition))) .build(); AssumeRoleWithWebIdentityRequest.Builder requestBuilder = AssumeRoleWithWebIdentityRequest .builder() .roleArn(credentialProperties.roleArn()) .roleSessionName(sessionName); if (credentialProperties.roleSessionDuration() != null) { requestBuilder.durationSeconds(NumericUtils.saturatedCast( credentialProperties.roleSessionDuration().getSeconds())); } AssumeRoleWithWebIdentityRequestSupplier supplier = AssumeRoleWithWebIdentityRequestSupplier.builder() .assumeRoleWithWebIdentityRequest(requestBuilder.build()) .webIdentityTokenFile(credentialProperties.webIdentityTokenFile()) .build(); StsAssumeRoleWithWebIdentityCredentialsProvider.Builder builder = StsAssumeRoleWithWebIdentityCredentialsProvider.builder() .asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled) .stsClient(stsClient) .refreshRequest(supplier); if (credentialProperties.prefetchTime() != null) { builder.prefetchTime(credentialProperties.prefetchTime()); } if (credentialProperties.staleTime() != null) { builder.staleTime(credentialProperties.staleTime()); } this.credentialsProvider = builder.build(); } @Override public AwsCredentials resolveCredentials() { return this.credentialsProvider.resolveCredentials(); } @Override public void close() { IoUtils.closeQuietly(credentialsProvider, null); IoUtils.closeQuietly(stsClient, null); } private void configureEndpoint(StsClientBuilder stsClientBuilder) { Region stsRegion; try { stsRegion = new DefaultAwsRegionProviderChain().getRegion(); } catch (RuntimeException e) { stsRegion = null; } if (stsRegion != null) { stsClientBuilder.region(stsRegion); } else { stsClientBuilder.region(Region.US_EAST_1); stsClientBuilder.endpointOverride(URI.create("https://sts.amazonaws.com")); } } } }
4,890
0
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/internal/StsProfileCredentialsProviderFactory.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.services.sts.internal; import java.net.URI; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.ChildProfileCredentialsProviderFactory; import software.amazon.awssdk.profiles.Profile; import software.amazon.awssdk.profiles.ProfileProperty; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.awssdk.services.sts.StsClientBuilder; import software.amazon.awssdk.services.sts.auth.StsAssumeRoleCredentialsProvider; import software.amazon.awssdk.services.sts.model.AssumeRoleRequest; import software.amazon.awssdk.utils.IoUtils; import software.amazon.awssdk.utils.SdkAutoCloseable; /** * An implementation of {@link ChildProfileCredentialsProviderFactory} that uses configuration in a profile to create a * {@link StsAssumeRoleCredentialsProvider}. */ @SdkInternalApi public final class StsProfileCredentialsProviderFactory implements ChildProfileCredentialsProviderFactory { private static final String MISSING_PROPERTY_ERROR_FORMAT = "'%s' must be set to use role-based credential loading in the " + "'%s' profile."; @Override public AwsCredentialsProvider create(AwsCredentialsProvider sourceCredentialsProvider, Profile profile) { return new StsProfileCredentialsProvider(sourceCredentialsProvider, profile); } /** * A wrapper for a {@link StsAssumeRoleCredentialsProvider} that is returned by this factory when * {@link #create(AwsCredentialsProvider, Profile)} is invoked. This wrapper is important because it ensures the parent * credentials provider is closed when the assume-role credentials provider is no longer needed. */ private static final class StsProfileCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable { private final StsClient stsClient; private final AwsCredentialsProvider parentCredentialsProvider; private final StsAssumeRoleCredentialsProvider credentialsProvider; private StsProfileCredentialsProvider(AwsCredentialsProvider parentCredentialsProvider, Profile profile) { String roleArn = requireProperty(profile, ProfileProperty.ROLE_ARN); String roleSessionName = profile.property(ProfileProperty.ROLE_SESSION_NAME) .orElseGet(() -> "aws-sdk-java-" + System.currentTimeMillis()); String externalId = profile.property(ProfileProperty.EXTERNAL_ID).orElse(null); AssumeRoleRequest assumeRoleRequest = AssumeRoleRequest.builder() .roleArn(roleArn) .roleSessionName(roleSessionName) .externalId(externalId) .build(); this.stsClient = StsClient.builder() .applyMutation(client -> configureEndpoint(client, profile)) .credentialsProvider(parentCredentialsProvider) .build(); this.parentCredentialsProvider = parentCredentialsProvider; this.credentialsProvider = StsAssumeRoleCredentialsProvider.builder() .stsClient(stsClient) .refreshRequest(assumeRoleRequest) .build(); } private void configureEndpoint(StsClientBuilder stsClientBuilder, Profile profile) { Region stsRegion = profile.property(ProfileProperty.REGION) .map(Region::of) .orElseGet(() -> { try { return new DefaultAwsRegionProviderChain().getRegion(); } catch (RuntimeException e) { return null; } }); if (stsRegion != null) { stsClientBuilder.region(stsRegion); } else { stsClientBuilder.region(Region.US_EAST_1); stsClientBuilder.endpointOverride(URI.create("https://sts.amazonaws.com")); } } private String requireProperty(Profile profile, String requiredProperty) { return profile.property(requiredProperty) .orElseThrow(() -> new IllegalArgumentException(String.format(MISSING_PROPERTY_ERROR_FORMAT, requiredProperty, profile.name()))); } @Override public AwsCredentials resolveCredentials() { return this.credentialsProvider.resolveCredentials(); } @Override public void close() { IoUtils.closeIfCloseable(parentCredentialsProvider, null); IoUtils.closeQuietly(credentialsProvider, null); IoUtils.closeQuietly(stsClient, null); } } }
4,891
0
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts
Create_ds/aws-sdk-java-v2/services/sts/src/main/java/software/amazon/awssdk/services/sts/internal/AssumeRoleWithWebIdentityRequestSupplier.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.services.sts.internal; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityRequest; import software.amazon.awssdk.utils.IoUtils; @SdkInternalApi public class AssumeRoleWithWebIdentityRequestSupplier implements Supplier<AssumeRoleWithWebIdentityRequest> { private final AssumeRoleWithWebIdentityRequest request; private final Path webIdentityTokenFile; public AssumeRoleWithWebIdentityRequestSupplier(Builder builder) { this.request = builder.request; this.webIdentityTokenFile = builder.webIdentityTokenFile; } public static Builder builder() { return new Builder(); } @Override public AssumeRoleWithWebIdentityRequest get() { return request.toBuilder().webIdentityToken(getToken(webIdentityTokenFile)).build(); } //file extraction private String getToken(Path file) { try (InputStream webIdentityTokenStream = Files.newInputStream(file)) { return IoUtils.toUtf8String(webIdentityTokenStream); } catch (IOException e) { throw new UncheckedIOException(e); } } public static class Builder { private AssumeRoleWithWebIdentityRequest request; private Path webIdentityTokenFile; public Builder assumeRoleWithWebIdentityRequest(AssumeRoleWithWebIdentityRequest request) { this.request = request; return this; } public Builder webIdentityTokenFile(Path webIdentityTokenFile) { this.webIdentityTokenFile = webIdentityTokenFile; return this; } public AssumeRoleWithWebIdentityRequestSupplier build() { return new AssumeRoleWithWebIdentityRequestSupplier(this); } } }
4,892
0
Create_ds/aws-sdk-java-v2/services/acm/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/acm/src/it/java/software/amazon/awssdk/services/acm/AwsCertficateManagerIntegrationTest.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.services.acm; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.authcrt.signer.AwsCrtV4aSigner; import software.amazon.awssdk.core.client.config.SdkAdvancedClientOption; import software.amazon.awssdk.services.acm.model.AcmException; import software.amazon.awssdk.services.acm.model.GetCertificateRequest; import software.amazon.awssdk.services.acm.model.ListCertificatesRequest; import software.amazon.awssdk.services.acm.model.ListCertificatesResponse; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class AwsCertficateManagerIntegrationTest extends AwsIntegrationTestBase { private static AcmClient client; @BeforeClass public static void setUp() { client = AcmClient.builder().credentialsProvider(StaticCredentialsProvider.create(getCredentials())).build(); } @Test public void list_certificates() { ListCertificatesResponse result = client.listCertificates(ListCertificatesRequest.builder().build()); Assert.assertTrue(result.certificateSummaryList().size() >= 0); } @Test public void list_certificates_using_oldSigv4aSigner() { AcmClient client = AcmClient.builder() .credentialsProvider(StaticCredentialsProvider.create(getCredentials())) .overrideConfiguration(c -> c.putAdvancedOption(SdkAdvancedClientOption.SIGNER, AwsCrtV4aSigner.create())) .build(); ListCertificatesResponse result = client.listCertificates(ListCertificatesRequest.builder().build()); Assert.assertTrue(result.certificateSummaryList().size() >= 0); } /** * Ideally the service must be throwing a Invalid Arn exception * instead of SdkServiceException. Have reported this to service to * fix it. * TODO Change the expected when service fix this. */ @Test(expected = AcmException.class) public void get_certificate_fake_arn_throws_exception() { client.getCertificate(GetCertificateRequest.builder().certificateArn("arn:aws:acm:us-east-1:123456789:fakecert").build()); } }
4,893
0
Create_ds/aws-sdk-java-v2/services/route53/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/route53/src/test/java/software/amazon/awssdk/services/route53/Route53InterceptorTest.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.services.route53; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.core.interceptor.InterceptorContext; import software.amazon.awssdk.services.route53.internal.Route53IdInterceptor; import software.amazon.awssdk.services.route53.model.ActivateKeySigningKeyResponse; import software.amazon.awssdk.services.route53.model.ChangeInfo; import software.amazon.awssdk.services.route53.model.CreateHostedZoneRequest; import software.amazon.awssdk.services.route53.model.CreateHostedZoneResponse; import software.amazon.awssdk.services.route53.model.CreateKeySigningKeyResponse; import software.amazon.awssdk.services.route53.model.CreateReusableDelegationSetResponse; import software.amazon.awssdk.services.route53.model.DeactivateKeySigningKeyResponse; import software.amazon.awssdk.services.route53.model.DelegationSet; import software.amazon.awssdk.services.route53.model.DeleteKeySigningKeyResponse; import software.amazon.awssdk.services.route53.model.DisableHostedZoneDnssecResponse; import software.amazon.awssdk.services.route53.model.EnableHostedZoneDnssecResponse; import software.amazon.awssdk.services.route53.model.GetHostedZoneResponse; import software.amazon.awssdk.services.route53.model.GetReusableDelegationSetResponse; import software.amazon.awssdk.services.route53.model.ListReusableDelegationSetsResponse; /** * Unit test for request handler customization of delegation set id's */ //TODO: fix test, see comment on line 80") public class Route53InterceptorTest { private static final String delegationPrefix = "delegationset"; private static final String changeInfoPrefix = "change"; private static final String id = "delegationSetId"; private static final String changeInfoId = "changeInfoId"; private static final String delegationSetId = "/" + delegationPrefix + "/" + id; private static final String changeInfoIdWithPrefix = "/" + changeInfoPrefix + "/" + changeInfoId; /** * Tests if the request handler strips the delegation set prefixes. Asserts * that the result object has prefix removed. */ @Test public void testDelegationSetPrefixRemoval() { Route53IdInterceptor interceptor = new Route53IdInterceptor(); DelegationSet delegationSet = DelegationSet.builder().id(delegationSetId).build(); CreateHostedZoneResponse createResult = CreateHostedZoneResponse.builder() .delegationSet(delegationSet) .build(); createResult = (CreateHostedZoneResponse) modifyResponse(interceptor, createResult); assertEquals(createResult.delegationSet().id(), id); CreateReusableDelegationSetResponse createResuableResult = CreateReusableDelegationSetResponse.builder() .delegationSet(delegationSet) .build(); createResuableResult = (CreateReusableDelegationSetResponse) modifyResponse(interceptor, createResuableResult); assertEquals(createResuableResult.delegationSet().id(), id); GetHostedZoneResponse getZoneResult = GetHostedZoneResponse.builder() .delegationSet(delegationSet) .build(); getZoneResult = (GetHostedZoneResponse) modifyResponse(interceptor, getZoneResult); // This assert works, but only because of the other operations the are sequenced before this, that modify the id. assertEquals(getZoneResult.delegationSet().id(), id); GetReusableDelegationSetResponse getResuableResult = GetReusableDelegationSetResponse.builder() .delegationSet(delegationSet) .build(); getResuableResult = (GetReusableDelegationSetResponse) modifyResponse(interceptor, getResuableResult); assertEquals(getResuableResult.delegationSet().id(), id); ListReusableDelegationSetsResponse listResult = ListReusableDelegationSetsResponse.builder() .delegationSets(delegationSet) .build(); listResult = (ListReusableDelegationSetsResponse) modifyResponse(interceptor, listResult); assertEquals(listResult.delegationSets().get(0).id(), id); delegationSet = delegationSet.toBuilder().id(id).build(); createResult = CreateHostedZoneResponse.builder() .delegationSet(delegationSet) .build(); createResult = (CreateHostedZoneResponse) modifyResponse(interceptor, createResult); assertEquals(createResult.delegationSet().id(), id); } private SdkResponse modifyResponse(ExecutionInterceptor interceptor, SdkResponse responseObject) { return interceptor.modifyResponse(InterceptorContext.builder() .request(CreateHostedZoneRequest.builder().build()) .response(responseObject) .build(), new ExecutionAttributes()); } @Test public void testChangeInfoPrefixRemoval() { Route53IdInterceptor interceptor = new Route53IdInterceptor(); ChangeInfo changeInfo = ChangeInfo.builder().id(changeInfoIdWithPrefix).build(); CreateKeySigningKeyResponse createKeySigningKeyResponse = CreateKeySigningKeyResponse.builder() .changeInfo(changeInfo).build(); createKeySigningKeyResponse = (CreateKeySigningKeyResponse) modifyResponse(interceptor, createKeySigningKeyResponse); assertEquals(createKeySigningKeyResponse.changeInfo().id(), changeInfoId); DeleteKeySigningKeyResponse deleteKeySigningKeyResponse = DeleteKeySigningKeyResponse.builder() .changeInfo(changeInfo).build(); deleteKeySigningKeyResponse = (DeleteKeySigningKeyResponse) modifyResponse(interceptor, deleteKeySigningKeyResponse); assertEquals(deleteKeySigningKeyResponse.changeInfo().id(), changeInfoId); ActivateKeySigningKeyResponse activateKeySigningKeyResponse = ActivateKeySigningKeyResponse.builder() .changeInfo(changeInfo).build(); activateKeySigningKeyResponse = (ActivateKeySigningKeyResponse) modifyResponse(interceptor, activateKeySigningKeyResponse); assertEquals(activateKeySigningKeyResponse.changeInfo().id(), changeInfoId); DeactivateKeySigningKeyResponse deactivateKeySigningKeyResponse = DeactivateKeySigningKeyResponse.builder() .changeInfo(changeInfo).build(); deactivateKeySigningKeyResponse = (DeactivateKeySigningKeyResponse) modifyResponse(interceptor, deactivateKeySigningKeyResponse); assertEquals(deactivateKeySigningKeyResponse.changeInfo().id(), changeInfoId); EnableHostedZoneDnssecResponse enableHostedZoneDnssecResponse = EnableHostedZoneDnssecResponse.builder() .changeInfo(changeInfo).build(); enableHostedZoneDnssecResponse = (EnableHostedZoneDnssecResponse) modifyResponse(interceptor, enableHostedZoneDnssecResponse); assertEquals(enableHostedZoneDnssecResponse.changeInfo().id(), changeInfoId); DisableHostedZoneDnssecResponse disableHostedZoneDnssecResponse = DisableHostedZoneDnssecResponse.builder() .changeInfo(changeInfo).build(); disableHostedZoneDnssecResponse = (DisableHostedZoneDnssecResponse) modifyResponse(interceptor, disableHostedZoneDnssecResponse); assertEquals(disableHostedZoneDnssecResponse.changeInfo().id(), changeInfoId); } }
4,894
0
Create_ds/aws-sdk-java-v2/services/route53/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/route53/src/test/java/software/amazon/awssdk/services/route53/QueryParamBindingTest.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.services.route53; import static org.junit.jupiter.api.Assertions.assertEquals; import java.net.URI; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import software.amazon.awssdk.core.client.config.SdkClientConfiguration; import software.amazon.awssdk.core.client.config.SdkClientOption; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.protocols.xml.AwsXmlProtocolFactory; import software.amazon.awssdk.services.route53.model.GetHealthCheckLastFailureReasonRequest; import software.amazon.awssdk.services.route53.model.ListHealthChecksRequest; import software.amazon.awssdk.services.route53.transform.GetHealthCheckLastFailureReasonRequestMarshaller; import software.amazon.awssdk.services.route53.transform.ListHealthChecksRequestMarshaller; public class QueryParamBindingTest { protected static final AwsXmlProtocolFactory PROTOCOL_FACTORY = AwsXmlProtocolFactory .builder() .clientConfiguration(SdkClientConfiguration.builder() .option(SdkClientOption.ENDPOINT, URI.create("http://localhost")) .build()) .build(); /** * Make sure the marshaller is able to handle @UriLabel parameter values * containing special characters. */ @Test public void testReservedCharInParamValue() { final String VALUE_WITH_SEMICOLON = ";foo"; final String VALUE_WITH_AMPERSAND = "&bar"; final String VALUE_WITH_QUESTION_MARK = "?charlie"; ListHealthChecksRequest listReq = ListHealthChecksRequest.builder() .marker(VALUE_WITH_SEMICOLON) .maxItems(VALUE_WITH_AMPERSAND) .build(); SdkHttpFullRequest httpReq_List = new ListHealthChecksRequestMarshaller(PROTOCOL_FACTORY).marshall(listReq); assertEquals("/2013-04-01/healthcheck", httpReq_List.encodedPath()); Map<String, List<String>> queryParams = httpReq_List.rawQueryParameters(); assertEquals(2, queryParams.size()); assertEquals(VALUE_WITH_SEMICOLON, queryParams.get("marker").get(0)); assertEquals(VALUE_WITH_AMPERSAND, queryParams.get("maxitems").get(0)); GetHealthCheckLastFailureReasonRequest getFailureReq = GetHealthCheckLastFailureReasonRequest.builder() .healthCheckId(VALUE_WITH_QUESTION_MARK) .build(); SdkHttpFullRequest httpReq_GetFailure = new GetHealthCheckLastFailureReasonRequestMarshaller(PROTOCOL_FACTORY).marshall(getFailureReq); System.out.println(httpReq_GetFailure); // parameter value should be URL encoded assertEquals( "/2013-04-01/healthcheck/%3Fcharlie/lastfailurereason", httpReq_GetFailure.encodedPath()); queryParams = httpReq_GetFailure.rawQueryParameters(); assertEquals(0, queryParams.size()); } }
4,895
0
Create_ds/aws-sdk-java-v2/services/route53/src/it/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/route53/src/it/java/software/amazon/awssdk/services/route53/Route53IntegrationTest.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.services.route53; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.List; import java.util.UUID; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.SdkGlobalTime; import software.amazon.awssdk.core.exception.SdkServiceException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.route53.model.Change; import software.amazon.awssdk.services.route53.model.ChangeAction; import software.amazon.awssdk.services.route53.model.ChangeBatch; import software.amazon.awssdk.services.route53.model.ChangeInfo; import software.amazon.awssdk.services.route53.model.ChangeResourceRecordSetsRequest; import software.amazon.awssdk.services.route53.model.CreateHealthCheckRequest; import software.amazon.awssdk.services.route53.model.CreateHealthCheckResponse; import software.amazon.awssdk.services.route53.model.CreateHostedZoneRequest; import software.amazon.awssdk.services.route53.model.CreateHostedZoneResponse; import software.amazon.awssdk.services.route53.model.DelegationSet; import software.amazon.awssdk.services.route53.model.DeleteHealthCheckRequest; import software.amazon.awssdk.services.route53.model.DeleteHostedZoneRequest; import software.amazon.awssdk.services.route53.model.DeleteHostedZoneResponse; import software.amazon.awssdk.services.route53.model.GetChangeRequest; import software.amazon.awssdk.services.route53.model.GetHealthCheckRequest; import software.amazon.awssdk.services.route53.model.GetHealthCheckResponse; import software.amazon.awssdk.services.route53.model.GetHostedZoneRequest; import software.amazon.awssdk.services.route53.model.GetHostedZoneResponse; import software.amazon.awssdk.services.route53.model.HealthCheck; import software.amazon.awssdk.services.route53.model.HealthCheckConfig; import software.amazon.awssdk.services.route53.model.HostedZone; import software.amazon.awssdk.services.route53.model.HostedZoneConfig; import software.amazon.awssdk.services.route53.model.ListHostedZonesRequest; import software.amazon.awssdk.services.route53.model.ListResourceRecordSetsRequest; import software.amazon.awssdk.services.route53.model.RRType; import software.amazon.awssdk.services.route53.model.ResourceRecord; import software.amazon.awssdk.services.route53.model.ResourceRecordSet; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; /** * Integration tests that run through the various operations available in the * Route 53 API. */ public class Route53IntegrationTest extends AwsIntegrationTestBase { private static final String COMMENT = "comment"; private static final String ZONE_NAME = "java.sdk.com."; private static final String CALLER_REFERENCE = UUID.randomUUID().toString(); private static final int PORT_NUM = 22; private static final String TYPE = "TCP"; private static final String IP_ADDRESS = "12.12.12.12"; private static Route53Client route53; /** * The ID of the zone we created in this test. */ private static String createdZoneId; /** * The ID of the change that created our test zone. */ private static String createdZoneChangeId; /** * the ID of the health check. */ private String healthCheckId; @BeforeClass public static void setup() { route53 = Route53Client.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .region(Region.AWS_GLOBAL) .build(); // Create Hosted Zone CreateHostedZoneResponse result = route53.createHostedZone(CreateHostedZoneRequest.builder() .name(ZONE_NAME) .callerReference(CALLER_REFERENCE) .hostedZoneConfig(HostedZoneConfig.builder() .comment(COMMENT).build()).build() ); createdZoneId = result.hostedZone().id(); createdZoneChangeId = result.changeInfo().id(); } /** * Ensures the HostedZone we create during this test is correctly released. */ @AfterClass public static void tearDown() { try { route53.deleteHostedZone(DeleteHostedZoneRequest.builder().id(createdZoneId).build()); } catch (Exception e) { // Ignored or expected. } } /** * Runs through each of the APIs in the Route 53 client to make sure we can * correct send requests and unmarshall responses. */ @Test public void testRoute53() throws Exception { // Get Hosted Zone GetHostedZoneRequest hostedZoneRequest = GetHostedZoneRequest.builder().id(createdZoneId).build(); GetHostedZoneResponse hostedZoneResult = route53.getHostedZone(hostedZoneRequest); assertValidDelegationSet(hostedZoneResult.delegationSet()); assertValidCreatedHostedZone(hostedZoneResult.hostedZone()); // Create a health check HealthCheckConfig config = HealthCheckConfig.builder().type("TCP").port(PORT_NUM).ipAddress(IP_ADDRESS).build(); CreateHealthCheckResponse createHealthCheckResult = route53.createHealthCheck( CreateHealthCheckRequest.builder().healthCheckConfig(config).callerReference(CALLER_REFERENCE).build()); healthCheckId = createHealthCheckResult.healthCheck().id(); assertNotNull(createHealthCheckResult.location()); assertValidHealthCheck(createHealthCheckResult.healthCheck()); // Get the health check back GetHealthCheckResponse gealthCheckResult = route53 .getHealthCheck(GetHealthCheckRequest.builder().healthCheckId(healthCheckId).build()); assertValidHealthCheck(gealthCheckResult.healthCheck()); // Delete the health check route53.deleteHealthCheck(DeleteHealthCheckRequest.builder().healthCheckId(healthCheckId).build()); // Get the health check back try { gealthCheckResult = route53.getHealthCheck(GetHealthCheckRequest.builder().healthCheckId(healthCheckId).build()); fail(); } catch (AwsServiceException e) { assertNotNull(e.getMessage()); assertNotNull(e.awsErrorDetails().errorCode()); } // List Hosted Zones List<HostedZone> hostedZones = route53.listHostedZones(ListHostedZonesRequest.builder().build()).hostedZones(); assertTrue(hostedZones.size() > 0); for (HostedZone hostedZone : hostedZones) { assertNotNull(hostedZone.callerReference()); assertNotNull(hostedZone.id()); assertNotNull(hostedZone.name()); } // List Resource Record Sets List<ResourceRecordSet> resourceRecordSets = route53.listResourceRecordSets( ListResourceRecordSetsRequest.builder().hostedZoneId(createdZoneId).build()).resourceRecordSets(); assertTrue(resourceRecordSets.size() > 0); ResourceRecordSet existingResourceRecordSet = resourceRecordSets.get(0); for (ResourceRecordSet rrset : resourceRecordSets) { assertNotNull(rrset.name()); assertNotNull(rrset.type()); assertNotNull(rrset.ttl()); assertTrue(rrset.resourceRecords().size() > 0); } // Get Change ChangeInfo changeInfo = route53.getChange(GetChangeRequest.builder().id(createdZoneChangeId).build()).changeInfo(); assertTrue(changeInfo.id().endsWith(createdZoneChangeId)); assertValidChangeInfo(changeInfo); // Change Resource Record Sets ResourceRecordSet newResourceRecordSet = ResourceRecordSet.builder() .name(ZONE_NAME) .resourceRecords(existingResourceRecordSet.resourceRecords()) .ttl(existingResourceRecordSet.ttl() + 100) .type(existingResourceRecordSet.type()) .build(); changeInfo = route53.changeResourceRecordSets(ChangeResourceRecordSetsRequest.builder() .hostedZoneId(createdZoneId) .changeBatch(ChangeBatch.builder().comment(COMMENT) .changes(Change.builder().action( ChangeAction.DELETE) .resourceRecordSet( existingResourceRecordSet).build(), Change.builder().action( ChangeAction.CREATE) .resourceRecordSet( newResourceRecordSet).build()).build() ).build()).changeInfo(); assertValidChangeInfo(changeInfo); // Add a weighted Resource Record Set so we can reproduce the bug reported by customers // when they provide SetIdentifier containing special characters. String specialChars = "&<>'\""; newResourceRecordSet =ResourceRecordSet.builder() .name("weighted." + ZONE_NAME) .type(RRType.CNAME) .setIdentifier(specialChars) .weight(0L) .ttl(1000L) .resourceRecords(ResourceRecord.builder().value("www.example.com").build()) .build(); changeInfo = route53.changeResourceRecordSets(ChangeResourceRecordSetsRequest.builder() .hostedZoneId(createdZoneId) .changeBatch( ChangeBatch.builder().comment(COMMENT).changes( Change.builder().action(ChangeAction.CREATE) .resourceRecordSet( newResourceRecordSet).build()).build()).build() ).changeInfo(); assertValidChangeInfo(changeInfo); // Clear up the RR Set changeInfo = route53.changeResourceRecordSets(ChangeResourceRecordSetsRequest.builder() .hostedZoneId(createdZoneId) .changeBatch( ChangeBatch.builder().comment(COMMENT).changes( Change.builder().action(ChangeAction.DELETE) .resourceRecordSet( newResourceRecordSet).build()).build()).build() ).changeInfo(); // Delete Hosted Zone DeleteHostedZoneResponse deleteHostedZoneResult = route53.deleteHostedZone(DeleteHostedZoneRequest.builder().id(createdZoneId).build()); assertValidChangeInfo(deleteHostedZoneResult.changeInfo()); } /** * Asserts that the specified HostedZone is valid and represents the same * HostedZone that we initially created at the very start of this test. * * @param hostedZone The hosted zone to test. */ private void assertValidCreatedHostedZone(HostedZone hostedZone) { assertEquals(CALLER_REFERENCE, hostedZone.callerReference()); assertEquals(ZONE_NAME, hostedZone.name()); assertNotNull(hostedZone.id()); assertEquals(COMMENT, hostedZone.config().comment()); } /** * Asserts that the specified DelegationSet is valid. * * @param delegationSet The delegation set to test. */ private void assertValidDelegationSet(DelegationSet delegationSet) { assertTrue(delegationSet.nameServers().size() > 0); for (String server : delegationSet.nameServers()) { assertNotNull(server); } } /** * Asserts that the specified ChangeInfo is valid. * * @param change The ChangeInfo object to test. */ private void assertValidChangeInfo(ChangeInfo change) { assertNotNull(change.id()); assertNotNull(change.status()); assertNotNull(change.submittedAt()); } private void assertValidHealthCheck(HealthCheck healthCheck) { assertNotNull(CALLER_REFERENCE, healthCheck.callerReference()); assertNotNull(healthCheck.id()); assertEquals(PORT_NUM, healthCheck.healthCheckConfig().port().intValue()); assertEquals(TYPE, healthCheck.healthCheckConfig().typeAsString()); assertEquals(IP_ADDRESS, healthCheck.healthCheckConfig().ipAddress()); } /** * In the following test, we purposely setting the time offset to trigger a clock skew error. * The time offset must be fixed and then we validate the global value for time offset has been * update. */ @Test public void testClockSkew() throws SdkServiceException { SdkGlobalTime.setGlobalTimeOffset(3600); Route53Client clockSkewClient = Route53Client.builder() .region(Region.AWS_GLOBAL) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); clockSkewClient.listHostedZones(ListHostedZonesRequest.builder().build()); assertTrue("Clockskew is fixed!", SdkGlobalTime.getGlobalTimeOffset() < 60); } }
4,896
0
Create_ds/aws-sdk-java-v2/services/route53/src/main/java/software/amazon/awssdk/services/route53
Create_ds/aws-sdk-java-v2/services/route53/src/main/java/software/amazon/awssdk/services/route53/internal/Route53IdInterceptor.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.services.route53.internal; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.core.SdkResponse; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.services.route53.model.ActivateKeySigningKeyResponse; import software.amazon.awssdk.services.route53.model.AliasTarget; import software.amazon.awssdk.services.route53.model.ChangeInfo; import software.amazon.awssdk.services.route53.model.ChangeResourceRecordSetsResponse; import software.amazon.awssdk.services.route53.model.CreateHealthCheckResponse; import software.amazon.awssdk.services.route53.model.CreateHostedZoneResponse; import software.amazon.awssdk.services.route53.model.CreateKeySigningKeyResponse; import software.amazon.awssdk.services.route53.model.CreateReusableDelegationSetResponse; import software.amazon.awssdk.services.route53.model.DeactivateKeySigningKeyResponse; import software.amazon.awssdk.services.route53.model.DelegationSet; import software.amazon.awssdk.services.route53.model.DeleteHostedZoneResponse; import software.amazon.awssdk.services.route53.model.DeleteKeySigningKeyResponse; import software.amazon.awssdk.services.route53.model.DisableHostedZoneDnssecResponse; import software.amazon.awssdk.services.route53.model.EnableHostedZoneDnssecResponse; import software.amazon.awssdk.services.route53.model.GetChangeResponse; import software.amazon.awssdk.services.route53.model.GetHealthCheckResponse; import software.amazon.awssdk.services.route53.model.GetHostedZoneResponse; import software.amazon.awssdk.services.route53.model.GetReusableDelegationSetResponse; import software.amazon.awssdk.services.route53.model.HealthCheck; import software.amazon.awssdk.services.route53.model.HostedZone; import software.amazon.awssdk.services.route53.model.ListHealthChecksResponse; import software.amazon.awssdk.services.route53.model.ListHostedZonesResponse; import software.amazon.awssdk.services.route53.model.ListResourceRecordSetsResponse; import software.amazon.awssdk.services.route53.model.ListReusableDelegationSetsResponse; import software.amazon.awssdk.services.route53.model.ResourceRecordSet; /** * Route 53 returns a portion of the URL resource path as the ID for a few * elements, but when the service accepts those IDs, the resource path portion * cannot be included, otherwise requests fail. This handler removes those * partial resource path elements from IDs returned by Route 53. */ @SdkInternalApi public final class Route53IdInterceptor implements ExecutionInterceptor { @Override public SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes) { SdkResponse response = context.response(); if (response instanceof ChangeResourceRecordSetsResponse) { ChangeResourceRecordSetsResponse result = (ChangeResourceRecordSetsResponse) response; return result.toBuilder() .changeInfo(removePrefix(result.changeInfo())) .build(); } else if (response instanceof CreateHostedZoneResponse) { CreateHostedZoneResponse result = (CreateHostedZoneResponse) response; return result.toBuilder() .changeInfo(removePrefix(result.changeInfo())) .hostedZone(removePrefix(result.hostedZone())) .delegationSet(removePrefix(result.delegationSet())) .build(); } else if (response instanceof DeleteHostedZoneResponse) { DeleteHostedZoneResponse result = (DeleteHostedZoneResponse) response; return result.toBuilder() .changeInfo(removePrefix(result.changeInfo())) .build(); } else if (response instanceof GetChangeResponse) { GetChangeResponse result = (GetChangeResponse) response; return result.toBuilder() .changeInfo(removePrefix(result.changeInfo())) .build(); } else if (response instanceof GetHostedZoneResponse) { GetHostedZoneResponse result = (GetHostedZoneResponse) response; return result.toBuilder() .hostedZone(removePrefix(result.hostedZone())) .delegationSet(removePrefix(result.delegationSet())) .build(); } else if (response instanceof ListHostedZonesResponse) { ListHostedZonesResponse result = (ListHostedZonesResponse) response; return result.toBuilder() .hostedZones(result.hostedZones().stream() .map(this::removePrefix) .collect(Collectors.toList())) .build(); } else if (response instanceof ListResourceRecordSetsResponse) { ListResourceRecordSetsResponse result = (ListResourceRecordSetsResponse) response; return result.toBuilder() .resourceRecordSets(result.resourceRecordSets().stream() .map(this::removePrefix) .collect(Collectors.toList())) .build(); } else if (response instanceof CreateHealthCheckResponse) { CreateHealthCheckResponse result = (CreateHealthCheckResponse) response; return result.toBuilder() .healthCheck(removePrefix(result.healthCheck())) .build(); } else if (response instanceof GetHealthCheckResponse) { GetHealthCheckResponse result = (GetHealthCheckResponse) response; return result.toBuilder() .healthCheck(removePrefix(result.healthCheck())) .build(); } else if (response instanceof ListHealthChecksResponse) { ListHealthChecksResponse result = (ListHealthChecksResponse) response; return result.toBuilder() .healthChecks(result.healthChecks().stream() .map(this::removePrefix) .collect(Collectors.toList())) .build(); } else if (response instanceof CreateReusableDelegationSetResponse) { CreateReusableDelegationSetResponse result = (CreateReusableDelegationSetResponse) response; return result.toBuilder() .delegationSet(removePrefix(result.delegationSet())) .build(); } else if (response instanceof GetReusableDelegationSetResponse) { GetReusableDelegationSetResponse result = (GetReusableDelegationSetResponse) response; return result.toBuilder() .delegationSet(removePrefix(result.delegationSet())) .build(); } else if (response instanceof ListReusableDelegationSetsResponse) { ListReusableDelegationSetsResponse result = (ListReusableDelegationSetsResponse) response; return result.toBuilder() .delegationSets(result.delegationSets().stream() .map(this::removePrefix) .collect(Collectors.toList())) .build(); } else if (response instanceof CreateKeySigningKeyResponse) { CreateKeySigningKeyResponse result = (CreateKeySigningKeyResponse) response; return result.toBuilder() .changeInfo(removePrefix(result.changeInfo())) .build(); } else if (response instanceof DeleteKeySigningKeyResponse) { DeleteKeySigningKeyResponse result = (DeleteKeySigningKeyResponse) response; return result.toBuilder() .changeInfo(removePrefix(result.changeInfo())) .build(); } else if (response instanceof ActivateKeySigningKeyResponse) { ActivateKeySigningKeyResponse result = (ActivateKeySigningKeyResponse) response; return result.toBuilder() .changeInfo(removePrefix(result.changeInfo())) .build(); } else if (response instanceof DeactivateKeySigningKeyResponse) { DeactivateKeySigningKeyResponse result = (DeactivateKeySigningKeyResponse) response; return result.toBuilder() .changeInfo(removePrefix(result.changeInfo())) .build(); } else if (response instanceof EnableHostedZoneDnssecResponse) { EnableHostedZoneDnssecResponse result = (EnableHostedZoneDnssecResponse) response; return result.toBuilder() .changeInfo(removePrefix(result.changeInfo())) .build(); } else if (response instanceof DisableHostedZoneDnssecResponse) { DisableHostedZoneDnssecResponse result = (DisableHostedZoneDnssecResponse) response; return result.toBuilder() .changeInfo(removePrefix(result.changeInfo())) .build(); } return response; } private ResourceRecordSet removePrefix(ResourceRecordSet rrset) { if (rrset == null) { return null; } return rrset.toBuilder() .aliasTarget(removePrefix(rrset.aliasTarget())) .healthCheckId(removePrefix(rrset.healthCheckId())) .setIdentifier(removePrefix(rrset.setIdentifier())) .build(); } private AliasTarget removePrefix(AliasTarget aliasTarget) { if (aliasTarget == null) { return null; } return aliasTarget.toBuilder() .hostedZoneId(removePrefix(aliasTarget.hostedZoneId())) .build(); } private ChangeInfo removePrefix(ChangeInfo changeInfo) { if (changeInfo == null) { return null; } return changeInfo.toBuilder() .id(removePrefix(changeInfo.id())) .build(); } private HostedZone removePrefix(HostedZone hostedZone) { if (hostedZone == null) { return null; } return hostedZone.toBuilder() .id(removePrefix(hostedZone.id())) .build(); } private HealthCheck removePrefix(HealthCheck healthCheck) { if (healthCheck == null) { return null; } return healthCheck.toBuilder() .id(removePrefix(healthCheck.id())) .build(); } private DelegationSet removePrefix(DelegationSet delegationSet) { if (delegationSet == null) { return null; } return delegationSet.toBuilder() .id(removePrefix(delegationSet.id())) .build(); } private String removePrefix(String s) { if (s == null) { return null; } int lastIndex = s.lastIndexOf('/'); if (lastIndex > 0) { return s.substring(lastIndex + 1); } return s; } }
4,897
0
Create_ds/aws-sdk-java-v2/services/ec2/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ec2/src/test/java/software/amazon/awssdk/services/ec2/Ec2ResponseMetadataIntegrationTest.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.services.ec2; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesResponse; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class Ec2ResponseMetadataIntegrationTest extends AwsIntegrationTestBase { @Test public void ec2Response_shouldHaveRequestId() { Ec2Client ec2Client = Ec2Client.builder() .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); DescribeAvailabilityZonesResponse response = ec2Client.describeAvailabilityZones(); String requestId = response.responseMetadata().requestId(); assertThat(requestId).isNotEqualTo("UNKNOWN"); } }
4,898
0
Create_ds/aws-sdk-java-v2/services/ec2/src/test/java/software/amazon/awssdk/services
Create_ds/aws-sdk-java-v2/services/ec2/src/test/java/software/amazon/awssdk/services/ec2/Ec2AutoPaginatorIntegrationTest.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.services.ec2; import static org.assertj.core.api.Assertions.assertThat; import java.time.Instant; import java.util.stream.Stream; import org.junit.Test; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.ec2.model.SpotPrice; import software.amazon.awssdk.services.ec2.paginators.DescribeSpotPriceHistoryPublisher; import software.amazon.awssdk.testutils.service.AwsIntegrationTestBase; public class Ec2AutoPaginatorIntegrationTest extends AwsIntegrationTestBase { @Test public void testSpotPriceHistorySyncPaginator() { Ec2Client ec2Client = Ec2Client.builder() .region(Region.US_EAST_1) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); Stream<SpotPrice> spotPrices = ec2Client.describeSpotPriceHistoryPaginator(builder -> { builder.availabilityZone("us-east-1a") .productDescriptions("Linux/UNIX (Amazon VPC)") .instanceTypesWithStrings("t1.micro") .startTime(Instant.now().minusMillis(1)); }).spotPriceHistory().stream(); assertThat(spotPrices.count()).isEqualTo(1); } @Test public void testSpotPriceHistoryAsyncPaginator() { Ec2AsyncClient ec2Client = Ec2AsyncClient.builder() .region(Region.US_EAST_1) .credentialsProvider(CREDENTIALS_PROVIDER_CHAIN) .build(); DescribeSpotPriceHistoryPublisher publisher = ec2Client.describeSpotPriceHistoryPaginator(builder -> { builder.availabilityZone("us-east-1a") .productDescriptions("Linux/UNIX (Amazon VPC)") .instanceTypesWithStrings("t1.micro") .startTime(Instant.now().minusMillis(1)); }); publisher.subscribe(r -> assertThat(r.spotPriceHistory().size()).isEqualTo(1)) .join(); } }
4,899